drive-coding 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.he.md +98 -0
  3. package/README.md +97 -0
  4. package/dist/drive-coding.js +126981 -0
  5. package/frontend-dist/_app/env.js +1 -0
  6. package/frontend-dist/_app/immutable/assets/0.CU-P_407.css +1 -0
  7. package/frontend-dist/_app/immutable/assets/2.D9ALpOww.css +1 -0
  8. package/frontend-dist/_app/immutable/assets/3.E6ED7Syh.css +1 -0
  9. package/frontend-dist/_app/immutable/assets/5.YWA13FkN.css +1 -0
  10. package/frontend-dist/_app/immutable/assets/KaTeX_AMS-Regular.BQhdFMY1.woff2 +0 -0
  11. package/frontend-dist/_app/immutable/assets/KaTeX_AMS-Regular.DMm9YOAa.woff +0 -0
  12. package/frontend-dist/_app/immutable/assets/KaTeX_AMS-Regular.DRggAlZN.ttf +0 -0
  13. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Bold.ATXxdsX0.ttf +0 -0
  14. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Bold.BEiXGLvX.woff +0 -0
  15. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Bold.Dq_IR9rO.woff2 +0 -0
  16. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Regular.CTRA-rTL.woff +0 -0
  17. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Regular.Di6jR-x-.woff2 +0 -0
  18. package/frontend-dist/_app/immutable/assets/KaTeX_Caligraphic-Regular.wX97UBjC.ttf +0 -0
  19. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Bold.BdnERNNW.ttf +0 -0
  20. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Bold.BsDP51OF.woff +0 -0
  21. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Bold.CL6g_b3V.woff2 +0 -0
  22. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Regular.CB_wures.ttf +0 -0
  23. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Regular.CTYiF6lA.woff2 +0 -0
  24. package/frontend-dist/_app/immutable/assets/KaTeX_Fraktur-Regular.Dxdc4cR9.woff +0 -0
  25. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Bold.Cx986IdX.woff2 +0 -0
  26. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Bold.Jm3AIy58.woff +0 -0
  27. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Bold.waoOVXN0.ttf +0 -0
  28. package/frontend-dist/_app/immutable/assets/KaTeX_Main-BoldItalic.DxDJ3AOS.woff2 +0 -0
  29. package/frontend-dist/_app/immutable/assets/KaTeX_Main-BoldItalic.DzxPMmG6.ttf +0 -0
  30. package/frontend-dist/_app/immutable/assets/KaTeX_Main-BoldItalic.SpSLRI95.woff +0 -0
  31. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Italic.3WenGoN9.ttf +0 -0
  32. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Italic.BMLOBm91.woff +0 -0
  33. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Italic.NWA7e6Wa.woff2 +0 -0
  34. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Regular.B22Nviop.woff2 +0 -0
  35. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Regular.Dr94JaBh.woff +0 -0
  36. package/frontend-dist/_app/immutable/assets/KaTeX_Main-Regular.ypZvNtVU.ttf +0 -0
  37. package/frontend-dist/_app/immutable/assets/KaTeX_Math-BoldItalic.B3XSjfu4.ttf +0 -0
  38. package/frontend-dist/_app/immutable/assets/KaTeX_Math-BoldItalic.CZnvNsCZ.woff2 +0 -0
  39. package/frontend-dist/_app/immutable/assets/KaTeX_Math-BoldItalic.iY-2wyZ7.woff +0 -0
  40. package/frontend-dist/_app/immutable/assets/KaTeX_Math-Italic.DA0__PXp.woff +0 -0
  41. package/frontend-dist/_app/immutable/assets/KaTeX_Math-Italic.flOr_0UB.ttf +0 -0
  42. package/frontend-dist/_app/immutable/assets/KaTeX_Math-Italic.t53AETM-.woff2 +0 -0
  43. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Bold.CFMepnvq.ttf +0 -0
  44. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Bold.D1sUS0GD.woff2 +0 -0
  45. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Bold.DbIhKOiC.woff +0 -0
  46. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Italic.C3H0VqGB.woff2 +0 -0
  47. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Italic.DN2j7dab.woff +0 -0
  48. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Italic.YYjJ1zSn.ttf +0 -0
  49. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Regular.BNo7hRIc.ttf +0 -0
  50. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Regular.CS6fqUqJ.woff +0 -0
  51. package/frontend-dist/_app/immutable/assets/KaTeX_SansSerif-Regular.DDBCnlJ7.woff2 +0 -0
  52. package/frontend-dist/_app/immutable/assets/KaTeX_Script-Regular.C5JkGWo-.ttf +0 -0
  53. package/frontend-dist/_app/immutable/assets/KaTeX_Script-Regular.D3wIWfF6.woff2 +0 -0
  54. package/frontend-dist/_app/immutable/assets/KaTeX_Script-Regular.D5yQViql.woff +0 -0
  55. package/frontend-dist/_app/immutable/assets/KaTeX_Size1-Regular.C195tn64.woff +0 -0
  56. package/frontend-dist/_app/immutable/assets/KaTeX_Size1-Regular.Dbsnue_I.ttf +0 -0
  57. package/frontend-dist/_app/immutable/assets/KaTeX_Size1-Regular.mCD8mA8B.woff2 +0 -0
  58. package/frontend-dist/_app/immutable/assets/KaTeX_Size2-Regular.B7gKUWhC.ttf +0 -0
  59. package/frontend-dist/_app/immutable/assets/KaTeX_Size2-Regular.Dy4dx90m.woff2 +0 -0
  60. package/frontend-dist/_app/immutable/assets/KaTeX_Size2-Regular.oD1tc_U0.woff +0 -0
  61. package/frontend-dist/_app/immutable/assets/KaTeX_Size3-Regular.CTq5MqoE.woff +0 -0
  62. package/frontend-dist/_app/immutable/assets/KaTeX_Size3-Regular.DgpXs0kz.ttf +0 -0
  63. package/frontend-dist/_app/immutable/assets/KaTeX_Size4-Regular.BF-4gkZK.woff +0 -0
  64. package/frontend-dist/_app/immutable/assets/KaTeX_Size4-Regular.DWFBv043.ttf +0 -0
  65. package/frontend-dist/_app/immutable/assets/KaTeX_Size4-Regular.Dl5lxZxV.woff2 +0 -0
  66. package/frontend-dist/_app/immutable/assets/KaTeX_Typewriter-Regular.C0xS9mPB.woff +0 -0
  67. package/frontend-dist/_app/immutable/assets/KaTeX_Typewriter-Regular.CO6r4hn1.woff2 +0 -0
  68. package/frontend-dist/_app/immutable/assets/KaTeX_Typewriter-Regular.D3Ib7_Hf.ttf +0 -0
  69. package/frontend-dist/_app/immutable/assets/LoadingModal.DNP0Snt_.css +1 -0
  70. package/frontend-dist/_app/immutable/assets/ort-wasm-simd-threaded.jsep.CyqnNavA.wasm +0 -0
  71. package/frontend-dist/_app/immutable/chunks/6wE5kWJZ.js +1 -0
  72. package/frontend-dist/_app/immutable/chunks/BQWUQCb9.js +1 -0
  73. package/frontend-dist/_app/immutable/chunks/Ba9FG7d8.js +1 -0
  74. package/frontend-dist/_app/immutable/chunks/BeCtfktE.js +292 -0
  75. package/frontend-dist/_app/immutable/chunks/Bg0A44SF.js +1 -0
  76. package/frontend-dist/_app/immutable/chunks/CKhUHIER.js +1 -0
  77. package/frontend-dist/_app/immutable/chunks/CeZBaqrV.js +1 -0
  78. package/frontend-dist/_app/immutable/chunks/CisdKsFD.js +1 -0
  79. package/frontend-dist/_app/immutable/chunks/CqwDxRdj.js +1 -0
  80. package/frontend-dist/_app/immutable/chunks/CuPEg3Gz.js +2 -0
  81. package/frontend-dist/_app/immutable/chunks/CuT6ZSeQ.js +1 -0
  82. package/frontend-dist/_app/immutable/chunks/DgOhoED9.js +1 -0
  83. package/frontend-dist/_app/immutable/chunks/DvwKyUJ9.js +1 -0
  84. package/frontend-dist/_app/immutable/chunks/JqqgS7yq.js +1 -0
  85. package/frontend-dist/_app/immutable/chunks/LL0hSDod.js +1 -0
  86. package/frontend-dist/_app/immutable/chunks/LNR4j0nK.js +7 -0
  87. package/frontend-dist/_app/immutable/chunks/Oe6tjNLB.js +1 -0
  88. package/frontend-dist/_app/immutable/chunks/SrseV9LB.js +109 -0
  89. package/frontend-dist/_app/immutable/chunks/cseHWQnP.js +2 -0
  90. package/frontend-dist/_app/immutable/chunks/iM4ae5dg.js +1 -0
  91. package/frontend-dist/_app/immutable/entry/app.Dtr_WULu.js +2 -0
  92. package/frontend-dist/_app/immutable/entry/start.DNvi4k83.js +1 -0
  93. package/frontend-dist/_app/immutable/nodes/0.D_beALrd.js +423 -0
  94. package/frontend-dist/_app/immutable/nodes/1.BDPrJE0T.js +1 -0
  95. package/frontend-dist/_app/immutable/nodes/2.CFtWC6Ki.js +1 -0
  96. package/frontend-dist/_app/immutable/nodes/3.D_3DlZlE.js +9 -0
  97. package/frontend-dist/_app/immutable/nodes/4.xmsDSvqR.js +4 -0
  98. package/frontend-dist/_app/immutable/nodes/5.CihE_QrF.js +2881 -0
  99. package/frontend-dist/_app/version.json +1 -0
  100. package/frontend-dist/icons/apple-touch-icon.png +0 -0
  101. package/frontend-dist/icons/favicon-64.png +0 -0
  102. package/frontend-dist/icons/icon-180.png +0 -0
  103. package/frontend-dist/icons/icon-192.png +0 -0
  104. package/frontend-dist/icons/icon-512-maskable.png +0 -0
  105. package/frontend-dist/icons/icon-512.png +0 -0
  106. package/frontend-dist/index.html +67 -0
  107. package/frontend-dist/manifest.webmanifest +17 -0
  108. package/frontend-dist/wake-word/models/alexa_v0.1.onnx +0 -0
  109. package/frontend-dist/wake-word/models/embedding_model.onnx +0 -0
  110. package/frontend-dist/wake-word/models/hey_jarvis_v0.1.onnx +0 -0
  111. package/frontend-dist/wake-word/models/hey_mycroft_v0.1.onnx +0 -0
  112. package/frontend-dist/wake-word/models/hey_rhasspy_v0.1.onnx +0 -0
  113. package/frontend-dist/wake-word/models/melspectrogram.onnx +0 -0
  114. package/frontend-dist/wake-word/models/silero_vad.onnx +0 -0
  115. package/package.json +42 -0
  116. package/plugins/README.md +47 -0
  117. package/plugins/prompt-injector.ts +83 -0
@@ -0,0 +1,423 @@
1
+ var LI=Object.defineProperty;var ip=t=>{throw TypeError(t)};var GI=(t,e,n)=>e in t?LI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Z=(t,e,n)=>GI(t,typeof e!="symbol"?e+"":e,n),ou=(t,e,n)=>e.has(t)||ip("Cannot "+n);var g=(t,e,n)=>(ou(t,e,"read from private field"),n?n.call(t):e.get(t)),D=(t,e,n)=>e.has(t)?ip("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),O=(t,e,n,o)=>(ou(t,e,"write to private field"),o?o.call(t,n):e.set(t,n),n),$=(t,e,n)=>(ou(t,e,"access private method"),n);var sp=(t,e,n,o)=>({set _(i){O(t,e,i,n)},get _(){return g(t,e,o)}});import{c as zI,a as FI}from"../chunks/DgOhoED9.js";import{bl as se,aY as qe,am as Y,b9 as te,bq as VI,bu as ws,bv as Ga,ag as qI,bs as BI,aZ as HI,aj as ZI,aW as JI,a9 as WI,aS as KI,$ as YI}from"../chunks/LL0hSDod.js";import{b as An,e as XI,t as iu,y as QI,F as jI,x as eS,E as tS,G as nS,z as oS,J as iS,B as sS,u as rS,H as aS,D as lS,I as uS,A as cS,w as dS,s as pS,C as fS,v as hS,K as mS}from"../chunks/BQWUQCb9.js";import{h as gS}from"../chunks/DvwKyUJ9.js";import{p as vS}from"../chunks/CeZBaqrV.js";import{t as ti}from"../chunks/SrseV9LB.js";import"../chunks/CuT6ZSeQ.js";import{D as Og,T as yS}from"../chunks/Oe6tjNLB.js";import{t as Is}from"../chunks/CqwDxRdj.js";const _S=!1,TS=!1,ES=!0,u9=Object.freeze(Object.defineProperty({__proto__:null,csr:ES,prerender:TS,ssr:_S},Symbol.toStringTag,{value:"Module"})),wS=globalThis.__sveltekit_mrx7ku.env;var tn,Zn,Du,ka;class IS{constructor(){D(this,Zn);Z(this,"enabled",!0);D(this,tn,null)}play(e){if(this.enabled&&!(typeof globalThis.AudioContext>"u")){if(g(this,tn)===null)try{O(this,tn,new AudioContext)}catch{return}switch(g(this,tn).state==="suspended"&&g(this,tn).resume(),e){case"recordingStart":$(this,Zn,Du).call(this,880,120);break;case"recordingStop":$(this,Zn,Du).call(this,660,120);break;case"thinking":$(this,Zn,ka).call(this,523,659,300);break;case"speaking":$(this,Zn,ka).call(this,659,523,300);break;case"error":$(this,Zn,ka).call(this,329,220,400);break}}}async close(){g(this,tn)!==null&&(await g(this,tn).close(),O(this,tn,null))}}tn=new WeakMap,Zn=new WeakSet,Du=function(e,n){const o=g(this,tn);if(o===null)return;const i=o.currentTime,s=o.createOscillator(),r=o.createGain();s.frequency.value=e,s.type="sine",r.gain.setValueAtTime(0,i),r.gain.linearRampToValueAtTime(.2,i+.005),r.gain.linearRampToValueAtTime(0,i+n/1e3),s.connect(r).connect(o.destination),s.start(i),s.stop(i+n/1e3+.05)},ka=function(e,n,o){const i=g(this,tn);if(i===null)return;const s=i.currentTime,r=i.createOscillator(),a=i.createGain();r.frequency.setValueAtTime(e,s),r.frequency.linearRampToValueAtTime(n,s+o/1e3),r.type="sine",a.gain.setValueAtTime(0,s),a.gain.linearRampToValueAtTime(.2,s+.005),a.gain.linearRampToValueAtTime(0,s+o/1e3),r.connect(a).connect(i.destination),r.start(s),r.stop(s+o/1e3+.05)};var no,Fo,Gn,Rt,Lg,$u,Uu,Gg,zg,Fg;class SS{constructor(){D(this,Rt);D(this,no,null);D(this,Fo,!1);D(this,Gn,null)}setEnabled(e){O(this,Fo,e),e?($(this,Rt,zg).call(this),$(this,Rt,$u).call(this)):($(this,Rt,Fg).call(this),$(this,Rt,Uu).call(this))}dispose(){this.setEnabled(!1)}}no=new WeakMap,Fo=new WeakMap,Gn=new WeakMap,Rt=new WeakSet,Lg=function(){return typeof navigator<"u"&&"wakeLock"in navigator},$u=async function(){if(!$(this,Rt,Lg).call(this)||g(this,no)!==null)return;const e=g(this,Fo);let n;try{n=await navigator.wakeLock.request("screen")}catch{return}if(!g(this,Fo)||!e||document.visibilityState!=="visible"){try{await n.release()}catch{}return}O(this,no,n),n.addEventListener("release",()=>{O(this,no,null)})},Uu=async function(){const e=g(this,no);if(e!==null){O(this,no,null);try{await e.release()}catch{}}},Gg=function(){g(this,Fo)&&document.visibilityState==="visible"?$(this,Rt,$u).call(this):$(this,Rt,Uu).call(this)},zg=function(){g(this,Gn)===null&&(O(this,Gn,()=>$(this,Rt,Gg).call(this)),document.addEventListener("visibilitychange",g(this,Gn)))},Fg=function(){g(this,Gn)!==null&&(document.removeEventListener("visibilitychange",g(this,Gn)),O(this,Gn,null))};async function Ln(t,e,n){var u;const o=new AbortController;(u=n==null?void 0:n.signal)==null||u.addEventListener("abort",()=>o.abort(),{once:!0});let i,s;const r=new Promise((c,p)=>{i=p});r.catch(()=>{}),s=setTimeout(()=>{o.abort(),i(new Error(`${(n==null?void 0:n.label)??"operation"} timeout ${e}ms`))},e);const a=t(o.signal);a.catch(()=>{});try{return await Promise.race([a,r])}finally{clearTimeout(s)}}const Qr=1e4;async function rp(t,e){const n=await Ln(o=>fetch(An("/api/agents"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:o}),Qr,{signal:e,label:"createAgent"});if(!n.ok){const o=await n.text().catch(()=>"");throw new Error(`createAgent failed: ${n.status} ${o}`)}return await n.json()}async function Vg(t){const e=await Ln(o=>fetch(An("/api/agents"),{signal:o}),Qr,{signal:t,label:"listAgents"});if(!e.ok)throw new Error(`listAgents failed: ${e.status}`);return(await e.json()).agents}async function us(t,e,n){await Ln(o=>fetch(An(`/api/agents/${t}/session-attached`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e,...n!=null&&n.replace?{replace:!0}:{}}),signal:o}),Qr,{label:"notifySessionAttached"})}async function Ou(t){const e=await Ln(n=>fetch(An(`/api/agents/${t}`),{method:"DELETE",signal:n}),Qr,{label:"deleteAgent"});if(!e.ok){const n=await e.text().catch(()=>"");throw new Error(`deleteAgent failed: ${e.status} ${n}`)}}async function CS(t,e){const n=await Ln(o=>fetch(An(`/api/agents/${t}/persistent`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({persistent:e}),signal:o}),Qr,{label:"setAgentPersistent"});if(!n.ok){const o=await n.text().catch(()=>"");throw new Error(`setAgentPersistent failed: ${n.status} ${o}`)}}var Us,Os,Ls;class AS{constructor(){D(this,Us,se(qe([])));D(this,Os,se(!1));D(this,Ls,se(null));Z(this,"refresh",async()=>{this.loading=!0,this.error=null;try{this.agents=await Vg()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}});Z(this,"setPersistent",async(e,n)=>{await CS(e,n),await this.refresh()});Z(this,"kill",async e=>{await Ou(e),await this.refresh()})}get agents(){return Y(g(this,Us))}set agents(e){te(g(this,Us),e,!0)}get loading(){return Y(g(this,Os))}set loading(e){te(g(this,Os),e,!0)}get error(){return Y(g(this,Ls))}set error(e){te(g(this,Ls),e,!0)}}Us=new WeakMap,Os=new WeakMap,Ls=new WeakMap;async function bS(t){const e=await fetch(An("/api/projects"),{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({cwd:t})});if(!e.ok)throw new Error(`remove project failed: ${e.status}`)}async function RS(t){const e=await fetch(An("/api/projects"),{signal:t});if(!e.ok)throw new Error(`projects failed: ${e.status}`);return((await e.json()).projects??[]).map(kS)}function kS(t){const e=t;return{cwd:String(e.cwd??""),kind:String(e.kind??"claude"),lastSeen:String(e.lastSeen??""),lastSessionId:e.lastSessionId?String(e.lastSessionId):void 0}}var Gs,zs,Fs;class PS{constructor(){D(this,Gs,se(qe([])));D(this,zs,se(!1));D(this,Fs,se(null));Z(this,"refresh",async()=>{this.loading=!0,this.error=null;try{this.projects=await RS()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}});Z(this,"remove",async e=>{const n=this.projects;this.projects=this.projects.filter(o=>o.cwd!==e);try{await bS(e)}catch(o){this.error=o instanceof Error?o.message:String(o),this.projects=n}})}get projects(){return Y(g(this,Gs))}set projects(e){te(g(this,Gs),e,!0)}get loading(){return Y(g(this,zs))}set loading(e){te(g(this,zs),e,!0)}get error(){return Y(g(this,Fs))}set error(e){te(g(this,Fs),e,!0)}}Gs=new WeakMap,zs=new WeakMap,Fs=new WeakMap;const ae={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},Re={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},qg=Object.freeze({status:"aborted"});function V(t,e,n){function o(a,u){var c;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(c=a._zod).traits??(c.traits=new Set),a._zod.traits.add(t),e(a,u);for(const p in r.prototype)p in a||Object.defineProperty(a,p,{value:r.prototype[p].bind(a)});a._zod.constr=r,a._zod.def=u}const i=(n==null?void 0:n.Parent)??Object;class s extends i{}Object.defineProperty(s,"name",{value:t});function r(a){var u;const c=n!=null&&n.Parent?new s:this;o(c,a),(u=c._zod).deferred??(u.deferred=[]);for(const p of c._zod.deferred)p();return c}return Object.defineProperty(r,"init",{value:o}),Object.defineProperty(r,Symbol.hasInstance,{value:a=>{var u,c;return n!=null&&n.Parent&&a instanceof n.Parent?!0:(c=(u=a==null?void 0:a._zod)==null?void 0:u.traits)==null?void 0:c.has(t)}}),Object.defineProperty(r,"name",{value:t}),r}let vi=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Bg=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};const Hg={};function To(t){return Hg}function NS(t){const e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,i])=>e.indexOf(+o)===-1).map(([o,i])=>i)}function Lu(t,e){return typeof e=="bigint"?e.toString():e}function Pc(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Nc(t){return t==null}function Mc(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function MS(t,e){const n=(t.toString().split(".")[1]||"").length,o=e.toString();let i=(o.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(o)){const u=o.match(/\d?e-(\d?)/);u!=null&&u[1]&&(i=Number.parseInt(u[1]))}const s=n>i?n:i,r=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return r%a/10**s}const ap=Symbol("evaluating");function Ze(t,e,n){let o;Object.defineProperty(t,e,{get(){if(o!==ap)return o===void 0&&(o=ap,o=n()),o},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function xS(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Ao(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Wi(...t){const e={};for(const n of t){const o=Object.getOwnPropertyDescriptors(n);Object.assign(e,o)}return Object.defineProperties({},e)}function lp(t){return JSON.stringify(t)}const Zg="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function za(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const DS=Pc(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function zi(t){if(za(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(za(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Jg(t){return zi(t)?{...t}:Array.isArray(t)?[...t]:t}const $S=new Set(["string","number","symbol"]);function Fi(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bo(t,e,n){const o=new t._zod.constr(e??t._zod.def);return(!e||n!=null&&n.parent)&&(o._zod.parent=t),o}function le(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function US(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const OS={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function LS(t,e){const n=t._zod.def,o=Wi(t._zod.def,{get shape(){const i={};for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(i[s]=n.shape[s])}return Ao(this,"shape",i),i},checks:[]});return bo(t,o)}function GS(t,e){const n=t._zod.def,o=Wi(t._zod.def,{get shape(){const i={...t._zod.def.shape};for(const s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete i[s]}return Ao(this,"shape",i),i},checks:[]});return bo(t,o)}function zS(t,e){if(!zi(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const i=Wi(t._zod.def,{get shape(){const s={...t._zod.def.shape,...e};return Ao(this,"shape",s),s},checks:[]});return bo(t,i)}function FS(t,e){if(!zi(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...t._zod.def,get shape(){const o={...t._zod.def.shape,...e};return Ao(this,"shape",o),o},checks:t._zod.def.checks};return bo(t,n)}function VS(t,e){const n=Wi(t._zod.def,{get shape(){const o={...t._zod.def.shape,...e._zod.def.shape};return Ao(this,"shape",o),o},get catchall(){return e._zod.def.catchall},checks:[]});return bo(t,n)}function qS(t,e,n){const o=Wi(e._zod.def,{get shape(){const i=e._zod.def.shape,s={...i};if(n)for(const r in n){if(!(r in i))throw new Error(`Unrecognized key: "${r}"`);n[r]&&(s[r]=t?new t({type:"optional",innerType:i[r]}):i[r])}else for(const r in i)s[r]=t?new t({type:"optional",innerType:i[r]}):i[r];return Ao(this,"shape",s),s},checks:[]});return bo(e,o)}function BS(t,e,n){const o=Wi(e._zod.def,{get shape(){const i=e._zod.def.shape,s={...i};if(n)for(const r in n){if(!(r in s))throw new Error(`Unrecognized key: "${r}"`);n[r]&&(s[r]=new t({type:"nonoptional",innerType:i[r]}))}else for(const r in i)s[r]=new t({type:"nonoptional",innerType:i[r]});return Ao(this,"shape",s),s},checks:[]});return bo(e,o)}function pi(t,e=0){var n;if(t.aborted===!0)return!0;for(let o=e;o<t.issues.length;o++)if(((n=t.issues[o])==null?void 0:n.continue)!==!0)return!0;return!1}function fi(t,e){return e.map(n=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(t),n})}function fa(t){return typeof t=="string"?t:t==null?void 0:t.message}function Eo(t,e,n){var i,s,r,a,u,c;const o={...t,path:t.path??[]};if(!t.message){const p=fa((r=(s=(i=t.inst)==null?void 0:i._zod.def)==null?void 0:s.error)==null?void 0:r.call(s,t))??fa((a=e==null?void 0:e.error)==null?void 0:a.call(e,t))??fa((u=n.customError)==null?void 0:u.call(n,t))??fa((c=n.localeError)==null?void 0:c.call(n,t))??"Invalid input";o.message=p}return delete o.inst,delete o.continue,e!=null&&e.reportInput||delete o.input,o}function xc(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ss(...t){const[e,n,o]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:o}:{...e}}const Wg=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Lu,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Kg=V("$ZodError",Wg),Yg=V("$ZodError",Wg,{Parent:Error});function HS(t,e=n=>n.message){const n={},o=[];for(const i of t.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(e(i))):o.push(e(i));return{formErrors:o,fieldErrors:n}}function ZS(t,e){const n=e||function(s){return s.message},o={_errors:[]},i=s=>{for(const r of s.issues)if(r.code==="invalid_union"&&r.errors.length)r.errors.map(a=>i({issues:a}));else if(r.code==="invalid_key")i({issues:r.issues});else if(r.code==="invalid_element")i({issues:r.issues});else if(r.path.length===0)o._errors.push(n(r));else{let a=o,u=0;for(;u<r.path.length;){const c=r.path[u];u===r.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(r))):a[c]=a[c]||{_errors:[]},a=a[c],u++}}};return i(t),o}const Dc=t=>(e,n,o,i)=>{const s=o?Object.assign(o,{async:!1}):{async:!1},r=e._zod.run({value:n,issues:[]},s);if(r instanceof Promise)throw new vi;if(r.issues.length){const a=new((i==null?void 0:i.Err)??t)(r.issues.map(u=>Eo(u,s,To())));throw Zg(a,i==null?void 0:i.callee),a}return r.value},$c=t=>async(e,n,o,i)=>{const s=o?Object.assign(o,{async:!0}):{async:!0};let r=e._zod.run({value:n,issues:[]},s);if(r instanceof Promise&&(r=await r),r.issues.length){const a=new((i==null?void 0:i.Err)??t)(r.issues.map(u=>Eo(u,s,To())));throw Zg(a,i==null?void 0:i.callee),a}return r.value},Sl=t=>(e,n,o)=>{const i=o?{...o,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new vi;return s.issues.length?{success:!1,error:new(t??Kg)(s.issues.map(r=>Eo(r,i,To())))}:{success:!0,data:s.value}},JS=Sl(Yg),Cl=t=>async(e,n,o)=>{const i=o?Object.assign(o,{async:!0}):{async:!0};let s=e._zod.run({value:n,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(r=>Eo(r,i,To())))}:{success:!0,data:s.value}},WS=Cl(Yg),KS=t=>(e,n,o)=>{const i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Dc(t)(e,n,i)},YS=t=>(e,n,o)=>Dc(t)(e,n,o),XS=t=>async(e,n,o)=>{const i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return $c(t)(e,n,i)},QS=t=>async(e,n,o)=>$c(t)(e,n,o),jS=t=>(e,n,o)=>{const i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Sl(t)(e,n,i)},e0=t=>(e,n,o)=>Sl(t)(e,n,o),t0=t=>async(e,n,o)=>{const i=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Cl(t)(e,n,i)},n0=t=>async(e,n,o)=>Cl(t)(e,n,o),o0=/^[cC][^\s-]{8,}$/,i0=/^[0-9a-z]+$/,s0=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,r0=/^[0-9a-vA-V]{20}$/,a0=/^[A-Za-z0-9]{27}$/,l0=/^[a-zA-Z0-9_-]{21}$/,u0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,c0=/^([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})$/,up=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,d0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,p0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function f0(){return new RegExp(p0,"u")}const h0=/^(?:(?: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])$/,m0=/^(([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}|:))$/,g0=/^((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])$/,v0=/^(([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])$/,y0=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Xg=/^[A-Za-z0-9_-]*$/,_0=/^(?=.{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])?)*\.?$/,T0=/^\+(?:[0-9]){6,14}[0-9]$/,Qg="(?:(?:\\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])))",E0=new RegExp(`^${Qg}$`);function jg(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function w0(t){return new RegExp(`^${jg(t)}$`)}function I0(t){const e=jg({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const o=`${e}(?:${n.join("|")})`;return new RegExp(`^${Qg}T(?:${o})$`)}const S0=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},C0=/^-?\d+$/,A0=/^-?\d+(?:\.\d+)?/,b0=/^(?:true|false)$/i,R0=/^[^A-Z]*$/,k0=/^[^a-z]*$/,zt=V("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),ev={number:"number",bigint:"bigint",object:"date"},tv=V("$ZodCheckLessThan",(t,e)=>{zt.init(t,e);const n=ev[typeof e.value];t._zod.onattach.push(o=>{const i=o._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:n,code:"too_big",maximum:e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),nv=V("$ZodCheckGreaterThan",(t,e)=>{zt.init(t,e);const n=ev[typeof e.value];t._zod.onattach.push(o=>{const i=o._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:n,code:"too_small",minimum:e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),P0=V("$ZodCheckMultipleOf",(t,e)=>{zt.init(t,e),t._zod.onattach.push(n=>{var o;(o=n._zod.bag).multipleOf??(o.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):MS(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),N0=V("$ZodCheckNumberFormat",(t,e)=>{var r;zt.init(t,e),e.format=e.format||"float64";const n=(r=e.format)==null?void 0:r.includes("int"),o=n?"int":"number",[i,s]=OS[e.format];t._zod.onattach.push(a=>{const u=a._zod.bag;u.format=e.format,u.minimum=i,u.maximum=s,n&&(u.pattern=C0)}),t._zod.check=a=>{const u=a.value;if(n){if(!Number.isInteger(u)){a.issues.push({expected:o,format:e.format,code:"invalid_type",continue:!1,input:u,inst:t});return}if(!Number.isSafeInteger(u)){u>0?a.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,continue:!e.abort}):a.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,continue:!e.abort});return}}u<i&&a.issues.push({origin:"number",input:u,code:"too_small",minimum:i,inclusive:!0,inst:t,continue:!e.abort}),u>s&&a.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inst:t})}}),M0=V("$ZodCheckMaxLength",(t,e)=>{var n;zt.init(t,e),(n=t._zod.def).when??(n.when=o=>{const i=o.value;return!Nc(i)&&i.length!==void 0}),t._zod.onattach.push(o=>{const i=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(o._zod.bag.maximum=e.maximum)}),t._zod.check=o=>{const i=o.value;if(i.length<=e.maximum)return;const r=xc(i);o.issues.push({origin:r,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),x0=V("$ZodCheckMinLength",(t,e)=>{var n;zt.init(t,e),(n=t._zod.def).when??(n.when=o=>{const i=o.value;return!Nc(i)&&i.length!==void 0}),t._zod.onattach.push(o=>{const i=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{const i=o.value;if(i.length>=e.minimum)return;const r=xc(i);o.issues.push({origin:r,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),D0=V("$ZodCheckLengthEquals",(t,e)=>{var n;zt.init(t,e),(n=t._zod.def).when??(n.when=o=>{const i=o.value;return!Nc(i)&&i.length!==void 0}),t._zod.onattach.push(o=>{const i=o._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=o=>{const i=o.value,s=i.length;if(s===e.length)return;const r=xc(i),a=s>e.length;o.issues.push({origin:r,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),Al=V("$ZodCheckStringFormat",(t,e)=>{var n,o;zt.init(t,e),t._zod.onattach.push(i=>{const s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),$0=V("$ZodCheckRegex",(t,e)=>{Al.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),U0=V("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=R0),Al.init(t,e)}),O0=V("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=k0),Al.init(t,e)}),L0=V("$ZodCheckIncludes",(t,e)=>{zt.init(t,e);const n=Fi(e.includes),o=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=o,t._zod.onattach.push(i=>{const s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),G0=V("$ZodCheckStartsWith",(t,e)=>{zt.init(t,e);const n=new RegExp(`^${Fi(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=o=>{o.value.startsWith(e.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:o.value,inst:t,continue:!e.abort})}}),z0=V("$ZodCheckEndsWith",(t,e)=>{zt.init(t,e);const n=new RegExp(`.*${Fi(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=o=>{o.value.endsWith(e.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:o.value,inst:t,continue:!e.abort})}}),F0=V("$ZodCheckOverwrite",(t,e)=>{zt.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});let V0=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const o=e.split(`
2
+ `).filter(r=>r),i=Math.min(...o.map(r=>r.length-r.trimStart().length)),s=o.map(r=>r.slice(i)).map(r=>" ".repeat(this.indent*2)+r);for(const r of s)this.content.push(r)}compile(){const e=Function,n=this==null?void 0:this.args,i=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new e(...n,i.join(`
3
+ `))}};const q0={major:4,minor:1,patch:8},ot=V("$ZodType",(t,e)=>{var i;var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=q0;const o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(const s of o)for(const r of s._zod.onattach)r(t);if(o.length===0)(n=t._zod).deferred??(n.deferred=[]),(i=t._zod.deferred)==null||i.push(()=>{t._zod.run=t._zod.parse});else{const s=(a,u,c)=>{let p=pi(a),f;for(const h of u){if(h._zod.def.when){if(!h._zod.def.when(a))continue}else if(p)continue;const m=a.issues.length,v=h._zod.check(a);if(v instanceof Promise&&(c==null?void 0:c.async)===!1)throw new vi;if(f||v instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await v,a.issues.length!==m&&(p||(p=pi(a,m)))});else{if(a.issues.length===m)continue;p||(p=pi(a,m))}}return f?f.then(()=>a):a},r=(a,u,c)=>{if(pi(a))return a.aborted=!0,a;const p=s(u,o,c);if(p instanceof Promise){if(c.async===!1)throw new vi;return p.then(f=>t._zod.parse(f,c))}return t._zod.parse(p,c)};t._zod.run=(a,u)=>{if(u.skipChecks)return t._zod.parse(a,u);if(u.direction==="backward"){const p=t._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});return p instanceof Promise?p.then(f=>r(f,a,u)):r(p,a,u)}const c=t._zod.parse(a,u);if(c instanceof Promise){if(u.async===!1)throw new vi;return c.then(p=>s(p,o,u))}return s(c,o,u)}}t["~standard"]={validate:s=>{var r;try{const a=JS(t,s);return a.success?{value:a.data}:{issues:(r=a.error)==null?void 0:r.issues}}catch{return WS(t,s).then(u=>{var c;return u.success?{value:u.data}:{issues:(c=u.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),Uc=V("$ZodString",(t,e)=>{var n;ot.init(t,e),t._zod.pattern=[...((n=t==null?void 0:t._zod.bag)==null?void 0:n.patterns)??[]].pop()??S0(t._zod.bag),t._zod.parse=(o,i)=>{if(e.coerce)try{o.value=String(o.value)}catch{}return typeof o.value=="string"||o.issues.push({expected:"string",code:"invalid_type",input:o.value,inst:t}),o}}),je=V("$ZodStringFormat",(t,e)=>{Al.init(t,e),Uc.init(t,e)}),B0=V("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=c0),je.init(t,e)}),H0=V("$ZodUUID",(t,e)=>{if(e.version){const o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(o===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=up(o))}else e.pattern??(e.pattern=up());je.init(t,e)}),Z0=V("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=d0),je.init(t,e)}),J0=V("$ZodURL",(t,e)=>{je.init(t,e),t._zod.check=n=>{try{const o=n.value.trim(),i=new URL(o);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_0.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=i.href:n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),W0=V("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=f0()),je.init(t,e)}),K0=V("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=l0),je.init(t,e)}),Y0=V("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=o0),je.init(t,e)}),X0=V("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=i0),je.init(t,e)}),Q0=V("$ZodULID",(t,e)=>{e.pattern??(e.pattern=s0),je.init(t,e)}),j0=V("$ZodXID",(t,e)=>{e.pattern??(e.pattern=r0),je.init(t,e)}),eC=V("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=a0),je.init(t,e)}),tC=V("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=I0(e)),je.init(t,e)}),nC=V("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=E0),je.init(t,e)}),oC=V("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=w0(e)),je.init(t,e)}),iC=V("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=u0),je.init(t,e)}),sC=V("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=h0),je.init(t,e),t._zod.onattach.push(n=>{const o=n._zod.bag;o.format="ipv4"})}),rC=V("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=m0),je.init(t,e),t._zod.onattach.push(n=>{const o=n._zod.bag;o.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),aC=V("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=g0),je.init(t,e)}),lC=V("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=v0),je.init(t,e),t._zod.check=n=>{const o=n.value.split("/");try{if(o.length!==2)throw new Error;const[i,s]=o;if(!s)throw new Error;const r=Number(s);if(`${r}`!==s)throw new Error;if(r<0||r>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function ov(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const uC=V("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=y0),je.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{ov(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function cC(t){if(!Xg.test(t))return!1;const e=t.replace(/[-_]/g,o=>o==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return ov(n)}const dC=V("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Xg),je.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{cC(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),pC=V("$ZodE164",(t,e)=>{e.pattern??(e.pattern=T0),je.init(t,e)});function fC(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[o]=n;if(!o)return!1;const i=JSON.parse(atob(o));return!("typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}const hC=V("$ZodJWT",(t,e)=>{je.init(t,e),t._zod.check=n=>{fC(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),iv=V("$ZodNumber",(t,e)=>{ot.init(t,e),t._zod.pattern=t._zod.bag.pattern??A0,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...s?{received:s}:{}}),n}}),mC=V("$ZodNumber",(t,e)=>{N0.init(t,e),iv.init(t,e)}),gC=V("$ZodBoolean",(t,e)=>{ot.init(t,e),t._zod.pattern=b0,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),n}}),vC=V("$ZodUnknown",(t,e)=>{ot.init(t,e),t._zod.parse=n=>n}),yC=V("$ZodNever",(t,e)=>{ot.init(t,e),t._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function cp(t,e,n){t.issues.length&&e.issues.push(...fi(n,t.issues)),e.value[n]=t.value}const _C=V("$ZodArray",(t,e)=>{ot.init(t,e),t._zod.parse=(n,o)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),n;n.value=Array(i.length);const s=[];for(let r=0;r<i.length;r++){const a=i[r],u=e.element._zod.run({value:a,issues:[]},o);u instanceof Promise?s.push(u.then(c=>cp(c,n,r))):cp(u,n,r)}return s.length?Promise.all(s).then(()=>n):n}});function Fa(t,e,n,o){t.issues.length&&e.issues.push(...fi(n,t.issues)),t.value===void 0?n in o&&(e.value[n]=void 0):e.value[n]=t.value}function sv(t){var o,i,s,r;const e=Object.keys(t.shape);for(const a of e)if(!((r=(s=(i=(o=t.shape)==null?void 0:o[a])==null?void 0:i._zod)==null?void 0:s.traits)!=null&&r.has("$ZodType")))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const n=US(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function rv(t,e,n,o,i,s){const r=[],a=i.keySet,u=i.catchall._zod,c=u.def.type;for(const p of Object.keys(e)){if(a.has(p))continue;if(c==="never"){r.push(p);continue}const f=u.run({value:e[p],issues:[]},o);f instanceof Promise?t.push(f.then(h=>Fa(h,n,p,e))):Fa(f,n,p,e)}return r.length&&n.issues.push({code:"unrecognized_keys",keys:r,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}const TC=V("$ZodObject",(t,e)=>{ot.init(t,e);const n=Pc(()=>sv(e));Ze(t._zod,"propValues",()=>{const r=e.shape,a={};for(const u in r){const c=r[u]._zod;if(c.values){a[u]??(a[u]=new Set);for(const p of c.values)a[u].add(p)}}return a});const o=za,i=e.catchall;let s;t._zod.parse=(r,a)=>{s??(s=n.value);const u=r.value;if(!o(u))return r.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),r;r.value={};const c=[],p=s.shape;for(const f of s.keys){const m=p[f]._zod.run({value:u[f],issues:[]},a);m instanceof Promise?c.push(m.then(v=>Fa(v,r,f,u))):Fa(m,r,f,u)}return i?rv(c,u,r,a,n.value,t):c.length?Promise.all(c).then(()=>r):r}}),EC=V("$ZodObjectJIT",(t,e)=>{TC.init(t,e);const n=t._zod.parse,o=Pc(()=>sv(e)),i=h=>{const m=new V0(["shape","payload","ctx"]),v=o.value,_=A=>{const R=lp(A);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};m.write("const input = payload.value;");const w=Object.create(null);let C=0;for(const A of v.keys)w[A]=`key_${C++}`;m.write("const newResult = {};");for(const A of v.keys){const R=w[A],k=lp(A);m.write(`const ${R} = ${_(A)};`),m.write(`
4
+ if (${R}.issues.length) {
5
+ payload.issues = payload.issues.concat(${R}.issues.map(iss => ({
6
+ ...iss,
7
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
8
+ })));
9
+ }
10
+
11
+
12
+ if (${R}.value === undefined) {
13
+ if (${k} in input) {
14
+ newResult[${k}] = undefined;
15
+ }
16
+ } else {
17
+ newResult[${k}] = ${R}.value;
18
+ }
19
+
20
+ `)}m.write("payload.value = newResult;"),m.write("return payload;");const E=m.compile();return(A,R)=>E(h,A,R)};let s;const r=za,a=!Hg.jitless,c=a&&DS.value,p=e.catchall;let f;t._zod.parse=(h,m)=>{f??(f=o.value);const v=h.value;return r(v)?a&&c&&(m==null?void 0:m.async)===!1&&m.jitless!==!0?(s||(s=i(e.shape)),h=s(h,m),p?rv([],v,h,m,f,t):h):n(h,m):(h.issues.push({expected:"object",code:"invalid_type",input:v,inst:t}),h)}});function dp(t,e,n,o){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;const i=t.filter(s=>!pi(s));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(r=>Eo(r,o,To())))}),e)}const wC=V("$ZodUnion",(t,e)=>{ot.init(t,e),Ze(t._zod,"optin",()=>e.options.some(i=>i._zod.optin==="optional")?"optional":void 0),Ze(t._zod,"optout",()=>e.options.some(i=>i._zod.optout==="optional")?"optional":void 0),Ze(t._zod,"values",()=>{if(e.options.every(i=>i._zod.values))return new Set(e.options.flatMap(i=>Array.from(i._zod.values)))}),Ze(t._zod,"pattern",()=>{if(e.options.every(i=>i._zod.pattern)){const i=e.options.map(s=>s._zod.pattern);return new RegExp(`^(${i.map(s=>Mc(s.source)).join("|")})$`)}});const n=e.options.length===1,o=e.options[0]._zod.run;t._zod.parse=(i,s)=>{if(n)return o(i,s);let r=!1;const a=[];for(const u of e.options){const c=u._zod.run({value:i.value,issues:[]},s);if(c instanceof Promise)a.push(c),r=!0;else{if(c.issues.length===0)return c;a.push(c)}}return r?Promise.all(a).then(u=>dp(u,i,t,s)):dp(a,i,t,s)}}),IC=V("$ZodIntersection",(t,e)=>{ot.init(t,e),t._zod.parse=(n,o)=>{const i=n.value,s=e.left._zod.run({value:i,issues:[]},o),r=e.right._zod.run({value:i,issues:[]},o);return s instanceof Promise||r instanceof Promise?Promise.all([s,r]).then(([u,c])=>pp(n,u,c)):pp(n,s,r)}});function Gu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(zi(t)&&zi(e)){const n=Object.keys(e),o=Object.keys(t).filter(s=>n.indexOf(s)!==-1),i={...t,...e};for(const s of o){const r=Gu(t[s],e[s]);if(!r.valid)return{valid:!1,mergeErrorPath:[s,...r.mergeErrorPath]};i[s]=r.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let o=0;o<t.length;o++){const i=t[o],s=e[o],r=Gu(i,s);if(!r.valid)return{valid:!1,mergeErrorPath:[o,...r.mergeErrorPath]};n.push(r.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function pp(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),pi(t))return t;const o=Gu(e.value,n.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return t.value=o.data,t}const SC=V("$ZodRecord",(t,e)=>{ot.init(t,e),t._zod.parse=(n,o)=>{const i=n.value;if(!zi(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),n;const s=[];if(e.keyType._zod.values){const r=e.keyType._zod.values;n.value={};for(const u of r)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){const c=e.valueType._zod.run({value:i[u],issues:[]},o);c instanceof Promise?s.push(c.then(p=>{p.issues.length&&n.issues.push(...fi(u,p.issues)),n.value[u]=p.value})):(c.issues.length&&n.issues.push(...fi(u,c.issues)),n.value[u]=c.value)}let a;for(const u in i)r.has(u)||(a=a??[],a.push(u));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:a})}else{n.value={};for(const r of Reflect.ownKeys(i)){if(r==="__proto__")continue;const a=e.keyType._zod.run({value:r,issues:[]},o);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(c=>Eo(c,o,To())),input:r,path:[r],inst:t}),n.value[a.value]=a.value;continue}const u=e.valueType._zod.run({value:i[r],issues:[]},o);u instanceof Promise?s.push(u.then(c=>{c.issues.length&&n.issues.push(...fi(r,c.issues)),n.value[a.value]=c.value})):(u.issues.length&&n.issues.push(...fi(r,u.issues)),n.value[a.value]=u.value)}}return s.length?Promise.all(s).then(()=>n):n}}),CC=V("$ZodEnum",(t,e)=>{ot.init(t,e);const n=NS(e.entries),o=new Set(n);t._zod.values=o,t._zod.pattern=new RegExp(`^(${n.filter(i=>$S.has(typeof i)).map(i=>typeof i=="string"?Fi(i):i.toString()).join("|")})$`),t._zod.parse=(i,s)=>{const r=i.value;return o.has(r)||i.issues.push({code:"invalid_value",values:n,input:r,inst:t}),i}}),AC=V("$ZodLiteral",(t,e)=>{if(ot.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Fi(n):n?Fi(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{const i=n.value;return t._zod.values.has(i)||n.issues.push({code:"invalid_value",values:e.values,input:i,inst:t}),n}}),bC=V("$ZodTransform",(t,e)=>{ot.init(t,e),t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Bg(t.constructor.name);const i=e.transform(n.value,n);if(o.async)return(i instanceof Promise?i:Promise.resolve(i)).then(r=>(n.value=r,n));if(i instanceof Promise)throw new vi;return n.value=i,n}});function fp(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}const RC=V("$ZodOptional",(t,e)=>{ot.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ze(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ze(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Mc(n.source)})?$`):void 0}),t._zod.parse=(n,o)=>{if(e.innerType._zod.optin==="optional"){const i=e.innerType._zod.run(n,o);return i instanceof Promise?i.then(s=>fp(s,n.value)):fp(i,n.value)}return n.value===void 0?n:e.innerType._zod.run(n,o)}}),kC=V("$ZodNullable",(t,e)=>{ot.init(t,e),Ze(t._zod,"optin",()=>e.innerType._zod.optin),Ze(t._zod,"optout",()=>e.innerType._zod.optout),Ze(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Mc(n.source)}|null)$`):void 0}),Ze(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,o)=>n.value===null?n:e.innerType._zod.run(n,o)}),PC=V("$ZodDefault",(t,e)=>{ot.init(t,e),t._zod.optin="optional",Ze(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);if(n.value===void 0)return n.value=e.defaultValue,n;const i=e.innerType._zod.run(n,o);return i instanceof Promise?i.then(s=>hp(s,e)):hp(i,e)}});function hp(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const NC=V("$ZodPrefault",(t,e)=>{ot.init(t,e),t._zod.optin="optional",Ze(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>(o.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,o))}),MC=V("$ZodNonOptional",(t,e)=>{ot.init(t,e),Ze(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(o=>o!==void 0)):void 0}),t._zod.parse=(n,o)=>{const i=e.innerType._zod.run(n,o);return i instanceof Promise?i.then(s=>mp(s,t)):mp(i,t)}});function mp(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const xC=V("$ZodCatch",(t,e)=>{ot.init(t,e),Ze(t._zod,"optin",()=>e.innerType._zod.optin),Ze(t._zod,"optout",()=>e.innerType._zod.optout),Ze(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);const i=e.innerType._zod.run(n,o);return i instanceof Promise?i.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(r=>Eo(r,o,To()))},input:n.value}),n.issues=[]),n)):(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(s=>Eo(s,o,To()))},input:n.value}),n.issues=[]),n)}}),DC=V("$ZodPipe",(t,e)=>{ot.init(t,e),Ze(t._zod,"values",()=>e.in._zod.values),Ze(t._zod,"optin",()=>e.in._zod.optin),Ze(t._zod,"optout",()=>e.out._zod.optout),Ze(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,o)=>{if(o.direction==="backward"){const s=e.out._zod.run(n,o);return s instanceof Promise?s.then(r=>ha(r,e.in,o)):ha(s,e.in,o)}const i=e.in._zod.run(n,o);return i instanceof Promise?i.then(s=>ha(s,e.out,o)):ha(i,e.out,o)}});function ha(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},n)}const $C=V("$ZodReadonly",(t,e)=>{ot.init(t,e),Ze(t._zod,"propValues",()=>e.innerType._zod.propValues),Ze(t._zod,"values",()=>e.innerType._zod.values),Ze(t._zod,"optin",()=>e.innerType._zod.optin),Ze(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);const i=e.innerType._zod.run(n,o);return i instanceof Promise?i.then(gp):gp(i)}});function gp(t){return t.value=Object.freeze(t.value),t}const UC=V("$ZodCustom",(t,e)=>{zt.init(t,e),ot.init(t,e),t._zod.parse=(n,o)=>n,t._zod.check=n=>{const o=n.value,i=e.fn(o);if(i instanceof Promise)return i.then(s=>vp(s,n,o,t));vp(i,n,o,t)}});function vp(t,e,n,o){if(!t){const i={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(i.params=o._zod.def.params),e.issues.push(Ss(i))}}let OC=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){const o=n[0];if(this._map.set(e,o),o&&typeof o=="object"&&"id"in o){if(this._idmap.has(o.id))throw new Error(`ID ${o.id} already exists in the registry`);this._idmap.set(o.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const o={...this.get(n)??{}};delete o.id;const i={...o,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function LC(){return new OC}const ma=LC();function GC(t,e){return new t({type:"string",...le(e)})}function zC(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...le(e)})}function yp(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...le(e)})}function FC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...le(e)})}function VC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...le(e)})}function qC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...le(e)})}function BC(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...le(e)})}function av(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...le(e)})}function HC(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...le(e)})}function ZC(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...le(e)})}function JC(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...le(e)})}function WC(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...le(e)})}function KC(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...le(e)})}function YC(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...le(e)})}function XC(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...le(e)})}function QC(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...le(e)})}function jC(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...le(e)})}function eA(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...le(e)})}function tA(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...le(e)})}function nA(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...le(e)})}function oA(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...le(e)})}function iA(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...le(e)})}function sA(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...le(e)})}function rA(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...le(e)})}function aA(t,e){return new t({type:"string",format:"date",check:"string_format",...le(e)})}function lA(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...le(e)})}function uA(t,e){return new t({type:"string",format:"duration",check:"string_format",...le(e)})}function cA(t,e){return new t({type:"number",checks:[],...le(e)})}function dA(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...le(e)})}function pA(t,e){return new t({type:"boolean",...le(e)})}function fA(t){return new t({type:"unknown"})}function hA(t,e){return new t({type:"never",...le(e)})}function _p(t,e){return new tv({check:"less_than",...le(e),value:t,inclusive:!1})}function su(t,e){return new tv({check:"less_than",...le(e),value:t,inclusive:!0})}function Tp(t,e){return new nv({check:"greater_than",...le(e),value:t,inclusive:!1})}function ru(t,e){return new nv({check:"greater_than",...le(e),value:t,inclusive:!0})}function Ep(t,e){return new P0({check:"multiple_of",...le(e),value:t})}function lv(t,e){return new M0({check:"max_length",...le(e),maximum:t})}function Va(t,e){return new x0({check:"min_length",...le(e),minimum:t})}function uv(t,e){return new D0({check:"length_equals",...le(e),length:t})}function mA(t,e){return new $0({check:"string_format",format:"regex",...le(e),pattern:t})}function gA(t){return new U0({check:"string_format",format:"lowercase",...le(t)})}function vA(t){return new O0({check:"string_format",format:"uppercase",...le(t)})}function yA(t,e){return new L0({check:"string_format",format:"includes",...le(e),includes:t})}function _A(t,e){return new G0({check:"string_format",format:"starts_with",...le(e),prefix:t})}function TA(t,e){return new z0({check:"string_format",format:"ends_with",...le(e),suffix:t})}function jr(t){return new F0({check:"overwrite",tx:t})}function EA(t){return jr(e=>e.normalize(t))}function wA(){return jr(t=>t.trim())}function IA(){return jr(t=>t.toLowerCase())}function SA(){return jr(t=>t.toUpperCase())}function CA(t,e,n){return new t({type:"array",element:e,...le(n)})}function AA(t,e,n){return new t({type:"custom",check:"custom",fn:e,...le(n)})}function bA(t){const e=RA(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(Ss(o,n.value,e._zod.def));else{const i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!e._zod.def.abort),n.issues.push(Ss(i))}},t(n.value,n)));return e}function RA(t,e){const n=new zt({check:"custom",...le(e)});return n._zod.check=t,n}const kA=V("ZodISODateTime",(t,e)=>{tC.init(t,e),it.init(t,e)});function PA(t){return rA(kA,t)}const NA=V("ZodISODate",(t,e)=>{nC.init(t,e),it.init(t,e)});function MA(t){return aA(NA,t)}const xA=V("ZodISOTime",(t,e)=>{oC.init(t,e),it.init(t,e)});function DA(t){return lA(xA,t)}const $A=V("ZodISODuration",(t,e)=>{iC.init(t,e),it.init(t,e)});function UA(t){return uA($A,t)}const OA=(t,e)=>{Kg.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ZS(t,n)},flatten:{value:n=>HS(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Lu,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Lu,2)}},isEmpty:{get(){return t.issues.length===0}}})},pn=V("ZodError",OA,{Parent:Error}),LA=Dc(pn),GA=$c(pn),zA=Sl(pn),FA=Cl(pn),VA=KS(pn),qA=YS(pn),BA=XS(pn),HA=QS(pn),ZA=jS(pn),JA=e0(pn),WA=t0(pn),KA=n0(pn),lt=V("ZodType",(t,e)=>(ot.init(t,e),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),t.clone=(n,o)=>bo(t,n,o),t.brand=()=>t,t.register=((n,o)=>(n.add(t,o),t)),t.parse=(n,o)=>LA(t,n,o,{callee:t.parse}),t.safeParse=(n,o)=>zA(t,n,o),t.parseAsync=async(n,o)=>GA(t,n,o,{callee:t.parseAsync}),t.safeParseAsync=async(n,o)=>FA(t,n,o),t.spa=t.safeParseAsync,t.encode=(n,o)=>VA(t,n,o),t.decode=(n,o)=>qA(t,n,o),t.encodeAsync=async(n,o)=>BA(t,n,o),t.decodeAsync=async(n,o)=>HA(t,n,o),t.safeEncode=(n,o)=>ZA(t,n,o),t.safeDecode=(n,o)=>JA(t,n,o),t.safeEncodeAsync=async(n,o)=>WA(t,n,o),t.safeDecodeAsync=async(n,o)=>KA(t,n,o),t.refine=(n,o)=>t.check(zb(n,o)),t.superRefine=n=>t.check(Fb(n)),t.overwrite=n=>t.check(jr(n)),t.optional=()=>Ip(t),t.nullable=()=>Sp(t),t.nullish=()=>Ip(Sp(t)),t.nonoptional=n=>xb(t,n),t.array=()=>Be(t),t.or=n=>fe([t,n]),t.and=n=>wo(t,n),t.transform=n=>Cp(t,bb(n)),t.default=n=>Pb(t,n),t.prefault=n=>Mb(t,n),t.catch=n=>$b(t,n),t.pipe=n=>Cp(t,n),t.readonly=()=>Lb(t),t.describe=n=>{const o=t.clone();return ma.add(o,{description:n}),o},Object.defineProperty(t,"description",{get(){var n;return(n=ma.get(t))==null?void 0:n.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return ma.get(t);const o=t.clone();return ma.add(o,n[0]),o},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),cv=V("_ZodString",(t,e)=>{Uc.init(t,e),lt.init(t,e);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...o)=>t.check(mA(...o)),t.includes=(...o)=>t.check(yA(...o)),t.startsWith=(...o)=>t.check(_A(...o)),t.endsWith=(...o)=>t.check(TA(...o)),t.min=(...o)=>t.check(Va(...o)),t.max=(...o)=>t.check(lv(...o)),t.length=(...o)=>t.check(uv(...o)),t.nonempty=(...o)=>t.check(Va(1,...o)),t.lowercase=o=>t.check(gA(o)),t.uppercase=o=>t.check(vA(o)),t.trim=()=>t.check(wA()),t.normalize=(...o)=>t.check(EA(...o)),t.toLowerCase=()=>t.check(IA()),t.toUpperCase=()=>t.check(SA())}),YA=V("ZodString",(t,e)=>{Uc.init(t,e),cv.init(t,e),t.email=n=>t.check(zC(XA,n)),t.url=n=>t.check(av(dv,n)),t.jwt=n=>t.check(sA(fb,n)),t.emoji=n=>t.check(HC(jA,n)),t.guid=n=>t.check(yp(wp,n)),t.uuid=n=>t.check(FC(ga,n)),t.uuidv4=n=>t.check(VC(ga,n)),t.uuidv6=n=>t.check(qC(ga,n)),t.uuidv7=n=>t.check(BC(ga,n)),t.nanoid=n=>t.check(ZC(eb,n)),t.guid=n=>t.check(yp(wp,n)),t.cuid=n=>t.check(JC(tb,n)),t.cuid2=n=>t.check(WC(nb,n)),t.ulid=n=>t.check(KC(ob,n)),t.base64=n=>t.check(nA(cb,n)),t.base64url=n=>t.check(oA(db,n)),t.xid=n=>t.check(YC(ib,n)),t.ksuid=n=>t.check(XC(sb,n)),t.ipv4=n=>t.check(QC(rb,n)),t.ipv6=n=>t.check(jC(ab,n)),t.cidrv4=n=>t.check(eA(lb,n)),t.cidrv6=n=>t.check(tA(ub,n)),t.e164=n=>t.check(iA(pb,n)),t.datetime=n=>t.check(PA(n)),t.date=n=>t.check(MA(n)),t.time=n=>t.check(DA(n)),t.duration=n=>t.check(UA(n))});function y(t){return GC(YA,t)}const it=V("ZodStringFormat",(t,e)=>{je.init(t,e),cv.init(t,e)}),XA=V("ZodEmail",(t,e)=>{Z0.init(t,e),it.init(t,e)}),wp=V("ZodGUID",(t,e)=>{B0.init(t,e),it.init(t,e)}),ga=V("ZodUUID",(t,e)=>{H0.init(t,e),it.init(t,e)}),dv=V("ZodURL",(t,e)=>{J0.init(t,e),it.init(t,e)});function QA(t){return av(dv,t)}const jA=V("ZodEmoji",(t,e)=>{W0.init(t,e),it.init(t,e)}),eb=V("ZodNanoID",(t,e)=>{K0.init(t,e),it.init(t,e)}),tb=V("ZodCUID",(t,e)=>{Y0.init(t,e),it.init(t,e)}),nb=V("ZodCUID2",(t,e)=>{X0.init(t,e),it.init(t,e)}),ob=V("ZodULID",(t,e)=>{Q0.init(t,e),it.init(t,e)}),ib=V("ZodXID",(t,e)=>{j0.init(t,e),it.init(t,e)}),sb=V("ZodKSUID",(t,e)=>{eC.init(t,e),it.init(t,e)}),rb=V("ZodIPv4",(t,e)=>{sC.init(t,e),it.init(t,e)}),ab=V("ZodIPv6",(t,e)=>{rC.init(t,e),it.init(t,e)}),lb=V("ZodCIDRv4",(t,e)=>{aC.init(t,e),it.init(t,e)}),ub=V("ZodCIDRv6",(t,e)=>{lC.init(t,e),it.init(t,e)}),cb=V("ZodBase64",(t,e)=>{uC.init(t,e),it.init(t,e)}),db=V("ZodBase64URL",(t,e)=>{dC.init(t,e),it.init(t,e)}),pb=V("ZodE164",(t,e)=>{pC.init(t,e),it.init(t,e)}),fb=V("ZodJWT",(t,e)=>{hC.init(t,e),it.init(t,e)}),pv=V("ZodNumber",(t,e)=>{iv.init(t,e),lt.init(t,e),t.gt=(o,i)=>t.check(Tp(o,i)),t.gte=(o,i)=>t.check(ru(o,i)),t.min=(o,i)=>t.check(ru(o,i)),t.lt=(o,i)=>t.check(_p(o,i)),t.lte=(o,i)=>t.check(su(o,i)),t.max=(o,i)=>t.check(su(o,i)),t.int=o=>t.check(Tt(o)),t.safe=o=>t.check(Tt(o)),t.positive=o=>t.check(Tp(0,o)),t.nonnegative=o=>t.check(ru(0,o)),t.negative=o=>t.check(_p(0,o)),t.nonpositive=o=>t.check(su(0,o)),t.multipleOf=(o,i)=>t.check(Ep(o,i)),t.step=(o,i)=>t.check(Ep(o,i)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function Ge(t){return cA(pv,t)}const hb=V("ZodNumberFormat",(t,e)=>{mC.init(t,e),pv.init(t,e)});function Tt(t){return dA(hb,t)}const mb=V("ZodBoolean",(t,e)=>{gC.init(t,e),lt.init(t,e)});function mt(t){return pA(mb,t)}const gb=V("ZodUnknown",(t,e)=>{vC.init(t,e),lt.init(t,e)});function P(){return fA(gb)}const vb=V("ZodNever",(t,e)=>{yC.init(t,e),lt.init(t,e)});function yb(t){return hA(vb,t)}const _b=V("ZodArray",(t,e)=>{_C.init(t,e),lt.init(t,e),t.element=e.element,t.min=(n,o)=>t.check(Va(n,o)),t.nonempty=n=>t.check(Va(1,n)),t.max=(n,o)=>t.check(lv(n,o)),t.length=(n,o)=>t.check(uv(n,o)),t.unwrap=()=>t.element});function Be(t,e){return CA(_b,t,e)}const Tb=V("ZodObject",(t,e)=>{EC.init(t,e),lt.init(t,e),Ze(t,"shape",()=>e.shape),t.keyof=()=>Sb(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:P()}),t.loose=()=>t.clone({...t._zod.def,catchall:P()}),t.strict=()=>t.clone({...t._zod.def,catchall:yb()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>zS(t,n),t.safeExtend=n=>FS(t,n),t.merge=n=>VS(t,n),t.pick=n=>LS(t,n),t.omit=n=>GS(t,n),t.partial=(...n)=>qS(fv,t,n[0]),t.required=(...n)=>BS(hv,t,n[0])});function S(t,e){const n={type:"object",get shape(){return Ao(this,"shape",t?xS(t):{}),this.shape},...le(e)};return new Tb(n)}const Eb=V("ZodUnion",(t,e)=>{wC.init(t,e),lt.init(t,e),t.options=e.options});function fe(t,e){return new Eb({type:"union",options:t,...le(e)})}const wb=V("ZodIntersection",(t,e)=>{IC.init(t,e),lt.init(t,e)});function wo(t,e){return new wb({type:"intersection",left:t,right:e})}const Ib=V("ZodRecord",(t,e)=>{SC.init(t,e),lt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function N(t,e,n){return new Ib({type:"record",keyType:t,valueType:e,...le(n)})}const zu=V("ZodEnum",(t,e)=>{CC.init(t,e),lt.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(o,i)=>{const s={};for(const r of o)if(n.has(r))s[r]=e.entries[r];else throw new Error(`Key ${r} not found in enum`);return new zu({...e,checks:[],...le(i),entries:s})},t.exclude=(o,i)=>{const s={...e.entries};for(const r of o)if(n.has(r))delete s[r];else throw new Error(`Key ${r} not found in enum`);return new zu({...e,checks:[],...le(i),entries:s})}});function Sb(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new zu({type:"enum",entries:n,...le(e)})}const Cb=V("ZodLiteral",(t,e)=>{AC.init(t,e),lt.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function z(t,e){return new Cb({type:"literal",values:Array.isArray(t)?t:[t],...le(e)})}const Ab=V("ZodTransform",(t,e)=>{bC.init(t,e),lt.init(t,e),t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new Bg(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Ss(s,n.value,e));else{const r=s;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),n.issues.push(Ss(r))}};const i=e.transform(n.value,n);return i instanceof Promise?i.then(s=>(n.value=s,n)):(n.value=i,n)}});function bb(t){return new Ab({type:"transform",transform:t})}const fv=V("ZodOptional",(t,e)=>{RC.init(t,e),lt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ip(t){return new fv({type:"optional",innerType:t})}const Rb=V("ZodNullable",(t,e)=>{kC.init(t,e),lt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Sp(t){return new Rb({type:"nullable",innerType:t})}const kb=V("ZodDefault",(t,e)=>{PC.init(t,e),lt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Pb(t,e){return new kb({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Jg(e)}})}const Nb=V("ZodPrefault",(t,e)=>{NC.init(t,e),lt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Mb(t,e){return new Nb({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Jg(e)}})}const hv=V("ZodNonOptional",(t,e)=>{MC.init(t,e),lt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xb(t,e){return new hv({type:"nonoptional",innerType:t,...le(e)})}const Db=V("ZodCatch",(t,e)=>{xC.init(t,e),lt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function $b(t,e){return new Db({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const Ub=V("ZodPipe",(t,e)=>{DC.init(t,e),lt.init(t,e),t.in=e.in,t.out=e.out});function Cp(t,e){return new Ub({type:"pipe",in:t,out:e})}const Ob=V("ZodReadonly",(t,e)=>{$C.init(t,e),lt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Lb(t){return new Ob({type:"readonly",innerType:t})}const Gb=V("ZodCustom",(t,e)=>{UC.init(t,e),lt.init(t,e)});function zb(t,e={}){return AA(Gb,t,e)}function Fb(t){return bA(t)}const Ap=Symbol("skippedItem");function T(t,e){return t.catch(e)}function Xt(t,e){const n=t.catch(e);return P().transform((o,i)=>o!==void 0?n.parse(o):(i.addIssue({code:"custom",message:"Required value is missing"}),qg))}function mv(t,e){if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t[e];return typeof n=="string"?n:void 0}function bl(t,e,n){return t.superRefine((o,i)=>{const s=mv(o,e);s!==void 0&&n.includes(s)&&i.addIssue({code:"custom",path:[e],message:`${e} ${JSON.stringify(s)} is reserved by a known variant, but the value does not match that variant's schema`})})}function Rl(t,e,n){return P().transform((o,i)=>{const s=t.safeParse(o);if(!s.success){for(const u of s.error.issues)i.addIssue({...u,input:o});return qg}const r=s.data,a=mv(o,e);if(a!==void 0&&!n.includes(a)){const u=o;for(const[c,p]of Object.entries(u))c!=="__proto__"&&(Object.hasOwn(r,c)||(r[c]=p))}return r})}function Ce(t){return Be(t.catch(Ap)).transform(e=>e.filter(n=>n!==Ap))}const Io=fe([Ge(),y()]).nullable(),Ne=y(),gv=S({sessionId:Ne,path:y(),content:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),vv=S({sessionId:Ne,path:y(),line:T(Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),limit:T(Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Oc=y(),yv=fe([z("read"),z("edit"),z("delete"),z("move"),z("search"),z("execute"),z("think"),z("fetch"),z("switch_mode"),z("other")]),_v=fe([z("pending"),z("in_progress"),z("completed"),z("failed")]),Vb=fe([z("assistant"),z("user")]),ea=S({audience:T(Ce(Vb).nullish(),()=>{}),lastModified:T(y().nullish(),()=>{}),priority:T(Ge().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),qb=S({annotations:T(ea.nullish(),()=>{}),text:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Bb=S({annotations:T(ea.nullish(),()=>{}),data:y(),mimeType:y(),uri:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Hb=S({annotations:T(ea.nullish(),()=>{}),data:y(),mimeType:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Zb=S({annotations:T(ea.nullish(),()=>{}),description:T(y().nullish(),()=>{}),mimeType:T(y().nullish(),()=>{}),name:y(),size:T(Ge().nullish(),()=>{}),title:T(y().nullish(),()=>{}),uri:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Jb=S({mimeType:T(y().nullish(),()=>{}),text:y(),uri:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Wb=S({blob:y(),mimeType:T(y().nullish(),()=>{}),uri:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Kb=fe([Jb,Wb]),Yb=S({annotations:T(ea.nullish(),()=>{}),resource:Kb,_meta:T(N(y(),P()).nullish(),()=>{})}),Lc=fe([qb.and(S({type:z("text")})),Bb.and(S({type:z("image")})),Hb.and(S({type:z("audio")})),Zb.and(S({type:z("resource_link")})),Yb.and(S({type:z("resource")}))]),Xb=S({content:Lc,_meta:T(N(y(),P()).nullish(),()=>{})}),Qb=S({path:y(),oldText:T(y().nullish(),()=>{}),newText:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Ki=y(),jb=S({terminalId:Ki,_meta:T(N(y(),P()).nullish(),()=>{})}),Tv=fe([Xb.and(S({type:z("content")})),Qb.and(S({type:z("diff")})),jb.and(S({type:z("terminal")}))]),Ev=S({path:y(),line:T(Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),wv=S({toolCallId:Oc,kind:T(yv.nullish(),()=>{}),status:T(_v.nullish(),()=>{}),title:T(y().nullish(),()=>{}),content:T(Ce(Tv).nullish(),()=>{}),locations:T(Ce(Ev).nullish(),()=>{}),rawInput:T(P().optional(),()=>{}),rawOutput:T(P().optional(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Iv=y(),eR=fe([z("allow_once"),z("allow_always"),z("reject_once"),z("reject_always")]),tR=S({optionId:Iv,name:y(),kind:eR,_meta:T(N(y(),P()).nullish(),()=>{})}),Sv=S({sessionId:Ne,toolCall:wv,options:Be(tR),_meta:T(N(y(),P()).nullish(),()=>{})}),Cv=S({name:y(),value:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Av=S({sessionId:Ne,command:y(),args:T(Ce(y()).optional(),()=>[]),env:T(Ce(Cv).optional(),()=>[]),cwd:T(y().nullish(),()=>{}),outputByteLimit:T(Ge().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),bv=S({sessionId:Ne,terminalId:Ki,_meta:T(N(y(),P()).nullish(),()=>{})}),Rv=S({sessionId:Ne,terminalId:Ki,_meta:T(N(y(),P()).nullish(),()=>{})}),kv=S({sessionId:Ne,terminalId:Ki,_meta:T(N(y(),P()).nullish(),()=>{})}),Pv=S({sessionId:Ne,terminalId:Ki,_meta:T(N(y(),P()).nullish(),()=>{})}),kl=S({sessionId:Ne,toolCallId:T(Oc.nullish(),()=>{})}),Pl=S({requestId:Io}),nR=z("object"),oR=fe([z("email"),z("uri"),z("date"),z("date-time")]),Nv=S({const:y(),title:y(),description:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Mv=S({title:T(y().nullish(),()=>{}),description:T(y().nullish(),()=>{}),minLength:Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:y().nullish(),format:oR.nullish(),default:T(y().nullish(),()=>{}),enum:Be(y()).nullish(),oneOf:Be(Nv).nullish(),_meta:T(N(y(),P()).nullish(),()=>{})}),xv=S({title:T(y().nullish(),()=>{}),description:T(y().nullish(),()=>{}),minimum:Ge().nullish(),maximum:Ge().nullish(),default:T(Ge().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Dv=S({title:T(y().nullish(),()=>{}),description:T(y().nullish(),()=>{}),minimum:Ge().nullish(),maximum:Ge().nullish(),default:T(Ge().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),$v=S({title:T(y().nullish(),()=>{}),description:T(y().nullish(),()=>{}),default:T(mt().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Uv=S({enum:Be(y()),_meta:T(N(y(),P()).nullish(),()=>{})}),iR=S({anyOf:Be(Nv),_meta:T(N(y(),P()).nullish(),()=>{})}),sR=Rl(fe([Uv.and(S({type:z("string")})),bl(S({type:y()}),"type",["string"]),iR]),"type",["string"]),Ov=S({title:T(y().nullish(),()=>{}),description:T(y().nullish(),()=>{}),minItems:Ge().nullish(),maxItems:Ge().nullish(),items:sR,default:T(Ce(y()).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),rR=Rl(fe([Mv.and(S({type:z("string")})),xv.and(S({type:z("number")})),Dv.and(S({type:z("integer")})),$v.and(S({type:z("boolean")})),Ov.and(S({type:z("array")})),bl(S({type:y()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),aR=S({type:T(nR.optional().default("object"),()=>"object"),title:T(y().nullish(),()=>{}),properties:N(y(),rR).optional().default({}),required:Be(y()).nullish(),description:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Lv=wo(fe([kl,Pl]),S({requestedSchema:aR})),Gv=y(),zv=wo(fe([kl,Pl]),S({elicitationId:Gv,url:QA()})),Fv=Rl(wo(fe([Lv.and(S({mode:z("form")})),zv.and(S({mode:z("url")})),bl(wo(fe([kl,Pl]),S({mode:y()})),"mode",["form","url"])]),S({message:y(),_meta:T(N(y(),P()).nullish(),()=>{})})),"mode",["form","url"]),Vv=y(),lR=S({serverId:Vv,_meta:T(N(y(),P()).nullish(),()=>{})}),Nl=y(),qv=S({connectionId:Nl,method:y(),params:N(y(),P()).nullish(),_meta:T(N(y(),P()).nullish(),()=>{})}),uR=S({connectionId:Nl,_meta:T(N(y(),P()).nullish(),()=>{})}),Bv=P();S({id:Io,method:y(),params:fe([gv,vv,Sv,Av,bv,Rv,kv,Pv,Fv,lR,qv,uR,Bv]).nullish()});const Hv=Tt().gte(0).lte(65535),cR=S({image:T(mt().optional().default(!1),()=>!1),audio:T(mt().optional().default(!1),()=>!1),embeddedContext:T(mt().optional().default(!1),()=>!1),_meta:T(N(y(),P()).nullish(),()=>{})}),dR=S({http:T(mt().optional().default(!1),()=>!1),sse:T(mt().optional().default(!1),()=>!1),acp:T(mt().optional().default(!1),()=>!1),_meta:T(N(y(),P()).nullish(),()=>{})}),pR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),fR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),hR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),mR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),gR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),vR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),yR=S({list:T(pR.nullish(),()=>{}),delete:T(fR.nullish(),()=>{}),additionalDirectories:T(hR.nullish(),()=>{}),fork:T(mR.nullish(),()=>{}),resume:T(gR.nullish(),()=>{}),close:T(vR.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),_R=S({_meta:T(N(y(),P()).nullish(),()=>{})}),TR=S({logout:T(_R.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),ER=S({_meta:T(N(y(),P()).nullish(),()=>{})}),wR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),IR=fe([z("full"),z("incremental")]),SR=S({syncKind:IR,_meta:T(N(y(),P()).nullish(),()=>{})}),CR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),AR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),bR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),RR=S({didOpen:T(wR.nullish(),()=>{}),didChange:T(SR.nullish(),()=>{}),didClose:T(CR.nullish(),()=>{}),didSave:T(AR.nullish(),()=>{}),didFocus:T(bR.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),kR=S({document:T(RR.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),PR=S({maxCount:T(Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),NR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),MR=S({maxCount:T(Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),xR=S({maxCount:T(Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),DR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),$R=S({_meta:T(N(y(),P()).nullish(),()=>{})}),UR=S({recentFiles:T(PR.nullish(),()=>{}),relatedSnippets:T(NR.nullish(),()=>{}),editHistory:T(MR.nullish(),()=>{}),userActions:T(xR.nullish(),()=>{}),openFiles:T(DR.nullish(),()=>{}),diagnostics:T($R.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),OR=S({events:T(kR.nullish(),()=>{}),context:T(UR.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Zv=fe([z("utf-16"),z("utf-32"),z("utf-8")]),LR=S({loadSession:T(mt().optional().default(!1),()=>!1),promptCapabilities:T(cR.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:T(dR.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:T(yR.optional().default({}),()=>({})),auth:T(TR.optional().default({}),()=>({})),providers:T(ER.nullish(),()=>{}),nes:T(OR.nullish(),()=>{}),positionEncoding:T(Zv.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Ml=y(),GR=S({name:y(),label:T(y().nullish(),()=>{}),secret:T(mt().optional().default(!0),()=>!0),optional:T(mt().optional().default(!1),()=>!1),_meta:T(N(y(),P()).nullish(),()=>{})}),zR=S({id:Ml,name:y(),description:T(y().nullish(),()=>{}),vars:Xt(Ce(GR),()=>[]),link:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),FR=S({id:Ml,name:y(),description:T(y().nullish(),()=>{}),args:T(Ce(y()).optional(),()=>[]),env:T(N(y(),y()).optional(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),VR=S({id:Ml,name:y(),description:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),qR=fe([zR.and(S({type:z("env_var")})),FR.and(S({type:z("terminal")})),VR]),Jv=S({name:y(),title:T(y().nullish(),()=>{}),version:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),BR=S({protocolVersion:Hv,agentCapabilities:T(LR.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:T(Ce(qR).optional().default([]),()=>[]),agentInfo:T(Jv.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),HR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),Gc=y(),zc=fe([z("anthropic"),z("openai"),z("azure"),z("vertex"),z("bedrock"),y()]),ZR=S({apiType:zc,baseUrl:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),JR=S({providerId:Gc,supported:Xt(Ce(zc),()=>[]),required:mt(),current:ZR.nullish(),_meta:T(N(y(),P()).nullish(),()=>{})}),WR=S({providers:Be(JR),_meta:T(N(y(),P()).nullish(),()=>{})}),KR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),YR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),XR=S({_meta:T(N(y(),P()).nullish(),()=>{})}),xl=y(),QR=S({id:xl,name:y(),description:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Dl=S({currentModeId:xl,availableModes:Xt(Ce(QR),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),Wv=y(),jR=fe([z("mode"),z("model"),z("model_config"),z("thought_level"),y()]),Fc=y(),Kv=S({value:Fc,name:y(),description:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),ek=y(),tk=S({group:ek,name:y(),options:Xt(Ce(Kv),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),nk=fe([Be(Kv),Be(tk)]),ok=S({currentValue:Fc,options:nk}),ik=S({currentValue:mt()}),Yi=wo(fe([ok.and(S({type:z("select")})),ik.and(S({type:z("boolean")}))]),S({id:Wv,name:y(),description:T(y().nullish(),()=>{}),category:T(jR.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})})),sk=S({sessionId:Ne,modes:T(Dl.nullish(),()=>{}),configOptions:T(Ce(Yi).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),rk=S({modes:T(Dl.nullish(),()=>{}),configOptions:T(Ce(Yi).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),ak=S({sessionId:Ne,cwd:y(),additionalDirectories:T(Ce(y()).optional(),()=>[]),title:T(y().nullish(),()=>{}),updatedAt:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),lk=S({sessions:Xt(Ce(ak),()=>[]),nextCursor:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),uk=S({_meta:T(N(y(),P()).nullish(),()=>{})}),ck=S({sessionId:Ne,modes:T(Dl.nullish(),()=>{}),configOptions:T(Ce(Yi).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),dk=S({modes:T(Dl.nullish(),()=>{}),configOptions:T(Ce(Yi).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),pk=S({_meta:T(N(y(),P()).nullish(),()=>{})}),fk=S({_meta:T(N(y(),P()).nullish(),()=>{})}),hk=S({configOptions:Xt(Ce(Yi),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),mk=fe([z("end_turn"),z("max_tokens"),z("max_turn_requests"),z("refusal"),z("cancelled")]),gk=S({totalTokens:Ge(),inputTokens:Ge(),outputTokens:Ge(),thoughtTokens:T(Ge().nullish(),()=>{}),cachedReadTokens:T(Ge().nullish(),()=>{}),cachedWriteTokens:T(Ge().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),vk=S({stopReason:mk,usage:T(gk.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),yk=S({sessionId:Ne,_meta:T(N(y(),P()).nullish(),()=>{})}),Xi=y(),So=S({line:Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),character:Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),_meta:T(N(y(),P()).nullish(),()=>{})}),Qi=S({start:So,end:So,_meta:T(N(y(),P()).nullish(),()=>{})}),_k=S({range:Qi,newText:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Tk=S({id:Xi,uri:y(),edits:Be(_k),cursorPosition:T(So.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Ek=S({id:Xi,uri:y(),position:So,_meta:T(N(y(),P()).nullish(),()=>{})}),wk=S({id:Xi,uri:y(),position:So,newName:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Ik=S({id:Xi,uri:y(),search:y(),replace:y(),isRegex:mt().nullish(),_meta:T(N(y(),P()).nullish(),()=>{})}),Sk=fe([Tk.and(S({kind:z("edit")})),Ek.and(S({kind:z("jump")})),wk.and(S({kind:z("rename")})),Ik.and(S({kind:z("searchAndReplace")}))]),Ck=S({suggestions:Be(Sk),_meta:T(N(y(),P()).nullish(),()=>{})}),Ak=S({_meta:T(N(y(),P()).nullish(),()=>{})}),Yv=P(),Xv=P(),bk=fe([z(-32700),z(-32600),z(-32601),z(-32602),z(-32603),z(-32800),z(-32e3),z(-32002),Tt().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),Qv=S({code:bk,message:y(),data:T(P().optional(),()=>{})});fe([S({id:Io,result:fe([BR,HR,WR,KR,YR,XR,sk,rk,lk,uk,ck,dk,pk,fk,hk,vk,yk,Ck,Ak,Yv,Xv])}),S({id:Io,error:Qv})]);const Rk=y(),au=S({content:Lc,messageId:T(Rk.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),kk=S({toolCallId:Oc,title:y(),kind:T(yv.optional(),()=>{}),status:T(_v.optional(),()=>{}),content:T(Ce(Tv).optional(),()=>[]),locations:T(Ce(Ev).optional(),()=>[]),rawInput:T(P().optional(),()=>{}),rawOutput:T(P().optional(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Pk=fe([z("high"),z("medium"),z("low")]),Nk=fe([z("pending"),z("in_progress"),z("completed")]),jv=S({content:y(),priority:Pk,status:Nk,_meta:T(N(y(),P()).nullish(),()=>{})}),Mk=S({entries:Xt(Ce(jv),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),$l=y(),xk=S({planId:$l,entries:Xt(Ce(jv),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),Dk=S({planId:$l,uri:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),$k=S({planId:$l,content:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Uk=fe([xk.and(S({type:z("items")})),Dk.and(S({type:z("file")})),$k.and(S({type:z("markdown")}))]),Ok=S({plan:Uk,_meta:T(N(y(),P()).nullish(),()=>{})}),Lk=S({planId:$l,_meta:T(N(y(),P()).nullish(),()=>{})}),Gk=S({hint:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),zk=Gk,Fk=S({name:y(),description:y(),input:T(zk.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Vk=S({availableCommands:Xt(Ce(Fk),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),qk=S({currentModeId:xl,_meta:T(N(y(),P()).nullish(),()=>{})}),Bk=S({configOptions:Xt(Ce(Yi),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),Hk=S({title:T(y().nullish(),()=>{}),updatedAt:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Zk=S({amount:Ge(),currency:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Jk=S({used:Ge(),size:Ge(),cost:T(Zk.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Wk=fe([au.and(S({sessionUpdate:z("user_message_chunk")})),au.and(S({sessionUpdate:z("agent_message_chunk")})),au.and(S({sessionUpdate:z("agent_thought_chunk")})),kk.and(S({sessionUpdate:z("tool_call")})),wv.and(S({sessionUpdate:z("tool_call_update")})),Mk.and(S({sessionUpdate:z("plan")})),Ok.and(S({sessionUpdate:z("plan_update")})),Lk.and(S({sessionUpdate:z("plan_removed")})),Vk.and(S({sessionUpdate:z("available_commands_update")})),qk.and(S({sessionUpdate:z("current_mode_update")})),Bk.and(S({sessionUpdate:z("config_option_update")})),Hk.and(S({sessionUpdate:z("session_info_update")})),Jk.and(S({sessionUpdate:z("usage_update")}))]),Vc=S({sessionId:Ne,update:Wk,_meta:T(N(y(),P()).nullish(),()=>{})}),ey=S({elicitationId:Gv,_meta:T(N(y(),P()).nullish(),()=>{})}),ty=S({connectionId:Nl,method:y(),params:T(N(y(),P()).nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),ny=P();S({method:y(),params:fe([Vc,ey,ty,ny]).nullish()});const Kk=S({readTextFile:T(mt().optional().default(!1),()=>!1),writeTextFile:T(mt().optional().default(!1),()=>!1),_meta:T(N(y(),P()).nullish(),()=>{})}),Yk=S({_meta:T(N(y(),P()).nullish(),()=>{})}),Xk=S({boolean:T(Yk.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),Qk=S({configOptions:T(Xk.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),jk=S({_meta:T(N(y(),P()).nullish(),()=>{})}),eP=S({terminal:T(mt().optional().default(!1),()=>!1),_meta:T(N(y(),P()).nullish(),()=>{})}),tP=S({_meta:T(N(y(),P()).nullish(),()=>{})}),nP=S({_meta:T(N(y(),P()).nullish(),()=>{})}),oP=S({form:T(tP.nullish(),()=>{}),url:T(nP.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),iP=S({_meta:T(N(y(),P()).nullish(),()=>{})}),sP=S({_meta:T(N(y(),P()).nullish(),()=>{})}),rP=S({_meta:T(N(y(),P()).nullish(),()=>{})}),aP=S({jump:T(iP.nullish(),()=>{}),rename:T(sP.nullish(),()=>{}),searchAndReplace:T(rP.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),lP=S({fs:T(Kk.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:T(mt().optional().default(!1),()=>!1),session:T(Qk.nullish(),()=>{}),plan:T(jk.nullish(),()=>{}),auth:T(eP.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:T(oP.nullish(),()=>{}),nes:T(aP.nullish(),()=>{}),positionEncodings:T(Ce(Zv).optional(),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),oy=S({protocolVersion:Hv,clientCapabilities:T(lP.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:T(Jv.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),iy=S({methodId:Ml,_meta:T(N(y(),P()).nullish(),()=>{})}),sy=S({_meta:T(N(y(),P()).nullish(),()=>{})}),ry=S({providerId:Gc,apiType:zc,baseUrl:y(),headers:N(y(),y()).optional(),_meta:T(N(y(),P()).nullish(),()=>{})}),ay=S({providerId:Gc,_meta:T(N(y(),P()).nullish(),()=>{})}),ly=S({_meta:T(N(y(),P()).nullish(),()=>{})}),uy=S({name:y(),value:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),uP=S({name:y(),url:y(),headers:Be(uy),_meta:T(N(y(),P()).nullish(),()=>{})}),cP=S({name:y(),url:y(),headers:Be(uy),_meta:T(N(y(),P()).nullish(),()=>{})}),dP=S({name:y(),serverId:Vv,_meta:T(N(y(),P()).nullish(),()=>{})}),pP=S({name:y(),command:y(),args:Be(y()),env:Be(Cv),_meta:T(N(y(),P()).nullish(),()=>{})}),Ul=fe([uP.and(S({type:z("http")})),cP.and(S({type:z("sse")})),dP.and(S({type:z("acp")})),pP]),cy=S({cwd:y(),additionalDirectories:T(Ce(y()).optional(),()=>[]),mcpServers:Xt(Ce(Ul),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),dy=S({mcpServers:Xt(Ce(Ul),()=>[]),cwd:y(),additionalDirectories:T(Ce(y()).optional(),()=>[]),sessionId:Ne,_meta:T(N(y(),P()).nullish(),()=>{})}),py=S({cwd:y().nullish(),cursor:y().nullish(),_meta:T(N(y(),P()).nullish(),()=>{})}),fy=S({sessionId:Ne,_meta:T(N(y(),P()).nullish(),()=>{})}),hy=S({sessionId:Ne,cwd:y(),additionalDirectories:T(Ce(y()).optional(),()=>[]),mcpServers:T(Ce(Ul).optional(),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),my=S({sessionId:Ne,cwd:y(),additionalDirectories:T(Ce(y()).optional(),()=>[]),mcpServers:T(Ce(Ul).optional(),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),gy=S({sessionId:Ne,_meta:T(N(y(),P()).nullish(),()=>{})}),vy=S({sessionId:Ne,modeId:xl,_meta:T(N(y(),P()).nullish(),()=>{})}),yy=wo(fe([S({value:mt(),type:z("boolean")}),S({value:Fc})]),S({sessionId:Ne,configId:Wv,_meta:T(N(y(),P()).nullish(),()=>{})})),_y=S({sessionId:Ne,prompt:Be(Lc),_meta:T(N(y(),P()).nullish(),()=>{})}),fP=S({uri:y(),name:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),hP=S({name:y(),owner:y(),remoteUrl:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Ty=S({workspaceUri:T(y().nullish(),()=>{}),workspaceFolders:Be(fP).nullish(),repository:T(hP.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),mP=fe([z("automatic"),z("diagnostic"),z("manual")]),gP=S({uri:y(),languageId:y(),text:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),vP=S({startLine:Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),endLine:Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),text:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),yP=S({uri:y(),excerpts:Be(vP),_meta:T(N(y(),P()).nullish(),()=>{})}),_P=S({uri:y(),diff:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),TP=S({action:y(),uri:y(),position:So,timestampMs:Ge(),_meta:T(N(y(),P()).nullish(),()=>{})}),EP=S({uri:y(),languageId:y(),visibleRange:T(Qi.nullish(),()=>{}),lastFocusedMs:T(Ge().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),wP=fe([z("error"),z("warning"),z("information"),z("hint")]),IP=S({uri:y(),range:Qi,severity:wP,message:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),SP=S({recentFiles:Be(gP).nullish(),relatedSnippets:Be(yP).nullish(),editHistory:Be(_P).nullish(),userActions:Be(TP).nullish(),openFiles:Be(EP).nullish(),diagnostics:Be(IP).nullish(),_meta:T(N(y(),P()).nullish(),()=>{})}),Ey=S({sessionId:Ne,uri:y(),version:Ge(),position:So,selection:Qi.nullish(),triggerKind:mP,context:SP.nullish(),_meta:T(N(y(),P()).nullish(),()=>{})}),wy=S({sessionId:Ne,_meta:T(N(y(),P()).nullish(),()=>{})});S({id:Io,method:y(),params:fe([oy,iy,sy,ry,ay,ly,cy,dy,py,fy,hy,my,gy,vy,yy,_y,Ty,Ey,wy,qv,Bv]).nullish()});const CP=S({_meta:T(N(y(),P()).nullish(),()=>{})}),AP=S({content:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),bP=S({optionId:Iv,_meta:T(N(y(),P()).nullish(),()=>{})}),RP=fe([S({outcome:z("cancelled")}),bP.and(S({outcome:z("selected")}))]),kP=S({outcome:RP,_meta:T(N(y(),P()).nullish(),()=>{})}),PP=S({terminalId:Ki,_meta:T(N(y(),P()).nullish(),()=>{})}),NP=S({exitCode:T(Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),MP=S({output:y(),truncated:mt(),exitStatus:T(NP.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),xP=S({_meta:T(N(y(),P()).nullish(),()=>{})}),DP=S({exitCode:T(Tt().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:T(y().nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})}),$P=S({_meta:T(N(y(),P()).nullish(),()=>{})}),UP=fe([y(),Ge(),Ge(),mt(),Be(y())]),Iy=S({content:N(y(),UP).nullish()}),OP=Rl(wo(fe([Iy.and(S({action:z("accept")})),S({action:z("decline")}),S({action:z("cancel")}),bl(S({action:y()}),"action",["accept","cancel","decline"])]),S({_meta:T(N(y(),P()).nullish(),()=>{})})),"action",["accept","cancel","decline"]),LP=S({connectionId:Nl,_meta:T(N(y(),P()).nullish(),()=>{})}),GP=S({_meta:T(N(y(),P()).nullish(),()=>{})});fe([S({id:Io,result:fe([CP,AP,kP,PP,MP,xP,DP,$P,OP,LP,GP,Xv,Yv])}),S({id:Io,error:Qv})]);const Sy=S({sessionId:Ne,_meta:T(N(y(),P()).nullish(),()=>{})}),Cy=S({sessionId:Ne,uri:y(),languageId:y(),version:Ge(),text:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),zP=S({range:Qi.nullish(),text:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Ay=S({sessionId:Ne,uri:y(),version:Ge(),contentChanges:Xt(Ce(zP),()=>[]),_meta:T(N(y(),P()).nullish(),()=>{})}),by=S({sessionId:Ne,uri:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),Ry=S({sessionId:Ne,uri:y(),_meta:T(N(y(),P()).nullish(),()=>{})}),ky=S({sessionId:Ne,uri:y(),version:Ge(),position:So,visibleRange:Qi,_meta:T(N(y(),P()).nullish(),()=>{})}),Py=S({sessionId:Ne,id:Xi,_meta:T(N(y(),P()).nullish(),()=>{})}),FP=fe([z("rejected"),z("ignored"),z("replaced"),z("cancelled")]),Ny=S({sessionId:Ne,id:Xi,reason:T(FP.nullish(),()=>{}),_meta:T(N(y(),P()).nullish(),()=>{})});S({method:y(),params:fe([Sy,Cy,Ay,by,Ry,ky,Py,Ny,ty,ny]).nullish()});S({requestId:Io,_meta:T(N(y(),P()).nullish(),()=>{})});Lv.and(S({mode:z("form")})).and(S({message:y()}));zv.and(S({mode:z("url")})).and(S({message:y()}));fe([kl,Pl]).and(S({message:y()}));Mv.and(S({type:z("string")}));xv.and(S({type:z("number")}));Dv.and(S({type:z("integer")}));$v.and(S({type:z("boolean")}));Ov.and(S({type:z("array")}));Uv.and(S({type:z("string")}));Iy.and(S({action:z("accept")}));S({action:z("decline")});S({action:z("cancel")});const bp="$/cancel_request";function qa(t){return typeof t=="object"&&t!==null}function VP(t){return t===null||typeof t=="string"||typeof t=="number"&&Number.isFinite(t)}function qP(t){if(!(!qa(t)||!VP(t.requestId)))return t.requestId}const sn={yes(){return{handled:!0}},no(t,e=!1){return{handled:!1,message:t,retry:e}}};function Pa(t){const e=Promise.reject(t);return e.catch(()=>{}),e}function BP(t){if(t instanceof Error||typeof t=="object"&&t!=null&&"message"in t&&typeof t.message=="string")return t.message}function HP(t){return typeof t=="object"&&t!==null&&"name"in t&&t.name==="ZodError"&&"issues"in t&&Array.isArray(t.issues)&&"format"in t&&typeof t.format=="function"}function My(t){if(t instanceof ft)return t.toResult();if(HP(t))return ft.invalidParams(t.format()).toResult();const e=BP(t);try{return ft.internalError(e?JSON.parse(e):{}).toResult()}catch{return ft.internalError({details:e}).toResult()}}function ZP(t){return t instanceof ft&&t.code===-32800?t:ft.requestCancelled(t)}function JP(t,e){const n=WP(t,e);return n?n.toResult():My(t)}function WP(t,e){if(!(!e.aborted||!KP(t)))return ZP(e.reason)}function KP(t){if(typeof t!="object"||t===null)return!1;const e=t;return e.name==="AbortError"||e.code==="ABORT_ERR"}class YP{constructor(e,n,o=new AbortController().signal,i){Z(this,"id");Z(this,"sendResult");Z(this,"signal");Z(this,"finishRequest");Z(this,"didRespond",!1);this.id=e,this.sendResult=n,this.signal=o,this.finishRequest=i}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){const n=e instanceof ft?e.toErrorResponse():e;return this.respondWithResult({error:n})}respondWithResult(e){return this.didRespond?Pa(new Error("JSON-RPC request already responded")):(this.didRespond=!0,this.sendResult(e).finally(()=>{var n;(n=this.finishRequest)==null||n.call(this)}))}}class qc{constructor(e){Z(this,"disposeHandler");Z(this,"active",!0);this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}}class XP{constructor(e){Z(this,"connection");this.connection=e}sendRequest(e,n,o,i){return this.connection.sendRequest(e,n,o,i)}sendNotification(e,n){return this.connection.sendNotification(e,n)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}}class xy{constructor(e,n,o,i){Z(this,"pendingResponses",new Map);Z(this,"incomingRequests",new Map);Z(this,"nextRequestId",0);Z(this,"staticHandlers",[]);Z(this,"dynamicHandlers",new Set);Z(this,"stream");Z(this,"writeQueue",Promise.resolve());Z(this,"abortController",new AbortController);Z(this,"closedPromise");Z(this,"retryQueue",[]);Z(this,"context",new XP(this));Z(this,"receiveReader");if(typeof e=="function"){const u=e,c=n,p=o;this.initialize(p,[...(i==null?void 0:i.handlers)??[],this.legacyHandler(u,c)]);return}const s=e,r=n,a=o;this.initialize(s,[...(a==null?void 0:a.handlers)??[],...r])}static builder(){return new QP}runUntil(e){let n=!1;const o=Promise.resolve().then(()=>e(this.context)).finally(()=>{n=!0}),i=this.closed.then(()=>{if(n)return new Promise(()=>{});throw this.closedReason()});return Promise.race([o,i]).finally(()=>{n=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(const n of this.retryQueue.splice(0))this.processIncomingMessage(n).catch(o=>this.close(o));return new qc(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,n,o,i={}){var c;if(this.abortController.signal.aborted)return Pa(this.closedReason());const s=this.nextRequestId++;let r=()=>{};const a=new Promise((p,f)=>{var m;const h={resolve:v=>{try{const _=o?o(v):v;p(_)}catch(_){f(_)}},reject:f};r=()=>{var v;h.cancellationSent||(h.cancellationSent=!0,(v=h.cleanup)==null||v.call(h),this.sendCancelRequest(s).catch(()=>{}))},(m=i.cancellationSignal)==null||m.addEventListener("abort",r,{once:!0}),h.cleanup=()=>{var v;(v=i.cancellationSignal)==null||v.removeEventListener("abort",r)},this.pendingResponses.set(s,h)});return a.catch(()=>{}),this.sendMessage({jsonrpc:"2.0",id:s,method:e,params:n}).catch(()=>{}),(c=i.cancellationSignal)!=null&&c.aborted&&r(),a}sendCancelRequest(e){return this.sendNotification(bp,{requestId:e})}sendNotification(e,n){return this.abortController.signal.aborted?Pa(this.closedReason()):this.sendMessage({jsonrpc:"2.0",method:e,params:n})}close(e){var o,i;if(this.abortController.signal.aborted)return;const n=e??new Error("ACP connection closed");this.abortController.abort(n);for(const s of this.pendingResponses.values())(o=s.cleanup)==null||o.call(s),s.reject(n);this.pendingResponses.clear();for(const s of this.incomingRequests.values())s.abort(n);this.incomingRequests.clear(),(i=this.receiveReader)==null||i.cancel(n).catch(()=>{})}initialize(e,n){this.stream=e,this.staticHandlers=n,this.closedPromise=new Promise(o=>{this.abortController.signal.addEventListener("abort",()=>o())}),this.receive()}legacyHandler(e,n){return{handleMessage:async(o,i)=>{if(o.kind==="request"){const s=await e(o.method,o.params,i);await o.responder.respond(s)}else await n(o.method,o.params,i);return sn.yes()}}}async receive(){let e;try{const n=this.stream.readable.getReader();this.receiveReader=n;try{for(;!this.abortController.signal.aborted;){const{value:o,done:i}=await n.read();if(this.abortController.signal.aborted||i)break;o&&this.receiveMessage(o)}}finally{this.receiveReader===n&&(this.receiveReader=void 0),n.releaseLock()}}catch(n){e=n}finally{this.close(e)}}receiveMessage(e){if(!this.abortController.signal.aborted){if(!qa(e)){console.error("Invalid message",{message:e});return}"method"in e?("id"in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e)).catch(n=>this.close(n))):"id"in e?this.handleResponse(e):console.error("Invalid message",{message:e})}}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let n=e,o=!1;try{for(const i of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;const s=await i.handleMessage(n,this.context)??{handled:!0};if(s.handled)return;n=s.message??n,o=o||!!s.retry}o?this.retryQueue.push(n):n.kind==="request"&&await n.responder.respondWithError(ft.methodNotFound(n.method))}catch(i){if(this.abortController.signal.aborted)return;if(n.kind==="request"&&!n.responder.responded)await n.responder.respondWithResult(JP(i,n.responder.signal));else{const s=My(i);"error"in s&&console.error("Error handling notification",e.raw,s.error)}}}toIncomingMessage(e){if("id"in e){const n=new AbortController;this.incomingRequests.set(e.id,n);const o=()=>{this.incomingRequests.get(e.id)===n&&this.incomingRequests.delete(e.id)};return{kind:"request",method:e.method,params:e.params,raw:e,signal:n.signal,responder:new YP(e.id,i=>this.sendMessage({jsonrpc:"2.0",id:e.id,...i}),n.signal,o)}}return{kind:"notification",method:e.method,params:e.params,raw:e}}handleResponse(e){var o;const n=this.pendingResponses.get(e.id);if(n)if(this.pendingResponses.delete(e.id),(o=n.cleanup)==null||o.call(n),"result"in e)n.resolve(e.result);else if("error"in e&&qa(e.error)){const{code:i,message:s,data:r}=e.error;n.reject(new ft(i,s,r))}else n.reject(ft.invalidRequest(e));else console.error("Got response to unknown request",e.id)}handleProtocolNotification(e){if(e.method!==bp)return;const n=qP(e.params);if(n===void 0)return;const o=this.incomingRequests.get(n);!o||o.signal.aborted||o.abort(ft.requestCancelled({requestId:n}))}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendMessage(e){return this.abortController.signal.aborted?Pa(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();const n=this.stream.writable.getWriter();try{await n.write(e)}finally{n.releaseLock()}}).catch(n=>{throw this.close(n),n}),this.writeQueue)}}class QP{constructor(){Z(this,"handlers",[]);Z(this,"connectionName")}name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(n,o)=>await e(n,o)??sn.no(n),describe:()=>this.connectionName??"onReceiveMessage"})}onReceiveRequest(e,n,o){return this.withHandler({handleMessage:async(i,s)=>{if(i.kind!=="request"||i.method!==e)return sn.no(i);const r=n(i.params);return await o(r,i.responder,s)??sn.yes()},describe:()=>`${this.connectionName??"request"}:${e}`})}onReceiveNotification(e,n,o){return this.withHandler({handleMessage:async(i,s)=>{if(i.kind!=="notification"||i.method!==e)return sn.no(i);const r=n(i.params);return await o(r,s)??sn.yes()},describe:()=>`${this.connectionName??"notification"}:${e}`})}connect(e,n){return new xy(e,this.handlers,n)}connectWith(e,n,o){return this.connect(e,o).runUntil(n)}}class ft extends Error{constructor(n,o,i){super(o);Z(this,"code");Z(this,"data");this.code=n,this.name="RequestError",this.data=i}static parseError(n,o){return new ft(-32700,`Parse error${o?`: ${o}`:""}`,n)}static invalidRequest(n,o){return new ft(-32600,`Invalid request${o?`: ${o}`:""}`,n)}static methodNotFound(n){return new ft(-32601,`"Method not found": ${n}`,{method:n})}static invalidParams(n,o){return new ft(-32602,`Invalid params${o?`: ${o}`:""}`,n)}static internalError(n,o){return new ft(-32603,`Internal error${o?`: ${o}`:""}`,n)}static requestCancelled(n,o){return new ft(-32800,`Request cancelled${o?`: ${o}`:""}`,n)}static authRequired(n,o){return new ft(-32e3,`Authentication required${o?`: ${o}`:""}`,n)}static resourceNotFound(n){return new ft(-32002,`Resource not found${n?`: ${n}`:""}`,n&&{uri:n})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}}const Rp=10;var zn,Vs,Fu;class jP{constructor(){D(this,Vs);D(this,zn,[])}push(e){const n=[];let o=0,i=e.indexOf(Rp,o);for(;i!==-1;)n.push($(this,Vs,Fu).call(this,e.subarray(o,i))),o=i+1,i=e.indexOf(Rp,o);return o<e.byteLength&&g(this,zn).push(o===0?e:new Uint8Array(e.subarray(o))),n}flush(){if(g(this,zn).length!==0)return $(this,Vs,Fu).call(this,new Uint8Array(0))}}zn=new WeakMap,Vs=new WeakSet,Fu=function(e){if(g(this,zn).length===0)return e;let n=e.byteLength;for(const s of g(this,zn))n+=s.byteLength;const o=new Uint8Array(n);let i=0;for(const s of g(this,zn))o.set(s,i),i+=s.byteLength;return o.set(e,i),O(this,zn,[]),o};function Dy(t,e){const n=new TextEncoder,o=new TextDecoder;let i=!1,s;const r=new ReadableStream({async start(u){const c=new jP,p=h=>{const m=o.decode(h).trim();if(m)try{const v=JSON.parse(m);qa(v)?u.enqueue(v):console.warn("Skipping JSON line that is not an object:",m)}catch(v){console.error("Failed to parse JSON message:",m,v)}},f=e.getReader();s=f;try{for(;;){const{value:m,done:v}=await f.read();if(i)return;if(v)break;if(m){for(const _ of c.push(m))if(p(_),i)return}}if(i)return;const h=c.flush();h&&p(h)}catch(h){if(i)return;u.error(h);return}finally{s===f&&(s=void 0),f.releaseLock()}i||u.close()},cancel(u){return i=!0,s==null?void 0:s.cancel(u)}}),a=new WritableStream({async write(u){const c=JSON.stringify(u)+`
21
+ `,p=t.getWriter();try{await p.write(n.encode(c))}finally{p.releaseLock()}}});return{readable:r,writable:a}}function ct(t){return t??{}}function eN(t){return typeof t=="object"&&t!==null&&"readable"in t&&"writable"in t}function tN(){const t=new TransformStream,e=new TransformStream;return[{readable:e.readable,writable:t.writable},{readable:t.readable,writable:e.writable}]}const $y=Symbol("startActiveSession");class Uy{constructor(e,n){Z(this,"cx");Z(this,"currentRequestId");this.cx=e,this.currentRequestId=n}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(e,n,o,i){return this.cx.sendRequest(e,n,o,i)}sendNotification(e,n){return this.cx.sendNotification(e,n)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}}class Bc extends Uy{constructor(e,n){super(e,n)}static create(e,n){return new Bc(e,n)}request(e,n,o){const i=zy[e];return this.sendRequest(e,n,i==null?void 0:i.mapResponse,o)}notify(e,n){return this.sendNotification(e,n)}}class Cs extends Uy{constructor(e,n){super(e,n)}static create(e,n){return new Cs(e,n)}[$y](e,n){return this.sendRequest(ae.session_new,e,o=>this.attachSession(o),n)}buildSession(e){return typeof e=="string"?Ba.create(this,{cwd:e,mcpServers:[]}):Ba.create(this,e)}attachSession(e){const n=new rN,o=this.connectionContext.signal,i=()=>{n.fail(o.reason??new Error("ACP connection closed"))};o.aborted?i():o.addEventListener("abort",i);const s=Fy(this.connectionContext).attach(e,n),r=new qc(()=>{o.removeEventListener("abort",i)});return Hc.create(this,e,n,[s,r])}request(e,n,o){const i=Gy[e];return this.sendRequest(e,n,i==null?void 0:i.mapResponse,o)}notify(e,n){return this.sendNotification(e,n)}}class Oy{constructor(e){Z(this,"connection");this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}}class nN extends Oy{constructor(n,o=[]){super(n);Z(this,"connectHandlers");Z(this,"client");Z(this,"didStartConnectHandlers",!1);this.connectHandlers=o,this.client=Bc.create(n.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Zc(this,this.connectHandlers))}}class oN extends Oy{constructor(n,o=[]){super(n);Z(this,"connectHandlers");Z(this,"agent");Z(this,"didStartConnectHandlers",!1);this.connectHandlers=o,this.agent=Cs.create(n.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Zc(this,this.connectHandlers))}}function iN(t,e=[]){return new nN(t,e)}function sN(t,e=[]){return new oN(t,e)}class rN{constructor(){Z(this,"values",[]);Z(this,"waiters",[]);Z(this,"failed",!1);Z(this,"failure")}enqueue(e){if(this.failed)return;const n=this.waiters.shift();n?n.resolve(e):this.values.push({kind:"value",value:e})}reject(e){if(!this.failed){if(this.waiters.length>0){for(const n of this.waiters.splice(0))n.reject(e);return}this.values.push({kind:"error",error:e})}}clearErrors(){this.values=this.values.filter(e=>e.kind==="value")}fail(e){if(!this.failed){this.failed=!0,this.failure=e;for(const n of this.waiters.splice(0))n.reject(e)}}next(){if(this.values.length>0){const e=this.values.shift();return e.kind==="error"?Promise.reject(e.error):Promise.resolve(e.value)}return this.failed?Promise.reject(this.failure):new Promise((e,n)=>{this.waiters.push({resolve:e,reject:n})})}}function kp(t){return{...t,additionalDirectories:t.additionalDirectories?[...t.additionalDirectories]:void 0,mcpServers:[...t.mcpServers]}}class Ba{constructor(e,n){Z(this,"cx");Z(this,"request");this.cx=e,this.request=kp(n)}static create(e,n){return new Ba(e,n)}toRequest(){return kp(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[$y](this.toRequest(),e)}async withSession(e){const n=await this.start();try{return await e(n)}finally{n.dispose()}}}class Hc{constructor(e,n,o,i){Z(this,"cx");Z(this,"sessionResponse");Z(this,"updates");Z(this,"registrations");this.cx=e,this.sessionResponse=n,this.updates=o,this.registrations=i}static create(e,n,o,i){return new Hc(e,n,o,i)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,n){this.updates.clearErrors();const o=this.cx.request(ae.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},n);return o.then(i=>{this.updates.enqueue({kind:"stop",response:i,stopReason:i.stopReason})},i=>{this.updates.reject(i)}),o}nextUpdate(){return this.updates.next()}async readText(){let e="";for(;;){const n=await this.nextUpdate();if(n.kind==="stop")return e;const{update:o}=n;o.sessionUpdate==="agent_message_chunk"&&o.content.type==="text"&&(e+=o.content.text)}}dispose(){for(const e of this.registrations.splice(0))e.dispose();this.updates.fail(new Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e:[e]}}function Ly(t,e){return t?typeof t=="function"?t(e):t.parse(e):e}function Fe(t,e,n){return{method:t,params:e,mapResponse:n}}function kn(t,e){return{method:t,params:e}}function aN(t,e,n,o){t.onReceiveRequest(e.method,i=>Ly(e.params,i),async(i,s,r)=>{const a=await o(n(i,r,s.signal,s.id));await s.respond(e.mapResponse?e.mapResponse(a):a)})}function lN(t,e,n,o){t.onReceiveNotification(e.method,i=>Ly(e.params,i),(i,s)=>o(n(i,s,s.signal)))}function Ol(t){const e={};for(const n of Object.values(t))e[n.method]=n;return e}const uN={initialize:Fe(ae.initialize,oy),newSession:Fe(ae.session_new,cy),loadSession:Fe(ae.session_load,dy,ct),unstable_forkSession:Fe(ae.session_fork,hy),listSessions:Fe(ae.session_list,py),deleteSession:Fe(ae.session_delete,fy,ct),resumeSession:Fe(ae.session_resume,my),closeSession:Fe(ae.session_close,gy,ct),setSessionMode:Fe(ae.session_set_mode,vy,ct),setSessionConfigOption:Fe(ae.session_set_config_option,yy),authenticate:Fe(ae.authenticate,iy,ct),unstable_listProviders:Fe(ae.providers_list,sy),unstable_setProvider:Fe(ae.providers_set,ry,ct),unstable_disableProvider:Fe(ae.providers_disable,ay,ct),logout:Fe(ae.logout,ly,ct),prompt:Fe(ae.session_prompt,_y),unstable_startNes:Fe(ae.nes_start,Ty),unstable_suggestNes:Fe(ae.nes_suggest,Ey),unstable_closeNes:Fe(ae.nes_close,wy,ct)},cN={cancel:kn(ae.session_cancel,Sy),unstable_didOpenDocument:kn(ae.document_did_open,Cy),unstable_didChangeDocument:kn(ae.document_did_change,Ay),unstable_didCloseDocument:kn(ae.document_did_close,by),unstable_didSaveDocument:kn(ae.document_did_save,Ry),unstable_didFocusDocument:kn(ae.document_did_focus,ky),unstable_acceptNes:kn(ae.nes_accept,Py),unstable_rejectNes:kn(ae.nes_reject,Ny)},dN={requestPermission:Fe(Re.session_request_permission,Sv),writeTextFile:Fe(Re.fs_write_text_file,gv,ct),readTextFile:Fe(Re.fs_read_text_file,vv),createTerminal:Fe(Re.terminal_create,Av),terminalOutput:Fe(Re.terminal_output,bv),releaseTerminal:Fe(Re.terminal_release,Rv,ct),waitForTerminalExit:Fe(Re.terminal_wait_for_exit,kv),killTerminal:Fe(Re.terminal_kill,Pv,ct),unstable_createElicitation:Fe(Re.elicitation_create,Fv)},pN={sessionUpdate:kn(Re.session_update,Vc),unstable_completeElicitation:kn(Re.elicitation_complete,ey)},Gy=Ol(uN);Ol(cN);const zy=Ol(dN),fN=Ol(pN);function hN(t,e,n,o){return{params:t,requestId:o,signal:n,agent:e}}function mN(t,e,n){return{params:t,signal:n,agent:e}}class gN{constructor(){Z(this,"activeSessions",new Map)}handleMessage(e){if(e.kind!=="notification"||e.method!==Re.session_update)return sn.no(e);const n=Vc.parse(e.params),o={kind:"session_update",notification:n,update:n.update},i=this.activeSessions.get(n.sessionId);if(i&&i.size>0)for(const s of i)s.enqueue(o);return sn.no(e)}attach(e,n){const o=this.activeSessions.get(e.sessionId)??new Set;return o.add(n),this.activeSessions.set(e.sessionId,o),new qc(()=>{o.delete(n),o.size===0&&this.activeSessions.delete(e.sessionId)})}}const Pp=new WeakMap;function Fy(t){let e=Pp.get(t);return e||(e=new gN,Pp.set(t,e)),e}function Zc(t,e){for(const n of e){let o;try{o=n(t)}catch(i){throw t.close(i),i}Promise.resolve(o).catch(i=>{t.close(i)})}}const As=Symbol("appBuilder"),vN=Symbol("runAgentConnectHandlers"),lu=Symbol("runClientConnectHandlers");function yN(t){return new _N(t)}class _N{constructor(e={}){Z(this,"builder",xy.builder());Z(this,"connectHandlers",[]);e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(n,o)=>Fy(o).handleMessage(n),describe:()=>"client-session-update-router"})}[As](){return this.builder}[lu](e){Zc(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,n){const{rawConnection:o,connection:i}=this.connectConnection(e);return o.runUntil(()=>n(i.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,n,o){if(o)return this.request({method:e,params:n},o);const i=zy[e];if(!i)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(i,n)}onNotification(e,n,o){if(o)return this.notification({method:e,params:n},o);const i=fN[e];if(!i)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(i,n)}request(e,n){return aN(this.builder,e,(o,i,s,r)=>hN(o,Cs.create(i,r),s,r),n),this}notification(e,n){return lN(this.builder,e,(o,i,s)=>mN(o,Cs.create(i),s),n),this}connectConnection(e){if(eN(e)){const a=this.openStreamConnection(e);return this[lu](a.connection),a}const[n,o]=tN(),i=e[As]().connect(o),s=iN(i),r=this.openStreamConnection(n);r.rawConnection.closed.then(()=>s.close()),i.closed.then(()=>r.connection.close());try{e[vN](s),this[lu](r.connection)}catch(a){throw s.close(a),r.connection.close(a),a}return r}openStreamConnection(e){const n=this.builder.connect(e);return{rawConnection:n,connection:sN(n,this.connectHandlers)}}}const TN=new Set([Re.session_request_permission,Re.fs_write_text_file,Re.fs_read_text_file,Re.terminal_create,Re.terminal_output,Re.terminal_release,Re.terminal_wait_for_exit,Re.terminal_kill,Re.elicitation_create]),EN=new Set([Re.session_update,Re.elicitation_complete]);function wN(t){const e=yN().onRequest(Re.session_request_permission,n=>t.requestPermission(n.params)).onNotification(Re.session_update,n=>t.sessionUpdate(n.params)).onRequest(Re.fs_write_text_file,async n=>{var o;return await((o=t.writeTextFile)==null?void 0:o.call(t,n.params))??{}}).onRequest(Re.fs_read_text_file,async n=>{var o;return await((o=t.readTextFile)==null?void 0:o.call(t,n.params))}).onRequest(Re.terminal_create,async n=>{var o;return await((o=t.createTerminal)==null?void 0:o.call(t,n.params))}).onRequest(Re.terminal_output,async n=>{var o;return await((o=t.terminalOutput)==null?void 0:o.call(t,n.params))}).onRequest(Re.terminal_release,async n=>{var o;return await((o=t.releaseTerminal)==null?void 0:o.call(t,n.params))??{}}).onRequest(Re.terminal_wait_for_exit,async n=>{var o;return await((o=t.waitForTerminalExit)==null?void 0:o.call(t,n.params))}).onRequest(Re.terminal_kill,async n=>{var o;return await((o=t.killTerminal)==null?void 0:o.call(t,n.params))??{}});return t.unstable_createElicitation&&e.onRequest(Re.elicitation_create,n=>t.unstable_createElicitation(n.params)),t.unstable_completeElicitation&&e.onNotification(Re.elicitation_complete,n=>t.unstable_completeElicitation(n.params)),t.extMethod&&e[As]().withHandler({handleMessage:async n=>n.kind!=="request"||TN.has(n.method)?sn.no(n):(await n.responder.respond(await t.extMethod(n.method,n.params)),sn.yes()),describe:()=>"legacy-client-extension-request"}),t.extNotification&&e[As]().withHandler({handleMessage:async n=>n.kind!=="notification"||EN.has(n.method)?sn.no(n):(await t.extNotification(n.method,n.params),sn.yes()),describe:()=>"legacy-client-extension-notification"}),e}class Vy{constructor(e,n){Z(this,"connection");this.connection=wN(e(this))[As]().connect(n)}initialize(e){return this.connection.sendRequest(ae.initialize,e)}newSession(e){return this.connection.sendRequest(ae.session_new,e)}loadSession(e){return this.connection.sendRequest(ae.session_load,e,ct)}unstable_forkSession(e){return this.connection.sendRequest(ae.session_fork,e)}listSessions(e){return this.connection.sendRequest(ae.session_list,e)}deleteSession(e){return this.connection.sendRequest(ae.session_delete,e,ct)}resumeSession(e){return this.connection.sendRequest(ae.session_resume,e)}closeSession(e){return this.connection.sendRequest(ae.session_close,e,ct)}setSessionMode(e){return this.connection.sendRequest(ae.session_set_mode,e,ct)}setSessionConfigOption(e){return this.connection.sendRequest(ae.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(ae.authenticate,e,ct)}unstable_listProviders(e){return this.connection.sendRequest(ae.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(ae.providers_set,e,ct)}unstable_disableProvider(e){return this.connection.sendRequest(ae.providers_disable,e,ct)}logout(e){return this.connection.sendRequest(ae.logout,e,ct)}prompt(e){return this.connection.sendRequest(ae.session_prompt,e)}cancel(e){return this.connection.sendNotification(ae.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(ae.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(ae.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(ae.nes_close,e,ct)}unstable_didOpenDocument(e){return this.connection.sendNotification(ae.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(ae.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(ae.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(ae.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(ae.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(ae.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(ae.nes_reject,e)}request(e,n,o){const i=Gy[e];return this.connection.sendRequest(e,n,i==null?void 0:i.mapResponse,o)}notify(e,n){return this.connection.sendNotification(e,n)}extMethod(e,n){return this.request(e,n)}extNotification(e,n){return this.notify(e,n)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}}function qy(t){return{async requestPermission(e){const n=i=>e.options.find(s=>s.kind===i),o=n("allow_once")??n("allow_always")??e.options.find(i=>!i.kind.startsWith("reject"))??e.options[0];return o?{outcome:{outcome:"selected",optionId:o.optionId}}:{outcome:{outcome:"cancelled"}}},async sessionUpdate(e){t.onUpdate(e)},async extNotification(e,n){var o;(o=t.onExtNotification)==null||o.call(t,e,n)},async extMethod(e,n){return e==="cursor/ask_question"?{outcome:{outcome:"skipped"}}:e==="cursor/create_plan"?{outcome:{outcome:"accepted"}}:{}}}}function IN(t){return typeof t=="string"?[{type:"text",text:t}]:t}const SN=1e4,CN=["cached_token","grok.com","cursor_login"];function AN(t){var n;if(!(t!=null&&t.length))return;const e=new Set(t.map(o=>o.id));return CN.find(o=>e.has(o))??((n=t[0])==null?void 0:n.id)}function Np(t){var n;const e=t;return((n=e==null?void 0:e.data)==null?void 0:n.code)==="auth_required"}function By(t,e,n){return{conn:t,capabilities:n,async newSession(o){return t.newSession({cwd:o.cwd,mcpServers:[],...o._meta!=null&&{_meta:o._meta}})},async loadSession(o){return t.loadSession({sessionId:o.sessionId,cwd:o.cwd,mcpServers:[],...o._meta!=null&&{_meta:o._meta}})},async listSessions(){return t.listSessions({})},async prompt(o,i){return t.prompt({sessionId:o,prompt:IN(i)})},async cancel(o){return t.cancel({sessionId:o})},close(){e.close()},async extMethod(o,i){return t.extMethod(o,i)},async setSessionConfigOption(o){return typeof o.value=="boolean"?t.setSessionConfigOption({sessionId:o.sessionId,configId:o.configId,type:"boolean",value:o.value}):t.setSessionConfigOption({sessionId:o.sessionId,configId:o.configId,value:o.value})},async setSessionMode(o){return t.setSessionMode({sessionId:o.sessionId,modeId:o.modeId})},async setSessionModel(o){await t.setSessionConfigOption({sessionId:o.sessionId,configId:"model",value:o.modelId})}}}async function Mp(t,e,n={}){const o=n.initTimeoutMs??SN,i=typeof e=="function"?{onUpdate:e}:e,s=Dy(t.writable,t.readable),r=qy({onUpdate:i.onUpdate,onExtNotification:i.onExtNotification}),a=new Vy(h=>r,s);let u,c;const p=a.initialize({protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1}},clientInfo:{name:"drive-coding",version:"0.2.0"}});p.catch(()=>{});try{c=await Promise.race([p,new Promise((h,m)=>{u=setTimeout(()=>{m(new Error(`ACP initialize timeout after ${o}ms — no response from agent (transport or child unresponsive)`))},o)})]),u!==void 0&&clearTimeout(u)}catch(h){if(u!==void 0&&clearTimeout(u),Np(h)){const m=new Error(`ACP agent requires authentication: ${h.message??"auth_required"}. Run in shell: '<cli> auth login'.`);throw m.kind="auth_required",t.close(),m}throw t.close(),h}const f=AN(c.authMethods);if(f)try{await a.authenticate({methodId:f})}catch(h){if(Np(h)){t.close();const v=new Error(`ACP agent authentication failed (methodId: ${f}): ${h.message??String(h)}. Run in shell: '<cli> auth login'.`);throw v.kind="auth_required",v}const m=h;console.warn(`[acp] authenticate(methodId=${f}) failed non-fatally — agent declared authMethods but RPC not implemented; continuing: ${(m==null?void 0:m.message)??String(h)}`)}return By(a,t,c.agentCapabilities)}function bN(t,e,n={}){const o=typeof e=="function"?{onUpdate:e}:e,i=Dy(t.writable,t.readable),s=qy({onUpdate:o.onUpdate,onExtNotification:o.onExtNotification}),r=new Vy(u=>s,i),a=n.capabilities??{};return By(r,t,a)}function RN(t){const e=t;return{sessionId:String(e.sessionId??""),cwd:String(e.cwd??""),title:String(e.title??""),updatedAt:String(e.updatedAt??"")}}function kN(t){if(!t.includes("$/"))return!1;const e=t.trim();if(!e.startsWith("{"))return!1;let n;try{n=JSON.parse(e)}catch{return!1}if(typeof n!="object"||n===null)return!1;const o=n;return typeof o.method=="string"&&o.method.startsWith("$/")&&o.id===void 0}function PN(t){const e=new TextEncoder,n=new TextDecoder,o=new ReadableStream({start(s){t.addEventListener("message",r=>{const a=typeof r.data=="string"?r.data:r.data instanceof ArrayBuffer?n.decode(r.data):String(r.data);kN(a)||s.enqueue(e.encode(a))}),t.addEventListener("close",()=>{try{s.close()}catch{}}),t.addEventListener("error",r=>{try{s.error(r)}catch{}})}}),i=new WritableStream({write(s){const r=n.decode(s);for(const a of r.split(`
22
+ `))if(a.trim().length>0)try{t.send(`${a}
23
+ `)}catch{}},close(){try{t.close()}catch{}},abort(s){try{t.close(1011,String(s))}catch{}}});return{readable:o,writable:i}}const NN=25e3;var St,wi,oo,si,Hy,Vu;class uu{constructor(e,n){D(this,si);Z(this,"readable");Z(this,"writable");D(this,St);D(this,wi,[]);D(this,oo);O(this,St,n??new WebSocket(e)),g(this,St).binaryType="arraybuffer",g(this,St).addEventListener("open",()=>{$(this,si,Hy).call(this)},{once:!0}),g(this,St).addEventListener("close",i=>{$(this,si,Vu).call(this);for(const s of g(this,wi).slice())s(i.code,i.reason)});const o=PN(g(this,St));this.readable=o.readable,this.writable=o.writable}async waitForOpen(){g(this,St).readyState!==WebSocket.OPEN&&await new Promise((e,n)=>{g(this,St).addEventListener("open",()=>e(),{once:!0}),g(this,St).addEventListener("error",()=>n(new Error("WS connect failed")),{once:!0})})}sendRaw(e){try{g(this,St).readyState===WebSocket.OPEN&&g(this,St).send(e)}catch{}}close(){$(this,si,Vu).call(this);try{g(this,St).close()}catch{}}onClose(e){g(this,wi).push(e)}async closeAndWait(e=1e3){if(g(this,St).readyState===WebSocket.CLOSED)return;const n=new Promise(o=>{g(this,wi).push(()=>o())});this.close(),await Promise.race([n,new Promise(o=>setTimeout(o,e))])}}St=new WeakMap,wi=new WeakMap,oo=new WeakMap,si=new WeakSet,Hy=function(){g(this,oo)===void 0&&O(this,oo,setInterval(()=>{if(g(this,St).readyState===WebSocket.OPEN)try{g(this,St).send(`${JSON.stringify({jsonrpc:"2.0",method:"$/ping"})}
24
+ `)}catch{}},NN))},Vu=function(){g(this,oo)!==void 0&&(clearInterval(g(this,oo)),O(this,oo,void 0))};const MN={claude:"bypassPermissions"};function xN(t,e){return!t||!e?!1:MN[t]===e}const DN={"_drive/setThinkingTokens":{params:ti({sessionId:"string",n:"number | null"}),result:ti({ok:"true"})}};function $N(t,e){const n=DN[t].params,o=n(e);if(o instanceof ti.errors)throw new Error(`Invalid params for ${t}: ${o.summary}`);return o}function cu(t){return{async setThinkingTokens(e,n){const o=$N("_drive/setThinkingTokens",{sessionId:e,n});await t.extMethod("_drive/setThinkingTokens",o)}}}const UN={},ON={claudeCode:{options:{thinking:{type:"adaptive",display:"summarized"},forwardSubagentText:!0},emitRawSDKMessages:[{type:"system",subtype:"task_started"},{type:"system",subtype:"task_progress"},{type:"system",subtype:"task_notification"},{type:"system",subtype:"task_updated"},{type:"assistant"}]}};var Ii,Vo,qs,Bs,Hs,Zs,Js,Ws,Ks,Ys,Xs,Qs,js,er,tr,nr,or,ir,sr,io,Pn,Ht,fl,q,hs,ms,Ee,Nn,qo,Si,vt,be,rr,Zt,Mn,Nt,Ci,Bo,nn,ar,hl,ml,gl,lr,Na,Zy,Jy,Ma,Ai,ur,Ho,vl,Wy,Bu,di,Ve,It,Oo,gs,Hu,Zu,kc,bi,Zo,Ky,Yy,xa,Xy,Ju;const _n=class _n{constructor(e){D(this,q);D(this,Ii);D(this,Vo);D(this,qs,se("idle"));D(this,Bs,se("idle"));D(this,Hs,se(null));D(this,Zs,se(qe([])));D(this,Js,se(null));D(this,Ws,se(null));D(this,Ks,se(0));D(this,Ys,se(!1));D(this,Xs,se(""));D(this,Qs,se(qe([])));D(this,js,se(null));D(this,er,se(null));D(this,tr,se(qe([])));D(this,nr,se(""));D(this,or,se(qe([])));D(this,ir,se(!1));D(this,sr,se(null));D(this,io,!1);D(this,Pn,!1);D(this,Ht,null);D(this,fl,1500);D(this,Ee,null);D(this,Nn,null);D(this,qo,null);D(this,Si,0);D(this,vt,null);D(this,be,null);D(this,rr,new Map);D(this,Zt,!1);D(this,Mn,!1);D(this,Nt,se(null));D(this,Ci,!1);D(this,Bo);D(this,nn,!1);D(this,ar,async()=>{if(g(this,be)===null||this.cwd===null)return null;try{const n=(await Vg()).find(o=>o.acpSessionId===g(this,be)&&o.cwd===this.cwd&&o.status!=="crashed"&&o.status!=="closed");return(n==null?void 0:n.id)??null}catch{return null}});D(this,Ai,async()=>{if(g(this,be)===null||this.cwd===null||Y(g(this,Nt))===null){O(this,nn,!1),$(this,q,Ve).call(this,"disconnected");return}g(this,vt)&&(await g(this,vt).closeAndWait(),O(this,Ee,null),O(this,vt,null));const e=await g(this,ar).call(this);if(e!==null&&await g(this,Ho).call(this,e)){this.status==="connected"&&(this.reconnectAttempt=0);return}await g(this,ur).call(this),this.status==="connected"&&(this.reconnectAttempt=0)});D(this,ur,async()=>{var n;const e=this.agentId;O(this,Mn,!0);try{try{(n=g(this,Ee))==null||n.close()}catch{}O(this,Ee,null),O(this,vt,null),(this.status==="connecting"||this.status==="connected")&&$(this,q,Ve).call(this,"disconnected");const o=g(this,be),i=this.cwd,s=Y(g(this,Nt));if(o===null||i===null||s===null)return;await this.loadSession({sessionId:o,cwd:i,cliKind:s})}finally{O(this,Mn,!1)}e&&e!==this.agentId&&Ou(e).catch(()=>{})});D(this,Ho,async e=>{O(this,Zt,!1),$(this,q,Ve).call(this,"connecting");for(let n=0;n<=g(_n,lr);n++){O(this,Ee,null),O(this,vt,null);const o=location.protocol==="https:"?"wss:":"ws:",i=new uu(`${o}//${location.host}/ws/agent/${e}`);O(this,vt,i);const s=new Promise(u=>{i.onClose((c,p)=>u({closed:!0,code:c,reason:p}))});let r=!1;const a=await Promise.race([i.waitForOpen().then(()=>(r=!0,null)).catch(()=>null),s]);if(!r){if(i.close(),(a&&"closed"in a?a.code:0)===1008&&n<g(_n,lr)){await new Promise(c=>setTimeout(c,g(_n,gl)));continue}return!1}i.onClose((u,c)=>{g(this,Zt)||g(this,Mn)||u!==1e3&&u!==1001&&$(this,q,Na).call(this,u,c)});try{this.agentId=e,O(this,Ee,bN(i,{onUpdate:g(this,Zo),onExtNotification:g(this,bi)},{capabilities:UN})),O(this,Nn,cu(g(this,Ee))),this.bubbles=[],this.isLoadingHistory=!0;try{const u=$(this,q,di).call(this),c=await g(this,Ee).loadSession({sessionId:g(this,be),cwd:this.cwd,...u&&{_meta:u}});$(this,q,Oo).call(this,c)}finally{this.isLoadingHistory=!1,$(this,q,It).call(this,"idle")}return await us(e,g(this,be),{replace:!0}).catch(()=>{}),$(this,q,Ve).call(this,"connected"),!0}catch{return O(this,Ee,null),O(this,vt,null),i.close(),!1}}return!1});Z(this,"attach",async e=>{if(this.status==="connecting"||this.status==="connected")throw new Error(`cannot attach in status ${this.status}`);$(this,q,Ve).call(this,"connecting"),this.error=null,this.bubbles=[],O(this,Zt,!1);try{const{agentId:n}=await rp({cwd:e.cwd,cliKind:e.cliKind});this.agentId=n,this.cwd=e.cwd,te(g(this,Nt),e.cliKind,!0);const o=location.protocol==="https:"?"wss:":"ws:",i=new uu(`${o}//${location.host}/ws/agent/${n}`);O(this,vt,i),i.onClose((a,u)=>{g(this,Zt)||g(this,Mn)||a!==1e3&&a!==1001&&$(this,q,Na).call(this,a,u)}),await i.waitForOpen(),O(this,Ee,await Mp(i,{onUpdate:g(this,Zo),onExtNotification:g(this,bi)})),O(this,Nn,cu(g(this,Ee)));const s=$(this,q,di).call(this),r=await g(this,Ee).newSession({cwd:e.cwd,...s&&{_meta:s}});if(O(this,be,r.sessionId??null),!g(this,be))throw new Error("newSession returned no sessionId");$(this,q,Oo).call(this,r),await us(n,g(this,be)).catch(()=>{}),$(this,q,Ve).call(this,"connected"),await $(this,q,Bu).call(this)}catch(n){const o=n instanceof Error?n.message:String(n);this.error=o,$(this,q,Ve).call(this,"error"),$(this,q,gs).call(this)}});Z(this,"detach",()=>{O(this,Zt,!0),$(this,q,Ma).call(this),O(this,nn,!1),this.reconnectAttempt=0,$(this,q,gs).call(this),$(this,q,Ve).call(this,"idle"),this.error=null,this.bubbles=[],this.sessions=[],O(this,io,!1),this.sessionsError=null});Z(this,"leaveRunning",()=>{O(this,Zt,!0),$(this,q,Ma).call(this),O(this,nn,!1),this.reconnectAttempt=0,$(this,q,gs).call(this,{keepAgent:!0}),$(this,q,Ve).call(this,"idle"),this.error=null,this.bubbles=[],this.sessions=[],O(this,io,!1),this.sessionsError=null});Z(this,"sendPrompt",async(e,n)=>{if(this.status!=="connected"||!g(this,Ee)||!g(this,be))return;const o=(n==null?void 0:n.attachments)??[];if(!e.trim()&&o.length===0)return;this.lastUserMessage=e;const i=[...e.trim()?[{type:"text",text:e}]:[],...o.map(r=>({type:"image",mimeType:r.mimeType,data:r.dataBase64}))],s={id:crypto.randomUUID(),kind:"user",messageId:null,createdAt:Date.now(),segments:[{id:crypto.randomUUID(),text:e}],...(n==null?void 0:n.recordingId)!==void 0?{recordingId:n.recordingId}:{},...o.length>0?{attachments:o.map(r=>({mimeType:r.mimeType,dataBase64:r.dataBase64}))}:{}};this.bubbles.push(s),$(this,q,It).call(this,"waiting"),$(this,q,ms).call(this);try{await g(this,Ee).prompt(g(this,be),i),O(this,Pn,!0),$(this,q,It).call(this,"idle")}catch(r){O(this,Pn,!0),$(this,q,It).call(this,"idle"),this.error=`prompt failed: ${r instanceof Error?r.message:String(r)}`,$(this,q,Ve).call(this,"error")}});Z(this,"loadSession",async e=>{if(this.status==="connecting"||this.status==="connected")throw new Error(`cannot loadSession in status ${this.status}`);$(this,q,Ve).call(this,"connecting"),this.error=null,this.bubbles=[],O(this,Zt,!1),$(this,q,ms).call(this);try{const{agentId:n}=await rp({cwd:e.cwd,cliKind:e.cliKind});this.agentId=n,this.cwd=e.cwd,te(g(this,Nt),e.cliKind,!0);const o=location.protocol==="https:"?"wss:":"ws:",i=new uu(`${o}//${location.host}/ws/agent/${n}`);O(this,vt,i),i.onClose((s,r)=>{g(this,Zt)||g(this,Mn)||s!==1e3&&s!==1001&&$(this,q,Na).call(this,s,r)}),await i.waitForOpen(),O(this,Ee,await Mp(i,{onUpdate:g(this,Zo),onExtNotification:g(this,bi)})),O(this,Nn,cu(g(this,Ee))),this.isLoadingHistory=!0;try{const s=$(this,q,di).call(this),r=await g(this,Ee).loadSession({sessionId:e.sessionId,cwd:e.cwd,...s&&{_meta:s}});$(this,q,Oo).call(this,r)}finally{this.isLoadingHistory=!1,$(this,q,It).call(this,"idle")}O(this,be,e.sessionId),this.sessionTitle=e.title??this.sessionTitle,await us(n,g(this,be)).catch(()=>{}),$(this,q,Ve).call(this,"connected")}catch(n){const o=n instanceof Error?n.message:String(n);this.error=`loadSession failed: ${o}`,$(this,q,It).call(this,"idle"),$(this,q,Ve).call(this,"error"),$(this,q,gs).call(this)}});Z(this,"reconnect",async()=>{g(this,be)===null||this.cwd===null||Y(g(this,Nt))===null||($(this,q,Ma).call(this),O(this,nn,!1),this.reconnectAttempt=0,await g(this,Ai).call(this))});Z(this,"attachToLiveAgent",async e=>{this.error=null,g(this,vt)&&(await g(this,vt).closeAndWait(),O(this,Ee,null),O(this,vt,null)),O(this,be,e.sessionId),this.cwd=e.cwd,te(g(this,Nt),e.cliKind,!0),this.sessionTitle="",await g(this,Ho).call(this,e.agentId)||(this.error="reconnect failed: agent no longer available",$(this,q,Ve).call(this,"error"))});Z(this,"switchSession",async e=>{if(g(this,Ee)===null)return this.loadSession(e);if(this.status!=="connected")throw new Error(`cannot switchSession in status ${this.status}`);$(this,q,ms).call(this),$(this,q,Ve).call(this,"connecting"),this.error=null,this.bubbles=[];try{this.isLoadingHistory=!0;try{const n=$(this,q,di).call(this),o=await g(this,Ee).loadSession({sessionId:e.sessionId,cwd:e.cwd,...n&&{_meta:n}});$(this,q,Oo).call(this,o)}finally{this.isLoadingHistory=!1,$(this,q,It).call(this,"idle")}O(this,be,e.sessionId),this.cwd=e.cwd,this.sessionTitle=e.title??this.sessionTitle,this.agentId&&await us(this.agentId,e.sessionId,{replace:!0}).catch(()=>{}),$(this,q,Ve).call(this,"connected")}catch(n){const o=n instanceof Error?n.message:String(n);this.error=`switchSession failed: ${o}`,$(this,q,It).call(this,"idle"),$(this,q,Ve).call(this,"error")}});Z(this,"newSession",async e=>{const n=e.cwd??this.cwd;if(g(this,Ee)===null){if(!n)throw new Error("newSession: no cwd available for fallback attach");return this.attach({cwd:n,cliKind:e.cliKind})}if(this.status!=="connected")throw new Error(`cannot newSession in status ${this.status}`);if(!n)throw new Error("newSession: no cwd");$(this,q,Ve).call(this,"connecting"),this.error=null,this.bubbles=[],this.sessionTitle="";try{const o=$(this,q,di).call(this),i=await g(this,Ee).newSession({cwd:n,...o&&{_meta:o}}),s=i.sessionId??null;if(!s)throw new Error("newSession returned no sessionId");O(this,be,s),this.cwd=n,$(this,q,Oo).call(this,i),this.agentId&&await us(this.agentId,s,{replace:!0}).catch(()=>{}),$(this,q,Ve).call(this,"connected"),await $(this,q,Bu).call(this)}catch(o){const i=o instanceof Error?o.message:String(o);this.error=`newSession failed: ${i}`,$(this,q,Ve).call(this,"error")}});Z(this,"applyConfigOption",async(e,n)=>{if(this.status!=="connected"||!g(this,Ee)||!g(this,be))return;const o=await g(this,vl).call(this,e,n),i=Y(g(this,Nt));o&&g(this,Vo)&&i&&g(this,Vo).setLastConfig(i,e,n)});D(this,vl,async(e,n)=>{if(this.configOptions.find(i=>i.id===e)){const i=await g(this,Ee).setSessionConfigOption({sessionId:g(this,be),configId:e,value:n});return this.configOptions=i.configOptions,!0}if(e==="model"&&typeof n=="string"){const i=this.configOptions.find(s=>s.category==="model");if(i){const s=await g(this,Ee).setSessionConfigOption({sessionId:g(this,be),configId:i.id,value:n});return this.configOptions=s.configOptions,!0}return await g(this,Ee).setSessionModel({sessionId:g(this,be),modelId:n}),this.models&&(this.models={...this.models,currentModelId:n}),!0}if(e==="mode"&&typeof n=="string"){const i=this.configOptions.find(s=>s.category==="mode");if(i){const s=await g(this,Ee).setSessionConfigOption({sessionId:g(this,be),configId:i.id,value:n});return this.configOptions=s.configOptions,!0}return await g(this,Ee).setSessionMode({sessionId:g(this,be),modeId:n}),this.modes&&(this.modes={...this.modes,currentModeId:n}),!0}return console.warn(`[AgentSession] configId "${e}" not available — skipping`),!1});Z(this,"setThinkingTokens",async e=>{this.status==="connected"&&(!g(this,Nn)||!g(this,be)||await g(this,Nn).setThinkingTokens(g(this,be),e))});Z(this,"listSessions",async(e=!1)=>{if(g(this,Ee)!==null&&!this.sessionsLoading&&!(g(this,io)&&!e)){this.sessionsLoading=!0,this.sessionsError=null;try{const o=(await g(this,Ee).listSessions()).sessions??[];this.sessions=o.map(RN),O(this,io,!0)}catch(n){n.code===-32601?(this.sessions=[],O(this,io,!0)):this.sessionsError=n instanceof Error?n.message:String(n)}finally{this.sessionsLoading=!1}}});Z(this,"cancelTurn",async()=>{if(this.turnState!=="idle"&&!(!g(this,Ee)||!g(this,be))){try{await g(this,Ee).cancel(g(this,be))}catch{}$(this,q,It).call(this,"idle")}});D(this,kc,async(e,n)=>{try{const o=await fetch(`/fixtures/${e}.json`);if(!o.ok)throw new Error(`fixture "${e}" not found (${o.status})`);const i=await o.json();this.cwd=n,O(this,be,`mock:${e}`),this.sessionTitle=`🧪 ${e}`,i.loadResult&&$(this,q,Oo).call(this,i.loadResult);const s=new URLSearchParams(typeof location<"u"?location.search:""),r=Number(s.get("stream")??"0")||0;$(this,q,ms).call(this),this.isLoadingHistory=!0;try{for(const a of i.updates)g(this,Zo).call(this,{update:a}),r>0&&await new Promise(u=>setTimeout(u,r));await VI()}finally{this.isLoadingHistory=!1,$(this,q,It).call(this,"idle")}this.status="connected"}catch(o){const i=o instanceof Error?o.message:String(o);this.error=`mock loadSession failed: ${i}`,$(this,q,It).call(this,"idle"),this.status="error"}});D(this,bi,(e,n)=>{if(e==="_claude/sdkMessage"){O(this,Si,g(this,Si)+1);return}e==="_drive/capabilities"&&O(this,qo,n)});D(this,Zo,e=>{var s,r;const n=e.update;if(n.sessionUpdate==="tool_call"){$(this,q,Ky).call(this,n);return}if(n.sessionUpdate==="tool_call_update"){$(this,q,Yy).call(this,n);return}if(n.sessionUpdate==="current_mode_update"){const a=n.currentModeId;typeof a=="string"&&(this.modes={availableModes:((s=this.modes)==null?void 0:s.availableModes)??[],currentModeId:a});return}if(n.sessionUpdate==="config_option_update"){const a=n.configOptions;Array.isArray(a)&&(this.configOptions=a);return}if(n.sessionUpdate==="available_commands_update"){const a=n.availableCommands;this.availableCommands=Array.isArray(a)?a:[];return}const o=n.messageId??null;if(n.sessionUpdate==="user_message_chunk"){const a=n.content;if((a==null?void 0:a.type)==="text")$(this,q,xa).call(this,"user",a.text??"",o);else if((a==null?void 0:a.type)==="image"&&a.data!==void 0&&a.mimeType!==void 0)$(this,q,Xy).call(this,o,{mimeType:a.mimeType,data:a.data});else if((a==null?void 0:a.type)==="resource_link"){const u=a.name??a.uri;$(this,q,Ju).call(this,o,{kind:"resource_link",label:u})}else{const u=(a==null?void 0:a.type)==="audio"?"audio":"resource";$(this,q,Ju).call(this,o,{kind:u})}return}const i=((r=n.content)==null?void 0:r.type)==="text"?n.content.text??"":"";i&&(n.sessionUpdate==="agent_message_chunk"?($(this,q,It).call(this,"responding"),g(this,Pn)&&$(this,q,hs).call(this),$(this,q,xa).call(this,"message",i,o)):n.sessionUpdate==="agent_thought_chunk"&&($(this,q,It).call(this,"thinking"),g(this,Pn)&&$(this,q,hs).call(this),$(this,q,xa).call(this,"thought",i,o)))});O(this,Ii,e==null?void 0:e.cues),O(this,Vo,e==null?void 0:e.settings),typeof document<"u"&&(O(this,Ci,document.hidden),document.addEventListener("visibilitychange",()=>{O(this,Ci,document.hidden)}))}get status(){return Y(g(this,qs))}set status(e){te(g(this,qs),e,!0)}get turnState(){return Y(g(this,Bs))}set turnState(e){te(g(this,Bs),e,!0)}get error(){return Y(g(this,Hs))}set error(e){te(g(this,Hs),e,!0)}get bubbles(){return Y(g(this,Zs))}set bubbles(e){te(g(this,Zs),e,!0)}get agentId(){return Y(g(this,Js))}set agentId(e){te(g(this,Js),e,!0)}get cwd(){return Y(g(this,Ws))}set cwd(e){te(g(this,Ws),e,!0)}get reconnectAttempt(){return Y(g(this,Ks))}set reconnectAttempt(e){te(g(this,Ks),e,!0)}get isLoadingHistory(){return Y(g(this,Ys))}set isLoadingHistory(e){te(g(this,Ys),e,!0)}get lastUserMessage(){return Y(g(this,Xs))}set lastUserMessage(e){te(g(this,Xs),e,!0)}get configOptions(){return Y(g(this,Qs))}set configOptions(e){te(g(this,Qs),e,!0)}get models(){return Y(g(this,js))}set models(e){te(g(this,js),e,!0)}get modes(){return Y(g(this,er))}set modes(e){te(g(this,er),e,!0)}get availableCommands(){return Y(g(this,tr))}set availableCommands(e){te(g(this,tr),e,!0)}get sessionTitle(){return Y(g(this,nr))}set sessionTitle(e){te(g(this,nr),e,!0)}get supportsImageInput(){var e,n,o;return((o=(n=(e=g(this,Ee))==null?void 0:e.capabilities)==null?void 0:n.promptCapabilities)==null?void 0:o.image)===!0}get capabilities(){return g(this,qo)}get claudeRawSdkMessageCount(){return g(this,Si)}get supports(){return g(this,qo)??{mcp:!1,compact:!1,commands:!1,usage:!1,configOptions:!1,rename:!1,thinkingTokens:!1}}get ext(){return g(this,Nn)}get sessions(){return Y(g(this,or))}set sessions(e){te(g(this,or),e,!0)}get sessionsLoading(){return Y(g(this,ir))}set sessionsLoading(e){te(g(this,ir),e,!0)}get sessionsError(){return Y(g(this,sr))}set sessionsError(e){te(g(this,sr),e,!0)}_setStatusForTest(e){$(this,q,Ve).call(this,e)}_setReconnectAttemptForTest(e){this.reconnectAttempt=e}_setTearingDownForTest(e){O(this,Mn,e)}_wouldReconnectOnCloseForTest(e){return g(this,Zt)||g(this,Mn)?!1:e!==1e3&&e!==1001}_setTransportForTest(e){O(this,vt,e)}_setSessionContextForTest(e){O(this,be,e.sessionId),this.cwd=e.cwd,te(g(this,Nt),e.cliKind,!0)}_mockFindReusableAgentForTest(e){O(this,ar,async()=>e)}_mockColdReconnectForTest(e){O(this,ur,async()=>{throw e})}_mockWarmReconnectForTest(e){O(this,Ho,async n=>(e&&$(this,q,Ve).call(this,"connected"),e))}_mockWarmReconnectCapturingStateForTest(e){O(this,Ho,async n=>{const o=e(this);return o&&$(this,q,Ve).call(this,"connected"),o})}_getSessionIdForTest(){return g(this,be)}_doReconnectForTest(){return g(this,Ai).call(this)}get bypassActive(){var o;const e=this.configOptions.find(i=>i.category==="mode"),n=e&&e.type==="select"?e.currentValue:void 0;return xN(Y(g(this,Nt)),n??((o=this.modes)==null?void 0:o.currentModeId))}get cliKind(){return Y(g(this,Nt))}recentAssistantMessages(e=3){const n=[];for(let o=this.bubbles.length-1;o>=0&&n.length<e;o--){const i=this.bubbles[o];(i==null?void 0:i.kind)==="message"&&n.unshift(i.segments.map(s=>s.text).join(""))}return n}};Ii=new WeakMap,Vo=new WeakMap,qs=new WeakMap,Bs=new WeakMap,Hs=new WeakMap,Zs=new WeakMap,Js=new WeakMap,Ws=new WeakMap,Ks=new WeakMap,Ys=new WeakMap,Xs=new WeakMap,Qs=new WeakMap,js=new WeakMap,er=new WeakMap,tr=new WeakMap,nr=new WeakMap,or=new WeakMap,ir=new WeakMap,sr=new WeakMap,io=new WeakMap,Pn=new WeakMap,Ht=new WeakMap,fl=new WeakMap,q=new WeakSet,hs=function(){g(this,Ht)!==null&&clearTimeout(g(this,Ht)),O(this,Ht,setTimeout(()=>{O(this,Ht,null),$(this,q,It).call(this,"idle")},g(this,fl)))},ms=function(){O(this,Pn,!1),g(this,Ht)!==null&&(clearTimeout(g(this,Ht)),O(this,Ht,null))},Ee=new WeakMap,Nn=new WeakMap,qo=new WeakMap,Si=new WeakMap,vt=new WeakMap,be=new WeakMap,rr=new WeakMap,Zt=new WeakMap,Mn=new WeakMap,Nt=new WeakMap,Ci=new WeakMap,Bo=new WeakMap,nn=new WeakMap,ar=new WeakMap,hl=new WeakMap,ml=new WeakMap,gl=new WeakMap,lr=new WeakMap,Na=function(e,n){if(this.error=`WS closed (${e}): ${n||"no reason"}`,g(this,Ci)){$(this,q,Ve).call(this,"disconnected");return}$(this,q,Zy).call(this)},Zy=function(){g(this,nn)||(O(this,nn,!0),this.reconnectAttempt=0,$(this,q,Ve).call(this,"disconnected"),$(this,q,Jy).call(this))},Jy=async function(){for(;this.reconnectAttempt<g(_n,hl);){const e=this.reconnectAttempt,n=g(_n,ml)[e]??16e3;if(this.reconnectAttempt=e+1,await new Promise(o=>{O(this,Bo,setTimeout(o,n))}),g(this,Zt)){O(this,nn,!1);return}try{await g(this,Ai).call(this)}catch{}if(this.status==="connected"){O(this,nn,!1),this.reconnectAttempt=0;return}}O(this,nn,!1),$(this,q,Ve).call(this,"disconnected")},Ma=function(){g(this,Bo)!==void 0&&(clearTimeout(g(this,Bo)),O(this,Bo,void 0))},Ai=new WeakMap,ur=new WeakMap,Ho=new WeakMap,vl=new WeakMap,Wy=function(e,n){if(e==="mode"&&this.modes)return typeof n=="string"&&this.modes.availableModes.some(i=>i.id===n);if(e==="model"&&this.models)return typeof n=="string"&&this.models.availableModels.some(i=>i.modelId===n);const o=this.configOptions.find(i=>i.id===e||i.category===e);return o?o.type==="select"&&typeof n=="string"?o.options.flatMap(s=>"options"in s&&s.options?s.options:[s]).some(s=>s.value===n):o.type==="boolean"?typeof n=="boolean":!0:!1},Bu=async function(){var o;const e=Y(g(this,Nt)),n=e?(o=g(this,Vo))==null?void 0:o.lastConfig[e]:void 0;if(n)for(const[i,s]of Object.entries(n))$(this,q,Wy).call(this,i,s)&&await this.applyConfigOption(i,s)},di=function(){return Y(g(this,Nt))==="claude"?ON:void 0},Ve=function(e){var o;const n=this.status;e!==n&&(this.status=e,e==="error"&&((o=g(this,Ii))==null||o.play("error")))},It=function(e){var o;const n=this.turnState;e!==n&&(this.turnState=e,n==="idle"&&e==="waiting"&&((o=g(this,Ii))==null||o.play("thinking")))},Oo=function(e){this.configOptions=e.configOptions??[],this.models=e.models??null,this.modes=e.modes??null,this.availableCommands=[]},gs=function(e){var o;const n=this.agentId;g(this,Ht)!==null&&(clearTimeout(g(this,Ht)),O(this,Ht,null)),e!=null&&e.keepAgent&&g(this,vt)&&g(this,vt).sendRaw(`${JSON.stringify({jsonrpc:"2.0",method:"$/detach"})}
25
+ `);try{(o=g(this,Ee))==null||o.close()}catch{}O(this,Ee,null),O(this,Nn,null),O(this,qo,null),O(this,Si,0),O(this,vt,null),O(this,be,null),this.agentId=null,!(e!=null&&e.keepAgent)&&n&&Ou(n).catch(()=>{})},Hu=function(e){if(!Array.isArray(e))return[];const n=[];for(const o of e){if(typeof o!="object"||o===null)continue;const i=o.type;if(i==="content"){const s=o.content;if((s==null?void 0:s.type)==="text"&&typeof s.text=="string")n.push({type:"text",text:s.text});else if((s==null?void 0:s.type)==="image"&&typeof s.data=="string"&&typeof s.mimeType=="string"&&s.mimeType.startsWith("image/")){const r=s;n.push({type:"image",data:r.data,mimeType:r.mimeType})}else if((s==null?void 0:s.type)==="resource"){const r=s.resource;typeof(r==null?void 0:r.blob)=="string"&&typeof r.mimeType=="string"&&r.mimeType.startsWith("image/")?n.push({type:"image",data:r.blob,mimeType:r.mimeType}):n.push({type:"other",raw:o})}else n.push({type:"other",raw:o})}else if(i==="diff"){const s=o;typeof s.path=="string"&&typeof s.newText=="string"?n.push({type:"diff",path:s.path,oldText:s.oldText??void 0,newText:s.newText}):n.push({type:"other",raw:o})}else if(i==="terminal"){const s=o;typeof s.terminalId=="string"?n.push({type:"terminal",terminalId:s.terminalId}):n.push({type:"other",raw:o})}else n.push({type:"other",raw:o})}return n},Zu=function(e){if(!Array.isArray(e))return[];const n=[];for(const o of e){if(typeof o!="object"||o===null)continue;const i=o;typeof i.path=="string"&&n.push({path:i.path,line:i.line})}return n},kc=new WeakMap,bi=new WeakMap,Zo=new WeakMap,Ky=function(e){if(e.toolCallId===void 0)return;const n={id:crypto.randomUUID(),kind:"tool",messageId:null,createdAt:Date.now(),toolCall:{toolCallId:e.toolCallId,name:e.kind??e.title??"tool",kind:e.kind,args:e.rawInput??{},status:e.status??"pending",title:e.title,narration:void 0,result:e.rawOutput,content:e.content!=null?$(this,q,Hu).call(this,e.content):void 0,locations:e.locations!=null?$(this,q,Zu).call(this,e.locations):void 0},segments:[]};this.bubbles.push(n),g(this,rr).set(e.toolCallId,n),$(this,q,It).call(this,"calling-tool"),g(this,Pn)&&$(this,q,hs).call(this)},Yy=function(e){if(e.toolCallId===void 0)return;(e.status==="pending"||e.status==="in_progress")&&($(this,q,It).call(this,"calling-tool"),g(this,Pn)&&$(this,q,hs).call(this));const n=this.bubbles.findIndex(s=>s.kind==="tool"&&s.toolCall.toolCallId===e.toolCallId);if(n===-1)return;const o=this.bubbles[n],i={...o.toolCall,...e.status!==void 0&&{status:e.status},...e.rawInput!==void 0&&{args:e.rawInput},...e.rawOutput!==void 0&&{result:e.rawOutput},...e.kind!==void 0&&{kind:e.kind},...e.title!==void 0&&{title:e.title},...e.content!==void 0&&{content:e.content===null?void 0:$(this,q,Hu).call(this,e.content)},...e.locations!==void 0&&{locations:e.locations===null?void 0:$(this,q,Zu).call(this,e.locations)}};this.bubbles[n]={...o,toolCall:i},g(this,rr).set(e.toolCallId,this.bubbles[n])},xa=function(e,n,o){const i=this.bubbles[this.bubbles.length-1];if(i!==void 0&&i.kind===e&&(o!==null?i.messageId===o:i.messageId===null)&&i!==void 0){const r={id:crypto.randomUUID(),text:n};(i.kind==="message"||i.kind==="thought"||i.kind==="user")&&i.segments.push(r)}else{const r=e==="message"?{id:crypto.randomUUID(),kind:"message",messageId:o,createdAt:Date.now(),segments:[{id:crypto.randomUUID(),text:n}]}:e==="thought"?{id:crypto.randomUUID(),kind:"thought",messageId:o,createdAt:Date.now(),segments:[{id:crypto.randomUUID(),text:n}]}:{id:crypto.randomUUID(),kind:"user",messageId:o,createdAt:Date.now(),segments:[{id:crypto.randomUUID(),text:n}]};this.bubbles.push(r)}},Xy=function(e,n){const o=this.bubbles[this.bubbles.length-1],i=o!==void 0&&o.kind==="user"&&(e!==null?o.messageId===e:o.messageId===null),s={mimeType:n.mimeType,dataBase64:n.data};if(i&&o!==void 0){const r=o;r.attachments=[...r.attachments??[],s]}else{const r={id:crypto.randomUUID(),kind:"user",messageId:e,createdAt:Date.now(),segments:[],attachments:[s]};this.bubbles.push(r)}},Ju=function(e,n){const o=this.bubbles[this.bubbles.length-1];if(o!==void 0&&o.kind==="user"&&(e!==null?o.messageId===e:o.messageId===null)&&o!==void 0){const s=o;s.contentPlaceholders=[...s.contentPlaceholders??[],n]}else{const s={id:crypto.randomUUID(),kind:"user",messageId:e,createdAt:Date.now(),segments:[],contentPlaceholders:[n]};this.bubbles.push(s)}},D(_n,hl,5),D(_n,ml,[1e3,2e3,4e3,8e3,16e3]),D(_n,gl,250),D(_n,lr,3);let qu=_n;function LN(t){const e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n}function Qy(t){let e="";for(let o=0;o<t.length;o+=8192)e+=String.fromCharCode(...t.subarray(o,o+8192));return btoa(e)}async function GN(t){const e=new Uint8Array(await t.arrayBuffer()),n=Qy(e),o=t.type||"audio/webm",i=await fetch("/api/recordings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audioBase64:n,mimeType:o})});if(!i.ok)throw new Error(`saveRecording: ${i.status} ${i.statusText}`);return{id:(await i.json()).id}}function zN(t){return`/api/recordings/${encodeURIComponent(t)}`}function FN(t,e){return new Promise(n=>{e.src=zN(t);const o=()=>{e.removeEventListener("ended",o),e.removeEventListener("error",i),n()},i=()=>{e.removeEventListener("ended",o),e.removeEventListener("error",i),n()};e.addEventListener("ended",o),e.addEventListener("error",i),e.play().catch(()=>n())})}async function VN(t,e,n){const o=`${n}|${e}|${t}`,i=new TextEncoder().encode(o),s=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(s)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function jy(t){const e=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}const qN=`Examples:
26
+ - Tool: read README.md → "אני בודק את ה-README כדי לראות מה הפרויקט"
27
+ - Tool: execute bash "ls" → "אני מציץ מה יש בתיקייה"
28
+ - Tool: edit hello.js → "מעדכן את הפונקציה שדיברנו עליה"
29
+ - Tool: execute "npm run build" → "מריץ build לראות שאין שגיאות"`;function BN(t,e){const n=t.recentMessages.length?t.recentMessages.join(" · "):"—";return`You are narrating a coding assistant's actions out loud in Hebrew.
30
+ Given the user's request and recent context, describe in ONE short
31
+ conversational Hebrew sentence what the assistant is about to do —
32
+ and WHY in this context. Don't list parameters; explain the intent.
33
+ Don't repeat the user's words verbatim.
34
+
35
+ ${qN}
36
+
37
+ User said: "${t.userMessage}"
38
+ Recent assistant context: ${n}
39
+
40
+ Tool: ${e.kind??"?"} — ${e.title}
41
+
42
+ Output ONLY the Hebrew sentence (no quotes, no markdown).`}const HN=/[.!?]\s*$|\n\s*$/;function ZN(t,e={}){const n=e.minChars??20,o=e.maxChars??200,i=e.locale??"he";if(t=t.replace(/[‎‏‪-‮⁦-⁩]/g,""),t.length===0)return{sentences:[],remaining:""};const s=new Intl.Segmenter(i,{granularity:"sentence"}),r=t.split(/\n{2,}/);r.length>1;const a=[];let u="";for(let p=0;p<r.length;p++){const f=r[p]??"";if(f.length===0){a.push([]);continue}const h=p===r.length-1,m=[];for(const _ of s.segment(f))m.push(_.segment);const v=[];for(let _=0;_<m.length;_++){const w=_===m.length-1,C=m[_]??"";h&&w?HN.test(C)?v.push(C):u=C:v.push(C)}a.push(v)}const c=[];for(const p of a){const f=p.map(v=>v.trim()).filter(v=>v.length>0),h=[];let m=null;for(let v=0;v<f.length;v++){const _=f[v]??"",w=m===null?_:`${m} ${_}`;w.length<n&&v+1<f.length?m=w:(h.push(w),m=null)}for(const v of h)if(v.length<=o)c.push(v);else for(const _ of JN(v,o,i))c.push(_)}return u=u.replace(/^\s+/,""),{sentences:c,remaining:u}}function JN(t,e,n){const o=new Intl.Segmenter(n,{granularity:"word"}),i=[];let s="";for(const r of o.segment(t)){const a=r.segment;(s+a).length>e&&s.trim().length>0?(i.push(s.trim()),s=a.replace(/^\s+/,"")):s+=a}return s.trim().length>0&&i.push(s.trim()),i}function WN(t,e){return`תרגם את הטקסט הבא לעברית טבעית ושוטפת, ללא הסברים. אם הטקסט כבר בעברית — החזר אותו כמו שהוא.
43
+
44
+ טקסט:
45
+ ${t}`}async function KN(t,e){if(!t)return{};const n=`narrate:${t}`,o={type:"narrate",toolCallId:t,createdAt:Date.now()};return e!==void 0&&(o.toolKind=e),{"x-cache-key":n,"x-cache-meta":JSON.stringify(o)}}async function YN(t,e,n){if(!t)return{};const o=await jy(`${t}|${e}`),i=`translate:${o}`,s={type:"translate",textHash:o,targetLang:e,createdAt:Date.now()};return n!==null&&(s.messageId=n),{"x-cache-key":i,"x-cache-meta":JSON.stringify(s)}}async function XN(t,e,n,o){if(!t||!e)return{};const i=await jy(`${t}|${n}`),s=`tts:${e}:${i}`,r={type:"tts",voiceId:e,textHash:i,createdAt:Date.now()};return o!==null&&(r.messageId=o),{"x-cache-key":s,"x-cache-meta":JSON.stringify(r)}}const QN=1e4,jN={format:"mp3",async synthesize(t){const e=t.modelId??"eleven_v3",n=await XN(t.text,t.voiceId,e,t.messageId??null),o=await Ln(i=>fetch(An(`/proxy/elevenlabs/v1/text-to-speech/${t.voiceId}/stream`),{method:"POST",headers:{"xi-api-key":"browser-placeholder","content-type":"application/json",accept:"audio/mpeg",...n},body:JSON.stringify({text:t.text,model_id:e,voice_settings:{stability:.5,similarity_boost:.75}}),signal:i}),QN,{signal:t.signal,label:"tts-connect"});if(!o.ok){const i=await o.text().catch(()=>"");throw new Error(`TTS failed: ${o.status} ${i}`)}if(!o.body)throw new Error("TTS: no body in response");return o.body}};var e_="vercel.ai.error",eM=Symbol.for(e_),xp,Dp,de=class t_ extends(Dp=Error,xp=eM,Dp){constructor({name:e,message:n,cause:o}){super(n),this[xp]=!0,this.name=e,this.cause=o}static isInstance(e){return t_.hasMarker(e,e_)}static hasMarker(e,n){const o=Symbol.for(n);return e!=null&&typeof e=="object"&&o in e&&typeof e[o]=="boolean"&&e[o]===!0}},n_="AI_APICallError",o_=`vercel.ai.error.${n_}`,tM=Symbol.for(o_),$p,Up,rt=class extends(Up=de,$p=tM,Up){constructor({message:t,url:e,requestBodyValues:n,statusCode:o,responseHeaders:i,responseBody:s,cause:r,isRetryable:a=o!=null&&(o===408||o===409||o===429||o>=500),data:u}){super({name:n_,message:t,cause:r}),this[$p]=!0,this.url=e,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=i,this.responseBody=s,this.isRetryable=a,this.data=u}static isInstance(t){return de.hasMarker(t,o_)}},i_="AI_EmptyResponseBodyError",s_=`vercel.ai.error.${i_}`,nM=Symbol.for(s_),Op,Lp,oM=class extends(Lp=de,Op=nM,Lp){constructor({message:t="Empty response body"}={}){super({name:i_,message:t}),this[Op]=!0}static isInstance(t){return de.hasMarker(t,s_)}};function ta(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var r_="AI_InvalidArgumentError",a_=`vercel.ai.error.${r_}`,iM=Symbol.for(a_),Gp,zp,l_=class extends(zp=de,Gp=iM,zp){constructor({message:e,cause:n,argument:o}){super({name:r_,message:e,cause:n}),this[Gp]=!0,this.argument=o}static isInstance(e){return de.hasMarker(e,a_)}},u_="AI_InvalidPromptError",c_=`vercel.ai.error.${u_}`,sM=Symbol.for(c_),Fp,Vp,Do=class extends(Vp=de,Fp=sM,Vp){constructor({prompt:t,message:e,cause:n}){super({name:u_,message:`Invalid prompt: ${e}`,cause:n}),this[Fp]=!0,this.prompt=t}static isInstance(t){return de.hasMarker(t,c_)}},d_="AI_JSONParseError",p_=`vercel.ai.error.${d_}`,rM=Symbol.for(p_),qp,Bp,bs=class extends(Bp=de,qp=rM,Bp){constructor({text:t,cause:e}){super({name:d_,message:`JSON parsing failed: Text: ${t}.
46
+ Error message: ${ta(e)}`,cause:e}),this[qp]=!0,this.text=t}static isInstance(t){return de.hasMarker(t,p_)}},f_="AI_LoadAPIKeyError",h_=`vercel.ai.error.${f_}`,aM=Symbol.for(h_),Hp,Zp,va=class extends(Zp=de,Hp=aM,Zp){constructor({message:t}){super({name:f_,message:t}),this[Hp]=!0}static isInstance(t){return de.hasMarker(t,h_)}},m_="AI_TooManyEmbeddingValuesForCallError",g_=`vercel.ai.error.${m_}`,lM=Symbol.for(g_),Jp,Wp,uM=class extends(Wp=de,Jp=lM,Wp){constructor(t){super({name:m_,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[Jp]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return de.hasMarker(t,g_)}},v_="AI_TypeValidationError",y_=`vercel.ai.error.${v_}`,cM=Symbol.for(y_),Kp,Yp,Ot=class Wu extends(Yp=de,Kp=cM,Yp){constructor({value:e,cause:n,context:o}){let i="Type validation failed";if(o!=null&&o.field&&(i+=` for ${o.field}`),o!=null&&o.entityName||o!=null&&o.entityId){i+=" (";const s=[];o.entityName&&s.push(o.entityName),o.entityId&&s.push(`id: "${o.entityId}"`),i+=s.join(", "),i+=")"}super({name:v_,message:`${i}: Value: ${JSON.stringify(e)}.
47
+ Error message: ${ta(n)}`,cause:n}),this[Kp]=!0,this.value=e,this.context=o}static isInstance(e){return de.hasMarker(e,y_)}static wrap({value:e,cause:n,context:o}){var i,s,r;return Wu.isInstance(n)&&n.value===e&&((i=n.context)==null?void 0:i.field)===(o==null?void 0:o.field)&&((s=n.context)==null?void 0:s.entityName)===(o==null?void 0:o.entityName)&&((r=n.context)==null?void 0:r.entityId)===(o==null?void 0:o.entityId)?n:new Wu({value:e,cause:n,context:o})}},__="AI_UnsupportedFunctionalityError",T_=`vercel.ai.error.${__}`,dM=Symbol.for(T_),Xp,Qp,Vi=class extends(Qp=de,Xp=dM,Qp){constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:__,message:e}),this[Xp]=!0,this.functionality=t}static isInstance(t){return de.hasMarker(t,T_)}};function Ha(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"?!0:Array.isArray(t)?t.every(Ha):typeof t=="object"?Object.entries(t).every(([e,n])=>typeof e=="string"&&(n===void 0||Ha(n))):!1}function jp(t){return Array.isArray(t)&&t.every(Ha)}function Za(t){return t!=null&&typeof t=="object"&&Object.entries(t).every(([e,n])=>typeof e=="string"&&(n===void 0||Ha(n)))}var ef;function F(t,e,n){function o(a,u){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:u,constr:r,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,u);const c=r.prototype,p=Object.keys(c);for(let f=0;f<p.length;f++){const h=p[f];h in a||(a[h]=c[h].bind(a))}}const i=(n==null?void 0:n.Parent)??Object;class s extends i{}Object.defineProperty(s,"name",{value:t});function r(a){var u;const c=n!=null&&n.Parent?new s:this;o(c,a),(u=c._zod).deferred??(u.deferred=[]);for(const p of c._zod.deferred)p();return c}return Object.defineProperty(r,"init",{value:o}),Object.defineProperty(r,Symbol.hasInstance,{value:a=>{var u,c;return n!=null&&n.Parent&&a instanceof n.Parent?!0:(c=(u=a==null?void 0:a._zod)==null?void 0:u.traits)==null?void 0:c.has(t)}}),Object.defineProperty(r,"name",{value:t}),r}class yi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class E_ extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(ef=globalThis).__zod_globalConfig??(ef.__zod_globalConfig={});const Jc=globalThis.__zod_globalConfig;function Jn(t){return Jc}function w_(t){const e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,i])=>e.indexOf(+o)===-1).map(([o,i])=>i)}function Ku(t,e){return typeof e=="bigint"?e.toString():e}function Ll(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Wc(t){return t==null}function Kc(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function pM(t,e){const n=t/e,o=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-o)<i?0:n-o}const tf=Symbol("evaluating");function ke(t,e,n){let o;Object.defineProperty(t,e,{get(){if(o!==tf)return o===void 0&&(o=tf,o=n()),o},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function ri(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ro(...t){const e={};for(const n of t){const o=Object.getOwnPropertyDescriptors(n);Object.assign(e,o)}return Object.defineProperties({},e)}function nf(t){return JSON.stringify(t)}function fM(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const I_="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Rs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const hM=Ll(()=>{var t;if(Jc.jitless||typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function qi(t){if(Rs(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const n=e.prototype;return!(Rs(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function S_(t){return qi(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}const mM=new Set(["string","number","symbol"]);function Bi(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ko(t,e,n){const o=new t._zod.constr(e??t._zod.def);return(!e||n!=null&&n.parent)&&(o._zod.parent=t),o}function ie(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function gM(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const vM={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function yM(t,e){const n=t._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=Ro(t._zod.def,{get shape(){const r={};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(r[a]=n.shape[a])}return ri(this,"shape",r),r},checks:[]});return ko(t,s)}function _M(t,e){const n=t._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=Ro(t._zod.def,{get shape(){const r={...t._zod.def.shape};for(const a in e){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete r[a]}return ri(this,"shape",r),r},checks:[]});return ko(t,s)}function TM(t,e){if(!qi(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0){const s=t._zod.def.shape;for(const r in e)if(Object.getOwnPropertyDescriptor(s,r)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Ro(t._zod.def,{get shape(){const s={...t._zod.def.shape,...e};return ri(this,"shape",s),s}});return ko(t,i)}function EM(t,e){if(!qi(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Ro(t._zod.def,{get shape(){const o={...t._zod.def.shape,...e};return ri(this,"shape",o),o}});return ko(t,n)}function wM(t,e){var o;if((o=t._zod.def.checks)!=null&&o.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Ro(t._zod.def,{get shape(){const i={...t._zod.def.shape,...e._zod.def.shape};return ri(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return ko(t,n)}function IM(t,e,n){const i=e._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const r=Ro(e._zod.def,{get shape(){const a=e._zod.def.shape,u={...a};if(n)for(const c in n){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);n[c]&&(u[c]=t?new t({type:"optional",innerType:a[c]}):a[c])}else for(const c in a)u[c]=t?new t({type:"optional",innerType:a[c]}):a[c];return ri(this,"shape",u),u},checks:[]});return ko(e,r)}function SM(t,e,n){const o=Ro(e._zod.def,{get shape(){const i=e._zod.def.shape,s={...i};if(n)for(const r in n){if(!(r in s))throw new Error(`Unrecognized key: "${r}"`);n[r]&&(s[r]=new t({type:"nonoptional",innerType:i[r]}))}else for(const r in i)s[r]=new t({type:"nonoptional",innerType:i[r]});return ri(this,"shape",s),s}});return ko(e,o)}function hi(t,e=0){var n;if(t.aborted===!0)return!0;for(let o=e;o<t.issues.length;o++)if(((n=t.issues[o])==null?void 0:n.continue)!==!0)return!0;return!1}function CM(t,e=0){var n;if(t.aborted===!0)return!0;for(let o=e;o<t.issues.length;o++)if(((n=t.issues[o])==null?void 0:n.continue)===!1)return!0;return!1}function mi(t,e){return e.map(n=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(t),n})}function ya(t){return typeof t=="string"?t:t==null?void 0:t.message}function Wn(t,e,n){var u,c,p,f,h,m;const o=t.message?t.message:ya((p=(c=(u=t.inst)==null?void 0:u._zod.def)==null?void 0:c.error)==null?void 0:p.call(c,t))??ya((f=e==null?void 0:e.error)==null?void 0:f.call(e,t))??ya((h=n.customError)==null?void 0:h.call(n,t))??ya((m=n.localeError)==null?void 0:m.call(n,t))??"Invalid input",{inst:i,continue:s,input:r,...a}=t;return a.path??(a.path=[]),a.message=o,e!=null&&e.reportInput&&(a.input=r),a}function Yc(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function ks(...t){const[e,n,o]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:o}:{...e}}const C_=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Ku,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},A_=F("$ZodError",C_),b_=F("$ZodError",C_,{Parent:Error});function AM(t,e=n=>n.message){const n={},o=[];for(const i of t.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(e(i))):o.push(e(i));return{formErrors:o,fieldErrors:n}}function bM(t,e=n=>n.message){const n={_errors:[]},o=(i,s=[])=>{for(const r of i.issues)if(r.code==="invalid_union"&&r.errors.length)r.errors.map(a=>o({issues:a},[...s,...r.path]));else if(r.code==="invalid_key")o({issues:r.issues},[...s,...r.path]);else if(r.code==="invalid_element")o({issues:r.issues},[...s,...r.path]);else{const a=[...s,...r.path];if(a.length===0)n._errors.push(e(r));else{let u=n,c=0;for(;c<a.length;){const p=a[c];c===a.length-1?(u[p]=u[p]||{_errors:[]},u[p]._errors.push(e(r))):u[p]=u[p]||{_errors:[]},u=u[p],c++}}}};return o(t),n}const Xc=t=>(e,n,o,i)=>{const s=o?{...o,async:!1}:{async:!1},r=e._zod.run({value:n,issues:[]},s);if(r instanceof Promise)throw new yi;if(r.issues.length){const a=new((i==null?void 0:i.Err)??t)(r.issues.map(u=>Wn(u,s,Jn())));throw I_(a,i==null?void 0:i.callee),a}return r.value},Qc=t=>async(e,n,o,i)=>{const s=o?{...o,async:!0}:{async:!0};let r=e._zod.run({value:n,issues:[]},s);if(r instanceof Promise&&(r=await r),r.issues.length){const a=new((i==null?void 0:i.Err)??t)(r.issues.map(u=>Wn(u,s,Jn())));throw I_(a,i==null?void 0:i.callee),a}return r.value},Gl=t=>(e,n,o)=>{const i=o?{...o,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new yi;return s.issues.length?{success:!1,error:new(t??A_)(s.issues.map(r=>Wn(r,i,Jn())))}:{success:!0,data:s.value}},RM=Gl(b_),zl=t=>async(e,n,o)=>{const i=o?{...o,async:!0}:{async:!0};let s=e._zod.run({value:n,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(r=>Wn(r,i,Jn())))}:{success:!0,data:s.value}},kM=zl(b_),PM=t=>(e,n,o)=>{const i=o?{...o,direction:"backward"}:{direction:"backward"};return Xc(t)(e,n,i)},NM=t=>(e,n,o)=>Xc(t)(e,n,o),MM=t=>async(e,n,o)=>{const i=o?{...o,direction:"backward"}:{direction:"backward"};return Qc(t)(e,n,i)},xM=t=>async(e,n,o)=>Qc(t)(e,n,o),DM=t=>(e,n,o)=>{const i=o?{...o,direction:"backward"}:{direction:"backward"};return Gl(t)(e,n,i)},$M=t=>(e,n,o)=>Gl(t)(e,n,o),UM=t=>async(e,n,o)=>{const i=o?{...o,direction:"backward"}:{direction:"backward"};return zl(t)(e,n,i)},OM=t=>async(e,n,o)=>zl(t)(e,n,o),LM=/^[cC][0-9a-z]{6,}$/,GM=/^[0-9a-z]+$/,zM=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,FM=/^[0-9a-vA-V]{20}$/,VM=/^[A-Za-z0-9]{27}$/,qM=/^[a-zA-Z0-9_-]{21}$/,BM=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,HM=/^([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})$/,of=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,ZM=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,JM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function WM(){return new RegExp(JM,"u")}const KM=/^(?:(?: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])$/,YM=/^(([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}|:))$/,XM=/^((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])$/,QM=/^(([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])$/,jM=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,R_=/^[A-Za-z0-9_-]*$/,ex=/^https?$/,tx=/^\+[1-9]\d{6,14}$/,k_="(?:(?:\\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])))",nx=new RegExp(`^${k_}$`);function P_(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ox(t){return new RegExp(`^${P_(t)}$`)}function ix(t){const e=P_({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const o=`${e}(?:${n.join("|")})`;return new RegExp(`^${k_}T(?:${o})$`)}const sx=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},rx=/^-?\d+$/,N_=/^-?\d+(?:\.\d+)?$/,ax=/^(?:true|false)$/i,lx=/^null$/i,ux=/^[^A-Z]*$/,cx=/^[^a-z]*$/,Ft=F("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),M_={number:"number",bigint:"bigint",object:"date"},x_=F("$ZodCheckLessThan",(t,e)=>{Ft.init(t,e);const n=M_[typeof e.value];t._zod.onattach.push(o=>{const i=o._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),D_=F("$ZodCheckGreaterThan",(t,e)=>{Ft.init(t,e);const n=M_[typeof e.value];t._zod.onattach.push(o=>{const i=o._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),dx=F("$ZodCheckMultipleOf",(t,e)=>{Ft.init(t,e),t._zod.onattach.push(n=>{var o;(o=n._zod.bag).multipleOf??(o.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):pM(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),px=F("$ZodCheckNumberFormat",(t,e)=>{var r;Ft.init(t,e),e.format=e.format||"float64";const n=(r=e.format)==null?void 0:r.includes("int"),o=n?"int":"number",[i,s]=vM[e.format];t._zod.onattach.push(a=>{const u=a._zod.bag;u.format=e.format,u.minimum=i,u.maximum=s,n&&(u.pattern=rx)}),t._zod.check=a=>{const u=a.value;if(n){if(!Number.isInteger(u)){a.issues.push({expected:o,format:e.format,code:"invalid_type",continue:!1,input:u,inst:t});return}if(!Number.isSafeInteger(u)){u>0?a.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort}):a.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort});return}}u<i&&a.issues.push({origin:"number",input:u,code:"too_small",minimum:i,inclusive:!0,inst:t,continue:!e.abort}),u>s&&a.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}}),fx=F("$ZodCheckMaxLength",(t,e)=>{var n;Ft.init(t,e),(n=t._zod.def).when??(n.when=o=>{const i=o.value;return!Wc(i)&&i.length!==void 0}),t._zod.onattach.push(o=>{const i=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(o._zod.bag.maximum=e.maximum)}),t._zod.check=o=>{const i=o.value;if(i.length<=e.maximum)return;const r=Yc(i);o.issues.push({origin:r,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),hx=F("$ZodCheckMinLength",(t,e)=>{var n;Ft.init(t,e),(n=t._zod.def).when??(n.when=o=>{const i=o.value;return!Wc(i)&&i.length!==void 0}),t._zod.onattach.push(o=>{const i=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{const i=o.value;if(i.length>=e.minimum)return;const r=Yc(i);o.issues.push({origin:r,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),mx=F("$ZodCheckLengthEquals",(t,e)=>{var n;Ft.init(t,e),(n=t._zod.def).when??(n.when=o=>{const i=o.value;return!Wc(i)&&i.length!==void 0}),t._zod.onattach.push(o=>{const i=o._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=o=>{const i=o.value,s=i.length;if(s===e.length)return;const r=Yc(i),a=s>e.length;o.issues.push({origin:r,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),Fl=F("$ZodCheckStringFormat",(t,e)=>{var n,o;Ft.init(t,e),t._zod.onattach.push(i=>{const s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),gx=F("$ZodCheckRegex",(t,e)=>{Fl.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),vx=F("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ux),Fl.init(t,e)}),yx=F("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=cx),Fl.init(t,e)}),_x=F("$ZodCheckIncludes",(t,e)=>{Ft.init(t,e);const n=Bi(e.includes),o=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=o,t._zod.onattach.push(i=>{const s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(o)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),Tx=F("$ZodCheckStartsWith",(t,e)=>{Ft.init(t,e);const n=new RegExp(`^${Bi(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=o=>{o.value.startsWith(e.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:o.value,inst:t,continue:!e.abort})}}),Ex=F("$ZodCheckEndsWith",(t,e)=>{Ft.init(t,e);const n=new RegExp(`.*${Bi(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=o=>{o.value.endsWith(e.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:o.value,inst:t,continue:!e.abort})}}),wx=F("$ZodCheckOverwrite",(t,e)=>{Ft.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class Ix{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const o=e.split(`
48
+ `).filter(r=>r),i=Math.min(...o.map(r=>r.length-r.trimStart().length)),s=o.map(r=>r.slice(i)).map(r=>" ".repeat(this.indent*2)+r);for(const r of s)this.content.push(r)}compile(){const e=Function,n=this==null?void 0:this.args,i=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new e(...n,i.join(`
49
+ `))}}const Sx={major:4,minor:4,patch:3},Ke=F("$ZodType",(t,e)=>{var i;var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Sx;const o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(const s of o)for(const r of s._zod.onattach)r(t);if(o.length===0)(n=t._zod).deferred??(n.deferred=[]),(i=t._zod.deferred)==null||i.push(()=>{t._zod.run=t._zod.parse});else{const s=(a,u,c)=>{let p=hi(a),f;for(const h of u){if(h._zod.def.when){if(CM(a)||!h._zod.def.when(a))continue}else if(p)continue;const m=a.issues.length,v=h._zod.check(a);if(v instanceof Promise&&(c==null?void 0:c.async)===!1)throw new yi;if(f||v instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await v,a.issues.length!==m&&(p||(p=hi(a,m)))});else{if(a.issues.length===m)continue;p||(p=hi(a,m))}}return f?f.then(()=>a):a},r=(a,u,c)=>{if(hi(a))return a.aborted=!0,a;const p=s(u,o,c);if(p instanceof Promise){if(c.async===!1)throw new yi;return p.then(f=>t._zod.parse(f,c))}return t._zod.parse(p,c)};t._zod.run=(a,u)=>{if(u.skipChecks)return t._zod.parse(a,u);if(u.direction==="backward"){const p=t._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});return p instanceof Promise?p.then(f=>r(f,a,u)):r(p,a,u)}const c=t._zod.parse(a,u);if(c instanceof Promise){if(u.async===!1)throw new yi;return c.then(p=>s(p,o,u))}return s(c,o,u)}}ke(t,"~standard",()=>({validate:s=>{var r;try{const a=RM(t,s);return a.success?{value:a.data}:{issues:(r=a.error)==null?void 0:r.issues}}catch{return kM(t,s).then(u=>{var c;return u.success?{value:u.data}:{issues:(c=u.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}))}),jc=F("$ZodString",(t,e)=>{var n;Ke.init(t,e),t._zod.pattern=[...((n=t==null?void 0:t._zod.bag)==null?void 0:n.patterns)??[]].pop()??sx(t._zod.bag),t._zod.parse=(o,i)=>{if(e.coerce)try{o.value=String(o.value)}catch{}return typeof o.value=="string"||o.issues.push({expected:"string",code:"invalid_type",input:o.value,inst:t}),o}}),et=F("$ZodStringFormat",(t,e)=>{Fl.init(t,e),jc.init(t,e)}),Cx=F("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=HM),et.init(t,e)}),Ax=F("$ZodUUID",(t,e)=>{if(e.version){const o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(o===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=of(o))}else e.pattern??(e.pattern=of());et.init(t,e)}),bx=F("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=ZM),et.init(t,e)}),Rx=F("$ZodURL",(t,e)=>{et.init(t,e),t._zod.check=n=>{var o;try{const i=n.value.trim();if(!e.normalize&&((o=e.protocol)==null?void 0:o.source)===ex.source&&!/^https?:\/\//i.test(i)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:t,continue:!e.abort});return}const s=new URL(i);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=s.href:n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),kx=F("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=WM()),et.init(t,e)}),Px=F("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=qM),et.init(t,e)}),Nx=F("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=LM),et.init(t,e)}),Mx=F("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=GM),et.init(t,e)}),xx=F("$ZodULID",(t,e)=>{e.pattern??(e.pattern=zM),et.init(t,e)}),Dx=F("$ZodXID",(t,e)=>{e.pattern??(e.pattern=FM),et.init(t,e)}),$x=F("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=VM),et.init(t,e)}),Ux=F("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=ix(e)),et.init(t,e)}),Ox=F("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=nx),et.init(t,e)}),Lx=F("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=ox(e)),et.init(t,e)}),Gx=F("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=BM),et.init(t,e)}),zx=F("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=KM),et.init(t,e),t._zod.bag.format="ipv4"}),Fx=F("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=YM),et.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Vx=F("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=XM),et.init(t,e)}),qx=F("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=QM),et.init(t,e),t._zod.check=n=>{const o=n.value.split("/");try{if(o.length!==2)throw new Error;const[i,s]=o;if(!s)throw new Error;const r=Number(s);if(`${r}`!==s)throw new Error;if(r<0||r>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function $_(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Bx=F("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=jM),et.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{$_(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function Hx(t){if(!R_.test(t))return!1;const e=t.replace(/[-_]/g,o=>o==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return $_(n)}const Zx=F("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=R_),et.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{Hx(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Jx=F("$ZodE164",(t,e)=>{e.pattern??(e.pattern=tx),et.init(t,e)});function Wx(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[o]=n;if(!o)return!1;const i=JSON.parse(atob(o));return!("typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}const Kx=F("$ZodJWT",(t,e)=>{et.init(t,e),t._zod.check=n=>{Wx(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),U_=F("$ZodNumber",(t,e)=>{Ke.init(t,e),t._zod.pattern=t._zod.bag.pattern??N_,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...s?{received:s}:{}}),n}}),Yx=F("$ZodNumberFormat",(t,e)=>{px.init(t,e),U_.init(t,e)}),Xx=F("$ZodBoolean",(t,e)=>{Ke.init(t,e),t._zod.pattern=ax,t._zod.parse=(n,o)=>{if(e.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),n}}),Qx=F("$ZodNull",(t,e)=>{Ke.init(t,e),t._zod.pattern=lx,t._zod.values=new Set([null]),t._zod.parse=(n,o)=>{const i=n.value;return i===null||n.issues.push({expected:"null",code:"invalid_type",input:i,inst:t}),n}}),jx=F("$ZodAny",(t,e)=>{Ke.init(t,e),t._zod.parse=n=>n}),eD=F("$ZodUnknown",(t,e)=>{Ke.init(t,e),t._zod.parse=n=>n}),tD=F("$ZodNever",(t,e)=>{Ke.init(t,e),t._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function sf(t,e,n){t.issues.length&&e.issues.push(...mi(n,t.issues)),e.value[n]=t.value}const nD=F("$ZodArray",(t,e)=>{Ke.init(t,e),t._zod.parse=(n,o)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),n;n.value=Array(i.length);const s=[];for(let r=0;r<i.length;r++){const a=i[r],u=e.element._zod.run({value:a,issues:[]},o);u instanceof Promise?s.push(u.then(c=>sf(c,n,r))):sf(u,n,r)}return s.length?Promise.all(s).then(()=>n):n}});function Ja(t,e,n,o,i,s){const r=n in o;if(t.issues.length){if(i&&s&&!r)return;e.issues.push(...mi(n,t.issues))}if(!r&&!i){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?r&&(e.value[n]=void 0):e.value[n]=t.value}function O_(t){var o,i,s,r;const e=Object.keys(t.shape);for(const a of e)if(!((r=(s=(i=(o=t.shape)==null?void 0:o[a])==null?void 0:i._zod)==null?void 0:s.traits)!=null&&r.has("$ZodType")))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const n=gM(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function L_(t,e,n,o,i,s){const r=[],a=i.keySet,u=i.catchall._zod,c=u.def.type,p=u.optin==="optional",f=u.optout==="optional";for(const h in e){if(h==="__proto__"||a.has(h))continue;if(c==="never"){r.push(h);continue}const m=u.run({value:e[h],issues:[]},o);m instanceof Promise?t.push(m.then(v=>Ja(v,n,h,e,p,f))):Ja(m,n,h,e,p,f)}return r.length&&n.issues.push({code:"unrecognized_keys",keys:r,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}const oD=F("$ZodObject",(t,e)=>{Ke.init(t,e);const n=Object.getOwnPropertyDescriptor(e,"shape");if(!(n!=null&&n.get)){const a=e.shape;Object.defineProperty(e,"shape",{get:()=>{const u={...a};return Object.defineProperty(e,"shape",{value:u}),u}})}const o=Ll(()=>O_(e));ke(t._zod,"propValues",()=>{const a=e.shape,u={};for(const c in a){const p=a[c]._zod;if(p.values){u[c]??(u[c]=new Set);for(const f of p.values)u[c].add(f)}}return u});const i=Rs,s=e.catchall;let r;t._zod.parse=(a,u)=>{r??(r=o.value);const c=a.value;if(!i(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:t}),a;a.value={};const p=[],f=r.shape;for(const h of r.keys){const m=f[h],v=m._zod.optin==="optional",_=m._zod.optout==="optional",w=m._zod.run({value:c[h],issues:[]},u);w instanceof Promise?p.push(w.then(C=>Ja(C,a,h,c,v,_))):Ja(w,a,h,c,v,_)}return s?L_(p,c,a,u,o.value,t):p.length?Promise.all(p).then(()=>a):a}}),iD=F("$ZodObjectJIT",(t,e)=>{oD.init(t,e);const n=t._zod.parse,o=Ll(()=>O_(e)),i=h=>{var A,R;const m=new Ix(["shape","payload","ctx"]),v=o.value,_=k=>{const b=nf(k);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};m.write("const input = payload.value;");const w=Object.create(null);let C=0;for(const k of v.keys)w[k]=`key_${C++}`;m.write("const newResult = {};");for(const k of v.keys){const b=w[k],U=nf(k),J=h[k],G=((A=J==null?void 0:J._zod)==null?void 0:A.optin)==="optional",L=((R=J==null?void 0:J._zod)==null?void 0:R.optout)==="optional";m.write(`const ${b} = ${_(k)};`),G&&L?m.write(`
50
+ if (${b}.issues.length) {
51
+ if (${U} in input) {
52
+ payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
53
+ ...iss,
54
+ path: iss.path ? [${U}, ...iss.path] : [${U}]
55
+ })));
56
+ }
57
+ }
58
+
59
+ if (${b}.value === undefined) {
60
+ if (${U} in input) {
61
+ newResult[${U}] = undefined;
62
+ }
63
+ } else {
64
+ newResult[${U}] = ${b}.value;
65
+ }
66
+
67
+ `):G?m.write(`
68
+ if (${b}.issues.length) {
69
+ payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
70
+ ...iss,
71
+ path: iss.path ? [${U}, ...iss.path] : [${U}]
72
+ })));
73
+ }
74
+
75
+ if (${b}.value === undefined) {
76
+ if (${U} in input) {
77
+ newResult[${U}] = undefined;
78
+ }
79
+ } else {
80
+ newResult[${U}] = ${b}.value;
81
+ }
82
+
83
+ `):m.write(`
84
+ const ${b}_present = ${U} in input;
85
+ if (${b}.issues.length) {
86
+ payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
87
+ ...iss,
88
+ path: iss.path ? [${U}, ...iss.path] : [${U}]
89
+ })));
90
+ }
91
+ if (!${b}_present && !${b}.issues.length) {
92
+ payload.issues.push({
93
+ code: "invalid_type",
94
+ expected: "nonoptional",
95
+ input: undefined,
96
+ path: [${U}]
97
+ });
98
+ }
99
+
100
+ if (${b}_present) {
101
+ if (${b}.value === undefined) {
102
+ newResult[${U}] = undefined;
103
+ } else {
104
+ newResult[${U}] = ${b}.value;
105
+ }
106
+ }
107
+
108
+ `)}m.write("payload.value = newResult;"),m.write("return payload;");const E=m.compile();return(k,b)=>E(h,k,b)};let s;const r=Rs,a=!Jc.jitless,c=a&&hM.value,p=e.catchall;let f;t._zod.parse=(h,m)=>{f??(f=o.value);const v=h.value;return r(v)?a&&c&&(m==null?void 0:m.async)===!1&&m.jitless!==!0?(s||(s=i(e.shape)),h=s(h,m),p?L_([],v,h,m,f,t):h):n(h,m):(h.issues.push({expected:"object",code:"invalid_type",input:v,inst:t}),h)}});function rf(t,e,n,o){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;const i=t.filter(s=>!hi(s));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(r=>Wn(r,o,Jn())))}),e)}const G_=F("$ZodUnion",(t,e)=>{Ke.init(t,e),ke(t._zod,"optin",()=>e.options.some(o=>o._zod.optin==="optional")?"optional":void 0),ke(t._zod,"optout",()=>e.options.some(o=>o._zod.optout==="optional")?"optional":void 0),ke(t._zod,"values",()=>{if(e.options.every(o=>o._zod.values))return new Set(e.options.flatMap(o=>Array.from(o._zod.values)))}),ke(t._zod,"pattern",()=>{if(e.options.every(o=>o._zod.pattern)){const o=e.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>Kc(i.source)).join("|")})$`)}});const n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(o,i)=>{if(n)return n(o,i);let s=!1;const r=[];for(const a of e.options){const u=a._zod.run({value:o.value,issues:[]},i);if(u instanceof Promise)r.push(u),s=!0;else{if(u.issues.length===0)return u;r.push(u)}}return s?Promise.all(r).then(a=>rf(a,o,t,i)):rf(r,o,t,i)}}),sD=F("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,G_.init(t,e);const n=t._zod.parse;ke(t._zod,"propValues",()=>{const i={};for(const s of e.options){const r=s._zod.propValues;if(!r||Object.keys(r).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(const[a,u]of Object.entries(r)){i[a]||(i[a]=new Set);for(const c of u)i[a].add(c)}}return i});const o=Ll(()=>{var r;const i=e.options,s=new Map;for(const a of i){const u=(r=a._zod.propValues)==null?void 0:r[e.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(const c of u){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,a)}}return s});t._zod.parse=(i,s)=>{const r=i.value;if(!Rs(r))return i.issues.push({code:"invalid_type",expected:"object",input:r,inst:t}),i;const a=o.value.get(r==null?void 0:r[e.discriminator]);return a?a._zod.run(i,s):e.unionFallback||s.direction==="backward"?n(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(o.value.keys()),input:r,path:[e.discriminator],inst:t}),i)}}),rD=F("$ZodIntersection",(t,e)=>{Ke.init(t,e),t._zod.parse=(n,o)=>{const i=n.value,s=e.left._zod.run({value:i,issues:[]},o),r=e.right._zod.run({value:i,issues:[]},o);return s instanceof Promise||r instanceof Promise?Promise.all([s,r]).then(([u,c])=>af(n,u,c)):af(n,s,r)}});function Yu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(qi(t)&&qi(e)){const n=Object.keys(e),o=Object.keys(t).filter(s=>n.indexOf(s)!==-1),i={...t,...e};for(const s of o){const r=Yu(t[s],e[s]);if(!r.valid)return{valid:!1,mergeErrorPath:[s,...r.mergeErrorPath]};i[s]=r.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let o=0;o<t.length;o++){const i=t[o],s=e[o],r=Yu(i,s);if(!r.valid)return{valid:!1,mergeErrorPath:[o,...r.mergeErrorPath]};n.push(r.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function af(t,e,n){const o=new Map;let i;for(const a of e.issues)if(a.code==="unrecognized_keys"){i??(i=a);for(const u of a.keys)o.has(u)||o.set(u,{}),o.get(u).l=!0}else t.issues.push(a);for(const a of n.issues)if(a.code==="unrecognized_keys")for(const u of a.keys)o.has(u)||o.set(u,{}),o.get(u).r=!0;else t.issues.push(a);const s=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&i&&t.issues.push({...i,keys:s}),hi(t))return t;const r=Yu(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}const aD=F("$ZodRecord",(t,e)=>{Ke.init(t,e),t._zod.parse=(n,o)=>{const i=n.value;if(!qi(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),n;const s=[],r=e.keyType._zod.values;if(r){n.value={};const a=new Set;for(const c of r)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);const p=e.keyType._zod.run({value:c,issues:[]},o);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(m=>Wn(m,o,Jn())),input:c,path:[c],inst:t});continue}const f=p.value,h=e.valueType._zod.run({value:i[c],issues:[]},o);h instanceof Promise?s.push(h.then(m=>{m.issues.length&&n.issues.push(...mi(c,m.issues)),n.value[f]=m.value})):(h.issues.length&&n.issues.push(...mi(c,h.issues)),n.value[f]=h.value)}let u;for(const c in i)a.has(c)||(u=u??[],u.push(c));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:u})}else{n.value={};for(const a of Reflect.ownKeys(i)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,a))continue;let u=e.keyType._zod.run({value:a,issues:[]},o);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&N_.test(a)&&u.issues.length){const f=e.keyType._zod.run({value:Number(a),issues:[]},o);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");f.issues.length===0&&(u=f)}if(u.issues.length){e.mode==="loose"?n.value[a]=i[a]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(f=>Wn(f,o,Jn())),input:a,path:[a],inst:t});continue}const p=e.valueType._zod.run({value:i[a],issues:[]},o);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&n.issues.push(...mi(a,f.issues)),n.value[u.value]=f.value})):(p.issues.length&&n.issues.push(...mi(a,p.issues)),n.value[u.value]=p.value)}}return s.length?Promise.all(s).then(()=>n):n}}),lD=F("$ZodEnum",(t,e)=>{Ke.init(t,e);const n=w_(e.entries),o=new Set(n);t._zod.values=o,t._zod.pattern=new RegExp(`^(${n.filter(i=>mM.has(typeof i)).map(i=>typeof i=="string"?Bi(i):i.toString()).join("|")})$`),t._zod.parse=(i,s)=>{const r=i.value;return o.has(r)||i.issues.push({code:"invalid_value",values:n,input:r,inst:t}),i}}),uD=F("$ZodLiteral",(t,e)=>{if(Ke.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(o=>typeof o=="string"?Bi(o):o?Bi(o.toString()):String(o)).join("|")})$`),t._zod.parse=(o,i)=>{const s=o.value;return n.has(s)||o.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),o}}),cD=F("$ZodTransform",(t,e)=>{Ke.init(t,e),t._zod.optin="optional",t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new E_(t.constructor.name);const i=e.transform(n.value,n);if(o.async)return(i instanceof Promise?i:Promise.resolve(i)).then(r=>(n.value=r,n.fallback=!0,n));if(i instanceof Promise)throw new yi;return n.value=i,n.fallback=!0,n}});function lf(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}const z_=F("$ZodOptional",(t,e)=>{Ke.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ke(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Kc(n.source)})?$`):void 0}),t._zod.parse=(n,o)=>{if(e.innerType._zod.optin==="optional"){const i=n.value,s=e.innerType._zod.run(n,o);return s instanceof Promise?s.then(r=>lf(r,i)):lf(s,i)}return n.value===void 0?n:e.innerType._zod.run(n,o)}}),dD=F("$ZodExactOptional",(t,e)=>{z_.init(t,e),ke(t._zod,"values",()=>e.innerType._zod.values),ke(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,o)=>e.innerType._zod.run(n,o)}),pD=F("$ZodNullable",(t,e)=>{Ke.init(t,e),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Kc(n.source)}|null)$`):void 0}),ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,o)=>n.value===null?n:e.innerType._zod.run(n,o)}),fD=F("$ZodDefault",(t,e)=>{Ke.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);if(n.value===void 0)return n.value=e.defaultValue,n;const i=e.innerType._zod.run(n,o);return i instanceof Promise?i.then(s=>uf(s,e)):uf(i,e)}});function uf(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const hD=F("$ZodPrefault",(t,e)=>{Ke.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>(o.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,o))}),mD=F("$ZodNonOptional",(t,e)=>{Ke.init(t,e),ke(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(o=>o!==void 0)):void 0}),t._zod.parse=(n,o)=>{const i=e.innerType._zod.run(n,o);return i instanceof Promise?i.then(s=>cf(s,t)):cf(i,t)}});function cf(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const gD=F("$ZodCatch",(t,e)=>{Ke.init(t,e),t._zod.optin="optional",ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);const i=e.innerType._zod.run(n,o);return i instanceof Promise?i.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(r=>Wn(r,o,Jn()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(s=>Wn(s,o,Jn()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),vD=F("$ZodPipe",(t,e)=>{Ke.init(t,e),ke(t._zod,"values",()=>e.in._zod.values),ke(t._zod,"optin",()=>e.in._zod.optin),ke(t._zod,"optout",()=>e.out._zod.optout),ke(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,o)=>{if(o.direction==="backward"){const s=e.out._zod.run(n,o);return s instanceof Promise?s.then(r=>_a(r,e.in,o)):_a(s,e.in,o)}const i=e.in._zod.run(n,o);return i instanceof Promise?i.then(s=>_a(s,e.out,o)):_a(i,e.out,o)}});function _a(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}const yD=F("$ZodReadonly",(t,e)=>{Ke.init(t,e),ke(t._zod,"propValues",()=>e.innerType._zod.propValues),ke(t._zod,"values",()=>e.innerType._zod.values),ke(t._zod,"optin",()=>{var n,o;return(o=(n=e.innerType)==null?void 0:n._zod)==null?void 0:o.optin}),ke(t._zod,"optout",()=>{var n,o;return(o=(n=e.innerType)==null?void 0:n._zod)==null?void 0:o.optout}),t._zod.parse=(n,o)=>{if(o.direction==="backward")return e.innerType._zod.run(n,o);const i=e.innerType._zod.run(n,o);return i instanceof Promise?i.then(df):df(i)}});function df(t){return t.value=Object.freeze(t.value),t}const _D=F("$ZodLazy",(t,e)=>{Ke.init(t,e),ke(t._zod,"innerType",()=>{const n=e;return n._cachedInner||(n._cachedInner=e.getter()),n._cachedInner}),ke(t._zod,"pattern",()=>{var n,o;return(o=(n=t._zod.innerType)==null?void 0:n._zod)==null?void 0:o.pattern}),ke(t._zod,"propValues",()=>{var n,o;return(o=(n=t._zod.innerType)==null?void 0:n._zod)==null?void 0:o.propValues}),ke(t._zod,"optin",()=>{var n,o;return((o=(n=t._zod.innerType)==null?void 0:n._zod)==null?void 0:o.optin)??void 0}),ke(t._zod,"optout",()=>{var n,o;return((o=(n=t._zod.innerType)==null?void 0:n._zod)==null?void 0:o.optout)??void 0}),t._zod.parse=(n,o)=>t._zod.innerType._zod.run(n,o)}),TD=F("$ZodCustom",(t,e)=>{Ft.init(t,e),Ke.init(t,e),t._zod.parse=(n,o)=>n,t._zod.check=n=>{const o=n.value,i=e.fn(o);if(i instanceof Promise)return i.then(s=>pf(s,n,o,t));pf(i,n,o,t)}});function pf(t,e,n,o){if(!t){const i={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(i.params=o._zod.def.params),e.issues.push(ks(i))}}var ff;class ED{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){const o=n[0];return this._map.set(e,o),o&&typeof o=="object"&&"id"in o&&this._idmap.set(o.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const o={...this.get(n)??{}};delete o.id;const i={...o,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function wD(){return new ED}(ff=globalThis).__zod_globalRegistry??(ff.__zod_globalRegistry=wD());const vs=globalThis.__zod_globalRegistry;function ID(t,e){return new t({type:"string",...ie(e)})}function SD(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ie(e)})}function hf(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ie(e)})}function CD(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ie(e)})}function AD(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ie(e)})}function bD(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ie(e)})}function RD(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ie(e)})}function kD(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ie(e)})}function PD(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ie(e)})}function ND(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ie(e)})}function MD(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ie(e)})}function xD(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ie(e)})}function DD(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ie(e)})}function $D(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ie(e)})}function UD(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ie(e)})}function OD(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ie(e)})}function LD(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ie(e)})}function GD(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ie(e)})}function zD(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ie(e)})}function FD(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ie(e)})}function VD(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ie(e)})}function qD(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ie(e)})}function BD(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ie(e)})}function HD(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ie(e)})}function ZD(t,e){return new t({type:"string",format:"date",check:"string_format",...ie(e)})}function JD(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ie(e)})}function WD(t,e){return new t({type:"string",format:"duration",check:"string_format",...ie(e)})}function KD(t,e){return new t({type:"number",checks:[],...ie(e)})}function YD(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ie(e)})}function XD(t,e){return new t({type:"boolean",...ie(e)})}function QD(t,e){return new t({type:"null",...ie(e)})}function jD(t){return new t({type:"any"})}function e$(t){return new t({type:"unknown"})}function t$(t,e){return new t({type:"never",...ie(e)})}function mf(t,e){return new x_({check:"less_than",...ie(e),value:t,inclusive:!1})}function du(t,e){return new x_({check:"less_than",...ie(e),value:t,inclusive:!0})}function gf(t,e){return new D_({check:"greater_than",...ie(e),value:t,inclusive:!1})}function pu(t,e){return new D_({check:"greater_than",...ie(e),value:t,inclusive:!0})}function vf(t,e){return new dx({check:"multiple_of",...ie(e),value:t})}function F_(t,e){return new fx({check:"max_length",...ie(e),maximum:t})}function Wa(t,e){return new hx({check:"min_length",...ie(e),minimum:t})}function V_(t,e){return new mx({check:"length_equals",...ie(e),length:t})}function n$(t,e){return new gx({check:"string_format",format:"regex",...ie(e),pattern:t})}function o$(t){return new vx({check:"string_format",format:"lowercase",...ie(t)})}function i$(t){return new yx({check:"string_format",format:"uppercase",...ie(t)})}function s$(t,e){return new _x({check:"string_format",format:"includes",...ie(e),includes:t})}function r$(t,e){return new Tx({check:"string_format",format:"starts_with",...ie(e),prefix:t})}function a$(t,e){return new Ex({check:"string_format",format:"ends_with",...ie(e),suffix:t})}function ji(t){return new wx({check:"overwrite",tx:t})}function l$(t){return ji(e=>e.normalize(t))}function u$(){return ji(t=>t.trim())}function c$(){return ji(t=>t.toLowerCase())}function d$(){return ji(t=>t.toUpperCase())}function p$(){return ji(t=>fM(t))}function f$(t,e,n){return new t({type:"array",element:e,...ie(n)})}function h$(t,e,n){const o=ie(n);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function m$(t,e,n){return new t({type:"custom",check:"custom",fn:e,...ie(n)})}function g$(t,e){const n=v$(o=>(o.addIssue=i=>{if(typeof i=="string")o.issues.push(ks(i,o.value,n._zod.def));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=o.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),o.issues.push(ks(s))}},t(o.value,o)),e);return n}function v$(t,e){const n=new Ft({check:"custom",...ie(e)});return n._zod.check=t,n}function Ka(t){let e=(t==null?void 0:t.target)??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:(t==null?void 0:t.metadata)??vs,target:e,unrepresentable:(t==null?void 0:t.unrepresentable)??"throw",override:(t==null?void 0:t.override)??(()=>{}),io:(t==null?void 0:t.io)??"output",counter:0,seen:new Map,cycles:(t==null?void 0:t.cycles)??"ref",reused:(t==null?void 0:t.reused)??"inline",external:(t==null?void 0:t.external)??void 0}}function We(t,e,n={path:[],schemaPath:[]}){var p,f;var o;const i=t._zod.def,s=e.seen.get(t);if(s)return s.count++,n.schemaPath.includes(t)&&(s.cycle=n.path),s.schema;const r={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,r);const a=(f=(p=t._zod).toJSONSchema)==null?void 0:f.call(p);if(a)r.schema=a;else{const h={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,r.schema,h);else{const v=r.schema,_=e.processors[i.type];if(!_)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);_(t,e,v,h)}const m=t._zod.parent;m&&(r.ref||(r.ref=m),We(m,e,h),e.seen.get(m).isParent=!0)}const u=e.metadataRegistry.get(t);return u&&Object.assign(r.schema,u),e.io==="input"&&Pt(t)&&(delete r.schema.examples,delete r.schema.default),e.io==="input"&&"_prefault"in r.schema&&((o=r.schema).default??(o.default=r.schema._prefault)),delete r.schema._prefault,e.seen.get(t).schema}function Ya(t,e){var r,a,u,c;const n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=new Map;for(const p of t.seen.entries()){const f=(r=t.metadataRegistry.get(p[0]))==null?void 0:r.id;if(f){const h=o.get(f);if(h&&h!==p[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(f,p[0])}}const i=p=>{var _;const f=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const w=(_=t.external.registry.get(p[0]))==null?void 0:_.id,C=t.external.uri??(A=>A);if(w)return{ref:C(w)};const E=p[1].defId??p[1].schema.id??`schema${t.counter++}`;return p[1].defId=E,{defId:E,ref:`${C("__shared")}#/${f}/${E}`}}if(p[1]===n)return{ref:"#"};const m=`#/${f}/`,v=p[1].schema.id??`__schema${t.counter++}`;return{defId:v,ref:m+v}},s=p=>{if(p[1].schema.$ref)return;const f=p[1],{ref:h,defId:m}=i(p);f.def={...f.schema},m&&(f.defId=m);const v=f.schema;for(const _ in v)delete v[_];v.$ref=h};if(t.cycles==="throw")for(const p of t.seen.entries()){const f=p[1];if(f.cycle)throw new Error(`Cycle detected: #/${(a=f.cycle)==null?void 0:a.join("/")}/<root>
109
+
110
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const p of t.seen.entries()){const f=p[1];if(e===p[0]){s(p);continue}if(t.external){const m=(u=t.external.registry.get(p[0]))==null?void 0:u.id;if(e!==p[0]&&m){s(p);continue}}if((c=t.metadataRegistry.get(p[0]))==null?void 0:c.id){s(p);continue}if(f.cycle){s(p);continue}if(f.count>1&&t.reused==="ref"){s(p);continue}}}function Xa(t,e){var a,u,c,p;const n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=f=>{const h=t.seen.get(f);if(h.ref===null)return;const m=h.def??h.schema,v={...m},_=h.ref;if(h.ref=null,_){o(_);const C=t.seen.get(_),E=C.schema;if(E.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(E)):Object.assign(m,E),Object.assign(m,v),f._zod.parent===_)for(const R in m)R==="$ref"||R==="allOf"||R in v||delete m[R];if(E.$ref&&C.def)for(const R in m)R==="$ref"||R==="allOf"||R in C.def&&JSON.stringify(m[R])===JSON.stringify(C.def[R])&&delete m[R]}const w=f._zod.parent;if(w&&w!==_){o(w);const C=t.seen.get(w);if(C!=null&&C.schema.$ref&&(m.$ref=C.schema.$ref,C.def))for(const E in m)E==="$ref"||E==="allOf"||E in C.def&&JSON.stringify(m[E])===JSON.stringify(C.def[E])&&delete m[E]}t.override({zodSchema:f,jsonSchema:m,path:h.path??[]})};for(const f of[...t.seen.entries()].reverse())o(f[0]);const i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,(a=t.external)!=null&&a.uri){const f=(u=t.external.registry.get(e))==null?void 0:u.id;if(!f)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(f)}Object.assign(i,n.def??n.schema);const s=(c=t.metadataRegistry.get(e))==null?void 0:c.id;s!==void 0&&i.id===s&&delete i.id;const r=((p=t.external)==null?void 0:p.defs)??{};for(const f of t.seen.entries()){const h=f[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,r[h.defId]=h.def)}t.external||Object.keys(r).length>0&&(t.target==="draft-2020-12"?i.$defs=r:i.definitions=r);try{const f=JSON.parse(JSON.stringify(i));return Object.defineProperty(f,"~standard",{value:{...e["~standard"],jsonSchema:{input:Qa(e,"input",t.processors),output:Qa(e,"output",t.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function Pt(t,e){const n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);const o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Pt(o.element,n);if(o.type==="set")return Pt(o.valueType,n);if(o.type==="lazy")return Pt(o.getter(),n);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Pt(o.innerType,n);if(o.type==="intersection")return Pt(o.left,n)||Pt(o.right,n);if(o.type==="record"||o.type==="map")return Pt(o.keyType,n)||Pt(o.valueType,n);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Pt(o.in,n)||Pt(o.out,n);if(o.type==="object"){for(const i in o.shape)if(Pt(o.shape[i],n))return!0;return!1}if(o.type==="union"){for(const i of o.options)if(Pt(i,n))return!0;return!1}if(o.type==="tuple"){for(const i of o.items)if(Pt(i,n))return!0;return!!(o.rest&&Pt(o.rest,n))}return!1}const y$=(t,e={})=>n=>{const o=Ka({...n,processors:e});return We(t,o),Ya(o,t),Xa(o,t)},Qa=(t,e,n={})=>o=>{const{libraryOptions:i,target:s}=o??{},r=Ka({...i??{},target:s,io:e,processors:n});return We(t,r),Ya(r,t),Xa(r,t)},_$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},q_=(t,e,n,o)=>{const i=n;i.type="string";const{minimum:s,maximum:r,format:a,patterns:u,contentEncoding:c}=t._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof r=="number"&&(i.maxLength=r),a&&(i.format=_$[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),c&&(i.contentEncoding=c),u&&u.size>0){const p=[...u];p.length===1?i.pattern=p[0].source:p.length>1&&(i.allOf=[...p.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},B_=(t,e,n,o)=>{const i=n,{minimum:s,maximum:r,format:a,multipleOf:u,exclusiveMaximum:c,exclusiveMinimum:p}=t._zod.bag;typeof a=="string"&&a.includes("int")?i.type="integer":i.type="number";const f=typeof p=="number"&&p>=(s??Number.NEGATIVE_INFINITY),h=typeof c=="number"&&c<=(r??Number.POSITIVE_INFINITY),m=e.target==="draft-04"||e.target==="openapi-3.0";f?m?(i.minimum=p,i.exclusiveMinimum=!0):i.exclusiveMinimum=p:typeof s=="number"&&(i.minimum=s),h?m?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof r=="number"&&(i.maximum=r),typeof u=="number"&&(i.multipleOf=u)},H_=(t,e,n,o)=>{n.type="boolean"},T$=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},E$=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Z_=(t,e,n,o)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},w$=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},I$=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},J_=(t,e,n,o)=>{n.not={}},W_=(t,e,n,o)=>{},K_=(t,e,n,o)=>{},S$=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Y_=(t,e,n,o)=>{const i=t._zod.def,s=w_(i.entries);s.every(r=>typeof r=="number")&&(n.type="number"),s.every(r=>typeof r=="string")&&(n.type="string"),n.enum=s},X_=(t,e,n,o)=>{const i=t._zod.def,s=[];for(const r of i.values)if(r===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof r=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(r))}else s.push(r);if(s.length!==0)if(s.length===1){const r=s[0];n.type=r===null?"null":typeof r,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[r]:n.const=r}else s.every(r=>typeof r=="number")&&(n.type="number"),s.every(r=>typeof r=="string")&&(n.type="string"),s.every(r=>typeof r=="boolean")&&(n.type="boolean"),s.every(r=>r===null)&&(n.type="null"),n.enum=s},C$=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},A$=(t,e,n,o)=>{const i=n,s=t._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=s.source},b$=(t,e,n,o)=>{const i=n,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:r,maximum:a,mime:u}=t._zod.bag;r!==void 0&&(s.minLength=r),a!==void 0&&(s.maxLength=a),u?u.length===1?(s.contentMediaType=u[0],Object.assign(i,s)):(Object.assign(i,s),i.anyOf=u.map(c=>({contentMediaType:c}))):Object.assign(i,s)},R$=(t,e,n,o)=>{n.type="boolean"},Q_=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},k$=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},j_=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},P$=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},N$=(t,e,n,o)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},eT=(t,e,n,o)=>{const i=n,s=t._zod.def,{minimum:r,maximum:a}=t._zod.bag;typeof r=="number"&&(i.minItems=r),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=We(s.element,e,{...o,path:[...o.path,"items"]})},tT=(t,e,n,o)=>{var c;const i=n,s=t._zod.def;i.type="object",i.properties={};const r=s.shape;for(const p in r)i.properties[p]=We(r[p],e,{...o,path:[...o.path,"properties",p]});const a=new Set(Object.keys(r)),u=new Set([...a].filter(p=>{const f=s.shape[p]._zod;return e.io==="input"?f.optin===void 0:f.optout===void 0}));u.size>0&&(i.required=Array.from(u)),((c=s.catchall)==null?void 0:c._zod.def.type)==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=We(s.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},nT=(t,e,n,o)=>{const i=t._zod.def,s=i.inclusive===!1,r=i.options.map((a,u)=>We(a,e,{...o,path:[...o.path,s?"oneOf":"anyOf",u]}));s?n.oneOf=r:n.anyOf=r},oT=(t,e,n,o)=>{const i=t._zod.def,s=We(i.left,e,{...o,path:[...o.path,"allOf",0]}),r=We(i.right,e,{...o,path:[...o.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,u=[...a(s)?s.allOf:[s],...a(r)?r.allOf:[r]];n.allOf=u},M$=(t,e,n,o)=>{const i=n,s=t._zod.def;i.type="array";const r=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",u=s.items.map((h,m)=>We(h,e,{...o,path:[...o.path,r,m]})),c=s.rest?We(s.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[s.items.length]:[]]}):null;e.target==="draft-2020-12"?(i.prefixItems=u,c&&(i.items=c)):e.target==="openapi-3.0"?(i.items={anyOf:u},c&&i.items.anyOf.push(c),i.minItems=u.length,c||(i.maxItems=u.length)):(i.items=u,c&&(i.additionalItems=c));const{minimum:p,maximum:f}=t._zod.bag;typeof p=="number"&&(i.minItems=p),typeof f=="number"&&(i.maxItems=f)},iT=(t,e,n,o)=>{const i=n,s=t._zod.def;i.type="object";const r=s.keyType,a=r._zod.bag,u=a==null?void 0:a.patterns;if(s.mode==="loose"&&u&&u.size>0){const p=We(s.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});i.patternProperties={};for(const f of u)i.patternProperties[f.source]=p}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=We(s.keyType,e,{...o,path:[...o.path,"propertyNames"]})),i.additionalProperties=We(s.valueType,e,{...o,path:[...o.path,"additionalProperties"]});const c=r._zod.values;if(c){const p=[...c].filter(f=>typeof f=="string"||typeof f=="number");p.length>0&&(i.required=p)}},sT=(t,e,n,o)=>{const i=t._zod.def,s=We(i.innerType,e,o),r=e.seen.get(t);e.target==="openapi-3.0"?(r.ref=i.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},rT=(t,e,n,o)=>{const i=t._zod.def;We(i.innerType,e,o);const s=e.seen.get(t);s.ref=i.innerType},aT=(t,e,n,o)=>{const i=t._zod.def;We(i.innerType,e,o);const s=e.seen.get(t);s.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},lT=(t,e,n,o)=>{const i=t._zod.def;We(i.innerType,e,o);const s=e.seen.get(t);s.ref=i.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},uT=(t,e,n,o)=>{const i=t._zod.def;We(i.innerType,e,o);const s=e.seen.get(t);s.ref=i.innerType;let r;try{r=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=r},cT=(t,e,n,o)=>{const i=t._zod.def,s=i.in._zod.traits.has("$ZodTransform"),r=e.io==="input"?s?i.out:i.in:i.out;We(r,e,o);const a=e.seen.get(t);a.ref=r},dT=(t,e,n,o)=>{const i=t._zod.def;We(i.innerType,e,o);const s=e.seen.get(t);s.ref=i.innerType,n.readOnly=!0},x$=(t,e,n,o)=>{const i=t._zod.def;We(i.innerType,e,o);const s=e.seen.get(t);s.ref=i.innerType},ed=(t,e,n,o)=>{const i=t._zod.def;We(i.innerType,e,o);const s=e.seen.get(t);s.ref=i.innerType},pT=(t,e,n,o)=>{const i=t._zod.innerType;We(i,e,o);const s=e.seen.get(t);s.ref=i},yf={string:q_,number:B_,boolean:H_,bigint:T$,symbol:E$,null:Z_,undefined:w$,void:I$,never:J_,any:W_,unknown:K_,date:S$,enum:Y_,literal:X_,nan:C$,template_literal:A$,file:b$,success:R$,custom:Q_,function:k$,transform:j_,map:P$,set:N$,array:eT,object:tT,union:nT,intersection:oT,tuple:M$,record:iT,nullable:sT,nonoptional:rT,default:aT,prefault:lT,catch:uT,pipe:cT,readonly:dT,promise:x$,optional:ed,lazy:pT};function D$(t,e){if("_idmap"in t){const o=t,i=Ka({...e,processors:yf}),s={};for(const u of o._idmap.entries()){const[c,p]=u;We(p,i)}const r={},a={registry:o,uri:e==null?void 0:e.uri,defs:s};i.external=a;for(const u of o._idmap.entries()){const[c,p]=u;Ya(i,p),r[c]=Xa(i,p)}if(Object.keys(s).length>0){const u=i.target==="draft-2020-12"?"$defs":"definitions";r.__shared={[u]:s}}return{schemas:r}}const n=Ka({...e,processors:yf});return We(t,n),Ya(n,t),Xa(n,t)}const $$=F("ZodISODateTime",(t,e)=>{Ux.init(t,e),st.init(t,e)});function U$(t){return HD($$,t)}const O$=F("ZodISODate",(t,e)=>{Ox.init(t,e),st.init(t,e)});function L$(t){return ZD(O$,t)}const G$=F("ZodISOTime",(t,e)=>{Lx.init(t,e),st.init(t,e)});function z$(t){return JD(G$,t)}const F$=F("ZodISODuration",(t,e)=>{Gx.init(t,e),st.init(t,e)});function V$(t){return WD(F$,t)}const q$=(t,e)=>{A_.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>bM(t,n)},flatten:{value:n=>AM(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Ku,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Ku,2)}},isEmpty:{get(){return t.issues.length===0}}})},fn=F("ZodError",q$,{Parent:Error}),B$=Xc(fn),H$=Qc(fn),Z$=Gl(fn),fT=zl(fn),J$=PM(fn),W$=NM(fn),K$=MM(fn),Y$=xM(fn),X$=DM(fn),Q$=$M(fn),j$=UM(fn),eU=OM(fn),_f=new WeakMap;function na(t,e,n){const o=Object.getPrototypeOf(t);let i=_f.get(o);if(i||(i=new Set,_f.set(o,i)),!i.has(e)){i.add(e);for(const s in n){const r=n[s];Object.defineProperty(o,s,{configurable:!0,enumerable:!1,get(){const a=r.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}const Ye=F("ZodType",(t,e)=>(Ke.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Qa(t,"input"),output:Qa(t,"output")}}),t.toJSONSchema=y$(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,o)=>B$(t,n,o,{callee:t.parse}),t.safeParse=(n,o)=>Z$(t,n,o),t.parseAsync=async(n,o)=>H$(t,n,o,{callee:t.parseAsync}),t.safeParseAsync=async(n,o)=>fT(t,n,o),t.spa=t.safeParseAsync,t.encode=(n,o)=>J$(t,n,o),t.decode=(n,o)=>W$(t,n,o),t.encodeAsync=async(n,o)=>K$(t,n,o),t.decodeAsync=async(n,o)=>Y$(t,n,o),t.safeEncode=(n,o)=>X$(t,n,o),t.safeDecode=(n,o)=>Q$(t,n,o),t.safeEncodeAsync=async(n,o)=>j$(t,n,o),t.safeDecodeAsync=async(n,o)=>eU(t,n,o),na(t,"ZodType",{check(...n){const o=this.def;return this.clone(Ro(o,{checks:[...o.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,o){return ko(this,n,o)},brand(){return this},register(n,o){return n.add(this,o),this},refine(n,o){return this.check(XU(n,o))},superRefine(n,o){return this.check(QU(n,o))},overwrite(n){return this.check(ji(n))},optional(){return If(this)},exactOptional(){return UU(this)},nullable(){return Sf(this)},nullish(){return If(Sf(this))},nonoptional(n){return VU(this,n)},array(){return ee(this)},or(n){return $e([this,n])},and(n){return NU(this,n)},transform(n){return Cf(this,DU(n))},default(n){return GU(this,n)},prefault(n){return FU(this,n)},catch(n){return BU(this,n)},pipe(n){return Cf(this,n)},readonly(){return JU(this)},describe(n){const o=this.clone();return vs.add(o,{description:n}),o},meta(...n){if(n.length===0)return vs.get(this);const o=this.clone();return vs.add(o,n[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){var n;return(n=vs.get(t))==null?void 0:n.description},configurable:!0}),t)),hT=F("_ZodString",(t,e)=>{jc.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(o,i,s)=>q_(t,o,i);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,na(t,"_ZodString",{regex(...o){return this.check(n$(...o))},includes(...o){return this.check(s$(...o))},startsWith(...o){return this.check(r$(...o))},endsWith(...o){return this.check(a$(...o))},min(...o){return this.check(Wa(...o))},max(...o){return this.check(F_(...o))},length(...o){return this.check(V_(...o))},nonempty(...o){return this.check(Wa(1,...o))},lowercase(o){return this.check(o$(o))},uppercase(o){return this.check(i$(o))},trim(){return this.check(u$())},normalize(...o){return this.check(l$(...o))},toLowerCase(){return this.check(c$())},toUpperCase(){return this.check(d$())},slugify(){return this.check(p$())}})}),tU=F("ZodString",(t,e)=>{jc.init(t,e),hT.init(t,e),t.email=n=>t.check(SD(nU,n)),t.url=n=>t.check(kD(oU,n)),t.jwt=n=>t.check(BD(yU,n)),t.emoji=n=>t.check(PD(iU,n)),t.guid=n=>t.check(hf(Tf,n)),t.uuid=n=>t.check(CD(Ta,n)),t.uuidv4=n=>t.check(AD(Ta,n)),t.uuidv6=n=>t.check(bD(Ta,n)),t.uuidv7=n=>t.check(RD(Ta,n)),t.nanoid=n=>t.check(ND(sU,n)),t.guid=n=>t.check(hf(Tf,n)),t.cuid=n=>t.check(MD(rU,n)),t.cuid2=n=>t.check(xD(aU,n)),t.ulid=n=>t.check(DD(lU,n)),t.base64=n=>t.check(FD(mU,n)),t.base64url=n=>t.check(VD(gU,n)),t.xid=n=>t.check($D(uU,n)),t.ksuid=n=>t.check(UD(cU,n)),t.ipv4=n=>t.check(OD(dU,n)),t.ipv6=n=>t.check(LD(pU,n)),t.cidrv4=n=>t.check(GD(fU,n)),t.cidrv6=n=>t.check(zD(hU,n)),t.e164=n=>t.check(qD(vU,n)),t.datetime=n=>t.check(U$(n)),t.date=n=>t.check(L$(n)),t.time=n=>t.check(z$(n)),t.duration=n=>t.check(V$(n))});function I(t){return ID(tU,t)}const st=F("ZodStringFormat",(t,e)=>{et.init(t,e),hT.init(t,e)}),nU=F("ZodEmail",(t,e)=>{bx.init(t,e),st.init(t,e)}),Tf=F("ZodGUID",(t,e)=>{Cx.init(t,e),st.init(t,e)}),Ta=F("ZodUUID",(t,e)=>{Ax.init(t,e),st.init(t,e)}),oU=F("ZodURL",(t,e)=>{Rx.init(t,e),st.init(t,e)}),iU=F("ZodEmoji",(t,e)=>{kx.init(t,e),st.init(t,e)}),sU=F("ZodNanoID",(t,e)=>{Px.init(t,e),st.init(t,e)}),rU=F("ZodCUID",(t,e)=>{Nx.init(t,e),st.init(t,e)}),aU=F("ZodCUID2",(t,e)=>{Mx.init(t,e),st.init(t,e)}),lU=F("ZodULID",(t,e)=>{xx.init(t,e),st.init(t,e)}),uU=F("ZodXID",(t,e)=>{Dx.init(t,e),st.init(t,e)}),cU=F("ZodKSUID",(t,e)=>{$x.init(t,e),st.init(t,e)}),dU=F("ZodIPv4",(t,e)=>{zx.init(t,e),st.init(t,e)}),pU=F("ZodIPv6",(t,e)=>{Fx.init(t,e),st.init(t,e)}),fU=F("ZodCIDRv4",(t,e)=>{Vx.init(t,e),st.init(t,e)}),hU=F("ZodCIDRv6",(t,e)=>{qx.init(t,e),st.init(t,e)}),mU=F("ZodBase64",(t,e)=>{Bx.init(t,e),st.init(t,e)}),gU=F("ZodBase64URL",(t,e)=>{Zx.init(t,e),st.init(t,e)}),vU=F("ZodE164",(t,e)=>{Jx.init(t,e),st.init(t,e)}),yU=F("ZodJWT",(t,e)=>{Kx.init(t,e),st.init(t,e)}),mT=F("ZodNumber",(t,e)=>{U_.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(o,i,s)=>B_(t,o,i),na(t,"ZodNumber",{gt(o,i){return this.check(gf(o,i))},gte(o,i){return this.check(pu(o,i))},min(o,i){return this.check(pu(o,i))},lt(o,i){return this.check(mf(o,i))},lte(o,i){return this.check(du(o,i))},max(o,i){return this.check(du(o,i))},int(o){return this.check(Ef(o))},safe(o){return this.check(Ef(o))},positive(o){return this.check(gf(0,o))},nonnegative(o){return this.check(pu(0,o))},negative(o){return this.check(mf(0,o))},nonpositive(o){return this.check(du(0,o))},multipleOf(o,i){return this.check(vf(o,i))},step(o,i){return this.check(vf(o,i))},finite(){return this}});const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function W(t){return KD(mT,t)}const _U=F("ZodNumberFormat",(t,e)=>{Yx.init(t,e),mT.init(t,e)});function Ef(t){return YD(_U,t)}const TU=F("ZodBoolean",(t,e)=>{Xx.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>H_(t,n,o)});function ht(t){return XD(TU,t)}const EU=F("ZodNull",(t,e)=>{Qx.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Z_(t,n,o)});function wU(t){return QD(EU,t)}const IU=F("ZodAny",(t,e)=>{jx.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>W_()});function rn(){return jD(IU)}const SU=F("ZodUnknown",(t,e)=>{eD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>K_()});function at(){return e$(SU)}const CU=F("ZodNever",(t,e)=>{tD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>J_(t,n,o)});function AU(t){return t$(CU,t)}const bU=F("ZodArray",(t,e)=>{nD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>eT(t,n,o,i),t.element=e.element,na(t,"ZodArray",{min(n,o){return this.check(Wa(n,o))},nonempty(n){return this.check(Wa(1,n))},max(n,o){return this.check(F_(n,o))},length(n,o){return this.check(V_(n,o))},unwrap(){return this.element}})});function ee(t,e){return f$(bU,t,e)}const RU=F("ZodObject",(t,e)=>{iD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>tT(t,n,o,i),ke(t,"shape",()=>e.shape),na(t,"ZodObject",{keyof(){return Te(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:at()})},loose(){return this.clone({...this._zod.def,catchall:at()})},strict(){return this.clone({...this._zod.def,catchall:AU()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return TM(this,n)},safeExtend(n){return EM(this,n)},merge(n){return wM(this,n)},pick(n){return yM(this,n)},omit(n){return _M(this,n)},partial(...n){return IM(vT,this,n[0])},required(...n){return SM(yT,this,n[0])}})});function M(t,e){const n={type:"object",shape:t??{},...ie(e)};return new RU(n)}const gT=F("ZodUnion",(t,e)=>{G_.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>nT(t,n,o,i),t.options=e.options});function $e(t,e){return new gT({type:"union",options:t,...ie(e)})}const kU=F("ZodDiscriminatedUnion",(t,e)=>{gT.init(t,e),sD.init(t,e)});function Vl(t,e,n){return new kU({type:"union",options:e,discriminator:t,...ie(n)})}const PU=F("ZodIntersection",(t,e)=>{rD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>oT(t,n,o,i)});function NU(t,e){return new PU({type:"intersection",left:t,right:e})}const wf=F("ZodRecord",(t,e)=>{aD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>iT(t,n,o,i),t.keyType=e.keyType,t.valueType=e.valueType});function Et(t,e,n){return!e||!e._zod?new wf({type:"record",keyType:I(),valueType:t,...ie(e)}):new wf({type:"record",keyType:t,valueType:e,...ie(n)})}const Xu=F("ZodEnum",(t,e)=>{lD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(o,i,s)=>Y_(t,o,i),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(o,i)=>{const s={};for(const r of o)if(n.has(r))s[r]=e.entries[r];else throw new Error(`Key ${r} not found in enum`);return new Xu({...e,checks:[],...ie(i),entries:s})},t.exclude=(o,i)=>{const s={...e.entries};for(const r of o)if(n.has(r))delete s[r];else throw new Error(`Key ${r} not found in enum`);return new Xu({...e,checks:[],...ie(i),entries:s})}});function Te(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Xu({type:"enum",entries:n,...ie(e)})}const MU=F("ZodLiteral",(t,e)=>{uD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>X_(t,n,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ne(t,e){return new MU({type:"literal",values:Array.isArray(t)?t:[t],...ie(e)})}const xU=F("ZodTransform",(t,e)=>{cD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>j_(t,n),t._zod.parse=(n,o)=>{if(o.direction==="backward")throw new E_(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(ks(s,n.value,e));else{const r=s;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),n.issues.push(ks(r))}};const i=e.transform(n.value,n);return i instanceof Promise?i.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function DU(t){return new xU({type:"transform",transform:t})}const vT=F("ZodOptional",(t,e)=>{z_.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>ed(t,n,o,i),t.unwrap=()=>t._zod.def.innerType});function If(t){return new vT({type:"optional",innerType:t})}const $U=F("ZodExactOptional",(t,e)=>{dD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>ed(t,n,o,i),t.unwrap=()=>t._zod.def.innerType});function UU(t){return new $U({type:"optional",innerType:t})}const OU=F("ZodNullable",(t,e)=>{pD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>sT(t,n,o,i),t.unwrap=()=>t._zod.def.innerType});function Sf(t){return new OU({type:"nullable",innerType:t})}const LU=F("ZodDefault",(t,e)=>{fD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>aT(t,n,o,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function GU(t,e){return new LU({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():S_(e)}})}const zU=F("ZodPrefault",(t,e)=>{hD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>lT(t,n,o,i),t.unwrap=()=>t._zod.def.innerType});function FU(t,e){return new zU({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():S_(e)}})}const yT=F("ZodNonOptional",(t,e)=>{mD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>rT(t,n,o,i),t.unwrap=()=>t._zod.def.innerType});function VU(t,e){return new yT({type:"nonoptional",innerType:t,...ie(e)})}const qU=F("ZodCatch",(t,e)=>{gD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>uT(t,n,o,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function BU(t,e){return new qU({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const HU=F("ZodPipe",(t,e)=>{vD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>cT(t,n,o,i),t.in=e.in,t.out=e.out});function Cf(t,e){return new HU({type:"pipe",in:t,out:e})}const ZU=F("ZodReadonly",(t,e)=>{yD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>dT(t,n,o,i),t.unwrap=()=>t._zod.def.innerType});function JU(t){return new ZU({type:"readonly",innerType:t})}const WU=F("ZodLazy",(t,e)=>{_D.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>pT(t,n,o,i),t.unwrap=()=>t._zod.def.getter()});function KU(t){return new WU({type:"lazy",getter:t})}const td=F("ZodCustom",(t,e)=>{TD.init(t,e),Ye.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Q_(t,n)});function YU(t,e){return h$(td,t??(()=>!0),e)}function XU(t,e={}){return m$(td,t,e)}function QU(t,e){return g$(t,e)}function ja(t,e={}){const n=new td({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...ie(e)});return n._zod.bag.Class=t,n._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:n,path:[...n._zod.def.path??[]]})},n}var me;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(me||(me={}));class Af extends Error{constructor(e,n){super(e),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}const bf=10,jU=13,$o=32;function fu(t){}function eO(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=fu,onError:n=fu,onRetry:o=fu,onComment:i}=t,s=[];let r=!0,a,u="",c=0,p;function f(C){if(r&&(r=!1,C.charCodeAt(0)===239&&C.charCodeAt(1)===187&&C.charCodeAt(2)===191&&(C=C.slice(3))),s.length===0){const R=h(C);R!==""&&s.push(R);return}if(C.indexOf(`
111
+ `)===-1&&C.indexOf("\r")===-1){s.push(C);return}s.push(C);const E=s.join("");s.length=0;const A=h(E);A!==""&&s.push(A)}function h(C){let E=0;if(C.indexOf("\r")===-1){let A=C.indexOf(`
112
+ `,E);for(;A!==-1;){if(E===A){c>0&&e({id:a,event:p,data:u}),a=void 0,u="",c=0,p=void 0,E=A+1,A=C.indexOf(`
113
+ `,E);continue}const R=C.charCodeAt(E);if(Rf(C,E,R)){const k=C.charCodeAt(E+5)===$o?E+6:E+5,b=C.slice(k,A);if(c===0&&C.charCodeAt(A+1)===bf){e({id:a,event:p,data:b}),a=void 0,u="",p=void 0,E=A+2,A=C.indexOf(`
114
+ `,E);continue}u=c===0?b:`${u}
115
+ ${b}`,c++}else kf(C,E,R)?p=C.slice(C.charCodeAt(E+6)===$o?E+7:E+6,A)||void 0:m(C,E,A);E=A+1,A=C.indexOf(`
116
+ `,E)}return C.slice(E)}for(;E<C.length;){const A=C.indexOf("\r",E),R=C.indexOf(`
117
+ `,E);let k=-1;if(A!==-1&&R!==-1?k=A<R?A:R:A!==-1?A===C.length-1?k=-1:k=A:R!==-1&&(k=R),k===-1)break;m(C,E,k),E=k+1,C.charCodeAt(E-1)===jU&&C.charCodeAt(E)===bf&&E++}return C.slice(E)}function m(C,E,A){if(E===A){_();return}const R=C.charCodeAt(E);if(Rf(C,E,R)){const L=C.charCodeAt(E+5)===$o?E+6:E+5,B=C.slice(L,A);u=c===0?B:`${u}
118
+ ${B}`,c++;return}if(kf(C,E,R)){p=C.slice(C.charCodeAt(E+6)===$o?E+7:E+6,A)||void 0;return}if(R===105&&C.charCodeAt(E+1)===100&&C.charCodeAt(E+2)===58){const L=C.slice(C.charCodeAt(E+3)===$o?E+4:E+3,A);a=L.includes("\0")?void 0:L;return}if(R===58){if(i){const L=C.slice(E,A);i(L.slice(C.charCodeAt(E+1)===$o?2:1))}return}const k=C.slice(E,A),b=k.indexOf(":");if(b===-1){v(k,"",k);return}const U=k.slice(0,b),J=k.charCodeAt(b+1)===$o?2:1,G=k.slice(b+J);v(U,G,k)}function v(C,E,A){switch(C){case"event":p=E||void 0;break;case"data":u=c===0?E:`${u}
119
+ ${E}`,c++;break;case"id":a=E.includes("\0")?void 0:E;break;case"retry":/^\d+$/.test(E)?o(parseInt(E,10)):n(new Af(`Invalid \`retry\` value: "${E}"`,{type:"invalid-retry",value:E,line:A}));break;default:n(new Af(`Unknown field "${C.length>20?`${C.slice(0,20)}…`:C}"`,{type:"unknown-field",field:C,value:E,line:A}));break}}function _(){c>0&&e({id:a,event:p,data:u}),a=void 0,u="",c=0,p=void 0}function w(C={}){if(C.consume&&s.length>0){const E=s.join("");m(E,0,E.length)}r=!0,a=void 0,u="",c=0,p=void 0,s.length=0}return{feed:f,reset:w}}function Rf(t,e,n){return n===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function kf(t,e,n){return n===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}class tO extends TransformStream{constructor({onError:e,onRetry:n,onComment:o}={}){let i;super({start(s){i=eO({onEvent:r=>{s.enqueue(r)},onError(r){e==="terminate"?s.error(r):typeof e=="function"&&e(r)},onRetry:n,onComment:o})},transform(s){i.feed(s)}})}}var _T={};function Dt(...t){return t.reduce((e,n)=>({...e,...n??{}}),{})}async function _i(t,e){if(t==null)return Promise.resolve();const n=e==null?void 0:e.abortSignal;return new Promise((o,i)=>{if(n!=null&&n.aborted){i(Pf());return}const s=setTimeout(()=>{r(),o()},t),r=()=>{clearTimeout(s),n==null||n.removeEventListener("abort",a)},a=()=>{r(),i(Pf())};n==null||n.addEventListener("abort",a)})}function Pf(){return new DOMException("Delay was aborted","AbortError")}function oa(t){return Object.fromEntries([...t.headers])}var{btoa:nO,atob:oO}=globalThis;function nd(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=oO(e);return Uint8Array.from(n,o=>o.codePointAt(0))}function ni(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCodePoint(t[n]);return nO(e)}function Ps(t){return t instanceof Uint8Array?ni(t):t}var TT="AI_DownloadError",ET=`vercel.ai.error.${TT}`,iO=Symbol.for(ET),Nf,Mf,In=class extends(Mf=de,Nf=iO,Mf){constructor({url:t,statusCode:e,statusText:n,cause:o,message:i=o==null?`Failed to download ${t}: ${e} ${n}`:`Failed to download ${t}: ${o}`}){super({name:TT,message:i,cause:o}),this[Nf]=!0,this.url=t,this.statusCode=e,this.statusText=n}static isInstance(t){return de.hasMarker(t,ET)}},wT=2*1024*1024*1024;async function sO({response:t,url:e,maxBytes:n=wT}){const o=t.headers.get("content-length");if(o!=null){const p=parseInt(o,10);if(!isNaN(p)&&p>n)throw new In({url:e,message:`Download of ${e} exceeded maximum size of ${n} bytes (Content-Length: ${p}).`})}const i=t.body;if(i==null)return new Uint8Array(0);const s=i.getReader(),r=[];let a=0;try{for(;;){const{done:p,value:f}=await s.read();if(p)break;if(a+=f.length,a>n)throw new In({url:e,message:`Download of ${e} exceeded maximum size of ${n} bytes.`});r.push(f)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const u=new Uint8Array(a);let c=0;for(const p of r)u.set(p,c),c+=p.length;return u}function xf(t){let e;try{e=new URL(t)}catch{throw new In({url:t,message:`Invalid URL: ${t}`})}if(e.protocol==="data:")return;if(e.protocol!=="http:"&&e.protocol!=="https:")throw new In({url:t,message:`URL scheme must be http, https, or data, got ${e.protocol}`});const n=e.hostname;if(!n)throw new In({url:t,message:"URL must have a hostname"});if(n==="localhost"||n.endsWith(".local")||n.endsWith(".localhost"))throw new In({url:t,message:`URL with hostname ${n} is not allowed`});if(n.startsWith("[")&&n.endsWith("]")){const o=n.slice(1,-1);if(rO(o))throw new In({url:t,message:`URL with IPv6 address ${n} is not allowed`});return}if(IT(n)){if(Qu(n))throw new In({url:t,message:`URL with IP address ${n} is not allowed`});return}}function IT(t){const e=t.split(".");return e.length!==4?!1:e.every(n=>{const o=Number(n);return Number.isInteger(o)&&o>=0&&o<=255&&String(o)===n})}function Qu(t){const e=t.split(".").map(Number),[n,o]=e;return n===0||n===10||n===127||n===169&&o===254||n===172&&o>=16&&o<=31||n===192&&o===168}function rO(t){const e=t.toLowerCase();if(e==="::1"||e==="::")return!0;if(e.startsWith("::ffff:")){const n=e.slice(7);if(IT(n))return Qu(n);const o=n.split(":");if(o.length===2){const i=parseInt(o[0],16),s=parseInt(o[1],16);if(!isNaN(i)&&!isNaN(s)){const r=i>>8&255,a=i&255,u=s>>8&255,c=s&255;return Qu(`${r}.${a}.${u}.${c}`)}}}return!!(e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe80"))}var ia=({prefix:t,size:e=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:o="-"}={})=>{const i=()=>{const s=n.length,r=new Array(e);for(let a=0;a<e;a++)r[a]=n[Math.random()*s|0];return r.join("")};if(t==null)return i;if(n.includes(o))throw new l_({argument:"separator",message:`The separator "${o}" must not be part of the alphabet "${n}".`});return()=>`${t}${o}${i()}`},Hn=ia();function ST(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function Kn(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var aO=["fetch failed","failed to fetch"],lO=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function uO(t){if(!(t instanceof Error))return!1;const e=t.code;return!!(typeof e=="string"&&lO.includes(e))}function CT({error:t,url:e,requestBodyValues:n}){if(Kn(t))return t;if(t instanceof TypeError&&aO.includes(t.message.toLowerCase())){const o=t.cause;if(o!=null)return new rt({message:`Cannot connect to API: ${o.message}`,cause:o,url:e,requestBodyValues:n,isRetryable:!0})}return uO(t)?new rt({message:`Cannot connect to API: ${t.message}`,cause:t,url:e,requestBodyValues:n,isRetryable:!0}):t}function ql(t=globalThis){var e,n,o;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(o=(n=t.process)==null?void 0:n.versions)!=null&&o.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function cO(t){if(t==null)return{};const e={};if(t instanceof Headers)t.forEach((n,o)=>{e[o.toLowerCase()]=n});else{Array.isArray(t)||(t=Object.entries(t));for(const[n,o]of t)o!=null&&(e[n.toLowerCase()]=o)}return e}function Po(t,...e){const n=new Headers(cO(t)),o=n.get("user-agent")||"";return n.set("user-agent",[o,...e].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var AT="4.0.27",dO=()=>globalThis.fetch,oi=async({url:t,headers:e={},successfulResponseHandler:n,failedResponseHandler:o,abortSignal:i,fetch:s=dO()})=>{try{const r=await s(t,{method:"GET",headers:Po(e,`ai-sdk/provider-utils/${AT}`,ql()),signal:i}),a=oa(r);if(!r.ok){let u;try{u=await o({response:r,url:t,requestBodyValues:{}})}catch(c){throw Kn(c)||rt.isInstance(c)?c:new rt({message:"Failed to process error response",cause:c,statusCode:r.status,url:t,responseHeaders:a,requestBodyValues:{}})}throw u.value}try{return await n({response:r,url:t,requestBodyValues:{}})}catch(u){throw u instanceof Error&&(Kn(u)||rt.isInstance(u))?u:new rt({message:"Failed to process successful response",cause:u,statusCode:r.status,url:t,responseHeaders:a,requestBodyValues:{}})}}catch(r){throw CT({error:r,url:t,requestBodyValues:{}})}};function pO({mediaType:t,url:e,supportedUrls:n}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(n).map(([o,i])=>{const s=o.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:i}:{mediaTypePrefix:s.replace(/\*/,""),regexes:i}}).filter(({mediaTypePrefix:o})=>t.startsWith(o)).flatMap(({regexes:o})=>o).some(o=>o.test(e))}function fO({apiKey:t,environmentVariableName:e,apiKeyParameterName:n="apiKey",description:o}){if(typeof t=="string")return t;if(t!=null)throw new va({message:`${o} API key must be a string.`});if(typeof process>"u")throw new va({message:`${o} API key is missing. Pass it using the '${n}' parameter. Environment variables are not supported in this environment.`});if(t=_T[e],t==null)throw new va({message:`${o} API key is missing. Pass it using the '${n}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new va({message:`${o} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function ys({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=_T[e],!(t==null||typeof t!="string")))return t}var hO=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,mO=/"(?: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 Df(t){const e=JSON.parse(t);return e===null||typeof e!="object"||hO.test(t)===!1&&mO.test(t)===!1?e:gO(e)}function gO(t){let e=[t];for(;e.length;){const n=e;e=[];for(const o of n){if(Object.prototype.hasOwnProperty.call(o,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(o,"constructor")&&o.constructor!==null&&typeof o.constructor=="object"&&Object.prototype.hasOwnProperty.call(o.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const i in o){const s=o[i];s&&typeof s=="object"&&e.push(s)}}}return t}function bT(t){const{stackTraceLimit:e}=Error;try{Error.stackTraceLimit=0}catch{return Df(t)}try{return Df(t)}finally{Error.stackTraceLimit=e}}function od(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;const{properties:n}=t;if(n!=null)for(const o of Object.keys(n))n[o]=Uo(n[o])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(Uo):Uo(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(Uo)),t.allOf!=null&&(t.allOf=t.allOf.map(Uo)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(Uo));const{definitions:e}=t;if(e!=null)for(const n of Object.keys(e))e[n]=Uo(e[n]);return t}function Uo(t){return typeof t=="boolean"?t:od(t)}var vO=Symbol("Let zodToJsonSchema decide on which parser to use"),$f={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"},yO=t=>typeof t=="string"?{...$f,name:t}:{...$f,...t};function Yt(){return{}}function _O(t,e){var n,o,i;const s={type:"array"};return(n=t.type)!=null&&n._def&&((i=(o=t.type)==null?void 0:o._def)==null?void 0:i.typeName)!==me.ZodAny&&(s.items=ze(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(s.minItems=t.minLength.value),t.maxLength&&(s.maxItems=t.maxLength.value),t.exactLength&&(s.minItems=t.exactLength.value,s.maxItems=t.exactLength.value),s}function TO(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const n of t.checks)switch(n.kind){case"min":n.inclusive?e.minimum=n.value:e.exclusiveMinimum=n.value;break;case"max":n.inclusive?e.maximum=n.value:e.exclusiveMaximum=n.value;break;case"multipleOf":e.multipleOf=n.value;break}return e}function EO(){return{type:"boolean"}}function RT(t,e){return ze(t.type._def,e)}var wO=(t,e)=>ze(t.innerType._def,e);function kT(t,e,n){const o=n??e.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((i,s)=>kT(t,e,i))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return IO(t)}}var IO=t=>{const e={type:"integer",format:"unix-time"};for(const n of t.checks)switch(n.kind){case"min":e.minimum=n.value;break;case"max":e.maximum=n.value;break}return e};function SO(t,e){return{...ze(t.innerType._def,e),default:t.defaultValue()}}function CO(t,e){return e.effectStrategy==="input"?ze(t.schema._def,e):Yt()}function AO(t){return{type:"string",enum:Array.from(t.values)}}var bO=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function RO(t,e){const n=[ze(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ze(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),o=[];return n.forEach(i=>{if(bO(i))o.push(...i.allOf);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){const{additionalProperties:r,...a}=i;s=a}o.push(s)}}),o.length?{allOf:o}:void 0}function kO(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var hu=void 0,gn={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:()=>(hu===void 0&&(hu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),hu),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 PT(t,e){const n={type:"string"};if(t.checks)for(const o of t.checks)switch(o.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,o.value):o.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,o.value):o.value;break;case"email":switch(e.emailStrategy){case"format:email":vn(n,"email",o.message,e);break;case"format:idn-email":vn(n,"idn-email",o.message,e);break;case"pattern:zod":kt(n,gn.email,o.message,e);break}break;case"url":vn(n,"uri",o.message,e);break;case"uuid":vn(n,"uuid",o.message,e);break;case"regex":kt(n,o.regex,o.message,e);break;case"cuid":kt(n,gn.cuid,o.message,e);break;case"cuid2":kt(n,gn.cuid2,o.message,e);break;case"startsWith":kt(n,RegExp(`^${mu(o.value,e)}`),o.message,e);break;case"endsWith":kt(n,RegExp(`${mu(o.value,e)}$`),o.message,e);break;case"datetime":vn(n,"date-time",o.message,e);break;case"date":vn(n,"date",o.message,e);break;case"time":vn(n,"time",o.message,e);break;case"duration":vn(n,"duration",o.message,e);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,o.value):o.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,o.value):o.value;break;case"includes":{kt(n,RegExp(mu(o.value,e)),o.message,e);break}case"ip":{o.version!=="v6"&&vn(n,"ipv4",o.message,e),o.version!=="v4"&&vn(n,"ipv6",o.message,e);break}case"base64url":kt(n,gn.base64url,o.message,e);break;case"jwt":kt(n,gn.jwt,o.message,e);break;case"cidr":{o.version!=="v6"&&kt(n,gn.ipv4Cidr,o.message,e),o.version!=="v4"&&kt(n,gn.ipv6Cidr,o.message,e);break}case"emoji":kt(n,gn.emoji(),o.message,e);break;case"ulid":{kt(n,gn.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{vn(n,"binary",o.message,e);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{kt(n,gn.base64,o.message,e);break}}break}case"nanoid":kt(n,gn.nanoid,o.message,e)}return n}function mu(t,e){return e.patternStrategy==="escape"?NO(t):t}var PO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function NO(t){let e="";for(let n=0;n<t.length;n++)PO.has(t[n])||(e+="\\"),e+=t[n];return e}function vn(t,e,n,o){var i;t.format||(i=t.anyOf)!=null&&i.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...n&&o.errorMessages&&{errorMessage:{format:n}}})):t.format=e}function kt(t,e,n,o){var i;t.pattern||(i=t.allOf)!=null&&i.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Uf(e,o),...n&&o.errorMessages&&{errorMessage:{pattern:n}}})):t.pattern=Uf(e,o)}function Uf(t,e){var n;if(!e.applyRegexFlags||!t.flags)return t.source;const o={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},i=o.i?t.source.toLowerCase():t.source;let s="",r=!1,a=!1,u=!1;for(let c=0;c<i.length;c++){if(r){s+=i[c],r=!1;continue}if(o.i){if(a){if(i[c].match(/[a-z]/)){u?(s+=i[c],s+=`${i[c-2]}-${i[c]}`.toUpperCase(),u=!1):i[c+1]==="-"&&((n=i[c+2])!=null&&n.match(/[a-z]/))?(s+=i[c],u=!0):s+=`${i[c]}${i[c].toUpperCase()}`;continue}}else if(i[c].match(/[a-z]/)){s+=`[${i[c]}${i[c].toUpperCase()}]`;continue}}if(o.m){if(i[c]==="^"){s+=`(^|(?<=[\r
120
+ ]))`;continue}else if(i[c]==="$"){s+=`($|(?=[\r
121
+ ]))`;continue}}if(o.s&&i[c]==="."){s+=a?`${i[c]}\r
122
+ `:`[${i[c]}\r
123
+ ]`;continue}s+=i[c],i[c]==="\\"?r=!0:a&&i[c]==="]"?a=!1:!a&&i[c]==="["&&(a=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function NT(t,e){var n,o,i,s,r,a;const u={type:"object",additionalProperties:(n=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?n:e.allowedAdditionalProperties};if(((o=t.keyType)==null?void 0:o._def.typeName)===me.ZodString&&((i=t.keyType._def.checks)!=null&&i.length)){const{type:c,...p}=PT(t.keyType._def,e);return{...u,propertyNames:p}}else{if(((s=t.keyType)==null?void 0:s._def.typeName)===me.ZodEnum)return{...u,propertyNames:{enum:t.keyType._def.values}};if(((r=t.keyType)==null?void 0:r._def.typeName)===me.ZodBranded&&t.keyType._def.type._def.typeName===me.ZodString&&((a=t.keyType._def.type._def.checks)!=null&&a.length)){const{type:c,...p}=RT(t.keyType._def,e);return{...u,propertyNames:p}}}return u}function MO(t,e){if(e.mapStrategy==="record")return NT(t,e);const n=ze(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Yt(),o=ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Yt();return{type:"array",maxItems:125,items:{type:"array",items:[n,o],minItems:2,maxItems:2}}}function xO(t){const e=t.values,o=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),i=Array.from(new Set(o.map(s=>typeof s)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:o}}function DO(){return{not:Yt()}}function $O(){return{type:"null"}}var ju={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function UO(t,e){const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(o=>o._def.typeName in ju&&(!o._def.checks||!o._def.checks.length))){const o=n.reduce((i,s)=>{const r=ju[s._def.typeName];return r&&!i.includes(r)?[...i,r]:i},[]);return{type:o.length>1?o:o[0]}}else if(n.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){const o=n.reduce((i,s)=>{const r=typeof s._def.value;switch(r){case"string":case"number":case"boolean":return[...i,r];case"bigint":return[...i,"integer"];case"object":if(s._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(o.length===n.length){const i=o.filter((s,r,a)=>a.indexOf(s)===r);return{type:i.length>1?i:i[0],enum:n.reduce((s,r)=>s.includes(r._def.value)?s:[...s,r._def.value],[])}}}else if(n.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((o,i)=>[...o,...i._def.values.filter(s=>!o.includes(s))],[])};return OO(t,e)}var OO=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((o,i)=>ze(o._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(o=>!!o&&(!e.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return n.length?{anyOf:n}:void 0};function LO(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[ju[t.innerType._def.typeName],"null"]};const n=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function GO(t){const e={type:"number"};if(!t.checks)return e;for(const n of t.checks)switch(n.kind){case"int":e.type="integer";break;case"min":n.inclusive?e.minimum=n.value:e.exclusiveMinimum=n.value;break;case"max":n.inclusive?e.maximum=n.value:e.exclusiveMaximum=n.value;break;case"multipleOf":e.multipleOf=n.value;break}return e}function zO(t,e){const n={type:"object",properties:{}},o=[],i=t.shape();for(const r in i){let a=i[r];if(a===void 0||a._def===void 0)continue;const u=VO(a),c=ze(a._def,{...e,currentPath:[...e.currentPath,"properties",r],propertyPath:[...e.currentPath,"properties",r]});c!==void 0&&(n.properties[r]=c,u||o.push(r))}o.length&&(n.required=o);const s=FO(t,e);return s!==void 0&&(n.additionalProperties=s),n}function FO(t,e){if(t.catchall._def.typeName!=="ZodNever")return ze(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function VO(t){try{return t.isOptional()}catch{return!0}}var qO=(t,e)=>{var n;if(e.currentPath.toString()===((n=e.propertyPath)==null?void 0:n.toString()))return ze(t.innerType._def,e);const o=ze(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return o?{anyOf:[{not:Yt()},o]}:Yt()},BO=(t,e)=>{if(e.pipeStrategy==="input")return ze(t.in._def,e);if(e.pipeStrategy==="output")return ze(t.out._def,e);const n=ze(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=ze(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(i=>i!==void 0)}};function HO(t,e){return ze(t.type._def,e)}function ZO(t,e){const o={type:"array",uniqueItems:!0,items:ze(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(o.minItems=t.minSize.value),t.maxSize&&(o.maxItems=t.maxSize.value),o}function JO(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,o)=>ze(n._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((n,o)=>o===void 0?n:[...n,o],[]),additionalItems:ze(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,o)=>ze(n._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((n,o)=>o===void 0?n:[...n,o],[])}}function WO(){return{not:Yt()}}function KO(){return Yt()}var YO=(t,e)=>ze(t.innerType._def,e),XO=(t,e,n)=>{switch(e){case me.ZodString:return PT(t,n);case me.ZodNumber:return GO(t);case me.ZodObject:return zO(t,n);case me.ZodBigInt:return TO(t);case me.ZodBoolean:return EO();case me.ZodDate:return kT(t,n);case me.ZodUndefined:return WO();case me.ZodNull:return $O();case me.ZodArray:return _O(t,n);case me.ZodUnion:case me.ZodDiscriminatedUnion:return UO(t,n);case me.ZodIntersection:return RO(t,n);case me.ZodTuple:return JO(t,n);case me.ZodRecord:return NT(t,n);case me.ZodLiteral:return kO(t);case me.ZodEnum:return AO(t);case me.ZodNativeEnum:return xO(t);case me.ZodNullable:return LO(t,n);case me.ZodOptional:return qO(t,n);case me.ZodMap:return MO(t,n);case me.ZodSet:return ZO(t,n);case me.ZodLazy:return()=>t.getter()._def;case me.ZodPromise:return HO(t,n);case me.ZodNaN:case me.ZodNever:return DO();case me.ZodEffects:return CO(t,n);case me.ZodAny:return Yt();case me.ZodUnknown:return KO();case me.ZodDefault:return SO(t,n);case me.ZodBranded:return RT(t,n);case me.ZodReadonly:return YO(t,n);case me.ZodCatch:return wO(t,n);case me.ZodPipeline:return BO(t,n);case me.ZodFunction:case me.ZodVoid:case me.ZodSymbol:return;default:return(o=>{})()}},QO=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")};function ze(t,e,n=!1){var o;const i=e.seen.get(t);if(e.override){const u=(o=e.override)==null?void 0:o.call(e,t,e,i,n);if(u!==vO)return u}if(i&&!n){const u=jO(i,e);if(u!==void 0)return u}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const r=XO(t,t.typeName,e),a=typeof r=="function"?ze(r(),e):r;if(a&&eL(t,e,a),e.postProcess){const u=e.postProcess(a,t,e);return s.jsonSchema=a,u}return s.jsonSchema=a,a}var jO=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:QO(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Yt()):e.$refStrategy==="seen"?Yt():void 0}},eL=(t,e,n)=>(t.description&&(n.description=t.description),n),tL=t=>{const e=yO(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([o,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,o],jsonSchema:void 0}]))}},nL=(t,e)=>{var n;const o=tL(e);let i=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[p,f])=>{var h;return{...c,[p]:(h=ze(f._def,{...o,currentPath:[...o.basePath,o.definitionPath,p]},!0))!=null?h:Yt()}},{}):void 0;const s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,r=(n=ze(t._def,s===void 0?o:{...o,currentPath:[...o.basePath,o.definitionPath,s]},!1))!=null?n:Yt(),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(r.title=a);const u=s===void 0?i?{...r,[o.definitionPath]:i}:r:{$ref:[...o.$refStrategy==="relative"?[]:o.basePath,o.definitionPath,s].join("/"),[o.definitionPath]:{...i,[s]:r}};return u.$schema="http://json-schema.org/draft-07/schema#",u},ec=Symbol.for("vercel.ai.schema");function xe(t){let e;return()=>(e==null&&(e=t()),e)}function sa(t,{validate:e}={}){return{[ec]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function oL(t){return typeof t=="object"&&t!==null&&ec in t&&t[ec]===!0&&"jsonSchema"in t&&"validate"in t}function Co(t){return t==null?sa({properties:{},additionalProperties:!1}):oL(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Me(t):iL(t):t()}function iL(t){return sa(()=>od(t["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async e=>{const n=await t["~standard"].validate(e);return"value"in n?{success:!0,value:n.value}:{success:!1,error:new Ot({value:e,cause:n.issues})}}})}function sL(t,e){var n;const o=(n=void 0)!=null?n:!1;return sa(()=>nL(t,{$refStrategy:o?"root":"none"}),{validate:async i=>{const s=await t.safeParseAsync(i);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function rL(t,e){var n;const o=(n=void 0)!=null?n:!1;return sa(()=>od(D$(t,{target:"draft-7",io:"input",reused:o?"ref":"inline"})),{validate:async i=>{const s=await fT(t,i);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function aL(t){return"_zod"in t}function Me(t,e){return aL(t)?rL(t):sL(t)}async function lL({value:t,schema:e,context:n}){const o=await Gt({value:t,schema:e,context:n});if(!o.success)throw Ot.wrap({value:t,cause:o.error,context:n});return o.value}async function Gt({value:t,schema:e,context:n}){const o=Co(e);try{if(o.validate==null)return{success:!0,value:t,rawValue:t};const i=await o.validate(t);return i.success?{success:!0,value:i.value,rawValue:t}:{success:!1,error:Ot.wrap({value:t,cause:i.error,context:n}),rawValue:t}}catch(i){return{success:!1,error:Ot.wrap({value:t,cause:i,context:n}),rawValue:t}}}async function uL({text:t,schema:e}){try{const n=bT(t);return e==null?n:lL({value:n,schema:e})}catch(n){throw bs.isInstance(n)||Ot.isInstance(n)?n:new bs({text:t,cause:n})}}async function cn({text:t,schema:e}){try{const n=bT(t);return e==null?{success:!0,value:n,rawValue:n}:await Gt({value:n,schema:e})}catch(n){return{success:!1,error:bs.isInstance(n)?n:new bs({text:t,cause:n}),rawValue:void 0}}}function MT({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new tO).pipeThrough(new TransformStream({async transform({data:n},o){n!=="[DONE]"&&o.enqueue(await cn({text:n,schema:e}))}}))}async function Hi({provider:t,providerOptions:e,schema:n}){if((e==null?void 0:e[t])==null)return;const o=await Gt({value:e[t],schema:n});if(!o.success)throw new l_({argument:"providerOptions",message:`invalid ${t} provider options`,cause:o.error});return o.value}var cL=()=>globalThis.fetch,xt=async({url:t,headers:e,body:n,failedResponseHandler:o,successfulResponseHandler:i,abortSignal:s,fetch:r})=>dL({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(n),values:n},failedResponseHandler:o,successfulResponseHandler:i,abortSignal:s,fetch:r}),dL=async({url:t,headers:e={},body:n,successfulResponseHandler:o,failedResponseHandler:i,abortSignal:s,fetch:r=cL()})=>{try{const a=await r(t,{method:"POST",headers:Po(e,`ai-sdk/provider-utils/${AT}`,ql()),body:n.content,signal:s}),u=oa(a);if(!a.ok){let c;try{c=await i({response:a,url:t,requestBodyValues:n.values})}catch(p){throw Kn(p)||rt.isInstance(p)?p:new rt({message:"Failed to process error response",cause:p,statusCode:a.status,url:t,responseHeaders:u,requestBodyValues:n.values})}throw c.value}try{return await o({response:a,url:t,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(Kn(c)||rt.isInstance(c))?c:new rt({message:"Failed to process successful response",cause:c,statusCode:a.status,url:t,responseHeaders:u,requestBodyValues:n.values})}}catch(a){throw CT({error:a,url:t,requestBodyValues:n.values})}};function es({id:t,inputSchema:e}){return({execute:n,outputSchema:o,needsApproval:i,toModelOutput:s,onInputStart:r,onInputDelta:a,onInputAvailable:u,...c})=>({type:"provider",id:t,args:c,inputSchema:e,outputSchema:o,execute:n,needsApproval:i,toModelOutput:s,onInputStart:r,onInputDelta:a,onInputAvailable:u})}function id({id:t,inputSchema:e,outputSchema:n,supportsDeferredResults:o}){return({execute:i,needsApproval:s,toModelOutput:r,onInputStart:a,onInputDelta:u,onInputAvailable:c,...p})=>({type:"provider",id:t,args:p,inputSchema:e,outputSchema:n,execute:i,needsApproval:s,toModelOutput:r,onInputStart:a,onInputDelta:u,onInputAvailable:c,supportsDeferredResults:o})}async function He(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var Cn=({errorSchema:t,errorToMessage:e,isRetryable:n})=>async({response:o,url:i,requestBodyValues:s})=>{const r=await o.text(),a=oa(o);if(r.trim()==="")return{responseHeaders:a,value:new rt({message:o.statusText,url:i,requestBodyValues:s,statusCode:o.status,responseHeaders:a,responseBody:r,isRetryable:n==null?void 0:n(o)})};try{const u=await uL({text:r,schema:t});return{responseHeaders:a,value:new rt({message:e(u),url:i,requestBodyValues:s,statusCode:o.status,responseHeaders:a,responseBody:r,data:u,isRetryable:n==null?void 0:n(o,u)})}}catch{return{responseHeaders:a,value:new rt({message:o.statusText,url:i,requestBodyValues:s,statusCode:o.status,responseHeaders:a,responseBody:r,isRetryable:n==null?void 0:n(o)})}}},Bl=t=>async({response:e})=>{const n=oa(e);if(e.body==null)throw new oM({});return{responseHeaders:n,value:MT({stream:e.body,schema:t})}},Ct=t=>async({response:e,url:n,requestBodyValues:o})=>{const i=await e.text(),s=await cn({text:i,schema:t}),r=oa(e);if(!s.success)throw new rt({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:r,responseBody:i,url:n,requestBodyValues:o});return{responseHeaders:r,value:s.value,rawValue:s.rawValue}};function xT(t){return t==null?void 0:t.replace(/\/$/,"")}function pL(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*fL({execute:t,input:e,options:n}){const o=t(e,n);if(pL(o)){let i;for await(const s of o)i=s,yield{type:"preliminary",output:s};yield{type:"final",output:i}}else yield{type:"final",output:await o}}var hL="3.0.75",mL=xe(()=>Me(M({error:M({code:W().nullable(),message:I(),status:I()})}))),an=Cn({errorSchema:mL,errorToMessage:t=>t.error.message}),gL=$e([M({text:I()}),M({inlineData:M({mimeType:I(),data:I()})}),M({fileData:M({fileUri:I(),mimeType:I()})})]),vL=xe(()=>Me(M({outputDimensionality:W().optional(),taskType:Te(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),content:ee(ee(gL).min(1).nullable()).optional()}))),yL=class{constructor(t,e){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:n,providerOptions:o}){const i=await Hi({provider:"google",providerOptions:o,schema:vL});if(t.length>this.maxEmbeddingsPerCall)throw new uM({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const s=Dt(await He(this.config.headers),e),r=i==null?void 0:i.content;if(r!=null&&r.length!==t.length)throw new Error(`The number of multimodal content entries (${r.length}) must match the number of values (${t.length}).`);if(t.length===1){const p=r==null?void 0:r[0],f=t[0]?[{text:t[0]}]:[],h=p!=null?[...f,...p]:[{text:t[0]}],{responseHeaders:m,value:v,rawValue:_}=await xt({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:s,body:{model:`models/${this.modelId}`,content:{parts:h},outputDimensionality:i==null?void 0:i.outputDimensionality,taskType:i==null?void 0:i.taskType},failedResponseHandler:an,successfulResponseHandler:Ct(TL),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:[v.embedding.values],usage:void 0,response:{headers:m,body:_}}}const{responseHeaders:a,value:u,rawValue:c}=await xt({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:s,body:{requests:t.map((p,f)=>{const h=r==null?void 0:r[f],m=p?[{text:p}]:[];return{model:`models/${this.modelId}`,content:{role:"user",parts:h!=null?[...m,...h]:[{text:p}]},outputDimensionality:i==null?void 0:i.outputDimensionality,taskType:i==null?void 0:i.taskType}})},failedResponseHandler:an,successfulResponseHandler:Ct(_L),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:u.embeddings.map(p=>p.values),usage:void 0,response:{headers:a,body:c}}}},_L=xe(()=>Me(M({embeddings:ee(M({values:ee(W())}))}))),TL=xe(()=>Me(M({embedding:M({values:ee(W())})})));function Of(t){var e,n,o,i;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(e=t.promptTokenCount)!=null?e:0,r=(n=t.candidatesTokenCount)!=null?n:0,a=(o=t.cachedContentTokenCount)!=null?o:0,u=(i=t.thoughtsTokenCount)!=null?i:0;return{inputTokens:{total:s,noCache:s-a,cacheRead:a,cacheWrite:void 0},outputTokens:{total:r+u,text:r,reasoning:u},raw:t}}function Tn(t,e=!0){if(t==null)return;if(EL(t))return e?void 0:typeof t=="object"&&t.description?{type:"object",description:t.description}:{type:"object"};if(typeof t=="boolean")return{type:"boolean",properties:{}};const{type:n,description:o,required:i,properties:s,items:r,allOf:a,anyOf:u,oneOf:c,format:p,const:f,minLength:h,enum:m}=t,v={};if(o&&(v.description=o),i&&(v.required=i),p&&(v.format=p),f!==void 0&&(v.enum=[f]),n)if(Array.isArray(n)){const _=n.includes("null"),w=n.filter(C=>C!=="null");w.length===0?v.type="null":(v.anyOf=w.map(C=>({type:C})),_&&(v.nullable=!0))}else v.type=n;if(m!==void 0&&(v.enum=m),s!=null&&(v.properties=Object.entries(s).reduce((_,[w,C])=>(_[w]=Tn(C,!1),_),{})),r&&(v.items=Array.isArray(r)?r.map(_=>Tn(_,!1)):Tn(r,!1)),a&&(v.allOf=a.map(_=>Tn(_,!1))),u)if(u.some(_=>typeof _=="object"&&(_==null?void 0:_.type)==="null")){const _=u.filter(w=>!(typeof w=="object"&&(w==null?void 0:w.type)==="null"));if(_.length===1){const w=Tn(_[0],!1);typeof w=="object"&&(v.nullable=!0,Object.assign(v,w))}else v.anyOf=_.map(w=>Tn(w,!1)),v.nullable=!0}else v.anyOf=u.map(_=>Tn(_,!1));return c&&(v.oneOf=c.map(_=>Tn(_,!1))),h!==void 0&&(v.minLength=h),v}function EL(t){return t!=null&&typeof t=="object"&&t.type==="object"&&(t.properties==null||Object.keys(t.properties).length===0)&&!t.additionalProperties}var wL=/^data:([^;,]+);base64,(.+)$/s;function IL(t){const e=wL.exec(t);if(e!=null)return{mediaType:e[1],data:e[2]}}function SL(t){const e=IL(t);if(e!=null)return{inlineData:{mimeType:e.mediaType,data:e.data}}}function CL(t,e,n,o){const i=[],s=[];for(const r of n)switch(r.type){case"text":{s.push(r.text);break}case"image-data":case"file-data":{i.push({inlineData:{mimeType:r.mediaType,data:r.data}});break}case"image-url":case"file-url":{const a=SL(r.url);a!=null?i.push(a):s.push(JSON.stringify(r));break}default:{s.push(JSON.stringify(r));break}}t.push({functionResponse:{...o!=null?{id:o}:{},name:e,response:{name:e,content:s.length>0?s.join(`
124
+ `):"Tool executed successfully."},...i.length>0?{parts:i}:{}}})}function AL(t,e,n,o){for(const i of n)switch(i.type){case"text":t.push({functionResponse:{...o!=null?{id:o}:{},name:e,response:{name:e,content:i.text}}});break;case"image-data":t.push({inlineData:{mimeType:String(i.mediaType),data:String(i.data)}},{text:"Tool executed successfully and returned this image as a response"});break;default:t.push({text:JSON.stringify(i)});break}}function bL(t,e){var n,o,i,s,r,a,u,c;const p=[],f=[];let h=!0;const m=(n=e==null?void 0:e.isGemmaModel)!=null?n:!1,v=(o=e==null?void 0:e.providerOptionsName)!=null?o:"google",_=(i=e==null?void 0:e.supportsFunctionResponseParts)!=null?i:!0;for(const{role:w,content:C}of t)switch(w){case"system":{if(!h)throw new Vi({functionality:"system messages are only supported at the beginning of the conversation"});p.push({text:C});break}case"user":{h=!1;const E=[];for(const A of C)switch(A.type){case"text":{E.push({text:A.text});break}case"file":{const R=A.mediaType==="image/*"?"image/jpeg":A.mediaType;E.push(A.data instanceof URL?{fileData:{mimeType:R,fileUri:A.data.toString()}}:{inlineData:{mimeType:R,data:Ps(A.data)}});break}}f.push({role:"user",parts:E});break}case"assistant":{h=!1,f.push({role:"model",parts:C.map(E=>{var A,R,k,b;const U=(b=(A=E.providerOptions)==null?void 0:A[v])!=null?b:v!=="google"?(R=E.providerOptions)==null?void 0:R.google:(k=E.providerOptions)==null?void 0:k.vertex,J=(U==null?void 0:U.thoughtSignature)!=null?String(U.thoughtSignature):void 0;switch(E.type){case"text":return E.text.length===0?void 0:{text:E.text,thoughtSignature:J};case"reasoning":return E.text.length===0?void 0:{text:E.text,thought:!0,thoughtSignature:J};case"file":{if(E.data instanceof URL)throw new Vi({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:E.mediaType,data:Ps(E.data)},...(U==null?void 0:U.thought)===!0?{thought:!0}:{},thoughtSignature:J}}case"tool-call":{const G=(U==null?void 0:U.serverToolCallId)!=null?String(U.serverToolCallId):void 0,L=(U==null?void 0:U.serverToolType)!=null?String(U.serverToolType):void 0;return G&&L?{toolCall:{toolType:L,args:typeof E.input=="string"?JSON.parse(E.input):E.input,id:G},thoughtSignature:J}:{functionCall:{...E.toolCallId!=null?{id:E.toolCallId}:{},name:E.toolName,args:E.input},thoughtSignature:J}}case"tool-result":{const G=(U==null?void 0:U.serverToolCallId)!=null?String(U.serverToolCallId):void 0,L=(U==null?void 0:U.serverToolType)!=null?String(U.serverToolType):void 0;return G&&L?{toolResponse:{toolType:L,response:E.output.type==="json"?E.output.value:{},id:G},thoughtSignature:J}:void 0}}}).filter(E=>E!==void 0)});break}case"tool":{h=!1;const E=[];for(const A of C){if(A.type==="tool-approval-response")continue;const R=(u=(s=A.providerOptions)==null?void 0:s[v])!=null?u:v!=="google"?(r=A.providerOptions)==null?void 0:r.google:(a=A.providerOptions)==null?void 0:a.vertex,k=(R==null?void 0:R.serverToolCallId)!=null?String(R.serverToolCallId):void 0,b=(R==null?void 0:R.serverToolType)!=null?String(R.serverToolType):void 0;if(k&&b){const J=(R==null?void 0:R.thoughtSignature)!=null?String(R.thoughtSignature):void 0;if(f.length>0){const G=f[f.length-1];if(G.role==="model"){G.parts.push({toolResponse:{toolType:b,response:A.output.type==="json"?A.output.value:{},id:k},thoughtSignature:J});continue}}}const U=A.output;U.type==="content"?_?CL(E,A.toolName,U.value,A.toolCallId):AL(E,A.toolName,U.value,A.toolCallId):E.push({functionResponse:{...A.toolCallId!=null?{id:A.toolCallId}:{},name:A.toolName,response:{name:A.toolName,content:U.type==="execution-denied"?(c=U.reason)!=null?c:"Tool execution denied.":U.value}}})}f.push({role:"user",parts:E});break}}if(m&&p.length>0&&f.length>0&&f[0].role==="user"){const w=p.map(C=>C.text).join(`
125
+
126
+ `);f[0].parts.unshift({text:w+`
127
+
128
+ `})}return{systemInstruction:p.length>0&&!m?{parts:p}:void 0,contents:f}}function Lf(t){return t.includes("/")?t:`models/${t}`}var Gf=xe(()=>Me(M({responseModalities:ee(Te(["TEXT","IMAGE"])).optional(),thinkingConfig:M({thinkingBudget:W().optional(),includeThoughts:ht().optional(),thinkingLevel:Te(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:I().optional(),structuredOutputs:ht().optional(),safetySettings:ee(M({category:Te(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:Te(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:Te(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:ht().optional(),labels:Et(I(),I()).optional(),mediaResolution:Te(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:M({aspectRatio:Te(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).optional(),imageSize:Te(["1K","2K","4K","512"]).optional()}).optional(),retrievalConfig:M({latLng:M({latitude:W(),longitude:W()}).optional()}).optional(),streamFunctionCallArguments:ht().optional(),serviceTier:Te(["standard","flex","priority"]).optional()}))),RL={standard:"SERVICE_TIER_STANDARD",flex:"SERVICE_TIER_FLEX",priority:"SERVICE_TIER_PRIORITY"};function kL({tools:t,toolChoice:e,modelId:n,isVertexProvider:o=!1}){var i,s;t=t!=null&&t.length?t:void 0;const r=[],a=["gemini-flash-latest","gemini-flash-lite-latest","gemini-pro-latest"].some(w=>w===n),u=n.includes("gemini-2")||n.includes("gemini-3")||n.includes("nano-banana")||a,c=n.includes("gemini-3"),p=n.includes("gemini-2.5")||n.includes("gemini-3");if(t==null)return{tools:void 0,toolConfig:void 0,toolWarnings:r};const f=t.some(w=>w.type==="function"),h=t.some(w=>w.type==="provider");if(f&&h&&!c&&r.push({type:"unsupported",feature:"combination of function and provider-defined tools"}),h){const w=[];if(t.filter(E=>E.type==="provider").forEach(E=>{switch(E.id){case"google.google_search":u?w.push({googleSearch:{...E.args}}):r.push({type:"unsupported",feature:`provider-defined tool ${E.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":u?w.push({enterpriseWebSearch:{}}):r.push({type:"unsupported",feature:`provider-defined tool ${E.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":u?w.push({urlContext:{}}):r.push({type:"unsupported",feature:`provider-defined tool ${E.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":u?w.push({codeExecution:{}}):r.push({type:"unsupported",feature:`provider-defined tool ${E.id}`,details:"The code execution tool is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":p?w.push({fileSearch:{...E.args}}):r.push({type:"unsupported",feature:`provider-defined tool ${E.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":u?w.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:E.args.ragCorpus},similarity_top_k:E.args.topK}}}):r.push({type:"unsupported",feature:`provider-defined tool ${E.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":u?w.push({googleMaps:{}}):r.push({type:"unsupported",feature:`provider-defined tool ${E.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:r.push({type:"unsupported",feature:`provider-defined tool ${E.id}`});break}}),f&&c&&w.length>0){const E=[];for(const R of t)R.type==="function"&&E.push({name:R.name,description:(i=R.description)!=null?i:"",parameters:Tn(R.inputSchema)});const A={functionCallingConfig:{mode:"VALIDATED"},...!o&&{includeServerSideToolInvocations:!0}};if(e!=null)switch(e.type){case"auto":break;case"none":A.functionCallingConfig={mode:"NONE"};break;case"required":A.functionCallingConfig={mode:"ANY"};break;case"tool":A.functionCallingConfig={mode:"ANY",allowedFunctionNames:[e.toolName]};break}return{tools:[...w,{functionDeclarations:E}],toolConfig:A,toolWarnings:r}}return{tools:w.length>0?w:void 0,toolConfig:void 0,toolWarnings:r}}const m=[];let v=!1;for(const w of t)switch(w.type){case"function":m.push({name:w.name,description:(s=w.description)!=null?s:"",parameters:Tn(w.inputSchema)}),w.strict===!0&&(v=!0);break;default:r.push({type:"unsupported",feature:`function tool ${w.name}`});break}if(e==null)return{tools:[{functionDeclarations:m}],toolConfig:v?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:r};const _=e.type;switch(_){case"auto":return{tools:[{functionDeclarations:m}],toolConfig:{functionCallingConfig:{mode:v?"VALIDATED":"AUTO"}},toolWarnings:r};case"none":return{tools:[{functionDeclarations:m}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:r};case"required":return{tools:[{functionDeclarations:m}],toolConfig:{functionCallingConfig:{mode:v?"VALIDATED":"ANY"}},toolWarnings:r};case"tool":return{tools:[{functionDeclarations:m}],toolConfig:{functionCallingConfig:{mode:v?"VALIDATED":"ANY",allowedFunctionNames:[e.toolName]}},toolWarnings:r};default:{const w=_;throw new Vi({functionality:`tool choice type: ${w}`})}}}var PL=class{constructor(){this.accumulatedArgs={},this.jsonText="",this.pathStack=[],this.stringOpen=!1}processPartialArgs(t){let e="";for(const n of t){const o=n.jsonPath.replace(/^\$\./,"");if(!o)continue;const i=NL(o),s=ML(this.accumulatedArgs,i);if(n.stringValue!=null&&s!==void 0){const u=JSON.stringify(n.stringValue).slice(1,-1);zf(this.accumulatedArgs,i,s+n.stringValue),e+=u;continue}const a=xL(n);a!=null&&(zf(this.accumulatedArgs,i,a.value),e+=this.emitNavigationTo(i,n,a.json))}return this.jsonText+=e,{currentJSON:this.accumulatedArgs,textDelta:e}}finalize(){const t=JSON.stringify(this.accumulatedArgs),e=t.slice(this.jsonText.length);return{finalJSON:t,closingDelta:e}}ensureRoot(){return this.pathStack.length===0?(this.pathStack.push({segment:"",isArray:!1,childCount:0}),"{"):""}emitNavigationTo(t,e,n){let o="";this.stringOpen&&(o+='"',this.stringOpen=!1),o+=this.ensureRoot();const i=t.slice(0,-1),s=t[t.length-1],r=this.findCommonStackDepth(i);return o+=this.closeDownTo(r),o+=this.openDownTo(i,s),o+=this.emitLeaf(s,e,n),o}findCommonStackDepth(t){const e=Math.min(this.pathStack.length-1,t.length);let n=0;for(let o=0;o<e&&this.pathStack[o+1].segment===t[o];o++)n++;return n+1}closeDownTo(t){let e="";for(;this.pathStack.length>t;){const n=this.pathStack.pop();e+=n.isArray?"]":"}"}return e}openDownTo(t,e){let n="";const o=this.pathStack.length-1;for(let i=o;i<t.length;i++){const s=t[i],r=this.pathStack[this.pathStack.length-1];r.childCount>0&&(n+=","),r.childCount++,typeof s=="string"&&(n+=`${JSON.stringify(s)}:`);const u=typeof(i+1<t.length?t[i+1]:e)=="number";n+=u?"[":"{",this.pathStack.push({segment:s,isArray:u,childCount:0})}return n}emitLeaf(t,e,n){let o="";const i=this.pathStack[this.pathStack.length-1];return i.childCount>0&&(o+=","),i.childCount++,typeof t=="string"&&(o+=`${JSON.stringify(t)}:`),e.stringValue!=null&&e.willContinue?(o+=n.slice(0,-1),this.stringOpen=!0):o+=n,o}};function NL(t){const e=[];for(const n of t.split(".")){const o=n.indexOf("[");if(o===-1)e.push(n);else{o>0&&e.push(n.slice(0,o));for(const i of n.matchAll(/\[(\d+)\]/g))e.push(parseInt(i[1],10))}}return e}function ML(t,e){let n=t;for(const o of e){if(n==null||typeof n!="object")return;n=n[o]}return n}function zf(t,e,n){let o=t;for(let i=0;i<e.length-1;i++){const s=e[i],r=e[i+1];o[s]==null&&(o[s]=typeof r=="number"?[]:{}),o=o[s]}o[e[e.length-1]]=n}function xL(t){var e,n;const o=(n=(e=t.stringValue)!=null?e:t.numberValue)!=null?n:t.boolValue;if(o!=null)return{value:o,json:JSON.stringify(o)};if("nullValue"in t)return{value:null,json:"null"}}function Ff({finishReason:t,hasToolCalls:e}){switch(t){case"STOP":return e?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"MALFORMED_FUNCTION_CALL":return"error";case"FINISH_REASON_UNSPECIFIED":case"OTHER":default:return"other"}}var DT=class{constructor(t,e){this.specificationVersion="v3";var n;this.modelId=t,this.config=e,this.generateId=(n=e.generateId)!=null?n:Hn}get provider(){return this.config.provider}get supportedUrls(){var t,e,n;return(n=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?n:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:n,topP:o,topK:i,frequencyPenalty:s,presencePenalty:r,stopSequences:a,responseFormat:u,seed:c,tools:p,toolChoice:f,providerOptions:h},{isStreaming:m=!1}={}){var v,_;const w=[],C=this.config.provider.includes("vertex")?"vertex":"google";let E=await Hi({provider:C,providerOptions:h,schema:Gf});E==null&&C!=="google"&&(E=await Hi({provider:"google",providerOptions:h,schema:Gf}));const A=this.config.provider.startsWith("google.vertex.");p!=null&&p.some(ye=>ye.type==="provider"&&ye.id==="google.vertex_rag_store")&&!A&&w.push({type:"other",message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`}),E!=null&&E.streamFunctionCallArguments&&!A&&w.push({type:"other",message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});let R=E==null?void 0:E.serviceTier;E!=null&&E.serviceTier&&A&&(R=RL[E.serviceTier]);const k=this.modelId.toLowerCase().startsWith("gemma-"),b=this.modelId.startsWith("gemini-3"),{contents:U,systemInstruction:J}=bL(t,{isGemmaModel:k,providerOptionsName:C,supportsFunctionResponseParts:b}),{tools:G,toolConfig:L,toolWarnings:B}=kL({tools:p,toolChoice:f,modelId:this.modelId,isVertexProvider:A}),ve=m&&A?(v=E==null?void 0:E.streamFunctionCallArguments)!=null?v:!1:void 0,Ae=L||ve||E!=null&&E.retrievalConfig?{...L,...ve&&{functionCallingConfig:{...L==null?void 0:L.functionCallingConfig,streamFunctionCallArguments:!0}},...(E==null?void 0:E.retrievalConfig)&&{retrievalConfig:E.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:e,temperature:n,topK:i,topP:o,frequencyPenalty:s,presencePenalty:r,stopSequences:a,seed:c,responseMimeType:(u==null?void 0:u.type)==="json"?"application/json":void 0,responseSchema:(u==null?void 0:u.type)==="json"&&u.schema!=null&&((_=E==null?void 0:E.structuredOutputs)==null||_)?Tn(u.schema):void 0,...(E==null?void 0:E.audioTimestamp)&&{audioTimestamp:E.audioTimestamp},responseModalities:E==null?void 0:E.responseModalities,thinkingConfig:E==null?void 0:E.thinkingConfig,...(E==null?void 0:E.mediaResolution)&&{mediaResolution:E.mediaResolution},...(E==null?void 0:E.imageConfig)&&{imageConfig:E.imageConfig}},contents:U,systemInstruction:k?void 0:J,safetySettings:E==null?void 0:E.safetySettings,tools:G,toolConfig:Ae,cachedContent:E==null?void 0:E.cachedContent,labels:E==null?void 0:E.labels,serviceTier:R},warnings:[...w,...B],providerOptionsName:C}}async doGenerate(t){var e,n,o,i,s,r,a,u,c,p,f,h,m,v,_,w,C,E;const{args:A,warnings:R,providerOptionsName:k}=await this.getArgs(t),b=Dt(await He(this.config.headers),t.headers),{responseHeaders:U,value:J,rawValue:G}=await xt({url:`${this.config.baseURL}/${Lf(this.modelId)}:generateContent`,headers:b,body:A,failedResponseHandler:an,successfulResponseHandler:Ct($L),abortSignal:t.abortSignal,fetch:this.config.fetch}),L=J.candidates[0],B=[],ve=(n=(e=L.content)==null?void 0:e.parts)!=null?n:[],Ae=J.usageMetadata;let ye,ue;for(const j of ve)if("executableCode"in j&&((o=j.executableCode)!=null&&o.code)){const re=this.config.generateId();ye=re,B.push({type:"tool-call",toolCallId:re,toolName:"code_execution",input:JSON.stringify(j.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in j&&j.codeExecutionResult)B.push({type:"tool-result",toolCallId:ye,toolName:"code_execution",result:{outcome:j.codeExecutionResult.outcome,output:(i=j.codeExecutionResult.output)!=null?i:""}}),ye=void 0;else if("text"in j&&j.text!=null){const re=j.thoughtSignature?{[k]:{thoughtSignature:j.thoughtSignature}}:void 0;if(j.text.length===0){if(re!=null&&B.length>0){const x=B[B.length-1];x.providerMetadata=re}}else B.push({type:j.thought===!0?"reasoning":"text",text:j.text,providerMetadata:re})}else if("functionCall"in j&&j.functionCall.name!=null)B.push({type:"tool-call",toolCallId:(s=j.functionCall.id)!=null?s:this.config.generateId(),toolName:j.functionCall.name,input:JSON.stringify((r=j.functionCall.args)!=null?r:{}),providerMetadata:j.thoughtSignature?{[k]:{thoughtSignature:j.thoughtSignature}}:void 0});else if("inlineData"in j){const re=j.thought===!0,x=!!j.thoughtSignature;B.push({type:"file",data:j.inlineData.data,mediaType:j.inlineData.mimeType,providerMetadata:re||x?{[k]:{...re?{thought:!0}:{},...x?{thoughtSignature:j.thoughtSignature}:{}}}:void 0})}else if("toolCall"in j&&j.toolCall){const re=(a=j.toolCall.id)!=null?a:this.config.generateId();ue=re,B.push({type:"tool-call",toolCallId:re,toolName:`server:${j.toolCall.toolType}`,input:JSON.stringify((u=j.toolCall.args)!=null?u:{}),providerExecuted:!0,dynamic:!0,providerMetadata:j.thoughtSignature?{[k]:{thoughtSignature:j.thoughtSignature,serverToolCallId:re,serverToolType:j.toolCall.toolType}}:{[k]:{serverToolCallId:re,serverToolType:j.toolCall.toolType}}})}else if("toolResponse"in j&&j.toolResponse){const re=(c=ue??j.toolResponse.id)!=null?c:this.config.generateId();B.push({type:"tool-result",toolCallId:re,toolName:`server:${j.toolResponse.toolType}`,result:(p=j.toolResponse.response)!=null?p:{},providerMetadata:j.thoughtSignature?{[k]:{thoughtSignature:j.thoughtSignature,serverToolCallId:re,serverToolType:j.toolResponse.toolType}}:{[k]:{serverToolCallId:re,serverToolType:j.toolResponse.toolType}}}),ue=void 0}const we=(f=Vf({groundingMetadata:L.groundingMetadata,generateId:this.config.generateId}))!=null?f:[];for(const j of we)B.push(j);return{content:B,finishReason:{unified:Ff({finishReason:L.finishReason,hasToolCalls:B.some(j=>j.type==="tool-call"&&!j.providerExecuted)}),raw:(h=L.finishReason)!=null?h:void 0},usage:Of(Ae),warnings:R,providerMetadata:{[k]:{promptFeedback:(m=J.promptFeedback)!=null?m:null,groundingMetadata:(v=L.groundingMetadata)!=null?v:null,urlContextMetadata:(_=L.urlContextMetadata)!=null?_:null,safetyRatings:(w=L.safetyRatings)!=null?w:null,usageMetadata:Ae??null,finishMessage:(C=L.finishMessage)!=null?C:null,serviceTier:(E=J.serviceTier)!=null?E:null}},request:{body:A},response:{headers:U,body:G}}}async doStream(t){const{args:e,warnings:n,providerOptionsName:o}=await this.getArgs(t,{isStreaming:!0}),i=Dt(await He(this.config.headers),t.headers),{responseHeaders:s,value:r}=await xt({url:`${this.config.baseURL}/${Lf(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:e,failedResponseHandler:an,successfulResponseHandler:Bl(UL),abortSignal:t.abortSignal,fetch:this.config.fetch});let a={unified:"other",raw:void 0},u,c,p=null,f=null,h=null;const m=this.config.generateId;let v=!1,_=null,w=null,C=0;const E=new Set;let A,R;const k=[];return{stream:r.pipeThrough(new TransformStream({start(b){b.enqueue({type:"stream-start",warnings:n})},transform(b,U){var J,G,L,B,ve,Ae,ye,ue,we,j,re,x,ce,H,X;if(t.includeRawChunks&&U.enqueue({type:"raw",rawValue:b.rawValue}),!b.success){U.enqueue({type:"error",error:b.error});return}const ge=b.value,oe=ge.usageMetadata;oe!=null&&(u=oe),ge.serviceTier!=null&&(h=ge.serviceTier);const _e=(J=ge.candidates)==null?void 0:J[0];if(_e==null)return;const wt=_e.content;_e.groundingMetadata!=null&&(p=_e.groundingMetadata),_e.urlContextMetadata!=null&&(f=_e.urlContextMetadata);const eo=Vf({groundingMetadata:_e.groundingMetadata,generateId:m});if(eo!=null)for(const Qt of eo)Qt.sourceType==="url"&&!E.has(Qt.url)&&(E.add(Qt.url),U.enqueue(Qt));if(wt!=null){const Qt=(G=wt.parts)!=null?G:[];for(const K of Qt)if("executableCode"in K&&((L=K.executableCode)!=null&&L.code)){const he=m();A=he,U.enqueue({type:"tool-call",toolCallId:he,toolName:"code_execution",input:JSON.stringify(K.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in K&&K.codeExecutionResult){const he=A;he&&(U.enqueue({type:"tool-result",toolCallId:he,toolName:"code_execution",result:{outcome:K.codeExecutionResult.outcome,output:(B=K.codeExecutionResult.output)!=null?B:""}}),A=void 0)}else if("text"in K&&K.text!=null){const he=K.thoughtSignature?{[o]:{thoughtSignature:K.thoughtSignature}}:void 0;K.text.length===0?he!=null&&_!==null&&U.enqueue({type:"text-delta",id:_,delta:"",providerMetadata:he}):K.thought===!0?(_!==null&&(U.enqueue({type:"text-end",id:_}),_=null),w===null&&(w=String(C++),U.enqueue({type:"reasoning-start",id:w,providerMetadata:he})),U.enqueue({type:"reasoning-delta",id:w,delta:K.text,providerMetadata:he})):(w!==null&&(U.enqueue({type:"reasoning-end",id:w}),w=null),_===null&&(_=String(C++),U.enqueue({type:"text-start",id:_,providerMetadata:he})),U.enqueue({type:"text-delta",id:_,delta:K.text,providerMetadata:he}))}else if("inlineData"in K){_!==null&&(U.enqueue({type:"text-end",id:_}),_=null),w!==null&&(U.enqueue({type:"reasoning-end",id:w}),w=null);const he=K.thought===!0,At=!!K.thoughtSignature,hn=he||At?{[o]:{...he?{thought:!0}:{},...At?{thoughtSignature:K.thoughtSignature}:{}}}:void 0;U.enqueue({type:"file",mediaType:K.inlineData.mimeType,data:K.inlineData.data,providerMetadata:hn})}else if("toolCall"in K&&K.toolCall){const he=(ve=K.toolCall.id)!=null?ve:m();R=he;const At={[o]:{...K.thoughtSignature?{thoughtSignature:K.thoughtSignature}:{},serverToolCallId:he,serverToolType:K.toolCall.toolType}};U.enqueue({type:"tool-call",toolCallId:he,toolName:`server:${K.toolCall.toolType}`,input:JSON.stringify((Ae=K.toolCall.args)!=null?Ae:{}),providerExecuted:!0,dynamic:!0,providerMetadata:At})}else if("toolResponse"in K&&K.toolResponse){const he=(ye=R??K.toolResponse.id)!=null?ye:m(),At={[o]:{...K.thoughtSignature?{thoughtSignature:K.thoughtSignature}:{},serverToolCallId:he,serverToolType:K.toolResponse.toolType}};U.enqueue({type:"tool-result",toolCallId:he,toolName:`server:${K.toolResponse.toolType}`,result:(ue=K.toolResponse.response)!=null?ue:{},providerMetadata:At}),R=void 0}for(const K of Qt){if(!("functionCall"in K))continue;const he=K.thoughtSignature?{[o]:{thoughtSignature:K.thoughtSignature}}:void 0,At=K.functionCall.partialArgs!=null||K.functionCall.name!=null&&K.functionCall.willContinue===!0,hn=K.functionCall.name==null&&K.functionCall.args==null&&K.functionCall.partialArgs==null&&K.functionCall.willContinue==null,Mo=K.functionCall.name!=null&&K.functionCall.args!=null&&K.functionCall.partialArgs==null,xo=K.functionCall.name!=null&&K.functionCall.args==null&&K.functionCall.partialArgs==null&&K.functionCall.willContinue!==!0;if(At){if(K.functionCall.name!=null&&K.functionCall.willContinue===!0){const De=(we=K.functionCall.id)!=null?we:m(),gt=new PL;if(k.push({toolCallId:De,toolName:K.functionCall.name,accumulator:gt,providerMetadata:he}),U.enqueue({type:"tool-input-start",id:De,toolName:K.functionCall.name,providerMetadata:he}),K.functionCall.partialArgs!=null){const{textDelta:Ue}=gt.processPartialArgs(K.functionCall.partialArgs);Ue.length>0&&U.enqueue({type:"tool-input-delta",id:De,delta:Ue,providerMetadata:he})}}else if(K.functionCall.partialArgs!=null&&k.length>0){const De=k[k.length-1],{textDelta:gt}=De.accumulator.processPartialArgs(K.functionCall.partialArgs);gt.length>0&&U.enqueue({type:"tool-input-delta",id:De.toolCallId,delta:gt,providerMetadata:he})}}else if(hn&&k.length>0){const De=k.pop(),{finalJSON:gt,closingDelta:Ue}=De.accumulator.finalize();Ue.length>0&&U.enqueue({type:"tool-input-delta",id:De.toolCallId,delta:Ue,providerMetadata:De.providerMetadata}),U.enqueue({type:"tool-input-end",id:De.toolCallId,providerMetadata:De.providerMetadata}),U.enqueue({type:"tool-call",toolCallId:De.toolCallId,toolName:De.toolName,input:gt,providerMetadata:De.providerMetadata}),v=!0}else if(Mo){const De=(j=K.functionCall.id)!=null?j:m(),gt=K.functionCall.name,Ue=typeof K.functionCall.args=="string"?K.functionCall.args:JSON.stringify((re=K.functionCall.args)!=null?re:{});U.enqueue({type:"tool-input-start",id:De,toolName:gt,providerMetadata:he}),U.enqueue({type:"tool-input-delta",id:De,delta:Ue,providerMetadata:he}),U.enqueue({type:"tool-input-end",id:De,providerMetadata:he}),U.enqueue({type:"tool-call",toolCallId:De,toolName:gt,input:Ue,providerMetadata:he}),v=!0}else if(xo){const De=(x=K.functionCall.id)!=null?x:m(),gt=K.functionCall.name;U.enqueue({type:"tool-input-start",id:De,toolName:gt,providerMetadata:he}),U.enqueue({type:"tool-input-end",id:De,providerMetadata:he}),U.enqueue({type:"tool-call",toolCallId:De,toolName:gt,input:"{}",providerMetadata:he}),v=!0}}}_e.finishReason!=null&&(a={unified:Ff({finishReason:_e.finishReason,hasToolCalls:v}),raw:_e.finishReason},c={[o]:{promptFeedback:(ce=ge.promptFeedback)!=null?ce:null,groundingMetadata:p,urlContextMetadata:f,safetyRatings:(H=_e.safetyRatings)!=null?H:null,usageMetadata:oe??null,finishMessage:(X=_e.finishMessage)!=null?X:null,serviceTier:h}})},flush(b){_!==null&&b.enqueue({type:"text-end",id:_}),w!==null&&b.enqueue({type:"reasoning-end",id:w}),b.enqueue({type:"finish",finishReason:a,usage:Of(u),providerMetadata:c})}})),response:{headers:s},request:{body:e}}}};function Vf({groundingMetadata:t,generateId:e}){var n,o,i,s,r,a;if(!(t!=null&&t.groundingChunks))return;const u=[];for(const c of t.groundingChunks)if(c.web!=null)u.push({type:"source",sourceType:"url",id:e(),url:c.web.uri,title:(n=c.web.title)!=null?n:void 0});else if(c.image!=null)u.push({type:"source",sourceType:"url",id:e(),url:c.image.sourceUri,title:(o=c.image.title)!=null?o:void 0});else if(c.retrievedContext!=null){const p=c.retrievedContext.uri,f=c.retrievedContext.fileSearchStore;if(p&&(p.startsWith("http://")||p.startsWith("https://")))u.push({type:"source",sourceType:"url",id:e(),url:p,title:(i=c.retrievedContext.title)!=null?i:void 0});else if(p){const h=(s=c.retrievedContext.title)!=null?s:"Unknown Document";let m="application/octet-stream",v;p.endsWith(".pdf")?(m="application/pdf",v=p.split("/").pop()):p.endsWith(".txt")?(m="text/plain",v=p.split("/").pop()):p.endsWith(".docx")?(m="application/vnd.openxmlformats-officedocument.wordprocessingml.document",v=p.split("/").pop()):p.endsWith(".doc")?(m="application/msword",v=p.split("/").pop()):(p.match(/\.(md|markdown)$/)&&(m="text/markdown"),v=p.split("/").pop()),u.push({type:"source",sourceType:"document",id:e(),mediaType:m,title:h,filename:v})}else if(f){const h=(r=c.retrievedContext.title)!=null?r:"Unknown Document";u.push({type:"source",sourceType:"document",id:e(),mediaType:"application/octet-stream",title:h,filename:f.split("/").pop()})}}else c.maps!=null&&c.maps.uri&&u.push({type:"source",sourceType:"url",id:e(),url:c.maps.uri,title:(a=c.maps.title)!=null?a:void 0});return u.length>0?u:void 0}var $T=()=>M({webSearchQueries:ee(I()).nullish(),imageSearchQueries:ee(I()).nullish(),retrievalQueries:ee(I()).nullish(),searchEntryPoint:M({renderedContent:I()}).nullish(),groundingChunks:ee(M({web:M({uri:I(),title:I().nullish()}).nullish(),image:M({sourceUri:I(),imageUri:I(),title:I().nullish(),domain:I().nullish()}).nullish(),retrievedContext:M({uri:I().nullish(),title:I().nullish(),text:I().nullish(),fileSearchStore:I().nullish()}).nullish(),maps:M({uri:I().nullish(),title:I().nullish(),text:I().nullish(),placeId:I().nullish()}).nullish()})).nullish(),groundingSupports:ee(M({segment:M({startIndex:W().nullish(),endIndex:W().nullish(),text:I().nullish()}).nullish(),segment_text:I().nullish(),groundingChunkIndices:ee(W()).nullish(),supportChunkIndices:ee(W()).nullish(),confidenceScores:ee(W()).nullish(),confidenceScore:ee(W()).nullish()})).nullish(),retrievalMetadata:$e([M({webDynamicRetrievalScore:W()}),M({})]).nullish()}),DL=M({jsonPath:I(),stringValue:I().nullish(),numberValue:W().nullish(),boolValue:ht().nullish(),nullValue:at().nullish(),willContinue:ht().nullish()}),UT=()=>M({parts:ee($e([M({functionCall:M({id:I().nullish(),name:I().nullish(),args:at().nullish(),partialArgs:ee(DL).nullish(),willContinue:ht().nullish()}),thoughtSignature:I().nullish()}),M({inlineData:M({mimeType:I(),data:I()}),thought:ht().nullish(),thoughtSignature:I().nullish()}),M({toolCall:M({toolType:I(),args:at().nullish(),id:I()}),thoughtSignature:I().nullish()}),M({toolResponse:M({toolType:I(),response:at().nullish(),id:I()}),thoughtSignature:I().nullish()}),M({executableCode:M({language:I(),code:I()}).nullish(),codeExecutionResult:M({outcome:I(),output:I().nullish()}).nullish(),text:I().nullish(),thought:ht().nullish(),thoughtSignature:I().nullish()})])).nullish()}),el=()=>M({category:I().nullish(),probability:I().nullish(),probabilityScore:W().nullish(),severity:I().nullish(),severityScore:W().nullish(),blocked:ht().nullish()}),qf=ee(M({modality:I(),tokenCount:W()})).nullish(),OT=M({cachedContentTokenCount:W().nullish(),thoughtsTokenCount:W().nullish(),promptTokenCount:W().nullish(),candidatesTokenCount:W().nullish(),totalTokenCount:W().nullish(),trafficType:I().nullish(),promptTokensDetails:qf,candidatesTokensDetails:qf}),LT=()=>M({urlMetadata:ee(M({retrievedUrl:I(),urlRetrievalStatus:I()})).nullish()}),$L=xe(()=>Me(M({candidates:ee(M({content:UT().nullish().or(M({}).strict()),finishReason:I().nullish(),finishMessage:I().nullish(),safetyRatings:ee(el()).nullish(),groundingMetadata:$T().nullish(),urlContextMetadata:LT().nullish()})),usageMetadata:OT.nullish(),promptFeedback:M({blockReason:I().nullish(),safetyRatings:ee(el()).nullish()}).nullish(),serviceTier:I().nullish()}))),UL=xe(()=>Me(M({candidates:ee(M({content:UT().nullish(),finishReason:I().nullish(),finishMessage:I().nullish(),safetyRatings:ee(el()).nullish(),groundingMetadata:$T().nullish(),urlContextMetadata:LT().nullish()})).nullish(),usageMetadata:OT.nullish(),promptFeedback:M({blockReason:I().nullish(),safetyRatings:ee(el()).nullish()}).nullish(),serviceTier:I().nullish()}))),OL=id({id:"google.code_execution",inputSchema:M({language:I().describe("The programming language of the code."),code:I().describe("The code to be executed.")}),outputSchema:M({outcome:I().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:I().describe("The output from the code execution.")})}),LL=es({id:"google.enterprise_web_search",inputSchema:xe(()=>Me(M({})))}),GL=M({fileSearchStoreNames:ee(I()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:W().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:I().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()}).passthrough(),zL=xe(()=>Me(GL)),FL=es({id:"google.file_search",inputSchema:zL}),VL=es({id:"google.google_maps",inputSchema:xe(()=>Me(M({})))}),qL=M({searchTypes:M({webSearch:M({}).optional(),imageSearch:M({}).optional()}).optional(),timeRangeFilter:M({startTime:I(),endTime:I()}).optional()}).passthrough(),BL=xe(()=>Me(qL)),HL=es({id:"google.google_search",inputSchema:BL}),ZL=es({id:"google.url_context",inputSchema:xe(()=>Me(M({})))}),JL=es({id:"google.vertex_rag_store",inputSchema:M({ragCorpus:I(),topK:W().optional()})}),WL={googleSearch:HL,enterpriseWebSearch:LL,googleMaps:VL,urlContext:ZL,fileSearch:FL,codeExecution:OL,vertexRagStore:JL},KL=class{constructor(t,e,n){this.modelId=t,this.settings=e,this.config=n,this.specificationVersion="v3"}get maxImagesPerCall(){return this.settings.maxImagesPerCall!=null?this.settings.maxImagesPerCall:Bf(this.modelId)?10:4}get provider(){return this.config.provider}async doGenerate(t){return Bf(this.modelId)?this.doGenerateGemini(t):this.doGenerateImagen(t)}async doGenerateImagen(t){var e,n,o;const{prompt:i,n:s=1,size:r,aspectRatio:a="1:1",seed:u,providerOptions:c,headers:p,abortSignal:f,files:h,mask:m}=t,v=[];if(h!=null&&h.length>0)throw new Error("Google Generative AI does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");if(m!=null)throw new Error("Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");r!=null&&v.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."}),u!=null&&v.push({type:"unsupported",feature:"seed",details:"This model does not support the `seed` option through this provider."});const _=await Hi({provider:"google",providerOptions:c,schema:XL}),w=(o=(n=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:n.call(e))!=null?o:new Date,C={sampleCount:s};a!=null&&(C.aspectRatio=a),_&&Object.assign(C,_);const E={instances:[{prompt:i}],parameters:C},{responseHeaders:A,value:R}=await xt({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:Dt(await He(this.config.headers),p),body:E,failedResponseHandler:an,successfulResponseHandler:Ct(YL),abortSignal:f,fetch:this.config.fetch});return{images:R.predictions.map(k=>k.bytesBase64Encoded),warnings:v,providerMetadata:{google:{images:R.predictions.map(()=>({}))}},response:{timestamp:w,modelId:this.modelId,headers:A}}}async doGenerateGemini(t){var e,n,o,i,s,r,a,u,c;const{prompt:p,n:f,size:h,aspectRatio:m,seed:v,providerOptions:_,headers:w,abortSignal:C,files:E,mask:A}=t,R=[];if(A!=null)throw new Error("Gemini image models do not support mask-based image editing.");if(f!=null&&f>1)throw new Error("Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.");h!=null&&R.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});const k=[];if(p!=null&&k.push({type:"text",text:p}),E!=null&&E.length>0)for(const B of E)B.type==="url"?k.push({type:"file",data:new URL(B.url),mediaType:"image/*"}):k.push({type:"file",data:typeof B.data=="string"?B.data:new Uint8Array(B.data),mediaType:B.mediaType});const b=[{role:"user",content:k}],J=await new DT(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:(e=this.config.headers)!=null?e:{},fetch:this.config.fetch,generateId:(n=this.config.generateId)!=null?n:Hn}).doGenerate({prompt:b,seed:v,providerOptions:{google:{responseModalities:["IMAGE"],imageConfig:m?{aspectRatio:m}:void 0,...(o=_==null?void 0:_.google)!=null?o:{}}},headers:w,abortSignal:C}),G=(r=(s=(i=this.config._internal)==null?void 0:i.currentDate)==null?void 0:s.call(i))!=null?r:new Date,L=[];for(const B of J.content)B.type==="file"&&B.mediaType.startsWith("image/")&&L.push(Ps(B.data));return{images:L,warnings:R,providerMetadata:{google:{images:L.map(()=>({}))}},response:{timestamp:G,modelId:this.modelId,headers:(a=J.response)==null?void 0:a.headers},usage:J.usage?{inputTokens:J.usage.inputTokens.total,outputTokens:J.usage.outputTokens.total,totalTokens:((u=J.usage.inputTokens.total)!=null?u:0)+((c=J.usage.outputTokens.total)!=null?c:0)}:void 0}}};function Bf(t){return t.startsWith("gemini-")}var YL=xe(()=>Me(M({predictions:ee(M({bytesBase64Encoded:I()})).default([])}))),XL=xe(()=>Me(M({personGeneration:Te(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:Te(["1:1","3:4","4:3","9:16","16:9"]).nullish()}))),QL=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3"}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async doGenerate(t){var e,n,o,i,s,r,a,u;const c=(o=(n=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:n.call(e))!=null?o:new Date,p=[],f=await Hi({provider:"google",providerOptions:t.providerOptions,schema:jL}),h=[{}],m=h[0];if(t.prompt!=null&&(m.prompt=t.prompt),t.image!=null)if(t.image.type==="url")p.push({type:"unsupported",feature:"URL-based image input",details:"Google Generative AI video models require base64-encoded images. URL will be ignored."});else{const B=typeof t.image.data=="string"?t.image.data:ni(t.image.data);m.image={inlineData:{mimeType:t.image.mediaType||"image/png",data:B}}}(f==null?void 0:f.referenceImages)!=null&&(m.referenceImages=f.referenceImages.map(B=>B.bytesBase64Encoded?{inlineData:{mimeType:"image/png",data:B.bytesBase64Encoded}}:B.gcsUri?{gcsUri:B.gcsUri}:B));const v={sampleCount:t.n};if(t.aspectRatio&&(v.aspectRatio=t.aspectRatio),t.resolution){const B={"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"};v.resolution=B[t.resolution]||t.resolution}if(t.duration&&(v.durationSeconds=t.duration),t.seed&&(v.seed=t.seed),f!=null){const B=f;B.personGeneration!==void 0&&B.personGeneration!==null&&(v.personGeneration=B.personGeneration),B.negativePrompt!==void 0&&B.negativePrompt!==null&&(v.negativePrompt=B.negativePrompt);for(const[ve,Ae]of Object.entries(B))["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","referenceImages"].includes(ve)||(v[ve]=Ae)}const{value:_}=await xt({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:Dt(await He(this.config.headers),t.headers),body:{instances:h,parameters:v},successfulResponseHandler:Ct(Hf),failedResponseHandler:an,abortSignal:t.abortSignal,fetch:this.config.fetch}),w=_.name;if(!w)throw new de({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No operation name returned from API"});const C=(i=f==null?void 0:f.pollIntervalMs)!=null?i:1e4,E=(s=f==null?void 0:f.pollTimeoutMs)!=null?s:6e5,A=Date.now();let R=_,k;for(;!R.done;){if(Date.now()-A>E)throw new de({name:"GOOGLE_VIDEO_GENERATION_TIMEOUT",message:`Video generation timed out after ${E}ms`});if(await _i(C),(r=t.abortSignal)!=null&&r.aborted)throw new de({name:"GOOGLE_VIDEO_GENERATION_ABORTED",message:"Video generation request was aborted"});const{value:B,responseHeaders:ve}=await oi({url:`${this.config.baseURL}/${w}`,headers:Dt(await He(this.config.headers),t.headers),successfulResponseHandler:Ct(Hf),failedResponseHandler:an,abortSignal:t.abortSignal,fetch:this.config.fetch});R=B,k=ve}if(R.error)throw new de({name:"GOOGLE_VIDEO_GENERATION_FAILED",message:`Video generation failed: ${R.error.message}`});const b=R.response;if(!((a=b==null?void 0:b.generateVideoResponse)!=null&&a.generatedSamples)||b.generateVideoResponse.generatedSamples.length===0)throw new de({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:`No videos in response. Response: ${JSON.stringify(R)}`});const U=[],J=[],G=await He(this.config.headers),L=G==null?void 0:G["x-goog-api-key"];for(const B of b.generateVideoResponse.generatedSamples)if((u=B.video)!=null&&u.uri){const ve=L?`${B.video.uri}${B.video.uri.includes("?")?"&":"?"}key=${L}`:B.video.uri;U.push({type:"url",url:ve,mediaType:"video/mp4"}),J.push({uri:B.video.uri})}if(U.length===0)throw new de({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{videos:U,warnings:p,response:{timestamp:c,modelId:this.modelId,headers:k},providerMetadata:{google:{videos:J}}}}},Hf=M({name:I().nullish(),done:ht().nullish(),error:M({code:W().nullish(),message:I(),status:I().nullish()}).nullish(),response:M({generateVideoResponse:M({generatedSamples:ee(M({video:M({uri:I().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}),jL=xe(()=>Me(M({pollIntervalMs:W().positive().nullish(),pollTimeoutMs:W().positive().nullish(),personGeneration:Te(["dont_allow","allow_adult","allow_all"]).nullish(),negativePrompt:I().nullish(),referenceImages:ee(M({bytesBase64Encoded:I().nullish(),gcsUri:I().nullish()})).nullish()}).passthrough()));function sd(t){var e,n,o,i,s,r,a,u;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const c=(e=t.total_input_tokens)!=null?e:0,p=(n=t.total_output_tokens)!=null?n:0,f=(o=t.total_thought_tokens)!=null?o:0,h=(i=t.total_cached_tokens)!=null?i:0;return{inputTokens:{total:(s=t.total_input_tokens)!=null?s:void 0,noCache:t.total_input_tokens==null?void 0:c-h,cacheRead:(r=t.total_cached_tokens)!=null?r:void 0,cacheWrite:void 0},outputTokens:{total:t.total_output_tokens==null&&t.total_thought_tokens==null?void 0:p+f,text:(a=t.total_output_tokens)!=null?a:void 0,reasoning:(u=t.total_thought_tokens)!=null?u:void 0},raw:t}}var e1={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function GT(t){const e=t.toLowerCase();for(const[n,o]of Object.entries(e1))if(e.endsWith(`.${n}`))return o;return"application/octet-stream"}function zT(t){const e=t.split("/"),n=e[e.length-1];return n&&n.length>0?n:void 0}function t1({annotation:t,generateId:e}){var n,o,i,s,r;switch(t.type){case"url_citation":{const a=t;return a.url==null||a.url.length===0?void 0:{type:"source",sourceType:"url",id:e(),url:a.url,...a.title!=null?{title:a.title}:{}}}case"file_citation":{const a=t,u=(o=(n=a.url)!=null?n:a.document_uri)!=null?o:a.file_name;if(u==null||u.length===0)return;if(u.startsWith("http://")||u.startsWith("https://"))return{type:"source",sourceType:"url",id:e(),url:u,...a.file_name!=null?{title:a.file_name}:{}};const c=(i=a.file_name)!=null?i:zT(u),p=GT(u);return{type:"source",sourceType:"document",id:e(),mediaType:p,title:(r=(s=a.file_name)!=null?s:c)!=null?r:u,...c!=null?{filename:c}:{}}}case"place_citation":{const a=t;return a.url==null||a.url.length===0?void 0:{type:"source",sourceType:"url",id:e(),url:a.url,...a.name!=null?{title:a.name}:{}}}default:return}}function FT({block:t,generateId:e}){var n,o,i,s,r,a,u,c,p,f,h;const m=[];switch(t.type){case"url_context_result":{const v=(n=t.result)!=null?n:[];for(const _ of v)(_==null?void 0:_.url)==null||_.url.length===0||_.status!=null&&_.status!=="success"||m.push({type:"source",sourceType:"url",id:e(),url:_.url});break}case"google_search_result":{const v=(o=t.result)!=null?o:[];for(const _ of v){const w=_==null?void 0:_.url;w==null||w.length===0||m.push({type:"source",sourceType:"url",id:e(),url:w,..._.title!=null?{title:_.title}:{}})}break}case"google_maps_result":{const v=(i=t.result)!=null?i:[];for(const _ of v)for(const w of(s=_.places)!=null?s:[])w.url==null||w.url.length===0||m.push({type:"source",sourceType:"url",id:e(),url:w.url,...w.name!=null?{title:w.name}:{}});break}case"file_search_result":{const v=(r=t.result)!=null?r:[];for(const _ of v){if(_==null||typeof _!="object")continue;const w=_,C=(u=(a=w.url)!=null?a:w.document_uri)!=null?u:w.file_name;if(C==null||C.length===0)continue;if(C.startsWith("http://")||C.startsWith("https://")){m.push({type:"source",sourceType:"url",id:e(),url:C,...w.title!=null?{title:w.title}:{}});continue}const E=(c=w.file_name)!=null?c:zT(C),A=GT(C);m.push({type:"source",sourceType:"document",id:e(),mediaType:A,title:(h=(f=(p=w.title)!=null?p:w.file_name)!=null?f:E)!=null?h:C,...E!=null?{filename:E}:{}})}break}}return m}function tc({annotations:t,generateId:e}){var n;if(t==null)return[];const o=new Set,i=[];for(const s of t){const r=t1({annotation:s,generateId:e});if(r==null)continue;const a=r.sourceType==="url"?`url:${r.url}`:`doc:${(n=r.filename)!=null?n:r.title}`;o.has(a)||(o.add(a),i.push(r))}return i}function rd({status:t,hasFunctionCall:e}){switch(t){case"completed":return e?"tool-calls":"stop";case"requires_action":return"tool-calls";case"failed":return"error";case"incomplete":return"length";case"cancelled":return"other";case"in_progress":default:return"other"}}var n1=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),o1=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function i1(t){return t.replace(/_call$/,"")}function s1(t){return t.replace(/_result$/,"")}function Zf({warnings:t,generateId:e,includeRawChunks:n,serviceTier:o}){let i,s,r=o,a,u=!1;const c=new Map,p=new Set;function f(h){var m;return h.sourceType==="url"?`url:${h.url}`:`doc:${(m=h.filename)!=null?m:h.title}`}return new TransformStream({start(h){h.enqueue({type:"stream-start",warnings:t})},transform(h,m){var v,_,w,C,E,A,R,k,b,U,J,G,L,B,ve,Ae,ye,ue;if(n&&m.enqueue({type:"raw",rawValue:h.rawValue}),!h.success){a="failed",m.enqueue({type:"error",error:h.error});return}const we=h.value,j=we.event_type;switch(j){case"interaction.created":{const x=we.interaction;i=(x==null?void 0:x.id)!=null&&x.id.length>0?x.id:void 0;const ce=x==null?void 0:x.created;let H;if(typeof ce=="string"){const X=new Date(ce);Number.isNaN(X.getTime())||(H=X)}m.enqueue({type:"response-metadata",...i!=null?{id:i}:{},modelId:x==null?void 0:x.model,...H?{timestamp:H}:{}});break}case"step.start":{const re=we,x=re.step,ce=re.index,H=`${i??"interaction"}:${ce}`,X=x==null?void 0:x.type;if(X==="model_output"){const ge=(v=x==null?void 0:x.content)==null?void 0:v[0];if((ge==null?void 0:ge.type)==="text"){c.set(ce,{kind:"text",id:H,emittedSourceKeys:new Set}),m.enqueue({type:"text-start",id:H});const oe=tc({annotations:ge.annotations,generateId:e});for(const _e of oe){const wt=f(_e);p.has(wt)||(p.add(wt),m.enqueue(_e))}}else(ge==null?void 0:ge.type)==="image"?c.set(ce,{kind:"image",id:H,...ge.data!=null?{data:ge.data}:{},...ge.mime_type!=null?{mimeType:ge.mime_type}:{},...ge.uri!=null?{uri:ge.uri}:{}}):c.set(ce,{kind:"pending_model_output",id:H})}else if(X==="thought"){const ge=x==null?void 0:x.signature;if(c.set(ce,{kind:"reasoning",id:H,...ge!=null?{signature:ge}:{}}),m.enqueue({type:"reasoning-start",id:H}),Array.isArray(x==null?void 0:x.summary))for(const oe of x.summary)(oe==null?void 0:oe.type)==="text"&&typeof oe.text=="string"&&m.enqueue({type:"reasoning-delta",id:H,delta:oe.text})}else if(X==="function_call"){const ge=(_=x==null?void 0:x.id)!=null?_:H,oe=(w=x==null?void 0:x.name)!=null?w:"unknown";u=!0;const _e={kind:"function_call",id:H,toolCallId:ge,toolName:oe,argumentsAccum:"",...(x==null?void 0:x.signature)!=null?{signature:x.signature}:{}};c.set(ce,_e),m.enqueue({type:"tool-input-start",id:ge,toolName:oe})}else if(X!=null&&n1.has(X)){const ge=X==="mcp_server_tool_call"?(C=x==null?void 0:x.name)!=null?C:"mcp_server_tool":i1(X),oe=(E=x==null?void 0:x.id)!=null?E:H,_e={kind:"builtin_tool_call",id:H,blockType:X,toolCallId:oe,toolName:ge,arguments:(A=x==null?void 0:x.arguments)!=null?A:{},callEmitted:!1};c.set(ce,_e)}else if(X!=null&&o1.has(X)){const ge=X==="mcp_server_tool_result"?(R=x==null?void 0:x.name)!=null?R:"mcp_server_tool":s1(X),oe=(k=x==null?void 0:x.call_id)!=null?k:H,_e={kind:"builtin_tool_result",id:H,blockType:X,callId:oe,toolName:ge,result:(b=x==null?void 0:x.result)!=null?b:null,...(x==null?void 0:x.is_error)!=null?{isError:x.is_error}:{},resultEmitted:!1};c.set(ce,_e)}else c.set(ce,{kind:"unknown",id:H});break}case"step.delta":{const re=we;let x=c.get(re.index);if(x==null)break;const ce=(U=re.delta)==null?void 0:U.type;if(x.kind==="pending_model_output"&&(ce==="text"||ce==="text_annotation"||ce==="text_annotation_delta")){const X={kind:"text",id:x.id,emittedSourceKeys:new Set};c.set(re.index,X),x=X,m.enqueue({type:"text-start",id:X.id})}if(ce==="image"&&(x.kind==="pending_model_output"||x.kind==="text"||x.kind==="image")){const X=re.delta,ge={};i!=null&&(ge.interactionId=i);const oe=Object.keys(ge).length>0?{google:ge}:void 0;if((X==null?void 0:X.data)!=null&&X.data.length>0)m.enqueue({type:"file",mediaType:(J=X.mime_type)!=null?J:"image/png",data:X.data,...oe?{providerMetadata:oe}:{}});else if((X==null?void 0:X.uri)!=null&&X.uri.length>0){const _e={google:{...i!=null?{interactionId:i}:{},imageUri:X.uri}};m.enqueue({type:"file",mediaType:(G=X.mime_type)!=null?G:"image/png",data:"",providerMetadata:_e})}x.kind==="image"&&(x.data=void 0,x.uri=void 0);break}const H=re.delta;if(x.kind==="text"&&(H==null?void 0:H.type)==="text"){const X=(L=H.text)!=null?L:"";X.length>0&&m.enqueue({type:"text-delta",id:x.id,delta:X})}else if(x.kind==="text"&&((H==null?void 0:H.type)==="text_annotation"||(H==null?void 0:H.type)==="text_annotation_delta")){const X=tc({annotations:H.annotations,generateId:e});for(const ge of X){const oe=f(ge);p.has(oe)||(p.add(oe),x.emittedSourceKeys.add(oe),m.enqueue(ge))}}else if(x.kind==="image"&&(H==null?void 0:H.type)==="image")H.data!=null&&(x.data=H.data),H.mime_type!=null&&(x.mimeType=H.mime_type),H.uri!=null&&(x.uri=H.uri);else if(x.kind==="reasoning"){if((H==null?void 0:H.type)==="thought_summary"){const X=H.content;(X==null?void 0:X.type)==="text"&&typeof X.text=="string"&&m.enqueue({type:"reasoning-delta",id:x.id,delta:X.text})}else if((H==null?void 0:H.type)==="thought_signature"){const X=H.signature;X!=null&&(x.signature=X)}}else if(x.kind==="function_call"&&(H==null?void 0:H.type)==="arguments_delta"){const X=typeof H.arguments=="string"?H.arguments:"";X.length>0&&(x.argumentsAccum+=X,m.enqueue({type:"tool-input-delta",id:x.toolCallId,delta:X})),H.id!=null&&(x.toolCallId=H.id),H.signature!=null&&(x.signature=H.signature),u=!0}else x.kind==="builtin_tool_call"&&(H==null?void 0:H.type)===x.blockType?(H.id!=null&&(x.toolCallId=H.id),H.arguments!=null&&typeof H.arguments=="object"&&(x.arguments=H.arguments),H.name!=null&&x.blockType==="mcp_server_tool_call"&&(x.toolName=H.name)):x.kind==="builtin_tool_result"&&(H==null?void 0:H.type)===x.blockType&&(H.call_id!=null&&(x.callId=H.call_id),H.result!==void 0&&(x.result=H.result),H.is_error!=null&&(x.isError=H.is_error),H.name!=null&&x.blockType==="mcp_server_tool_result"&&(x.toolName=H.name));break}case"step.stop":{const re=we,x=c.get(re.index);if(x==null)break;if(x.kind==="text"){const ce=i!=null?{google:{interactionId:i}}:void 0;m.enqueue({type:"text-end",id:x.id,...ce?{providerMetadata:ce}:{}})}else if(x.kind==="reasoning"){const ce={};x.signature!=null&&(ce.signature=x.signature),i!=null&&(ce.interactionId=i);const H=Object.keys(ce).length>0?{google:ce}:void 0;m.enqueue({type:"reasoning-end",id:x.id,...H?{providerMetadata:H}:{}})}else if(x.kind==="image"){const ce={};i!=null&&(ce.interactionId=i);const H=Object.keys(ce).length>0?{google:ce}:void 0;if(x.data!=null&&x.data.length>0)m.enqueue({type:"file",mediaType:(B=x.mimeType)!=null?B:"image/png",data:x.data,...H?{providerMetadata:H}:{}});else if(x.uri!=null&&x.uri.length>0){const X={google:{...i!=null?{interactionId:i}:{},imageUri:x.uri}};m.enqueue({type:"file",mediaType:(ve=x.mimeType)!=null?ve:"image/png",data:"",providerMetadata:X})}}else if(x.kind==="function_call"){const ce=x.argumentsAccum.length>0?x.argumentsAccum:"{}";m.enqueue({type:"tool-input-end",id:x.toolCallId});const H={};x.signature!=null&&(H.signature=x.signature),i!=null&&(H.interactionId=i);const X=Object.keys(H).length>0?{google:H}:void 0;m.enqueue({type:"tool-call",toolCallId:x.toolCallId,toolName:x.toolName,input:ce,...X?{providerMetadata:X}:{}})}else if(x.kind==="builtin_tool_call"&&!x.callEmitted)m.enqueue({type:"tool-call",toolCallId:x.toolCallId,toolName:x.toolName,input:JSON.stringify((Ae=x.arguments)!=null?Ae:{}),providerExecuted:!0}),x.callEmitted=!0;else if(x.kind==="builtin_tool_result"&&!x.resultEmitted){m.enqueue({type:"tool-result",toolCallId:x.callId,toolName:x.toolName,result:(ye=x.result)!=null?ye:null}),x.resultEmitted=!0;const ce=FT({block:{type:x.blockType,call_id:x.callId,result:x.result},generateId:e});for(const H of ce){const X=f(H);p.has(X)||(p.add(X),m.enqueue(H))}}c.delete(re.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{const re=we;re.status!=null?a=re.status:j==="interaction.requires_action"?a="requires_action":a="in_progress";break}case"interaction.completed":{const x=we.interaction;(x==null?void 0:x.id)!=null&&x.id.length>0&&(i=x.id),(x==null?void 0:x.status)!=null&&(a=x.status),(x==null?void 0:x.usage)!=null&&(s=x.usage),(x==null?void 0:x.service_tier)!=null&&(r=x.service_tier);break}case"error":{const re=we;a="failed";const x=(ue=re.error)!=null?ue:{message:"Unknown interaction error"};m.enqueue({type:"error",error:x});break}}},flush(h){const m={unified:rd({status:a,hasFunctionCall:u}),raw:a},v={google:{...i!=null?{interactionId:i}:{},...r!=null?{serviceTier:r}:{}}};h.enqueue({type:"finish",finishReason:m,usage:sd(s),providerMetadata:v})}})}function VT(t){const e=t.indexOf("/");return e===-1?t:t.substring(0,e)}function tl(t){const e=t.indexOf("/");if(e===-1)return!1;const n=t.substring(e+1);return n.length>0&&n!=="*"}function r1({prompt:t,previousInteractionId:e,store:n,mediaResolution:o}){var i,s,r,a,u,c,p;const f=[],h=e!=null&&n===!1,m=e!=null&&n!==!1;h&&f.push({type:"other",message:"google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted."});const v=m?a1({prompt:t,previousInteractionId:e}):t,_=[],w=[];for(const E of v)switch(E.role){case"system":{_.push(E.content);break}case"user":{const A=[];for(const k of E.content)if(k.type==="text")A.push({type:"text",text:k.text});else if(k.type==="file"){const b=Jf({part:k,warnings:f,mediaResolution:o});b!=null&&A.push(b)}const R=c1(A);R.length>0&&w.push({type:"user_input",content:R});break}case"assistant":{let A=[];const R=()=>{A.length>0&&(w.push({type:"model_output",content:A}),A=[])};for(const k of E.content)if(k.type==="text")A.push({type:"text",text:k.text});else if(k.type==="reasoning"){R();const b=(s=(i=k.providerOptions)==null?void 0:i.google)==null?void 0:s.signature;w.push({type:"thought",...b!=null?{signature:b}:{},summary:k.text.length>0?[{type:"text",text:k.text}]:void 0})}else if(k.type==="file"){const b=Jf({part:k,warnings:f,mediaResolution:o});b!=null&&A.push(b)}else if(k.type==="tool-call"){R();const b=(a=(r=k.providerOptions)==null?void 0:r.google)==null?void 0:a.signature,U=typeof k.input=="string"?l1(k.input):(u=k.input)!=null?u:{};w.push({type:"function_call",id:k.toolCallId,name:k.toolName,arguments:U,...b!=null?{signature:b}:{}})}else f.push({type:"other",message:`google.interactions: unsupported assistant content part type "${k.type}"; part dropped.`});R();break}case"tool":{const A=[];for(const R of E.content){if(R.type!=="tool-result"){f.push({type:"other",message:`google.interactions: unsupported tool message part type "${R.type}"; part dropped.`});continue}const k=u1({toolCallId:R.toolCallId,toolName:R.toolName,output:R.output,signature:(p=(c=R.providerOptions)==null?void 0:c.google)==null?void 0:p.signature,warnings:f});A.push(k)}A.length>0&&w.push({type:"user_input",content:A});break}}const C=_.length>0?_.join(`
129
+
130
+ `):void 0;return{input:w,systemInstruction:C,warnings:f}}function Jf({part:t,warnings:e,mediaResolution:n}){const o=VT(t.mediaType);let i;switch(o){case"image":i="image";break;case"audio":i="audio";break;case"video":i="video";break;case"application":i="document";break;default:i=void 0}if(i==null){e.push({type:"other",message:`google.interactions: unsupported file media type "${t.mediaType}"; part dropped.`});return}const s=n!=null&&(i==="image"||i==="video")?{resolution:n}:{};if(t.data instanceof URL)return{type:i,uri:t.data.toString(),...tl(t.mediaType)?{mime_type:t.mediaType}:{},...s};if(!tl(t.mediaType)){e.push({type:"other",message:`google.interactions: inline file data requires a full IANA media type (e.g. "image/png"), got "${t.mediaType}"; part dropped.`});return}return{type:i,data:Ps(t.data),mime_type:t.mediaType,...s}}function a1({prompt:t,previousInteractionId:e}){const n=[],o=new Set;for(const i of t){if(i.role==="assistant"){if(i.content.some(r=>{var a,u;return((u=(a=r.providerOptions)==null?void 0:a.google)==null?void 0:u.interactionId)===e})){for(const r of i.content)r.type==="tool-call"&&o.add(r.toolCallId);continue}n.push(i);continue}if(i.role==="tool"){const s=i.content.filter(r=>r.type!=="tool-result"?!0:!o.has(r.toolCallId));if(s.length===0)continue;n.push({...i,content:s});continue}n.push(i)}return n}function l1(t){try{const e=JSON.parse(t);return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}catch{return{value:t}}}function u1({toolCallId:t,toolName:e,output:n,signature:o,warnings:i}){var s;const r={type:"function_result",call_id:t,name:e,...o!=null?{signature:o}:{}};switch(n.type){case"text":return{...r,result:n.value};case"json":return{...r,result:JSON.stringify(n.value)};case"error-text":return{...r,is_error:!0,result:n.value};case"error-json":return{...r,is_error:!0,result:JSON.stringify(n.value)};case"execution-denied":return{...r,is_error:!0,result:(s=n.reason)!=null?s:"Tool execution denied by user."};case"content":{const a=[];for(const u of n.value)if(u.type==="text")a.push({type:"text",text:u.text});else if(u.type==="image-data"){const c=gu({part:{mediaType:u.mediaType,data:u.data},warnings:i});c!=null&&a.push(c)}else if(u.type==="image-url"){const c=gu({part:{mediaType:"image/*",data:new URL(u.url)},warnings:i});c!=null&&a.push(c)}else if(u.type==="file-data"||u.type==="file-url"){const c=u.type==="file-data"?u.mediaType:"application/*";if(VT(c)!=="image"){i.push({type:"other",message:`google.interactions: tool-result file with mediaType "${c}" is not supported (Interactions \`function_result.result\` accepts only text and image content); part dropped.`});continue}const f=gu({part:u.type==="file-data"?{mediaType:u.mediaType,data:u.data}:{mediaType:c,data:new URL(u.url)},warnings:i});f!=null&&a.push(f)}else i.push({type:"other",message:`google.interactions: tool-result content part type "${u.type}" is not supported; part dropped.`});return{...r,result:a}}}}function gu({part:t,warnings:e}){if(t.data instanceof URL)return{type:"image",uri:t.data.toString(),...tl(t.mediaType)?{mime_type:t.mediaType}:{}};if(!tl(t.mediaType)){e.push({type:"other",message:`google.interactions: tool-result image part requires a full IANA media type (e.g. "image/png"), got "${t.mediaType}"; part dropped.`});return}return{type:"image",data:Ps(t.data),mime_type:t.mediaType}}function c1(t){if(t.length<2)return t;const e=[];for(const n of t){const o=e[e.length-1];if(n.type==="text"&&o!=null&&o.type==="text"&&o.annotations==null&&n.annotations==null){const i={type:"text",text:`${o.text}
131
+
132
+ ${n.text}`};e[e.length-1]=i;continue}e.push(n)}return e}var Ea=()=>M({modality:I().nullish(),tokens:W().nullish()}).loose(),qT=()=>M({total_input_tokens:W().nullish(),total_output_tokens:W().nullish(),total_thought_tokens:W().nullish(),total_cached_tokens:W().nullish(),total_tool_use_tokens:W().nullish(),total_tokens:W().nullish(),input_tokens_by_modality:ee(Ea()).nullish(),output_tokens_by_modality:ee(Ea()).nullish(),cached_tokens_by_modality:ee(Ea()).nullish(),tool_use_tokens_by_modality:ee(Ea()).nullish(),grounding_tool_count:ee(M({type:I().nullish(),count:W().nullish()}).loose()).nullish()}).loose(),BT=()=>Te(["in_progress","requires_action","completed","failed","cancelled","incomplete"]),HT=()=>{const t=M({type:ne("url_citation"),url:I().nullish(),title:I().nullish(),start_index:W().nullish(),end_index:W().nullish()}).loose(),e=M({type:ne("file_citation"),file_name:I().nullish(),document_uri:I().nullish(),url:I().nullish(),page_number:W().nullish(),media_id:I().nullish(),start_index:W().nullish(),end_index:W().nullish(),custom_metadata:Et(I(),at()).nullish()}).loose(),n=M({type:ne("place_citation"),name:I().nullish(),url:I().nullish(),place_id:I().nullish(),start_index:W().nullish(),end_index:W().nullish()}).loose();return $e([t,e,n,M({type:I()}).loose()])},ZT=()=>M({type:I(),text:I().nullish(),data:I().nullish(),mime_type:I().nullish()}).loose(),Wf=()=>{const t=M({type:ne("text"),text:I(),annotations:ee(HT()).nullish()}).loose(),e=M({type:ne("image"),data:I().nullish(),mime_type:I().nullish(),resolution:Te(["low","medium","high","ultra_high"]).nullish(),uri:I().nullish()}).loose();return $e([t,e,M({type:I()}).loose()])},JT=["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"],WT=["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"],KT=()=>{const t=M({type:ne("user_input"),content:ee(Wf()).nullish()}).loose(),e=M({type:ne("model_output"),content:ee(Wf()).nullish()}).loose(),n=M({type:ne("function_call"),id:I(),name:I(),arguments:Et(I(),at()).nullish(),signature:I().nullish()}).loose(),o=M({type:ne("thought"),signature:I().nullish(),summary:ee(ZT()).nullish()}).loose(),i=M({type:Te(JT),id:I(),arguments:Et(I(),at()).nullish(),name:I().nullish(),server_name:I().nullish(),search_type:I().nullish(),signature:I().nullish()}).loose(),s=M({type:Te(WT),call_id:I(),result:at().nullish(),is_error:ht().nullish(),name:I().nullish(),server_name:I().nullish(),signature:I().nullish()}).loose();return $e([t,e,n,o,i,s,M({type:I()}).loose()])},nc=xe(()=>Me(M({id:I().nullish(),created:I().nullish(),updated:I().nullish(),status:BT(),model:I().nullish(),agent:I().nullish(),steps:ee(KT()).nullish(),usage:qT().nullish(),service_tier:I().nullish(),previous_interaction_id:I().nullish(),response_modalities:ee(I()).nullish()}).loose())),YT=xe(()=>Me((()=>{const t=BT(),e=HT(),n=ZT(),o=M({event_type:ne("interaction.created"),event_id:I().nullish(),interaction:M({id:I().nullish(),created:I().nullish(),model:I().nullish(),agent:I().nullish(),status:t.nullish()}).loose()}).loose(),i=M({event_type:ne("step.start"),event_id:I().nullish(),index:W(),step:KT()}).loose(),s=M({type:ne("text"),text:I()}).loose(),r=M({type:ne("thought_summary"),content:n.nullish()}).loose(),a=M({type:ne("thought_signature"),signature:I().nullish()}).loose(),u=M({type:ne("arguments_delta"),arguments:I().nullish(),id:I().nullish(),signature:I().nullish()}).loose(),c=M({type:Te(["text_annotation_delta","text_annotation"]),annotations:ee(e).nullish()}).loose(),p=M({type:ne("image"),data:I().nullish(),mime_type:I().nullish(),resolution:Te(["low","medium","high","ultra_high"]).nullish(),uri:I().nullish()}).loose(),f=M({type:Te(JT),id:I().nullish(),arguments:Et(I(),at()).nullish(),name:I().nullish(),server_name:I().nullish(),search_type:I().nullish(),signature:I().nullish()}).loose(),h=M({type:Te(WT),call_id:I().nullish(),result:at().nullish(),is_error:ht().nullish(),name:I().nullish(),server_name:I().nullish(),signature:I().nullish()}).loose(),m=M({type:I()}).loose(),v=$e([s,p,r,a,u,c,f,h,m]),_=M({event_type:ne("step.delta"),event_id:I().nullish(),index:W(),delta:v}).loose(),w=M({event_type:ne("step.stop"),event_id:I().nullish(),index:W()}).loose(),C=M({event_type:ne("interaction.status_update"),event_id:I().nullish(),interaction_id:I().nullish(),status:t.nullish()}).loose(),E=M({event_type:ne("interaction.in_progress"),event_id:I().nullish(),interaction_id:I().nullish(),status:t.nullish()}).loose(),A=M({event_type:ne("interaction.requires_action"),event_id:I().nullish(),interaction_id:I().nullish(),status:t.nullish()}).loose(),R=M({event_type:ne("interaction.completed"),event_id:I().nullish(),interaction:M({id:I().nullish(),status:t.nullish(),usage:qT().nullish(),service_tier:I().nullish()}).loose()}).loose(),k=M({event_type:ne("error"),event_id:I().nullish(),error:M({code:I().nullish(),message:I().nullish()}).loose().nullish()}).loose(),b=M({event_type:I()}).loose();return $e([o,i,_,w,C,E,A,R,k,b])})())),d1=xe(()=>Me(M({previousInteractionId:I().nullish(),store:ht().nullish(),agent:I().nullish(),agentConfig:$e([M({type:ne("dynamic")}).loose(),M({type:ne("deep-research"),thinkingSummaries:Te(["auto","none"]).nullish(),visualization:Te(["off","auto"]).nullish(),collaborativePlanning:ht().nullish()})]).nullish(),thinkingLevel:Te(["minimal","low","medium","high"]).nullish(),thinkingSummaries:Te(["auto","none"]).nullish(),responseFormat:ee($e([M({type:ne("text"),mimeType:I().nullish(),schema:at().nullish()}).loose(),M({type:ne("image"),mimeType:I().nullish(),aspectRatio:Te(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:Te(["1K","2K","4K","512"]).nullish()}).loose(),M({type:ne("audio"),mimeType:I().nullish()}).loose()])).nullish(),imageConfig:M({aspectRatio:Te(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9","1:8","8:1","1:4","4:1"]).nullish(),imageSize:Te(["1K","2K","4K","512"]).nullish()}).nullish(),mediaResolution:Te(["low","medium","high","ultra_high"]).nullish(),responseModalities:ee(Te(["text","image","audio","video","document"])).nullish(),serviceTier:Te(["flex","standard","priority"]).nullish(),systemInstruction:I().nullish(),signature:I().nullish(),interactionId:I().nullish(),pollingTimeoutMs:W().int().positive().nullish()})));function wa({signature:t,interactionId:e}){const n={};return t!=null&&(n.signature=t),e!=null&&(n.interactionId=e),Object.keys(n).length>0?{providerMetadata:{google:n}}:{}}var p1=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),f1=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function h1(t){return t.replace(/_call$/,"")}function m1(t){return t.replace(/_result$/,"")}function XT({steps:t,generateId:e,interactionId:n}){var o,i,s,r,a,u,c,p,f,h,m;const v=[];let _=!1;if(t==null)return{content:v,hasFunctionCall:_};for(const w of t){if(w==null||typeof w!="object")continue;const C=w.type;if(typeof C=="string")switch(C){case"user_input":break;case"model_output":{const E=(o=w.content)!=null?o:[];for(const A of E){if(A==null||typeof A!="object")continue;const R=A.type;if(R==="text"){const k=(i=A.text)!=null?i:"",b=A.annotations;v.push({type:"text",text:k,...wa({interactionId:n})});const U=tc({annotations:b,generateId:e});for(const J of U)v.push(J)}else if(R==="image"){const k=A;k.data!=null&&k.data.length>0?v.push({type:"file",mediaType:(s=k.mime_type)!=null?s:"image/png",data:k.data,...wa({interactionId:n})}):k.uri!=null&&k.uri.length>0&&v.push({type:"file",mediaType:(r=k.mime_type)!=null?r:"image/png",data:"",providerMetadata:{google:{...n!=null?{interactionId:n}:{},imageUri:k.uri}}})}}break}case"thought":{const E=w,R=(Array.isArray(E.summary)?E.summary:[]).filter(k=>(k==null?void 0:k.type)==="text"&&typeof k.text=="string").map(k=>k.text).join(`
133
+ `);v.push({type:"reasoning",text:R,...wa({signature:E.signature,interactionId:n})});break}case"function_call":{_=!0;const E=w;v.push({type:"tool-call",toolCallId:E.id,toolName:E.name,input:JSON.stringify((a=E.arguments)!=null?a:{}),...wa({signature:E.signature,interactionId:n})});break}default:{if(p1.has(C)){const E=w,A=C==="mcp_server_tool_call"?(u=E.name)!=null?u:"mcp_server_tool":h1(C),R=JSON.stringify((c=E.arguments)!=null?c:{});v.push({type:"tool-call",toolCallId:(p=E.id)!=null?p:e(),toolName:A,input:R,providerExecuted:!0})}else if(f1.has(C)){const E=w,A=C==="mcp_server_tool_result"?(f=E.name)!=null?f:"mcp_server_tool":m1(C);v.push({type:"tool-result",toolCallId:(h=E.call_id)!=null?h:e(),toolName:A,result:(m=E.result)!=null?m:null});const R=FT({block:w,generateId:e});for(const k of R)v.push(k)}break}}}return{content:v,hasFunctionCall:_}}var g1=()=>globalThis.fetch;async function QT({baseURL:t,interactionId:e,headers:n,fetch:o=g1()}){if(e==null||e.length===0)return;const i=`${t}/interactions/${encodeURIComponent(e)}/cancel`;try{const s=await o(i,{method:"POST",headers:Po(Dt({"Content-Type":"application/json"},n),ql()),body:"{}"});try{await s.text()}catch{}}catch{}}var v1=new Set(["completed","failed","cancelled","incomplete"]);function oc(t){return t!=null&&v1.has(t)}var y1=1e3,_1=1e4,T1=1800*1e3;async function E1({baseURL:t,interactionId:e,headers:n,fetch:o,abortSignal:i,initialDelayMs:s=y1,maxDelayMs:r=_1,timeoutMs:a=T1}){if(e==null||e.length===0)throw new Error("google.interactions: cannot poll a background interaction without an id. The POST response did not include an interaction id.");const u=Date.now();let c=s;const p=`${t}/interactions/${encodeURIComponent(e)}`,f=()=>QT({baseURL:t,interactionId:e,headers:n,fetch:o});try{for(;;){if(i!=null&&i.aborted)throw await f(),new DOMException("Polling was aborted","AbortError");if(Date.now()-u>a)throw new Error(`google.interactions: timed out polling interaction ${e} after ${a}ms.`);await _i(c,{abortSignal:i});const{value:h,rawValue:m,responseHeaders:v}=await oi({url:p,headers:n,failedResponseHandler:an,successfulResponseHandler:Ct(nc),abortSignal:i,fetch:o});if(oc(h.status))return{response:h,rawResponse:m,responseHeaders:v};c=Math.min(c*2,r)}}catch(h){throw Kn(h)&&await f(),h}}function w1({tools:t,toolChoice:e}){var n,o,i,s;const r=[],a=t!=null&&t.length?t:void 0;if(a==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const u=[];for(const f of a){if(f.type==="function"){u.push({type:"function",name:f.name,description:(n=f.description)!=null?n:"",parameters:f.inputSchema});continue}if(f.type==="provider"){const h=(o=f.args)!=null?o:{};switch(f.id){case"google.google_search":{const m=h.searchTypes;let v;if(m!=null&&typeof m=="object"){const _=[];m.webSearch!=null&&_.push("web_search"),m.imageSearch!=null&&_.push("image_search"),_.length>0&&(v=_)}u.push({type:"google_search",...v!=null?{search_types:v}:{}});break}case"google.code_execution":{u.push({type:"code_execution"});break}case"google.url_context":{u.push({type:"url_context"});break}case"google.file_search":{u.push({type:"file_search",...h.fileSearchStoreNames!=null?{file_search_store_names:h.fileSearchStoreNames}:{},...h.topK!=null?{top_k:h.topK}:{},...h.metadataFilter!=null?{metadata_filter:h.metadataFilter}:{}});break}case"google.google_maps":{u.push({type:"google_maps",...h.latitude!=null?{latitude:h.latitude}:{},...h.longitude!=null?{longitude:h.longitude}:{},...h.enableWidget!=null?{enable_widget:h.enableWidget}:{}});break}case"google.computer_use":{u.push({type:"computer_use",environment:(i=h.environment)!=null?i:"browser",...h.excludedPredefinedFunctions!=null?{excludedPredefinedFunctions:h.excludedPredefinedFunctions}:{}});break}case"google.mcp_server":{u.push({type:"mcp_server",...h.name!=null?{name:h.name}:{},...h.url!=null?{url:h.url}:{},...h.headers!=null?{headers:h.headers}:{},...h.allowedTools!=null?{allowed_tools:h.allowedTools}:{}});break}case"google.retrieval":{const m=(s=h.vertexAiSearchConfig)!=null?s:void 0;u.push({type:"retrieval",...h.retrievalTypes!=null?{retrieval_types:h.retrievalTypes}:{retrieval_types:["vertex_ai_search"]},...m!=null?{vertex_ai_search_config:m}:{}});break}default:{r.push({type:"unsupported",feature:`provider-defined tool ${f.id}`,details:`provider-defined tool ${f.id} is not supported by google.interactions; tool dropped.`});break}}continue}r.push({type:"unsupported",feature:`tool of type ${f.type}`,details:"Only function tools and google.* provider-defined tools are supported by google.interactions; tool dropped."})}const c=u.some(f=>f.type==="function");let p;if(e!=null&&c)switch(e.type){case"auto":p="auto";break;case"required":p="any";break;case"none":p="none";break;case"tool":p={allowed_tools:{mode:"validated",tools:[e.toolName]}};break}return{tools:u.length>0?u:void 0,toolChoice:p,toolWarnings:r}}var I1=3,S1=500;function C1({baseURL:t,interactionId:e,headers:n,fetch:o,abortSignal:i,maxRetries:s=I1,retryDelayMs:r=S1}){if(e.length===0)throw new Error("google.interactions: cannot stream a background interaction without an id.");const a={...n,accept:"text/event-stream"};let u,c=!1,p=0,f=!1,h;const m=new AbortController,v=()=>m.abort();i!=null&&(i.aborted?m.abort():i.addEventListener("abort",v,{once:!0}));const _=m.signal;function w(){const E=`${t}/interactions/${encodeURIComponent(e)}`,A=new URLSearchParams({stream:"true"});return u!=null&&A.set("last_event_id",u),`${E}?${A.toString()}`}async function C(){const{value:E}=await oi({url:w(),headers:a,failedResponseHandler:an,successfulResponseHandler:Bl(YT),abortSignal:_,fetch:o});return E.getReader()}return new ReadableStream({async start(E){try{for(;!c&&!_.aborted;){if(h==null)try{h=await C(),f=!1}catch(A){if(Kn(A)||_.aborted){E.error(A);return}if(p++,p>=s){E.error(A);return}await _i(r*p,{abortSignal:_});continue}try{const{done:A,value:R}=await h.read();if(A){if(h=void 0,c)break;if(f)p=0;else{if(p++,p>=s){E.error(new Error("google.interactions: SSE stream closed without producing any events."));return}await _i(r*p,{abortSignal:_})}continue}if(f=!0,R.success){const k=R.value;typeof k.event_id=="string"&&k.event_id.length>0&&(u=k.event_id),(k.event_type==="interaction.completed"||k.event_type==="error")&&(c=!0)}E.enqueue(R)}catch(A){if(Kn(A)||_.aborted){E.error(A);return}if(h=void 0,p++,p>=s){E.error(A);return}await _i(r*p,{abortSignal:_})}}E.close()}catch(A){E.error(A)}finally{i!=null&&i.removeEventListener("abort",v),h==null||h.cancel().catch(()=>{}),h=void 0,_.aborted&&!c&&await QT({baseURL:t,interactionId:e,headers:n,fetch:o})}},cancel(){m.abort(),h==null||h.cancel().catch(()=>{}),h=void 0}})}function A1({response:t,warnings:e,generateId:n,includeRawChunks:o,headerServiceTier:i}){return new ReadableStream({start(s){var r,a,u;s.enqueue({type:"stream-start",warnings:e});const c=typeof t.id=="string"&&t.id.length>0?t.id:void 0;let p;const f=t.created;if(typeof f=="string"){const A=new Date(f);Number.isNaN(A.getTime())||(p=A)}s.enqueue({type:"response-metadata",...c!=null?{id:c}:{},modelId:(r=t.model)!=null?r:void 0,...p?{timestamp:p}:{}}),o&&s.enqueue({type:"raw",rawValue:t});const{content:h,hasFunctionCall:m}=XT({steps:(a=t.steps)!=null?a:null,generateId:n,interactionId:c});let v=0;const _=()=>`${c??"agent"}:${v++}`;for(const A of h)switch(A.type){case"text":{const R=_(),k=A.providerMetadata;s.enqueue({type:"text-start",id:R}),A.text.length>0&&s.enqueue({type:"text-delta",id:R,delta:A.text}),s.enqueue({type:"text-end",id:R,...k?{providerMetadata:k}:{}});break}case"reasoning":{const R=_(),k=A.providerMetadata;s.enqueue({type:"reasoning-start",id:R}),A.text.length>0&&s.enqueue({type:"reasoning-delta",id:R,delta:A.text}),s.enqueue({type:"reasoning-end",id:R,...k?{providerMetadata:k}:{}});break}case"tool-call":{const R=A.providerMetadata;s.enqueue({type:"tool-input-start",id:A.toolCallId,toolName:A.toolName,...A.providerExecuted?{providerExecuted:A.providerExecuted}:{}}),s.enqueue({type:"tool-input-delta",id:A.toolCallId,delta:A.input}),s.enqueue({type:"tool-input-end",id:A.toolCallId}),s.enqueue({type:"tool-call",toolCallId:A.toolCallId,toolName:A.toolName,input:A.input,...A.providerExecuted?{providerExecuted:A.providerExecuted}:{},...R?{providerMetadata:R}:{}});break}case"tool-result":{s.enqueue({type:"tool-result",toolCallId:A.toolCallId,toolName:A.toolName,result:A.result});break}case"source":case"file":{s.enqueue(A);break}}const w=(u=t.service_tier)!=null?u:i,C={unified:rd({status:t.status,hasFunctionCall:m}),raw:t.status},E={google:{...c!=null?{interactionId:c}:{},...w!=null?{serviceTier:w}:{}}};s.enqueue({type:"finish",finishReason:C,usage:sd(t.usage),providerMetadata:E}),s.close()}})}var b1=class{constructor(t,e){this.specificationVersion="v3",typeof t=="string"?(this.modelId=t,this.agent=void 0):(this.modelId=t.agent,this.agent=t.agent),this.config=e}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?this.config.supportedUrls():{"image/*":[/^https?:\/\/.+/],"application/pdf":[/^https?:\/\/.+/],"audio/*":[/^https?:\/\/.+/],"video/*":[/^https?:\/\/(www\.)?youtube\.com\/watch\?v=.+/,/^https?:\/\/youtu\.be\/.+/,/^gs:\/\/.+/]}}async getArgs(t){var e,n,o,i,s,r,a,u,c,p,f,h,m,v,_,w,C,E,A,R,k,b,U,J;const G=[],L=await Hi({provider:"google",providerOptions:t.providerOptions,schema:d1}),B=this.agent!=null,ve=t.tools!=null&&t.tools.length>0;let Ae,ye;if(ve&&B)G.push({type:"other",message:"google.interactions: tools are not supported when an agent is set; tools will be omitted from the request body."});else if(ve){const oe=w1({tools:t.tools,toolChoice:t.toolChoice});Ae=oe.tools,ye=oe.toolChoice,G.push(...oe.toolWarnings)}const ue=[];if(((e=t.responseFormat)==null?void 0:e.type)==="json")if(B)G.push({type:"other",message:"google.interactions: structured output (responseFormat) is not supported when an agent is set; responseFormat will be ignored."});else{const oe={type:"text",mime_type:"application/json",...t.responseFormat.schema!=null?{schema:t.responseFormat.schema}:{}};ue.push(oe)}if((L==null?void 0:L.responseFormat)!=null)for(const oe of L.responseFormat)oe.type==="text"?ue.push(ci({type:"text",mime_type:(n=oe.mimeType)!=null?n:void 0,schema:(o=oe.schema)!=null?o:void 0})):oe.type==="image"?ue.push(ci({type:"image",mime_type:(i=oe.mimeType)!=null?i:void 0,aspect_ratio:(s=oe.aspectRatio)!=null?s:void 0,image_size:(r=oe.imageSize)!=null?r:void 0})):oe.type==="audio"&&ue.push(ci({type:"audio",mime_type:(a=oe.mimeType)!=null?a:void 0}));const{input:we,systemInstruction:j,warnings:re}=r1({prompt:t.prompt,previousInteractionId:(u=L==null?void 0:L.previousInteractionId)!=null?u:void 0,store:(c=L==null?void 0:L.store)!=null?c:void 0,mediaResolution:(p=L==null?void 0:L.mediaResolution)!=null?p:void 0});G.push(...re);let x=j;const ce=(f=L==null?void 0:L.systemInstruction)!=null?f:void 0;x!=null&&ce!=null?G.push({type:"other",message:"google.interactions: both AI SDK system message and providerOptions.google.systemInstruction were set; using the AI SDK system message."}):x==null&&ce!=null&&(x=ce);let H;if(B){const oe=[];t.temperature!=null&&oe.push("temperature"),t.topP!=null&&oe.push("topP"),t.seed!=null&&oe.push("seed"),t.stopSequences!=null&&t.stopSequences.length>0&&oe.push("stopSequences"),t.maxOutputTokens!=null&&oe.push("maxOutputTokens"),(L==null?void 0:L.thinkingLevel)!=null&&oe.push("thinkingLevel"),(L==null?void 0:L.thinkingSummaries)!=null&&oe.push("thinkingSummaries"),(L==null?void 0:L.imageConfig)!=null&&oe.push("imageConfig"),oe.length>0&&G.push({type:"other",message:`google.interactions: ${oe.join(", ")} ${oe.length===1?"is":"are"} not supported when an agent is set; use providerOptions.google.agentConfig instead. Dropped from the request body.`}),H=void 0}else if(H=ci({temperature:(h=t.temperature)!=null?h:void 0,top_p:(m=t.topP)!=null?m:void 0,seed:(v=t.seed)!=null?v:void 0,stop_sequences:t.stopSequences!=null&&t.stopSequences.length>0?t.stopSequences:void 0,max_output_tokens:(_=t.maxOutputTokens)!=null?_:void 0,thinking_level:(w=L==null?void 0:L.thinkingLevel)!=null?w:void 0,thinking_summaries:(C=L==null?void 0:L.thinkingSummaries)!=null?C:void 0,tool_choice:ye}),(L==null?void 0:L.imageConfig)!=null){const oe=ue.some(_e=>_e.type==="image");G.push({type:"other",message:oe?"google.interactions: providerOptions.google.imageConfig is deprecated and was ignored because providerOptions.google.responseFormat already supplies an image entry. Use responseFormat exclusively.":'google.interactions: providerOptions.google.imageConfig is deprecated. Use providerOptions.google.responseFormat with a { type: "image", ... } entry instead.'}),oe||ue.push({type:"image",mime_type:"image/png",...L.imageConfig.aspectRatio!=null?{aspect_ratio:L.imageConfig.aspectRatio}:{},...L.imageConfig.imageSize!=null?{image_size:L.imageConfig.imageSize}:{}})}let X;if(B&&(L==null?void 0:L.agentConfig)!=null){const oe=L.agentConfig;oe.type==="deep-research"?X=ci({type:"deep-research",thinking_summaries:(E=oe.thinkingSummaries)!=null?E:void 0,visualization:(A=oe.visualization)!=null?A:void 0,collaborative_planning:(R=oe.collaborativePlanning)!=null?R:void 0}):oe.type==="dynamic"&&(X={type:"dynamic"})}return{args:ci({...B?{agent:this.agent}:{model:this.modelId},input:we,system_instruction:x,tools:Ae,response_format:ue.length>0?ue:void 0,response_modalities:(L==null?void 0:L.responseModalities)!=null?L.responseModalities:void 0,previous_interaction_id:(k=L==null?void 0:L.previousInteractionId)!=null?k:void 0,service_tier:(b=L==null?void 0:L.serviceTier)!=null?b:void 0,store:(U=L==null?void 0:L.store)!=null?U:void 0,generation_config:H!=null&&Object.keys(H).length>0?H:void 0,agent_config:X,...B?{background:!0}:{}}),warnings:G,isAgent:B,pollingTimeoutMs:(J=L==null?void 0:L.pollingTimeoutMs)!=null?J:void 0}}async doGenerate(t){var e,n,o,i,s,r;const{args:a,warnings:u,isAgent:c,pollingTimeoutMs:p}=await this.getArgs(t),f=`${this.config.baseURL}/interactions`,h=Dt(Kf,this.config.headers?await He(this.config.headers):void 0,t.headers),m=await xt({url:f,headers:h,body:a,failedResponseHandler:an,successfulResponseHandler:Ct(nc),abortSignal:t.abortSignal,fetch:this.config.fetch});let{responseHeaders:v,value:_,rawValue:w}=m;if(c&&!oc(_.status)){const J=await E1({baseURL:this.config.baseURL,interactionId:_.id,headers:h,fetch:this.config.fetch,abortSignal:t.abortSignal,timeoutMs:p});_=J.response,w=J.rawResponse,v=(e=J.responseHeaders)!=null?e:v}const C=typeof _.id=="string"&&_.id.length>0?_.id:void 0,{content:E,hasFunctionCall:A}=XT({steps:(n=_.steps)!=null?n:null,generateId:(o=this.config.generateId)!=null?o:Hn,interactionId:C}),R={unified:rd({status:_.status,hasFunctionCall:A}),raw:_.status},k=(s=(i=_.service_tier)!=null?i:v==null?void 0:v["x-gemini-service-tier"])!=null?s:void 0,b={google:{...C!=null?{interactionId:C}:{},...k!=null?{serviceTier:k}:{}}};let U;if(typeof _.created=="string"){const J=new Date(_.created);Number.isNaN(J.getTime())||(U=J)}return{content:E,finishReason:R,usage:sd(_.usage),warnings:u,providerMetadata:b,request:{body:a},response:{headers:v,body:w,...C!=null?{id:C}:{},...U?{timestamp:U}:{},modelId:(r=_.model)!=null?r:void 0}}}async doStream(t){var e;const{args:n,warnings:o,isAgent:i,pollingTimeoutMs:s}=await this.getArgs(t),r=`${this.config.baseURL}/interactions`,a=Dt(Kf,this.config.headers?await He(this.config.headers):void 0,t.headers);if(i)return this.doStreamBackground({args:n,warnings:o,url:r,mergedHeaders:a,options:t,pollingTimeoutMs:s});const u={...n,stream:!0},{responseHeaders:c,value:p}=await xt({url:r,headers:a,body:u,failedResponseHandler:an,successfulResponseHandler:Bl(YT),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=c==null?void 0:c["x-gemini-service-tier"],h=Zf({warnings:o,generateId:(e=this.config.generateId)!=null?e:Hn,includeRawChunks:t.includeRawChunks,serviceTier:f});return{stream:p.pipeThrough(h),request:{body:u},response:{headers:c}}}async doStreamBackground({args:t,warnings:e,url:n,mergedHeaders:o,options:i,pollingTimeoutMs:s}){var r,a;const u=await xt({url:n,headers:o,body:t,failedResponseHandler:an,successfulResponseHandler:Ct(nc),abortSignal:i.abortSignal,fetch:this.config.fetch}),{responseHeaders:c,value:p}=u,f=p.id;if(f==null||f.length===0)throw new Error("google.interactions: background POST response did not include an interaction id; cannot stream the result.");const h=c==null?void 0:c["x-gemini-service-tier"];if(oc(p.status))return{stream:A1({response:p,warnings:e,generateId:(r=this.config.generateId)!=null?r:Hn,includeRawChunks:i.includeRawChunks,headerServiceTier:h}),request:{body:t},response:{headers:c}};const m=C1({baseURL:this.config.baseURL,interactionId:f,headers:o,fetch:this.config.fetch,abortSignal:i.abortSignal}),v=Zf({warnings:e,generateId:(a=this.config.generateId)!=null?a:Hn,includeRawChunks:i.includeRawChunks,serviceTier:h});return{stream:m.pipeThrough(v),request:{body:t},response:{headers:c}}}},Kf={"Api-Revision":"2026-05-20"};function ci(t){const e={};for(const[n,o]of Object.entries(t))o!==void 0&&(e[n]=o);return e}function jT(t={}){var e,n;const o=(e=xT(t.baseURL))!=null?e:"https://generativelanguage.googleapis.com/v1beta",i=(n=t.name)!=null?n:"google.generative-ai",s=()=>Po({"x-goog-api-key":fO({apiKey:t.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...t.headers},`ai-sdk/google/${hL}`),r=h=>{var m;return new DT(h,{provider:i,baseURL:o,headers:s,generateId:(m=t.generateId)!=null?m:Hn,supportedUrls:()=>({"*":[new RegExp(`^${o}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:t.fetch})},a=h=>new yL(h,{provider:i,baseURL:o,headers:s,fetch:t.fetch}),u=(h,m={})=>new KL(h,m,{provider:i,baseURL:o,headers:s,fetch:t.fetch}),c=h=>{var m;return new QL(h,{provider:i,baseURL:o,headers:s,fetch:t.fetch,generateId:(m=t.generateId)!=null?m:Hn})},p=h=>{var m;return new b1(h,{provider:`${i}.interactions`,baseURL:o,headers:s,generateId:(m=t.generateId)!=null?m:Hn,fetch:t.fetch})},f=function(h){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return r(h)};return f.specificationVersion="v3",f.languageModel=r,f.chat=r,f.generativeAI=r,f.embedding=a,f.embeddingModel=a,f.textEmbedding=a,f.textEmbeddingModel=a,f.image=u,f.imageModel=u,f.video=c,f.videoModel=c,f.interactions=p,f.tools=WL,f}jT();var cs={exports:{}},vu={},yu,Yf;function R1(){if(Yf)return yu;Yf=1;function t(e,n){typeof n=="boolean"&&(n={forever:n}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=n||{},this._maxRetryTime=n&&n.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return yu=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var n=new Date().getTime();if(e&&n-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var o=this._timeouts.shift();if(o===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),o=this._cachedTimeouts.slice(-1);else return!1;var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},o),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,n){this._fn=e,n&&(n.timeout&&(this._operationTimeout=n.timeout),n.cb&&(this._operationTimeoutCb=n.cb));var o=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){o._operationTimeoutCb()},o._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},n=null,o=0,i=0;i<this._errors.length;i++){var s=this._errors[i],r=s.message,a=(e[r]||0)+1;e[r]=a,a>=o&&(n=s,o=a)}return n},yu}var Xf;function k1(){return Xf||(Xf=1,(function(t){var e=R1();t.operation=function(n){var o=t.timeouts(n);return new e(o,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},t.timeouts=function(n){if(n instanceof Array)return[].concat(n);var o={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var i in n)o[i]=n[i];if(o.minTimeout>o.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var s=[],r=0;r<o.retries;r++)s.push(this.createTimeout(r,o));return n&&n.forever&&!s.length&&s.push(this.createTimeout(r,o)),s.sort(function(a,u){return a-u}),s},t.createTimeout=function(n,o){var i=o.randomize?Math.random()+1:1,s=Math.round(i*Math.max(o.minTimeout,1)*Math.pow(o.factor,n));return s=Math.min(s,o.maxTimeout),s},t.wrap=function(n,o,i){if(o instanceof Array&&(i=o,o=null),!i){i=[];for(var s in n)typeof n[s]=="function"&&i.push(s)}for(var r=0;r<i.length;r++){var a=i[r],u=n[a];n[a]=(function(p){var f=t.operation(o),h=Array.prototype.slice.call(arguments,1),m=h.pop();h.push(function(v){f.retry(v)||(v&&(arguments[0]=f.mainError()),m.apply(this,arguments))}),f.attempt(function(){p.apply(n,h)})}).bind(n,u),n[a].options=o}}})(vu)),vu}var _u,Qf;function P1(){return Qf||(Qf=1,_u=k1()),_u}var jf;function N1(){if(jf)return cs.exports;jf=1;const t=P1(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class n extends Error{constructor(a){super(),a instanceof Error?(this.originalError=a,{message:a}=a):(this.originalError=new Error(a),this.originalError.stack=this.stack),this.name="AbortError",this.message=a}}const o=(r,a,u)=>{const c=u.retries-(a-1);return r.attemptNumber=a,r.retriesLeft=c,r},i=r=>e.includes(r),s=(r,a)=>new Promise((u,c)=>{a={onFailedAttempt:()=>{},retries:10,...a};const p=t.operation(a);p.attempt(async f=>{try{u(await r(f))}catch(h){if(!(h instanceof Error)){c(new TypeError(`Non-error was thrown: "${h}". You should only throw errors.`));return}if(h instanceof n)p.stop(),c(h.originalError);else if(h instanceof TypeError&&!i(h.message))p.stop(),c(h);else{o(h,f,a);try{await a.onFailedAttempt(h)}catch(m){c(m);return}p.retry(h)||c(p.mainError())}}})});return cs.exports=s,cs.exports.default=s,cs.exports.AbortError=n,cs.exports}var eE=N1();const M1=XI(eE);var x1={};/**
134
+ * @license
135
+ * Copyright 2025 Google LLC
136
+ * SPDX-License-Identifier: Apache-2.0
137
+ */let D1,$1;function U1(){return{geminiUrl:D1,vertexUrl:$1}}function O1(t,e,n,o){var i,s;if(!(t!=null&&t.baseUrl)){const r=U1();return e?(i=r.vertexUrl)!==null&&i!==void 0?i:n:(s=r.geminiUrl)!==null&&s!==void 0?s:o}return t.baseUrl}/**
138
+ * @license
139
+ * Copyright 2025 Google LLC
140
+ * SPDX-License-Identifier: Apache-2.0
141
+ */class Qn{}function Q(t,e){const n=/\{([^}]+)\}/g;return t.replace(n,(o,i)=>{if(Object.prototype.hasOwnProperty.call(e,i)){const s=e[i];return s!=null?String(s):""}else throw new Error(`Key '${i}' not found in valueMap.`)})}function d(t,e,n){for(let s=0;s<e.length-1;s++){const r=e[s];if(r.endsWith("[]")){const a=r.slice(0,-2);if(!(a in t))if(Array.isArray(n))t[a]=Array.from({length:n.length},()=>({}));else throw new Error(`Value must be a list given an array path ${r}`);if(Array.isArray(t[a])){const u=t[a];if(Array.isArray(n))for(let c=0;c<u.length;c++){const p=u[c];d(p,e.slice(s+1),n[c])}else for(const c of u)d(c,e.slice(s+1),n)}return}else if(r.endsWith("[0]")){const a=r.slice(0,-3);a in t||(t[a]=[{}]);const u=t[a];d(u[0],e.slice(s+1),n);return}(!t[r]||typeof t[r]!="object")&&(t[r]={}),t=t[r]}const o=e[e.length-1],i=t[o];if(i!==void 0){if(!n||typeof n=="object"&&Object.keys(n).length===0||n===i)return;if(typeof i=="object"&&typeof n=="object"&&i!==null&&n!==null)Object.assign(i,n);else throw new Error(`Cannot set value for an existing key. Key: ${o}`)}else o==="_self"&&typeof n=="object"&&n!==null&&!Array.isArray(n)?Object.assign(t,n):t[o]=n}function l(t,e,n=void 0){try{if(e.length===1&&e[0]==="_self")return t;for(let o=0;o<e.length;o++){if(typeof t!="object"||t===null)return n;const i=e[o];if(i.endsWith("[]")){const s=i.slice(0,-2);if(s in t){const r=t[s];return Array.isArray(r)?r.map(a=>l(a,e.slice(o+1),n)):n}else return n}else t=t[i]}return t}catch(o){if(o instanceof TypeError)return n;throw o}}function L1(t,e){for(const[n,o]of Object.entries(e)){const i=n.split("."),s=o.split("."),r=new Set;let a=-1;for(let u=0;u<i.length;u++)if(i[u]==="*"){a=u;break}if(a!==-1&&s.length>a)for(let u=a;u<s.length;u++){const c=s[u];c!=="*"&&!c.endsWith("[]")&&!c.endsWith("[0]")&&r.add(c)}ic(t,i,s,0,r)}}function ic(t,e,n,o,i){if(o>=e.length||typeof t!="object"||t===null)return;const s=e[o];if(s.endsWith("[]")){const r=s.slice(0,-2),a=t;if(r in a&&Array.isArray(a[r]))for(const u of a[r])ic(u,e,n,o+1,i)}else if(s==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){const r=t,a=Object.keys(r).filter(c=>!c.startsWith("_")&&!i.has(c)),u={};for(const c of a)u[c]=r[c];for(const[c,p]of Object.entries(u)){const f=[];for(const h of n.slice(o))h==="*"?f.push(c):f.push(h);d(r,f,p)}for(const c of a)delete r[c]}}else{const r=t;s in r&&ic(r[s],e,n,o+1,i)}}/**
142
+ * @license
143
+ * Copyright 2025 Google LLC
144
+ * SPDX-License-Identifier: Apache-2.0
145
+ */function ad(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}/**
146
+ * @license
147
+ * Copyright 2025 Google LLC
148
+ * SPDX-License-Identifier: Apache-2.0
149
+ */function G1(t){const e={},n=l(t,["operationName"]);n!=null&&d(e,["operationName"],n);const o=l(t,["resourceName"]);return o!=null&&d(e,["_url","resourceName"],o),e}function z1(t){const e={},n=l(t,["name"]);n!=null&&d(e,["name"],n);const o=l(t,["metadata"]);o!=null&&d(e,["metadata"],o);const i=l(t,["done"]);i!=null&&d(e,["done"],i);const s=l(t,["error"]);s!=null&&d(e,["error"],s);const r=l(t,["response","generateVideoResponse"]);return r!=null&&d(e,["response"],V1(r)),e}function F1(t){const e={},n=l(t,["name"]);n!=null&&d(e,["name"],n);const o=l(t,["metadata"]);o!=null&&d(e,["metadata"],o);const i=l(t,["done"]);i!=null&&d(e,["done"],i);const s=l(t,["error"]);s!=null&&d(e,["error"],s);const r=l(t,["response"]);return r!=null&&d(e,["response"],q1(r)),e}function V1(t){const e={},n=l(t,["generatedSamples"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(r=>B1(r))),d(e,["generatedVideos"],s)}const o=l(t,["raiMediaFilteredCount"]);o!=null&&d(e,["raiMediaFilteredCount"],o);const i=l(t,["raiMediaFilteredReasons"]);return i!=null&&d(e,["raiMediaFilteredReasons"],i),e}function q1(t){const e={},n=l(t,["videos"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(r=>H1(r))),d(e,["generatedVideos"],s)}const o=l(t,["raiMediaFilteredCount"]);o!=null&&d(e,["raiMediaFilteredCount"],o);const i=l(t,["raiMediaFilteredReasons"]);return i!=null&&d(e,["raiMediaFilteredReasons"],i),e}function B1(t){const e={},n=l(t,["video"]);return n!=null&&d(e,["video"],X1(n)),e}function H1(t){const e={},n=l(t,["_self"]);return n!=null&&d(e,["video"],Q1(n)),e}function Z1(t){const e={},n=l(t,["operationName"]);return n!=null&&d(e,["_url","operationName"],n),e}function J1(t){const e={},n=l(t,["operationName"]);return n!=null&&d(e,["_url","operationName"],n),e}function W1(t){const e={},n=l(t,["name"]);n!=null&&d(e,["name"],n);const o=l(t,["metadata"]);o!=null&&d(e,["metadata"],o);const i=l(t,["done"]);i!=null&&d(e,["done"],i);const s=l(t,["error"]);s!=null&&d(e,["error"],s);const r=l(t,["response"]);return r!=null&&d(e,["response"],K1(r)),e}function K1(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["parent"]);o!=null&&d(e,["parent"],o);const i=l(t,["documentName"]);return i!=null&&d(e,["documentName"],i),e}function tE(t){const e={},n=l(t,["name"]);n!=null&&d(e,["name"],n);const o=l(t,["metadata"]);o!=null&&d(e,["metadata"],o);const i=l(t,["done"]);i!=null&&d(e,["done"],i);const s=l(t,["error"]);s!=null&&d(e,["error"],s);const r=l(t,["response"]);return r!=null&&d(e,["response"],Y1(r)),e}function Y1(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["parent"]);o!=null&&d(e,["parent"],o);const i=l(t,["documentName"]);return i!=null&&d(e,["documentName"],i),e}function X1(t){const e={},n=l(t,["uri"]);n!=null&&d(e,["uri"],n);const o=l(t,["encodedVideo"]);o!=null&&d(e,["videoBytes"],ad(o));const i=l(t,["encoding"]);return i!=null&&d(e,["mimeType"],i),e}function Q1(t){const e={},n=l(t,["gcsUri"]);n!=null&&d(e,["uri"],n);const o=l(t,["bytesBase64Encoded"]);o!=null&&d(e,["videoBytes"],ad(o));const i=l(t,["mimeType"]);return i!=null&&d(e,["mimeType"],i),e}/**
150
+ * @license
151
+ * Copyright 2025 Google LLC
152
+ * SPDX-License-Identifier: Apache-2.0
153
+ */var eh;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(eh||(eh={}));var th;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(th||(th={}));var nh;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(nh||(nh={}));var yo;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.STRING="STRING",t.NUMBER="NUMBER",t.INTEGER="INTEGER",t.BOOLEAN="BOOLEAN",t.ARRAY="ARRAY",t.OBJECT="OBJECT",t.NULL="NULL"})(yo||(yo={}));var oh;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(oh||(oh={}));var ih;(function(t){t.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",t.NO_AUTH="NO_AUTH",t.API_KEY_AUTH="API_KEY_AUTH",t.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",t.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",t.OAUTH="OAUTH",t.OIDC_AUTH="OIDC_AUTH"})(ih||(ih={}));var sh;(function(t){t.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",t.HTTP_IN_QUERY="HTTP_IN_QUERY",t.HTTP_IN_HEADER="HTTP_IN_HEADER",t.HTTP_IN_PATH="HTTP_IN_PATH",t.HTTP_IN_BODY="HTTP_IN_BODY",t.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(sh||(sh={}));var rh;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(rh||(rh={}));var ah;(function(t){t.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",t.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",t.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",t.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(ah||(ah={}));var lh;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(lh||(lh={}));var uh;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(uh||(uh={}));var ch;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(ch||(ch={}));var dh;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(dh||(dh={}));var ph;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(ph||(ph={}));var fh;(function(t){t.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",t.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",t.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(fh||(fh={}));var hh;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",t.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",t.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",t.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",t.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"})(hh||(hh={}));var mh;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(mh||(mh={}));var gh;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE",t.OFF="OFF"})(gh||(gh={}));var vh;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.IMAGE_SAFETY="IMAGE_SAFETY",t.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",t.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",t.NO_IMAGE="NO_IMAGE",t.IMAGE_RECITATION="IMAGE_RECITATION",t.IMAGE_OTHER="IMAGE_OTHER"})(vh||(vh={}));var yh;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(yh||(yh={}));var _h;(function(t){t.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",t.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",t.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",t.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",t.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(_h||(_h={}));var Th;(function(t){t.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",t.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",t.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",t.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",t.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(Th||(Th={}));var Eh;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.IMAGE_SAFETY="IMAGE_SAFETY",t.MODEL_ARMOR="MODEL_ARMOR",t.JAILBREAK="JAILBREAK"})(Eh||(Eh={}));var wh;(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",t.ON_DEMAND_FLEX="ON_DEMAND_FLEX",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(wh||(wh={}));var nl;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO",t.VIDEO="VIDEO"})(nl||(nl={}));var Ih;(function(t){t.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",t.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",t.EXPERIMENTAL="EXPERIMENTAL",t.PREVIEW="PREVIEW",t.STABLE="STABLE",t.LEGACY="LEGACY",t.DEPRECATED="DEPRECATED",t.RETIRED="RETIRED"})(Ih||(Ih={}));var Sh;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(Sh||(Sh={}));var Ch;(function(t){t.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",t.TUNING_MODE_FULL="TUNING_MODE_FULL",t.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(Ch||(Ch={}));var Ah;(function(t){t.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",t.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",t.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",t.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",t.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",t.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",t.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(Ah||(Ah={}));var sc;(function(t){t.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",t.JOB_STATE_QUEUED="JOB_STATE_QUEUED",t.JOB_STATE_PENDING="JOB_STATE_PENDING",t.JOB_STATE_RUNNING="JOB_STATE_RUNNING",t.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",t.JOB_STATE_FAILED="JOB_STATE_FAILED",t.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",t.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",t.JOB_STATE_PAUSED="JOB_STATE_PAUSED",t.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",t.JOB_STATE_UPDATING="JOB_STATE_UPDATING",t.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(sc||(sc={}));var bh;(function(t){t.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",t.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",t.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",t.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",t.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",t.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(bh||(bh={}));var Rh;(function(t){t.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",t.AVERAGE="AVERAGE",t.MODE="MODE",t.STANDARD_DEVIATION="STANDARD_DEVIATION",t.VARIANCE="VARIANCE",t.MINIMUM="MINIMUM",t.MAXIMUM="MAXIMUM",t.MEDIAN="MEDIAN",t.PERCENTILE_P90="PERCENTILE_P90",t.PERCENTILE_P95="PERCENTILE_P95",t.PERCENTILE_P99="PERCENTILE_P99"})(Rh||(Rh={}));var kh;(function(t){t.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",t.BASELINE="BASELINE",t.CANDIDATE="CANDIDATE",t.TIE="TIE"})(kh||(kh={}));var Ph;(function(t){t.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",t.TUNING_TASK_I2V="TUNING_TASK_I2V",t.TUNING_TASK_T2V="TUNING_TASK_T2V",t.TUNING_TASK_R2V="TUNING_TASK_R2V"})(Ph||(Ph={}));var Nh;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(Nh||(Nh={}));var Mh;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",t.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(Mh||(Mh={}));var xh;(function(t){t.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",t.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",t.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",t.URL_CONTEXT="URL_CONTEXT",t.GOOGLE_MAPS="GOOGLE_MAPS",t.FILE_SEARCH="FILE_SEARCH"})(xh||(xh={}));var rc;(function(t){t.COLLECTION="COLLECTION"})(rc||(rc={}));var Dh;(function(t){t.UNSPECIFIED="unspecified",t.FLEX="flex",t.STANDARD="standard",t.PRIORITY="priority"})(Dh||(Dh={}));var $h;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})($h||($h={}));var ol;(function(t){t.PREDICT="PREDICT",t.EMBED_CONTENT="EMBED_CONTENT"})(ol||(ol={}));var Uh;(function(t){t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(Uh||(Uh={}));var Oh;(function(t){t.auto="auto",t.en="en",t.ja="ja",t.ko="ko",t.hi="hi",t.zh="zh",t.pt="pt",t.es="es"})(Oh||(Oh={}));var Lh;(function(t){t.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",t.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",t.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",t.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",t.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(Lh||(Lh={}));var Gh;(function(t){t.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",t.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",t.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",t.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(Gh||(Gh={}));var zh;(function(t){t.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",t.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",t.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",t.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(zh||(zh={}));var Fh;(function(t){t.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",t.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",t.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",t.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",t.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",t.EDIT_MODE_STYLE="EDIT_MODE_STYLE",t.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",t.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(Fh||(Fh={}));var Vh;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(Vh||(Vh={}));var qh;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(qh||(qh={}));var Bh;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(Bh||(Bh={}));var Hh;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(Hh||(Hh={}));var Zh;(function(t){t.CROP="CROP",t.PAD="PAD"})(Zh||(Zh={}));var Jh;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING",t.DISTILLATION="DISTILLATION"})(Jh||(Jh={}));var Wh;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(Wh||(Wh={}));var Kh;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED",t.REGISTERED="REGISTERED"})(Kh||(Kh={}));var Yh;(function(t){t.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.RESPONSE_REJECTED="RESPONSE_REJECTED",t.NEED_MORE_INPUT="NEED_MORE_INPUT",t.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",t.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",t.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",t.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",t.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",t.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",t.INPUT_OTHER="INPUT_OTHER",t.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",t.BLOCKLIST="BLOCKLIST",t.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",t.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",t.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",t.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",t.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",t.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",t.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",t.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",t.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",t.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",t.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",t.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",t.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",t.GENERATED_OTHER="GENERATED_OTHER",t.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(Yh||(Yh={}));var Xh;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(Xh||(Xh={}));var Qh;(function(t){t.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",t.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",t.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(Qh||(Qh={}));var jh;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.ACTIVITY_START="ACTIVITY_START",t.ACTIVITY_END="ACTIVITY_END"})(jh||(jh={}));var em;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(em||(em={}));var tm;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(tm||(tm={}));var nm;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(nm||(nm={}));var om;(function(t){t.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",t.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",t.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",t.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(om||(om={}));var im;(function(t){t.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",t.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",t.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",t.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",t.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",t.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",t.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",t.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",t.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",t.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",t.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",t.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",t.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(im||(im={}));var sm;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(sm||(sm={}));var gi;(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(gi||(gi={}));class il{constructor(e){const n={};for(const o of e.headers.entries())n[o[0]]=o[1];this.headers=n,this.responseInternal=e}json(){return this.responseInternal.json()}}class ds{get text(){var e,n,o,i,s,r,a,u;if(((i=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let c="",p=!1;const f=[];for(const h of(u=(a=(r=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||r===void 0?void 0:r.content)===null||a===void 0?void 0:a.parts)!==null&&u!==void 0?u:[]){for(const[m,v]of Object.entries(h))m!=="text"&&m!=="thought"&&m!=="thoughtSignature"&&(v!==null||v!==void 0)&&f.push(m);if(typeof h.text=="string"){if(typeof h.thought=="boolean"&&h.thought)continue;p=!0,c+=h.text}}return f.length>0&&console.warn(`there are non-text parts ${f} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),p?c:void 0}get data(){var e,n,o,i,s,r,a,u;if(((i=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let c="";const p=[];for(const f of(u=(a=(r=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||r===void 0?void 0:r.content)===null||a===void 0?void 0:a.parts)!==null&&u!==void 0?u:[]){for(const[h,m]of Object.entries(f))h!=="inlineData"&&(m!==null||m!==void 0)&&p.push(h);f.inlineData&&typeof f.inlineData.data=="string"&&(c+=atob(f.inlineData.data))}return p.length>0&&console.warn(`there are non-data parts ${p} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),c.length>0?btoa(c):void 0}get functionCalls(){var e,n,o,i,s,r,a,u;if(((i=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");const c=(u=(a=(r=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||r===void 0?void 0:r.content)===null||a===void 0?void 0:a.parts)===null||u===void 0?void 0:u.filter(p=>p.functionCall).map(p=>p.functionCall).filter(p=>p!==void 0);if((c==null?void 0:c.length)!==0)return c}get executableCode(){var e,n,o,i,s,r,a,u,c;if(((i=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");const p=(u=(a=(r=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||r===void 0?void 0:r.content)===null||a===void 0?void 0:a.parts)===null||u===void 0?void 0:u.filter(f=>f.executableCode).map(f=>f.executableCode).filter(f=>f!==void 0);if((p==null?void 0:p.length)!==0)return(c=p==null?void 0:p[0])===null||c===void 0?void 0:c.code}get codeExecutionResult(){var e,n,o,i,s,r,a,u,c;if(((i=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||i===void 0?void 0:i.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");const p=(u=(a=(r=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||r===void 0?void 0:r.content)===null||a===void 0?void 0:a.parts)===null||u===void 0?void 0:u.filter(f=>f.codeExecutionResult).map(f=>f.codeExecutionResult).filter(f=>f!==void 0);if((p==null?void 0:p.length)!==0)return(c=p==null?void 0:p[0])===null||c===void 0?void 0:c.output}}class rm{}class am{}class j1{}class eG{}class tG{}class nG{}class lm{}class um{}class cm{}class oG{}class sl{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const o=new sl;let i;const s=e;return n?i=F1(s):i=z1(s),Object.assign(o,i),o}}class iG{}class dm{}class pm{}class fm{}class sG{}class rG{}class aG{}class ld{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const o=new ld,s=W1(e);return Object.assign(o,s),o}}class lG{}class uG{}class cG{}class dG{}class hm{}class pG{get text(){var e,n,o;let i="",s=!1;const r=[];for(const a of(o=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&o!==void 0?o:[]){for(const[u,c]of Object.entries(a))u!=="text"&&u!=="thought"&&c!==null&&r.push(u);if(typeof a.text=="string"){if(typeof a.thought=="boolean"&&a.thought)continue;s=!0,i+=a.text}}return r.length>0&&console.warn(`there are non-text parts ${r} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),s?i:void 0}get data(){var e,n,o;let i="";const s=[];for(const r of(o=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&o!==void 0?o:[]){for(const[a,u]of Object.entries(r))a!=="inlineData"&&u!==null&&s.push(a);r.inlineData&&typeof r.inlineData.data=="string"&&(i+=atob(r.inlineData.data))}return s.length>0&&console.warn(`there are non-data parts ${s} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),i.length>0?btoa(i):void 0}}class fG{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class ud{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const o=new ud,s=tE(e);return Object.assign(o,s),o}}/**
154
+ * @license
155
+ * Copyright 2025 Google LLC
156
+ * SPDX-License-Identifier: Apache-2.0
157
+ */function Pe(t,e){if(!e||typeof e!="string")throw new Error("model is required and must be a string");if(e.includes("..")||e.includes("?")||e.includes("&"))throw new Error("invalid model parameter");if(t.isVertexAI()){if(e.startsWith("publishers/")||e.startsWith("projects/")||e.startsWith("models/"))return e;if(e.indexOf("/")>=0){const n=e.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else return`publishers/google/models/${e}`}else return e.startsWith("models/")||e.startsWith("tunedModels/")?e:`models/${e}`}function nE(t,e){const n=Pe(t,e);return n?n.startsWith("publishers/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}`:n.startsWith("models/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/publishers/google/${n}`:n:""}function oE(t){return Array.isArray(t)?t.map(e=>rl(e)):[rl(t)]}function rl(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function iE(t){const e=rl(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function sE(t){const e=rl(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function mm(t){if(t==null)throw new Error("PartUnion is required");if(typeof t=="object")return t;if(typeof t=="string")return{text:t};throw new Error(`Unsupported part type: ${typeof t}`)}function rE(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>mm(e)):[mm(t)]}function ac(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function gm(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function vm(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function _t(t){if(t==null)throw new Error("ContentUnion is required");return ac(t)?t:{role:"user",parts:rE(t)}}function cd(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{const o=_t(n);return o.parts&&o.parts.length>0&&o.parts[0].text!==void 0?[o.parts[0].text]:[]});if(t.isVertexAI()){const n=_t(e);return n.parts&&n.parts.length>0&&n.parts[0].text!==void 0?[n.parts[0].text]:[]}return Array.isArray(e)?e.map(n=>_t(n)):[_t(e)]}function Ut(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(gm(t)||vm(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[_t(t)]}const e=[],n=[],o=ac(t[0]);for(const i of t){const s=ac(i);if(s!=o)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(s)e.push(i);else{if(gm(i)||vm(i))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");n.push(i)}}return o||e.push({role:"user",parts:rE(n)}),e}function hG(t,e){t.includes("null")&&(e.nullable=!0);const n=t.filter(o=>o!=="null");if(n.length===1)e.type=Object.values(yo).includes(n[0].toUpperCase())?n[0].toUpperCase():yo.TYPE_UNSPECIFIED;else{e.anyOf=[];for(const o of n)e.anyOf.push({type:Object.values(yo).includes(o.toUpperCase())?o.toUpperCase():yo.TYPE_UNSPECIFIED})}}function Ti(t){const e={},n=["items"],o=["anyOf"],i=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");const s=t.anyOf;s!=null&&s.length==2&&(s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type instanceof Array&&hG(t.type,e);for(const[r,a]of Object.entries(t))if(a!=null)if(r=="type"){if(a==="null")throw new Error("type: null can not be the only possible type for the field.");if(a instanceof Array)continue;e.type=Object.values(yo).includes(a.toUpperCase())?a.toUpperCase():yo.TYPE_UNSPECIFIED}else if(n.includes(r))e[r]=Ti(a);else if(o.includes(r)){const u=[];for(const c of a){if(c.type=="null"){e.nullable=!0;continue}u.push(Ti(c))}e[r]=u}else if(i.includes(r)){const u={};for(const[c,p]of Object.entries(a))u[c]=Ti(p);e[r]=u}else{if(r==="additionalProperties")continue;e[r]=a}return e}function dd(t){return Ti(t)}function pd(t){if(typeof t=="object")return t;if(typeof t=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:t}}};throw new Error(`Unsupported speechConfig type: ${typeof t}`)}function fd(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function ts(t){if(t.functionDeclarations)for(const e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=Ti(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Ti(e.response));return t}function ns(t){if(t==null)throw new Error("tools is required");if(!Array.isArray(t))throw new Error("tools is required and must be an array of Tools");const e=[];for(const n of t)e.push(n);return e}function mG(t,e,n,o=1){const i=!e.startsWith(`${n}/`)&&e.split("/").length===o;return t.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${t.getProject()}/${e}`:e.startsWith(`${n}/`)?`projects/${t.getProject()}/locations/${t.getLocation()}/${e}`:i?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}/${e}`:e:i?`${n}/${e}`:e}function jn(t,e){if(typeof e!="string")throw new Error("name must be a string");return mG(t,e,"cachedContents")}function aE(t){switch(t){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return t}}function No(t){return ad(t)}function gG(t){return t!=null&&typeof t=="object"&&"name"in t}function vG(t){return t!=null&&typeof t=="object"&&"video"in t}function yG(t){return t!=null&&typeof t=="object"&&"uri"in t}function lE(t){var e;let n;if(gG(t)&&(n=t.name),!(yG(t)&&(n=t.uri,n===void 0))&&!(vG(t)&&(n=(e=t.video)===null||e===void 0?void 0:e.uri,n===void 0))){if(typeof t=="string"&&(n=t),n===void 0)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){const i=n.split("files/")[1].match(/[a-z0-9]+/);if(i===null)throw new Error(`Could not extract file name from URI ${n}`);n=i[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function uE(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function cE(t){for(const e of["models","tunedModels","publisherModels"])if(_G(t,e))return t[e];return[]}function _G(t,e){return t!==null&&typeof t=="object"&&e in t}function TG(t,e={}){const n=t,o={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(o.responseJsonSchema=n.outputSchema),e.behavior&&(o.behavior=e.behavior),{functionDeclarations:[o]}}function EG(t,e={}){const n=[],o=new Set;for(const i of t){const s=i.name;if(o.has(s))throw new Error(`Duplicate function name ${s} found in MCP tools. Please ensure function names are unique.`);o.add(s);const r=TG(i,e);r.functionDeclarations&&n.push(...r.functionDeclarations)}return{functionDeclarations:n}}function dE(t,e){let n;if(typeof e=="string")if(t.isVertexAI())if(e.startsWith("gs://"))n={format:"jsonl",gcsUri:[e]};else if(e.startsWith("bq://"))n={format:"bigquery",bigqueryUri:e};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(e))n={format:"vertex-dataset",vertexDatasetName:e};else throw new Error(`Unsupported string source for Vertex AI: ${e}`);else if(e.startsWith("files/"))n={fileName:e};else throw new Error(`Unsupported string source for Gemini API: ${e}`);else if(Array.isArray(e)){if(t.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:e}}else n=e;const o=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,i=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(t.isVertexAI()){if(i>0||o!==1)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(o>0||i!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function wG(t){if(typeof t!="string")return t;const e=t;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw new Error(`Unsupported destination: ${e}`)}function pE(t){if(typeof t!="object"||t===null)return{};const e=t,n=e.inlinedResponses;if(typeof n!="object"||n===null)return t;const i=n.inlinedResponses;if(!Array.isArray(i)||i.length===0)return t;let s=!1;for(const r of i){if(typeof r!="object"||r===null)continue;const u=r.response;if(typeof u!="object"||u===null)continue;if(u.embedding!==void 0){s=!0;break}}return s&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function os(t,e){const n=e;if(!t.isVertexAI()){if(/batches\/[^/]+$/.test(n))return n.split("/").pop();throw new Error(`Invalid batch job name: ${n}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();if(/^\d+$/.test(n))return n;throw new Error(`Invalid batch job name: ${n}.`)}function fE(t){const e=t;return e==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":e==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":e==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":e==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":e==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":e==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":e==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":e}function IG(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}/**
158
+ * @license
159
+ * Copyright 2025 Google LLC
160
+ * SPDX-License-Identifier: Apache-2.0
161
+ */function SG(t){const e={},n=l(t,["apiKey"]);if(n!=null&&d(e,["apiKey"],n),l(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function CG(t){const e={},n=l(t,["responsesFile"]);n!=null&&d(e,["fileName"],n);const o=l(t,["inlinedResponses","inlinedResponses"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(r=>sz(r))),d(e,["inlinedResponses"],s)}const i=l(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>r)),d(e,["inlinedEmbedContentResponses"],s)}return e}function AG(t){const e={},n=l(t,["predictionsFormat"]);n!=null&&d(e,["format"],n);const o=l(t,["gcsDestination","outputUriPrefix"]);o!=null&&d(e,["gcsUri"],o);const i=l(t,["bigqueryDestination","outputUri"]);i!=null&&d(e,["bigqueryUri"],i);const s=l(t,["vertexMultimodalDatasetDestination"]);return s!=null&&d(e,["vertexDataset"],gz(s)),e}function bG(t){const e={},n=l(t,["format"]);n!=null&&d(e,["predictionsFormat"],n);const o=l(t,["gcsUri"]);o!=null&&d(e,["gcsDestination","outputUriPrefix"],o);const i=l(t,["bigqueryUri"]);if(i!=null&&d(e,["bigqueryDestination","outputUri"],i),l(t,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(t,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(t,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const s=l(t,["vertexDataset"]);return s!=null&&d(e,["vertexMultimodalDatasetDestination"],vz(s)),e}function Da(t){const e={},n=l(t,["name"]);n!=null&&d(e,["name"],n);const o=l(t,["metadata","displayName"]);o!=null&&d(e,["displayName"],o);const i=l(t,["metadata","state"]);i!=null&&d(e,["state"],fE(i));const s=l(t,["metadata","createTime"]);s!=null&&d(e,["createTime"],s);const r=l(t,["metadata","endTime"]);r!=null&&d(e,["endTime"],r);const a=l(t,["metadata","updateTime"]);a!=null&&d(e,["updateTime"],a);const u=l(t,["metadata","model"]);u!=null&&d(e,["model"],u);const c=l(t,["metadata","output"]);return c!=null&&d(e,["dest"],CG(pE(c))),e}function lc(t){const e={},n=l(t,["name"]);n!=null&&d(e,["name"],n);const o=l(t,["displayName"]);o!=null&&d(e,["displayName"],o);const i=l(t,["state"]);i!=null&&d(e,["state"],fE(i));const s=l(t,["error"]);s!=null&&d(e,["error"],s);const r=l(t,["createTime"]);r!=null&&d(e,["createTime"],r);const a=l(t,["startTime"]);a!=null&&d(e,["startTime"],a);const u=l(t,["endTime"]);u!=null&&d(e,["endTime"],u);const c=l(t,["updateTime"]);c!=null&&d(e,["updateTime"],c);const p=l(t,["model"]);p!=null&&d(e,["model"],p);const f=l(t,["inputConfig"]);f!=null&&d(e,["src"],RG(f));const h=l(t,["outputConfig"]);h!=null&&d(e,["dest"],AG(pE(h)));const m=l(t,["completionStats"]);m!=null&&d(e,["completionStats"],m);const v=l(t,["outputInfo"]);return v!=null&&d(e,["outputInfo"],v),e}function RG(t){const e={},n=l(t,["instancesFormat"]);n!=null&&d(e,["format"],n);const o=l(t,["gcsSource","uris"]);o!=null&&d(e,["gcsUri"],o);const i=l(t,["bigquerySource","inputUri"]);i!=null&&d(e,["bigqueryUri"],i);const s=l(t,["vertexMultimodalDatasetSource","datasetName"]);return s!=null&&d(e,["vertexDatasetName"],s),e}function kG(t,e){const n={};if(l(e,["format"])!==void 0)throw new Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(e,["fileName"]);o!=null&&d(n,["fileName"],o);const i=l(e,["inlinedRequests"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>iz(t,r))),d(n,["requests","requests"],s)}if(l(e,["vertexDatasetName"])!==void 0)throw new Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function PG(t){const e={},n=l(t,["format"]);n!=null&&d(e,["instancesFormat"],n);const o=l(t,["gcsUri"]);o!=null&&d(e,["gcsSource","uris"],o);const i=l(t,["bigqueryUri"]);if(i!=null&&d(e,["bigquerySource","inputUri"],i),l(t,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(t,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const s=l(t,["vertexDatasetName"]);return s!=null&&d(e,["vertexMultimodalDatasetSource","datasetName"],s),e}function NG(t){const e={},n=l(t,["data"]);if(n!=null&&d(e,["data"],n),l(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["mimeType"]);return o!=null&&d(e,["mimeType"],o),e}function MG(t,e){const n={},o=l(e,["name"]);return o!=null&&d(n,["_url","name"],os(t,o)),n}function xG(t,e){const n={},o=l(e,["name"]);return o!=null&&d(n,["_url","name"],os(t,o)),n}function DG(t){const e={},n=l(t,["content"]);n!=null&&d(e,["content"],n);const o=l(t,["citationMetadata"]);o!=null&&d(e,["citationMetadata"],$G(o));const i=l(t,["tokenCount"]);i!=null&&d(e,["tokenCount"],i);const s=l(t,["finishReason"]);s!=null&&d(e,["finishReason"],s);const r=l(t,["groundingMetadata"]);r!=null&&d(e,["groundingMetadata"],r);const a=l(t,["avgLogprobs"]);a!=null&&d(e,["avgLogprobs"],a);const u=l(t,["index"]);u!=null&&d(e,["index"],u);const c=l(t,["logprobsResult"]);c!=null&&d(e,["logprobsResult"],c);const p=l(t,["safetyRatings"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(m=>m)),d(e,["safetyRatings"],h)}const f=l(t,["urlContextMetadata"]);return f!=null&&d(e,["urlContextMetadata"],f),e}function $G(t){const e={},n=l(t,["citationSources"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>i)),d(e,["citations"],o)}return e}function hE(t){const e={},n=l(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>pz(s))),d(e,["parts"],i)}const o=l(t,["role"]);return o!=null&&d(e,["role"],o),e}function UG(t,e){const n={},o=l(t,["displayName"]);if(e!==void 0&&o!=null&&d(e,["batch","displayName"],o),l(t,["dest"])!==void 0)throw new Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const i=l(t,["webhookConfig"]);return e!==void 0&&i!=null&&d(e,["batch","webhookConfig"],i),n}function OG(t,e){const n={},o=l(t,["displayName"]);e!==void 0&&o!=null&&d(e,["displayName"],o);const i=l(t,["dest"]);if(e!==void 0&&i!=null&&d(e,["outputConfig"],bG(wG(i))),l(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function ym(t,e){const n={},o=l(e,["model"]);o!=null&&d(n,["_url","model"],Pe(t,o));const i=l(e,["src"]);i!=null&&d(n,["batch","inputConfig"],kG(t,dE(t,i)));const s=l(e,["config"]);return s!=null&&UG(s,n),n}function LG(t,e){const n={},o=l(e,["model"]);o!=null&&d(n,["model"],Pe(t,o));const i=l(e,["src"]);i!=null&&d(n,["inputConfig"],PG(dE(t,i)));const s=l(e,["config"]);return s!=null&&OG(s,n),n}function GG(t,e){const n={},o=l(t,["displayName"]);return e!==void 0&&o!=null&&d(e,["batch","displayName"],o),n}function zG(t,e){const n={},o=l(e,["model"]);o!=null&&d(n,["_url","model"],Pe(t,o));const i=l(e,["src"]);i!=null&&d(n,["batch","inputConfig"],JG(t,i));const s=l(e,["config"]);return s!=null&&GG(s,n),n}function FG(t,e){const n={},o=l(e,["name"]);return o!=null&&d(n,["_url","name"],os(t,o)),n}function VG(t,e){const n={},o=l(e,["name"]);return o!=null&&d(n,["_url","name"],os(t,o)),n}function qG(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["name"]);o!=null&&d(e,["name"],o);const i=l(t,["done"]);i!=null&&d(e,["done"],i);const s=l(t,["error"]);return s!=null&&d(e,["error"],s),e}function BG(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["name"]);o!=null&&d(e,["name"],o);const i=l(t,["done"]);i!=null&&d(e,["done"],i);const s=l(t,["error"]);return s!=null&&d(e,["error"],s),e}function HG(t,e){const n={},o=l(e,["contents"]);if(o!=null){let s=cd(t,o);Array.isArray(s)&&(s=s.map(r=>r)),d(n,["requests[]","request","content"],s)}const i=l(e,["config"]);return i!=null&&(d(n,["_self"],ZG(i,n)),L1(n,{"requests[].*":"requests[].request.*"})),n}function ZG(t,e){const n={},o=l(t,["taskType"]);e!==void 0&&o!=null&&d(e,["requests[]","taskType"],o);const i=l(t,["title"]);e!==void 0&&i!=null&&d(e,["requests[]","title"],i);const s=l(t,["outputDimensionality"]);if(e!==void 0&&s!=null&&d(e,["requests[]","outputDimensionality"],s),l(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function JG(t,e){const n={},o=l(e,["fileName"]);o!=null&&d(n,["file_name"],o);const i=l(e,["inlinedRequests"]);return i!=null&&d(n,["requests"],HG(t,i)),n}function WG(t){const e={};if(l(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=l(t,["fileUri"]);n!=null&&d(e,["fileUri"],n);const o=l(t,["mimeType"]);return o!=null&&d(e,["mimeType"],o),e}function KG(t){const e={},n=l(t,["id"]);n!=null&&d(e,["id"],n);const o=l(t,["args"]);o!=null&&d(e,["args"],o);const i=l(t,["name"]);if(i!=null&&d(e,["name"],i),l(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function YG(t){const e={},n=l(t,["allowedFunctionNames"]);n!=null&&d(e,["allowedFunctionNames"],n);const o=l(t,["mode"]);if(o!=null&&d(e,["mode"],o),l(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function XG(t,e,n){const o={},i=l(e,["systemInstruction"]);n!==void 0&&i!=null&&d(n,["systemInstruction"],hE(_t(i)));const s=l(e,["temperature"]);s!=null&&d(o,["temperature"],s);const r=l(e,["topP"]);r!=null&&d(o,["topP"],r);const a=l(e,["topK"]);a!=null&&d(o,["topK"],a);const u=l(e,["candidateCount"]);u!=null&&d(o,["candidateCount"],u);const c=l(e,["maxOutputTokens"]);c!=null&&d(o,["maxOutputTokens"],c);const p=l(e,["stopSequences"]);p!=null&&d(o,["stopSequences"],p);const f=l(e,["responseLogprobs"]);f!=null&&d(o,["responseLogprobs"],f);const h=l(e,["logprobs"]);h!=null&&d(o,["logprobs"],h);const m=l(e,["presencePenalty"]);m!=null&&d(o,["presencePenalty"],m);const v=l(e,["frequencyPenalty"]);v!=null&&d(o,["frequencyPenalty"],v);const _=l(e,["seed"]);_!=null&&d(o,["seed"],_);const w=l(e,["responseMimeType"]);w!=null&&d(o,["responseMimeType"],w);const C=l(e,["responseSchema"]);C!=null&&d(o,["responseSchema"],dd(C));const E=l(e,["responseJsonSchema"]);if(E!=null&&d(o,["responseJsonSchema"],E),l(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const A=l(e,["safetySettings"]);if(n!==void 0&&A!=null){let ye=A;Array.isArray(ye)&&(ye=ye.map(ue=>fz(ue))),d(n,["safetySettings"],ye)}const R=l(e,["tools"]);if(n!==void 0&&R!=null){let ye=ns(R);Array.isArray(ye)&&(ye=ye.map(ue=>mz(ts(ue)))),d(n,["tools"],ye)}const k=l(e,["toolConfig"]);if(n!==void 0&&k!=null&&d(n,["toolConfig"],hz(k)),l(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const b=l(e,["cachedContent"]);n!==void 0&&b!=null&&d(n,["cachedContent"],jn(t,b));const U=l(e,["responseModalities"]);U!=null&&d(o,["responseModalities"],U);const J=l(e,["mediaResolution"]);J!=null&&d(o,["mediaResolution"],J);const G=l(e,["speechConfig"]);if(G!=null&&d(o,["speechConfig"],pd(G)),l(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const L=l(e,["thinkingConfig"]);L!=null&&d(o,["thinkingConfig"],L);const B=l(e,["imageConfig"]);B!=null&&d(o,["imageConfig"],oz(B));const ve=l(e,["enableEnhancedCivicAnswers"]);if(ve!=null&&d(o,["enableEnhancedCivicAnswers"],ve),l(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const Ae=l(e,["serviceTier"]);return n!==void 0&&Ae!=null&&d(n,["serviceTier"],Ae),o}function QG(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["candidates"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(p=>DG(p))),d(e,["candidates"],c)}const i=l(t,["modelVersion"]);i!=null&&d(e,["modelVersion"],i);const s=l(t,["promptFeedback"]);s!=null&&d(e,["promptFeedback"],s);const r=l(t,["responseId"]);r!=null&&d(e,["responseId"],r);const a=l(t,["usageMetadata"]);a!=null&&d(e,["usageMetadata"],a);const u=l(t,["modelStatus"]);return u!=null&&d(e,["modelStatus"],u),e}function jG(t,e){const n={},o=l(e,["name"]);return o!=null&&d(n,["_url","name"],os(t,o)),n}function ez(t,e){const n={},o=l(e,["name"]);return o!=null&&d(n,["_url","name"],os(t,o)),n}function tz(t){const e={},n=l(t,["authConfig"]);n!=null&&d(e,["authConfig"],SG(n));const o=l(t,["enableWidget"]);return o!=null&&d(e,["enableWidget"],o),e}function nz(t){const e={},n=l(t,["searchTypes"]);if(n!=null&&d(e,["searchTypes"],n),l(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["timeRangeFilter"]);return o!=null&&d(e,["timeRangeFilter"],o),e}function oz(t){const e={},n=l(t,["aspectRatio"]);n!=null&&d(e,["aspectRatio"],n);const o=l(t,["imageSize"]);if(o!=null&&d(e,["imageSize"],o),l(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function iz(t,e){const n={},o=l(e,["model"]);o!=null&&d(n,["request","model"],Pe(t,o));const i=l(e,["contents"]);if(i!=null){let a=Ut(i);Array.isArray(a)&&(a=a.map(u=>hE(u))),d(n,["request","contents"],a)}const s=l(e,["metadata"]);s!=null&&d(n,["metadata"],s);const r=l(e,["config"]);return r!=null&&d(n,["request","generationConfig"],XG(t,r,l(n,["request"],{}))),n}function sz(t){const e={},n=l(t,["response"]);n!=null&&d(e,["response"],QG(n));const o=l(t,["metadata"]);o!=null&&d(e,["metadata"],o);const i=l(t,["error"]);return i!=null&&d(e,["error"],i),e}function rz(t,e){const n={},o=l(t,["pageSize"]);e!==void 0&&o!=null&&d(e,["_query","pageSize"],o);const i=l(t,["pageToken"]);if(e!==void 0&&i!=null&&d(e,["_query","pageToken"],i),l(t,["filter"])!==void 0)throw new Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function az(t,e){const n={},o=l(t,["pageSize"]);e!==void 0&&o!=null&&d(e,["_query","pageSize"],o);const i=l(t,["pageToken"]);e!==void 0&&i!=null&&d(e,["_query","pageToken"],i);const s=l(t,["filter"]);return e!==void 0&&s!=null&&d(e,["_query","filter"],s),n}function lz(t){const e={},n=l(t,["config"]);return n!=null&&rz(n,e),e}function uz(t){const e={},n=l(t,["config"]);return n!=null&&az(n,e),e}function cz(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["nextPageToken"]);o!=null&&d(e,["nextPageToken"],o);const i=l(t,["operations"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>Da(r))),d(e,["batchJobs"],s)}return e}function dz(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["nextPageToken"]);o!=null&&d(e,["nextPageToken"],o);const i=l(t,["batchPredictionJobs"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>lc(r))),d(e,["batchJobs"],s)}return e}function pz(t){const e={},n=l(t,["mediaResolution"]);n!=null&&d(e,["mediaResolution"],n);const o=l(t,["codeExecutionResult"]);o!=null&&d(e,["codeExecutionResult"],o);const i=l(t,["executableCode"]);i!=null&&d(e,["executableCode"],i);const s=l(t,["fileData"]);s!=null&&d(e,["fileData"],WG(s));const r=l(t,["functionCall"]);r!=null&&d(e,["functionCall"],KG(r));const a=l(t,["functionResponse"]);a!=null&&d(e,["functionResponse"],a);const u=l(t,["inlineData"]);u!=null&&d(e,["inlineData"],NG(u));const c=l(t,["text"]);c!=null&&d(e,["text"],c);const p=l(t,["thought"]);p!=null&&d(e,["thought"],p);const f=l(t,["thoughtSignature"]);f!=null&&d(e,["thoughtSignature"],f);const h=l(t,["videoMetadata"]);h!=null&&d(e,["videoMetadata"],h);const m=l(t,["toolCall"]);m!=null&&d(e,["toolCall"],m);const v=l(t,["toolResponse"]);v!=null&&d(e,["toolResponse"],v);const _=l(t,["partMetadata"]);return _!=null&&d(e,["partMetadata"],_),e}function fz(t){const e={},n=l(t,["category"]);if(n!=null&&d(e,["category"],n),l(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["threshold"]);return o!=null&&d(e,["threshold"],o),e}function hz(t){const e={},n=l(t,["retrievalConfig"]);n!=null&&d(e,["retrievalConfig"],n);const o=l(t,["functionCallingConfig"]);o!=null&&d(e,["functionCallingConfig"],YG(o));const i=l(t,["includeServerSideToolInvocations"]);return i!=null&&d(e,["includeServerSideToolInvocations"],i),e}function mz(t){const e={};if(l(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=l(t,["computerUse"]);n!=null&&d(e,["computerUse"],n);const o=l(t,["fileSearch"]);o!=null&&d(e,["fileSearch"],o);const i=l(t,["googleSearch"]);i!=null&&d(e,["googleSearch"],nz(i));const s=l(t,["googleMaps"]);s!=null&&d(e,["googleMaps"],tz(s));const r=l(t,["codeExecution"]);if(r!=null&&d(e,["codeExecution"],r),l(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const a=l(t,["functionDeclarations"]);if(a!=null){let f=a;Array.isArray(f)&&(f=f.map(h=>h)),d(e,["functionDeclarations"],f)}const u=l(t,["googleSearchRetrieval"]);if(u!=null&&d(e,["googleSearchRetrieval"],u),l(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const c=l(t,["urlContext"]);c!=null&&d(e,["urlContext"],c);const p=l(t,["mcpServers"]);if(p!=null){let f=p;Array.isArray(f)&&(f=f.map(h=>h)),d(e,["mcpServers"],f)}return e}function gz(t){const e={},n=l(t,["bigqueryDestination","outputUri"]);n!=null&&d(e,["bigqueryDestination"],n);const o=l(t,["displayName"]);return o!=null&&d(e,["displayName"],o),e}function vz(t){const e={},n=l(t,["bigqueryDestination"]);n!=null&&d(e,["bigqueryDestination","outputUri"],n);const o=l(t,["displayName"]);return o!=null&&d(e,["displayName"],o),e}/**
162
+ * @license
163
+ * Copyright 2025 Google LLC
164
+ * SPDX-License-Identifier: Apache-2.0
165
+ */var Yn;(function(t){t.PAGED_ITEM_BATCH_JOBS="batchJobs",t.PAGED_ITEM_MODELS="models",t.PAGED_ITEM_TUNING_JOBS="tuningJobs",t.PAGED_ITEM_FILES="files",t.PAGED_ITEM_CACHED_CONTENTS="cachedContents",t.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",t.PAGED_ITEM_DOCUMENTS="documents"})(Yn||(Yn={}));class ai{constructor(e,n,o,i){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,o,i)}init(e,n,o){var i,s;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n==null?void 0:n.sdkHttpResponse,this.idxInternal=0;let r={config:{}};!o||Object.keys(o).length===0?r={config:{}}:typeof o=="object"?r=Object.assign({},o):r=o,r.config&&(r.config.pageToken=n.nextPageToken),this.paramsInternal=r,this.pageInternalSize=(s=(i=r.config)===null||i===void 0?void 0:i.pageSize)!==null&&s!==void 0?s:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};const e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");const e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}}/**
166
+ * @license
167
+ * Copyright 2025 Google LLC
168
+ * SPDX-License-Identifier: Apache-2.0
169
+ */class yz extends Qn{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ai(Yn.PAGED_ITEM_BATCH_JOBS,o=>this.listInternal(o),await this.listInternal(n),n),this.create=async n=>(this.apiClient.isVertexAI()&&(n.config=this.formatDestination(n.src,n.config)),this.createInternal(n)),this.createEmbeddings=async n=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(n)}}createInlinedGenerateContentRequest(e){const n=ym(this.apiClient,e),o=n._url,i=Q("{model}:batchGenerateContent",o),a=n.batch.inputConfig.requests,u=a.requests,c=[];for(const p of u){const f=Object.assign({},p);if(f.systemInstruction){const h=f.systemInstruction;delete f.systemInstruction;const m=f.request;m.systemInstruction=h,f.request=m}c.push(f)}return a.requests=c,delete n.config,delete n._url,delete n._query,{path:i,body:n}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,n){const o=n?Object.assign({},n):{},i=Date.now().toString();if(o.displayName||(o.displayName=`genaiBatchJob_${i}`),o.dest===void 0){const s=this.getGcsUri(e),r=this.getBigqueryUri(e);if(s)s.endsWith(".jsonl")?o.dest=`${s.slice(0,-6)}/dest`:o.dest=`${s}_dest_${i}`;else if(r)o.dest=`${r}_dest_${i}`;else throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return o}async createInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=LG(this.apiClient,e);return a=Q("batchPredictionJobs",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),r.then(p=>lc(p))}else{const c=ym(this.apiClient,e);return a=Q("{model}:batchGenerateContent",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json()),r.then(p=>Da(p))}}async createEmbeddingsInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=zG(this.apiClient,e);return s=Q("{model}:asyncBatchEmbedContent",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>Da(u))}}async get(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=ez(this.apiClient,e);return a=Q("batchPredictionJobs/{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),r.then(p=>lc(p))}else{const c=jG(this.apiClient,e);return a=Q("batches/{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json()),r.then(p=>Da(p))}}async cancel(e){var n,o,i,s;let r="",a={};if(this.apiClient.isVertexAI()){const u=xG(this.apiClient,e);r=Q("batchPredictionJobs/{name}:cancel",u._url),a=u._query,delete u._url,delete u._query,await this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}else{const u=MG(this.apiClient,e);r=Q("batches/{name}:cancel",u._url),a=u._query,delete u._url,delete u._query,await this.apiClient.request({path:r,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal})}}async listInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=uz(e);return a=Q("batchPredictionJobs",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=dz(p),h=new hm;return Object.assign(h,f),h})}else{const c=lz(e);return a=Q("batches",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=cz(p),h=new hm;return Object.assign(h,f),h})}}async delete(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=VG(this.apiClient,e);return a=Q("batchPredictionJobs/{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>BG(p))}else{const c=FG(this.apiClient,e);return a=Q("batches/{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>qG(p))}}}/**
170
+ * @license
171
+ * Copyright 2025 Google LLC
172
+ * SPDX-License-Identifier: Apache-2.0
173
+ */function _z(t){const e={},n=l(t,["apiKey"]);if(n!=null&&d(e,["apiKey"],n),l(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Tz(t){const e={},n=l(t,["data"]);if(n!=null&&d(e,["data"],n),l(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["mimeType"]);return o!=null&&d(e,["mimeType"],o),e}function _m(t){const e={},n=l(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>Vz(s))),d(e,["parts"],i)}const o=l(t,["role"]);return o!=null&&d(e,["role"],o),e}function Tm(t){const e={},n=l(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>qz(s))),d(e,["parts"],i)}const o=l(t,["role"]);return o!=null&&d(e,["role"],o),e}function Ez(t,e){const n={},o=l(t,["ttl"]);e!==void 0&&o!=null&&d(e,["ttl"],o);const i=l(t,["expireTime"]);e!==void 0&&i!=null&&d(e,["expireTime"],i);const s=l(t,["displayName"]);e!==void 0&&s!=null&&d(e,["displayName"],s);const r=l(t,["contents"]);if(e!==void 0&&r!=null){let p=Ut(r);Array.isArray(p)&&(p=p.map(f=>_m(f))),d(e,["contents"],p)}const a=l(t,["systemInstruction"]);e!==void 0&&a!=null&&d(e,["systemInstruction"],_m(_t(a)));const u=l(t,["tools"]);if(e!==void 0&&u!=null){let p=u;Array.isArray(p)&&(p=p.map(f=>Zz(f))),d(e,["tools"],p)}const c=l(t,["toolConfig"]);if(e!==void 0&&c!=null&&d(e,["toolConfig"],Bz(c)),l(t,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function wz(t,e){const n={},o=l(t,["ttl"]);e!==void 0&&o!=null&&d(e,["ttl"],o);const i=l(t,["expireTime"]);e!==void 0&&i!=null&&d(e,["expireTime"],i);const s=l(t,["displayName"]);e!==void 0&&s!=null&&d(e,["displayName"],s);const r=l(t,["contents"]);if(e!==void 0&&r!=null){let f=Ut(r);Array.isArray(f)&&(f=f.map(h=>Tm(h))),d(e,["contents"],f)}const a=l(t,["systemInstruction"]);e!==void 0&&a!=null&&d(e,["systemInstruction"],Tm(_t(a)));const u=l(t,["tools"]);if(e!==void 0&&u!=null){let f=u;Array.isArray(f)&&(f=f.map(h=>Jz(h))),d(e,["tools"],f)}const c=l(t,["toolConfig"]);e!==void 0&&c!=null&&d(e,["toolConfig"],Hz(c));const p=l(t,["kmsKeyName"]);return e!==void 0&&p!=null&&d(e,["encryption_spec","kmsKeyName"],p),n}function Iz(t,e){const n={},o=l(e,["model"]);o!=null&&d(n,["model"],nE(t,o));const i=l(e,["config"]);return i!=null&&Ez(i,n),n}function Sz(t,e){const n={},o=l(e,["model"]);o!=null&&d(n,["model"],nE(t,o));const i=l(e,["config"]);return i!=null&&wz(i,n),n}function Cz(t,e){const n={},o=l(e,["name"]);return o!=null&&d(n,["_url","name"],jn(t,o)),n}function Az(t,e){const n={},o=l(e,["name"]);return o!=null&&d(n,["_url","name"],jn(t,o)),n}function bz(t){const e={},n=l(t,["sdkHttpResponse"]);return n!=null&&d(e,["sdkHttpResponse"],n),e}function Rz(t){const e={},n=l(t,["sdkHttpResponse"]);return n!=null&&d(e,["sdkHttpResponse"],n),e}function kz(t){const e={};if(l(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=l(t,["fileUri"]);n!=null&&d(e,["fileUri"],n);const o=l(t,["mimeType"]);return o!=null&&d(e,["mimeType"],o),e}function Pz(t){const e={},n=l(t,["id"]);n!=null&&d(e,["id"],n);const o=l(t,["args"]);o!=null&&d(e,["args"],o);const i=l(t,["name"]);if(i!=null&&d(e,["name"],i),l(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Nz(t){const e={},n=l(t,["allowedFunctionNames"]);n!=null&&d(e,["allowedFunctionNames"],n);const o=l(t,["mode"]);if(o!=null&&d(e,["mode"],o),l(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function Mz(t,e){const n={},o=l(e,["name"]);return o!=null&&d(n,["_url","name"],jn(t,o)),n}function xz(t,e){const n={},o=l(e,["name"]);return o!=null&&d(n,["_url","name"],jn(t,o)),n}function Dz(t){const e={},n=l(t,["authConfig"]);n!=null&&d(e,["authConfig"],_z(n));const o=l(t,["enableWidget"]);return o!=null&&d(e,["enableWidget"],o),e}function $z(t){const e={},n=l(t,["searchTypes"]);if(n!=null&&d(e,["searchTypes"],n),l(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["timeRangeFilter"]);return o!=null&&d(e,["timeRangeFilter"],o),e}function Uz(t,e){const n={},o=l(t,["pageSize"]);e!==void 0&&o!=null&&d(e,["_query","pageSize"],o);const i=l(t,["pageToken"]);return e!==void 0&&i!=null&&d(e,["_query","pageToken"],i),n}function Oz(t,e){const n={},o=l(t,["pageSize"]);e!==void 0&&o!=null&&d(e,["_query","pageSize"],o);const i=l(t,["pageToken"]);return e!==void 0&&i!=null&&d(e,["_query","pageToken"],i),n}function Lz(t){const e={},n=l(t,["config"]);return n!=null&&Uz(n,e),e}function Gz(t){const e={},n=l(t,["config"]);return n!=null&&Oz(n,e),e}function zz(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["nextPageToken"]);o!=null&&d(e,["nextPageToken"],o);const i=l(t,["cachedContents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>r)),d(e,["cachedContents"],s)}return e}function Fz(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["nextPageToken"]);o!=null&&d(e,["nextPageToken"],o);const i=l(t,["cachedContents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>r)),d(e,["cachedContents"],s)}return e}function Vz(t){const e={},n=l(t,["mediaResolution"]);n!=null&&d(e,["mediaResolution"],n);const o=l(t,["codeExecutionResult"]);o!=null&&d(e,["codeExecutionResult"],o);const i=l(t,["executableCode"]);i!=null&&d(e,["executableCode"],i);const s=l(t,["fileData"]);s!=null&&d(e,["fileData"],kz(s));const r=l(t,["functionCall"]);r!=null&&d(e,["functionCall"],Pz(r));const a=l(t,["functionResponse"]);a!=null&&d(e,["functionResponse"],a);const u=l(t,["inlineData"]);u!=null&&d(e,["inlineData"],Tz(u));const c=l(t,["text"]);c!=null&&d(e,["text"],c);const p=l(t,["thought"]);p!=null&&d(e,["thought"],p);const f=l(t,["thoughtSignature"]);f!=null&&d(e,["thoughtSignature"],f);const h=l(t,["videoMetadata"]);h!=null&&d(e,["videoMetadata"],h);const m=l(t,["toolCall"]);m!=null&&d(e,["toolCall"],m);const v=l(t,["toolResponse"]);v!=null&&d(e,["toolResponse"],v);const _=l(t,["partMetadata"]);return _!=null&&d(e,["partMetadata"],_),e}function qz(t){const e={},n=l(t,["mediaResolution"]);n!=null&&d(e,["mediaResolution"],n);const o=l(t,["codeExecutionResult"]);o!=null&&d(e,["codeExecutionResult"],o);const i=l(t,["executableCode"]);i!=null&&d(e,["executableCode"],i);const s=l(t,["fileData"]);s!=null&&d(e,["fileData"],s);const r=l(t,["functionCall"]);r!=null&&d(e,["functionCall"],r);const a=l(t,["functionResponse"]);a!=null&&d(e,["functionResponse"],a);const u=l(t,["inlineData"]);u!=null&&d(e,["inlineData"],u);const c=l(t,["text"]);c!=null&&d(e,["text"],c);const p=l(t,["thought"]);p!=null&&d(e,["thought"],p);const f=l(t,["thoughtSignature"]);f!=null&&d(e,["thoughtSignature"],f);const h=l(t,["videoMetadata"]);if(h!=null&&d(e,["videoMetadata"],h),l(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Bz(t){const e={},n=l(t,["retrievalConfig"]);n!=null&&d(e,["retrievalConfig"],n);const o=l(t,["functionCallingConfig"]);o!=null&&d(e,["functionCallingConfig"],Nz(o));const i=l(t,["includeServerSideToolInvocations"]);return i!=null&&d(e,["includeServerSideToolInvocations"],i),e}function Hz(t){const e={},n=l(t,["retrievalConfig"]);n!=null&&d(e,["retrievalConfig"],n);const o=l(t,["functionCallingConfig"]);if(o!=null&&d(e,["functionCallingConfig"],o),l(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Zz(t){const e={};if(l(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=l(t,["computerUse"]);n!=null&&d(e,["computerUse"],n);const o=l(t,["fileSearch"]);o!=null&&d(e,["fileSearch"],o);const i=l(t,["googleSearch"]);i!=null&&d(e,["googleSearch"],$z(i));const s=l(t,["googleMaps"]);s!=null&&d(e,["googleMaps"],Dz(s));const r=l(t,["codeExecution"]);if(r!=null&&d(e,["codeExecution"],r),l(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const a=l(t,["functionDeclarations"]);if(a!=null){let f=a;Array.isArray(f)&&(f=f.map(h=>h)),d(e,["functionDeclarations"],f)}const u=l(t,["googleSearchRetrieval"]);if(u!=null&&d(e,["googleSearchRetrieval"],u),l(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const c=l(t,["urlContext"]);c!=null&&d(e,["urlContext"],c);const p=l(t,["mcpServers"]);if(p!=null){let f=p;Array.isArray(f)&&(f=f.map(h=>h)),d(e,["mcpServers"],f)}return e}function Jz(t){const e={},n=l(t,["retrieval"]);n!=null&&d(e,["retrieval"],n);const o=l(t,["computerUse"]);if(o!=null&&d(e,["computerUse"],o),l(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const i=l(t,["googleSearch"]);i!=null&&d(e,["googleSearch"],i);const s=l(t,["googleMaps"]);s!=null&&d(e,["googleMaps"],s);const r=l(t,["codeExecution"]);r!=null&&d(e,["codeExecution"],r);const a=l(t,["enterpriseWebSearch"]);a!=null&&d(e,["enterpriseWebSearch"],a);const u=l(t,["functionDeclarations"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(m=>m)),d(e,["functionDeclarations"],h)}const c=l(t,["googleSearchRetrieval"]);c!=null&&d(e,["googleSearchRetrieval"],c);const p=l(t,["parallelAiSearch"]);p!=null&&d(e,["parallelAiSearch"],p);const f=l(t,["urlContext"]);if(f!=null&&d(e,["urlContext"],f),l(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function Wz(t,e){const n={},o=l(t,["ttl"]);e!==void 0&&o!=null&&d(e,["ttl"],o);const i=l(t,["expireTime"]);return e!==void 0&&i!=null&&d(e,["expireTime"],i),n}function Kz(t,e){const n={},o=l(t,["ttl"]);e!==void 0&&o!=null&&d(e,["ttl"],o);const i=l(t,["expireTime"]);return e!==void 0&&i!=null&&d(e,["expireTime"],i),n}function Yz(t,e){const n={},o=l(e,["name"]);o!=null&&d(n,["_url","name"],jn(t,o));const i=l(e,["config"]);return i!=null&&Wz(i,n),n}function Xz(t,e){const n={},o=l(e,["name"]);o!=null&&d(n,["_url","name"],jn(t,o));const i=l(e,["config"]);return i!=null&&Kz(i,n),n}/**
174
+ * @license
175
+ * Copyright 2025 Google LLC
176
+ * SPDX-License-Identifier: Apache-2.0
177
+ */class Qz extends Qn{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ai(Yn.PAGED_ITEM_CACHED_CONTENTS,o=>this.listInternal(o),await this.listInternal(n),n)}async create(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=Sz(this.apiClient,e);return a=Q("cachedContents",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),r.then(p=>p)}else{const c=Iz(this.apiClient,e);return a=Q("cachedContents",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json()),r.then(p=>p)}}async get(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=xz(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),r.then(p=>p)}else{const c=Mz(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json()),r.then(p=>p)}}async delete(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=Az(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=Rz(p),h=new pm;return Object.assign(h,f),h})}else{const c=Cz(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=bz(p),h=new pm;return Object.assign(h,f),h})}}async update(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=Xz(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),r.then(p=>p)}else{const c=Yz(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json()),r.then(p=>p)}}async listInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=Gz(e);return a=Q("cachedContents",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=Fz(p),h=new fm;return Object.assign(h,f),h})}else{const c=Lz(e);return a=Q("cachedContents",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=zz(p),h=new fm;return Object.assign(h,f),h})}}}function Un(t,e){var n={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,o=Object.getOwnPropertySymbols(t);i<o.length;i++)e.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(t,o[i])&&(n[o[i]]=t[o[i]]);return n}function Em(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],o=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&o>=t.length&&(t=void 0),{value:t&&t[o++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function pe(t){return this instanceof pe?(this.v=t,this):new pe(t)}function ln(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=n.apply(t,e||[]),i,s=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",r),i[Symbol.asyncIterator]=function(){return this},i;function r(m){return function(v){return Promise.resolve(v).then(m,f)}}function a(m,v){o[m]&&(i[m]=function(_){return new Promise(function(w,C){s.push([m,_,w,C])>1||u(m,_)})},v&&(i[m]=v(i[m])))}function u(m,v){try{c(o[m](v))}catch(_){h(s[0][3],_)}}function c(m){m.value instanceof pe?Promise.resolve(m.value.v).then(p,f):h(s[0][2],m)}function p(m){u("next",m)}function f(m){u("throw",m)}function h(m,v){m(v),s.shift(),s.length&&u(s[0][0],s[0][1])}}function un(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Em=="function"?Em(t):t[Symbol.iterator](),n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n);function o(s){n[s]=t[s]&&function(r){return new Promise(function(a,u){r=t[s](r),i(a,u,r.done,r.value)})}}function i(s,r,a,u){Promise.resolve(u).then(function(c){s({value:c,done:a})},r)}}/**
178
+ * @license
179
+ * Copyright 2025 Google LLC
180
+ * SPDX-License-Identifier: Apache-2.0
181
+ */function jz(t){var e;if(t.candidates==null||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;return n===void 0?!1:mE(n)}function mE(t){if(t.parts===void 0||t.parts.length===0)return!1;for(const e of t.parts)if(e===void 0||Object.keys(e).length===0)return!1;return!0}function eF(t){if(t.length!==0){for(const e of t)if(e.role!=="user"&&e.role!=="model")throw new Error(`Role must be user or model, but got ${e.role}.`)}}function wm(t){if(t===void 0||t.length===0)return[];const e=[],n=t.length;let o=0;for(;o<n;)if(t[o].role==="user")e.push(t[o]),o++;else{const i=[];let s=!0;for(;o<n&&t[o].role==="model";)i.push(t[o]),s&&!mE(t[o])&&(s=!1),o++;s?e.push(...i):e.pop()}return e}class tF{constructor(e,n){this.modelsModule=e,this.apiClient=n}create(e){return new nF(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}}class nF{constructor(e,n,o,i={},s=[]){this.apiClient=e,this.modelsModule=n,this.model=o,this.config=i,this.history=s,this.sendPromise=Promise.resolve(),eF(s)}async sendMessage(e){var n;await this.sendPromise;const o=_t(e.message),i=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(o),config:(n=e.config)!==null&&n!==void 0?n:this.config});return this.sendPromise=(async()=>{var s,r,a;const u=await i,c=(r=(s=u.candidates)===null||s===void 0?void 0:s[0])===null||r===void 0?void 0:r.content,p=u.automaticFunctionCallingHistory,f=this.getHistory(!0).length;let h=[];p!=null&&(h=(a=p.slice(f))!==null&&a!==void 0?a:[]);const m=c?[c]:[];this.recordHistory(o,m,h)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),i}async sendMessageStream(e){var n;await this.sendPromise;const o=_t(e.message),i=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(o),config:(n=e.config)!==null&&n!==void 0?n:this.config});this.sendPromise=i.then(()=>{}).catch(()=>{});const s=await i;return this.processStreamResponse(s,o)}getHistory(e=!1){const n=e?wm(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return ln(this,arguments,function*(){var i,s,r,a,u,c;const p=[];try{for(var f=!0,h=un(e),m;m=yield pe(h.next()),i=m.done,!i;f=!0){a=m.value,f=!1;const v=a;if(jz(v)){const _=(c=(u=v.candidates)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.content;_!==void 0&&p.push(_)}yield yield pe(v)}}catch(v){s={error:v}}finally{try{!f&&!i&&(r=h.return)&&(yield pe(r.call(h)))}finally{if(s)throw s.error}}this.recordHistory(n,p)})}recordHistory(e,n,o){let i=[];n.length>0&&n.every(s=>s.role!==void 0)?i=n:i.push({role:"model",parts:[]}),o&&o.length>0?this.history.push(...wm(o)):this.history.push(e),this.history.push(...i)}}/**
182
+ * @license
183
+ * Copyright 2025 Google LLC
184
+ * SPDX-License-Identifier: Apache-2.0
185
+ */class Hl extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,Hl.prototype)}}/**
186
+ * @license
187
+ * Copyright 2025 Google LLC
188
+ * SPDX-License-Identifier: Apache-2.0
189
+ */function oF(t){const e={},n=l(t,["file"]);return n!=null&&d(e,["file"],n),e}function iF(t){const e={},n=l(t,["sdkHttpResponse"]);return n!=null&&d(e,["sdkHttpResponse"],n),e}function sF(t){const e={},n=l(t,["name"]);return n!=null&&d(e,["_url","file"],lE(n)),e}function rF(t){const e={},n=l(t,["sdkHttpResponse"]);return n!=null&&d(e,["sdkHttpResponse"],n),e}function aF(t){const e={},n=l(t,["name"]);return n!=null&&d(e,["_url","file"],lE(n)),e}function lF(t){const e={},n=l(t,["uris"]);return n!=null&&d(e,["uris"],n),e}function uF(t,e){const n={},o=l(t,["pageSize"]);e!==void 0&&o!=null&&d(e,["_query","pageSize"],o);const i=l(t,["pageToken"]);return e!==void 0&&i!=null&&d(e,["_query","pageToken"],i),n}function cF(t){const e={},n=l(t,["config"]);return n!=null&&uF(n,e),e}function dF(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["nextPageToken"]);o!=null&&d(e,["nextPageToken"],o);const i=l(t,["files"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>r)),d(e,["files"],s)}return e}function pF(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["files"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>s)),d(e,["files"],i)}return e}/**
190
+ * @license
191
+ * Copyright 2025 Google LLC
192
+ * SPDX-License-Identifier: Apache-2.0
193
+ */class fF extends Qn{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ai(Yn.PAGED_ITEM_FILES,o=>this.listInternal(o),await this.listInternal(n),n)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(n=>n)}async download(e){await this.apiClient.downloadFile(e)}async registerFiles(e){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=cF(e);return s=Q("files",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json().then(c=>{const p=c;return p.sdkHttpResponse={headers:u.headers},p})),i.then(u=>{const c=dF(u),p=new lG;return Object.assign(p,c),p})}}async createInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=oF(e);return s=Q("upload/v1beta/files",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>{const c=iF(u),p=new uG;return Object.assign(p,c),p})}}async get(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=aF(e);return s=Q("files/{file}",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>u)}}async delete(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=sF(e);return s=Q("files/{file}",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json().then(c=>{const p=c;return p.sdkHttpResponse={headers:u.headers},p})),i.then(u=>{const c=rF(u),p=new cG;return Object.assign(p,c),p})}}async registerFilesInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=lF(e);return s=Q("files:register",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>{const c=pF(u),p=new dG;return Object.assign(p,c),p})}}}/**
194
+ * @license
195
+ * Copyright 2025 Google LLC
196
+ * SPDX-License-Identifier: Apache-2.0
197
+ */function Im(t){const e={};if(l(t,["languageCodes"])!==void 0)throw new Error("languageCodes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function hF(t){const e={},n=l(t,["apiKey"]);if(n!=null&&d(e,["apiKey"],n),l(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function $a(t){const e={},n=l(t,["data"]);if(n!=null&&d(e,["data"],n),l(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["mimeType"]);return o!=null&&d(e,["mimeType"],o),e}function mF(t){const e={},n=l(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>NF(s))),d(e,["parts"],i)}const o=l(t,["role"]);return o!=null&&d(e,["role"],o),e}function gF(t){const e={},n=l(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>MF(s))),d(e,["parts"],i)}const o=l(t,["role"]);return o!=null&&d(e,["role"],o),e}function vF(t){const e={};if(l(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=l(t,["fileUri"]);n!=null&&d(e,["fileUri"],n);const o=l(t,["mimeType"]);return o!=null&&d(e,["mimeType"],o),e}function yF(t){const e={},n=l(t,["id"]);n!=null&&d(e,["id"],n);const o=l(t,["args"]);o!=null&&d(e,["args"],o);const i=l(t,["name"]);if(i!=null&&d(e,["name"],i),l(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function _F(t){const e={},n=l(t,["modelSelectionConfig"]);n!=null&&d(e,["modelConfig"],n);const o=l(t,["responseJsonSchema"]);o!=null&&d(e,["responseJsonSchema"],o);const i=l(t,["audioTimestamp"]);i!=null&&d(e,["audioTimestamp"],i);const s=l(t,["candidateCount"]);s!=null&&d(e,["candidateCount"],s);const r=l(t,["enableAffectiveDialog"]);r!=null&&d(e,["enableAffectiveDialog"],r);const a=l(t,["frequencyPenalty"]);a!=null&&d(e,["frequencyPenalty"],a);const u=l(t,["logprobs"]);u!=null&&d(e,["logprobs"],u);const c=l(t,["maxOutputTokens"]);c!=null&&d(e,["maxOutputTokens"],c);const p=l(t,["mediaResolution"]);p!=null&&d(e,["mediaResolution"],p);const f=l(t,["presencePenalty"]);f!=null&&d(e,["presencePenalty"],f);const h=l(t,["responseLogprobs"]);h!=null&&d(e,["responseLogprobs"],h);const m=l(t,["responseMimeType"]);m!=null&&d(e,["responseMimeType"],m);const v=l(t,["responseModalities"]);v!=null&&d(e,["responseModalities"],v);const _=l(t,["responseSchema"]);_!=null&&d(e,["responseSchema"],_);const w=l(t,["routingConfig"]);w!=null&&d(e,["routingConfig"],w);const C=l(t,["seed"]);C!=null&&d(e,["seed"],C);const E=l(t,["speechConfig"]);E!=null&&d(e,["speechConfig"],E);const A=l(t,["stopSequences"]);A!=null&&d(e,["stopSequences"],A);const R=l(t,["temperature"]);R!=null&&d(e,["temperature"],R);const k=l(t,["thinkingConfig"]);k!=null&&d(e,["thinkingConfig"],k);const b=l(t,["topK"]);b!=null&&d(e,["topK"],b);const U=l(t,["topP"]);if(U!=null&&d(e,["topP"],U),l(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function TF(t){const e={},n=l(t,["authConfig"]);n!=null&&d(e,["authConfig"],hF(n));const o=l(t,["enableWidget"]);return o!=null&&d(e,["enableWidget"],o),e}function EF(t){const e={},n=l(t,["searchTypes"]);if(n!=null&&d(e,["searchTypes"],n),l(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["timeRangeFilter"]);return o!=null&&d(e,["timeRangeFilter"],o),e}function wF(t,e){const n={},o=l(t,["generationConfig"]);e!==void 0&&o!=null&&d(e,["setup","generationConfig"],o);const i=l(t,["responseModalities"]);e!==void 0&&i!=null&&d(e,["setup","generationConfig","responseModalities"],i);const s=l(t,["temperature"]);e!==void 0&&s!=null&&d(e,["setup","generationConfig","temperature"],s);const r=l(t,["topP"]);e!==void 0&&r!=null&&d(e,["setup","generationConfig","topP"],r);const a=l(t,["topK"]);e!==void 0&&a!=null&&d(e,["setup","generationConfig","topK"],a);const u=l(t,["maxOutputTokens"]);e!==void 0&&u!=null&&d(e,["setup","generationConfig","maxOutputTokens"],u);const c=l(t,["mediaResolution"]);e!==void 0&&c!=null&&d(e,["setup","generationConfig","mediaResolution"],c);const p=l(t,["seed"]);e!==void 0&&p!=null&&d(e,["setup","generationConfig","seed"],p);const f=l(t,["speechConfig"]);e!==void 0&&f!=null&&d(e,["setup","generationConfig","speechConfig"],fd(f));const h=l(t,["thinkingConfig"]);e!==void 0&&h!=null&&d(e,["setup","generationConfig","thinkingConfig"],h);const m=l(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&d(e,["setup","generationConfig","enableAffectiveDialog"],m);const v=l(t,["systemInstruction"]);e!==void 0&&v!=null&&d(e,["setup","systemInstruction"],mF(_t(v)));const _=l(t,["tools"]);if(e!==void 0&&_!=null){let G=ns(_);Array.isArray(G)&&(G=G.map(L=>$F(ts(L)))),d(e,["setup","tools"],G)}const w=l(t,["sessionResumption"]);e!==void 0&&w!=null&&d(e,["setup","sessionResumption"],DF(w));const C=l(t,["inputAudioTranscription"]);e!==void 0&&C!=null&&d(e,["setup","inputAudioTranscription"],Im(C));const E=l(t,["outputAudioTranscription"]);e!==void 0&&E!=null&&d(e,["setup","outputAudioTranscription"],Im(E));const A=l(t,["realtimeInputConfig"]);e!==void 0&&A!=null&&d(e,["setup","realtimeInputConfig"],A);const R=l(t,["contextWindowCompression"]);e!==void 0&&R!=null&&d(e,["setup","contextWindowCompression"],R);const k=l(t,["proactivity"]);if(e!==void 0&&k!=null&&d(e,["setup","proactivity"],k),l(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const b=l(t,["avatarConfig"]);e!==void 0&&b!=null&&d(e,["setup","avatarConfig"],b);const U=l(t,["safetySettings"]);if(e!==void 0&&U!=null){let G=U;Array.isArray(G)&&(G=G.map(L=>xF(L))),d(e,["setup","safetySettings"],G)}const J=l(t,["streamTranslationConfig"]);return e!==void 0&&J!=null&&d(e,["setup","generationConfig","streamTranslationConfig"],J),n}function IF(t,e){const n={},o=l(t,["generationConfig"]);e!==void 0&&o!=null&&d(e,["setup","generationConfig"],_F(o));const i=l(t,["responseModalities"]);e!==void 0&&i!=null&&d(e,["setup","generationConfig","responseModalities"],i);const s=l(t,["temperature"]);e!==void 0&&s!=null&&d(e,["setup","generationConfig","temperature"],s);const r=l(t,["topP"]);e!==void 0&&r!=null&&d(e,["setup","generationConfig","topP"],r);const a=l(t,["topK"]);e!==void 0&&a!=null&&d(e,["setup","generationConfig","topK"],a);const u=l(t,["maxOutputTokens"]);e!==void 0&&u!=null&&d(e,["setup","generationConfig","maxOutputTokens"],u);const c=l(t,["mediaResolution"]);e!==void 0&&c!=null&&d(e,["setup","generationConfig","mediaResolution"],c);const p=l(t,["seed"]);e!==void 0&&p!=null&&d(e,["setup","generationConfig","seed"],p);const f=l(t,["speechConfig"]);e!==void 0&&f!=null&&d(e,["setup","generationConfig","speechConfig"],fd(f));const h=l(t,["thinkingConfig"]);e!==void 0&&h!=null&&d(e,["setup","generationConfig","thinkingConfig"],h);const m=l(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&d(e,["setup","generationConfig","enableAffectiveDialog"],m);const v=l(t,["systemInstruction"]);e!==void 0&&v!=null&&d(e,["setup","systemInstruction"],gF(_t(v)));const _=l(t,["tools"]);if(e!==void 0&&_!=null){let G=ns(_);Array.isArray(G)&&(G=G.map(L=>UF(ts(L)))),d(e,["setup","tools"],G)}const w=l(t,["sessionResumption"]);e!==void 0&&w!=null&&d(e,["setup","sessionResumption"],w);const C=l(t,["inputAudioTranscription"]);e!==void 0&&C!=null&&d(e,["setup","inputAudioTranscription"],C);const E=l(t,["outputAudioTranscription"]);e!==void 0&&E!=null&&d(e,["setup","outputAudioTranscription"],E);const A=l(t,["realtimeInputConfig"]);e!==void 0&&A!=null&&d(e,["setup","realtimeInputConfig"],A);const R=l(t,["contextWindowCompression"]);e!==void 0&&R!=null&&d(e,["setup","contextWindowCompression"],R);const k=l(t,["proactivity"]);e!==void 0&&k!=null&&d(e,["setup","proactivity"],k);const b=l(t,["explicitVadSignal"]);e!==void 0&&b!=null&&d(e,["setup","explicitVadSignal"],b);const U=l(t,["avatarConfig"]);e!==void 0&&U!=null&&d(e,["setup","avatarConfig"],U);const J=l(t,["safetySettings"]);if(e!==void 0&&J!=null){let G=J;Array.isArray(G)&&(G=G.map(L=>L)),d(e,["setup","safetySettings"],G)}if(l(t,["streamTranslationConfig"])!==void 0)throw new Error("streamTranslationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function SF(t,e){const n={},o=l(e,["model"]);o!=null&&d(n,["setup","model"],Pe(t,o));const i=l(e,["config"]);return i!=null&&d(n,["config"],wF(i,n)),n}function CF(t,e){const n={},o=l(e,["model"]);o!=null&&d(n,["setup","model"],Pe(t,o));const i=l(e,["config"]);return i!=null&&d(n,["config"],IF(i,n)),n}function AF(t){const e={},n=l(t,["musicGenerationConfig"]);return n!=null&&d(e,["musicGenerationConfig"],n),e}function bF(t){const e={},n=l(t,["weightedPrompts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>i)),d(e,["weightedPrompts"],o)}return e}function RF(t){const e={},n=l(t,["media"]);if(n!=null){let c=oE(n);Array.isArray(c)&&(c=c.map(p=>$a(p))),d(e,["mediaChunks"],c)}const o=l(t,["audio"]);o!=null&&d(e,["audio"],$a(sE(o)));const i=l(t,["audioStreamEnd"]);i!=null&&d(e,["audioStreamEnd"],i);const s=l(t,["video"]);s!=null&&d(e,["video"],$a(iE(s)));const r=l(t,["text"]);r!=null&&d(e,["text"],r);const a=l(t,["activityStart"]);a!=null&&d(e,["activityStart"],a);const u=l(t,["activityEnd"]);return u!=null&&d(e,["activityEnd"],u),e}function kF(t){const e={},n=l(t,["media"]);if(n!=null){let c=oE(n);Array.isArray(c)&&(c=c.map(p=>p)),d(e,["mediaChunks"],c)}const o=l(t,["audio"]);o!=null&&d(e,["audio"],sE(o));const i=l(t,["audioStreamEnd"]);i!=null&&d(e,["audioStreamEnd"],i);const s=l(t,["video"]);s!=null&&d(e,["video"],iE(s));const r=l(t,["text"]);r!=null&&d(e,["text"],r);const a=l(t,["activityStart"]);a!=null&&d(e,["activityStart"],a);const u=l(t,["activityEnd"]);return u!=null&&d(e,["activityEnd"],u),e}function PF(t){const e={},n=l(t,["setupComplete"]);n!=null&&d(e,["setupComplete"],n);const o=l(t,["serverContent"]);o!=null&&d(e,["serverContent"],o);const i=l(t,["toolCall"]);i!=null&&d(e,["toolCall"],i);const s=l(t,["toolCallCancellation"]);s!=null&&d(e,["toolCallCancellation"],s);const r=l(t,["usageMetadata"]);r!=null&&d(e,["usageMetadata"],OF(r));const a=l(t,["goAway"]);a!=null&&d(e,["goAway"],a);const u=l(t,["sessionResumptionUpdate"]);u!=null&&d(e,["sessionResumptionUpdate"],u);const c=l(t,["voiceActivityDetectionSignal"]);c!=null&&d(e,["voiceActivityDetectionSignal"],c);const p=l(t,["voiceActivity"]);return p!=null&&d(e,["voiceActivity"],LF(p)),e}function NF(t){const e={},n=l(t,["mediaResolution"]);n!=null&&d(e,["mediaResolution"],n);const o=l(t,["codeExecutionResult"]);o!=null&&d(e,["codeExecutionResult"],o);const i=l(t,["executableCode"]);i!=null&&d(e,["executableCode"],i);const s=l(t,["fileData"]);s!=null&&d(e,["fileData"],vF(s));const r=l(t,["functionCall"]);r!=null&&d(e,["functionCall"],yF(r));const a=l(t,["functionResponse"]);a!=null&&d(e,["functionResponse"],a);const u=l(t,["inlineData"]);u!=null&&d(e,["inlineData"],$a(u));const c=l(t,["text"]);c!=null&&d(e,["text"],c);const p=l(t,["thought"]);p!=null&&d(e,["thought"],p);const f=l(t,["thoughtSignature"]);f!=null&&d(e,["thoughtSignature"],f);const h=l(t,["videoMetadata"]);h!=null&&d(e,["videoMetadata"],h);const m=l(t,["toolCall"]);m!=null&&d(e,["toolCall"],m);const v=l(t,["toolResponse"]);v!=null&&d(e,["toolResponse"],v);const _=l(t,["partMetadata"]);return _!=null&&d(e,["partMetadata"],_),e}function MF(t){const e={},n=l(t,["mediaResolution"]);n!=null&&d(e,["mediaResolution"],n);const o=l(t,["codeExecutionResult"]);o!=null&&d(e,["codeExecutionResult"],o);const i=l(t,["executableCode"]);i!=null&&d(e,["executableCode"],i);const s=l(t,["fileData"]);s!=null&&d(e,["fileData"],s);const r=l(t,["functionCall"]);r!=null&&d(e,["functionCall"],r);const a=l(t,["functionResponse"]);a!=null&&d(e,["functionResponse"],a);const u=l(t,["inlineData"]);u!=null&&d(e,["inlineData"],u);const c=l(t,["text"]);c!=null&&d(e,["text"],c);const p=l(t,["thought"]);p!=null&&d(e,["thought"],p);const f=l(t,["thoughtSignature"]);f!=null&&d(e,["thoughtSignature"],f);const h=l(t,["videoMetadata"]);if(h!=null&&d(e,["videoMetadata"],h),l(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function xF(t){const e={},n=l(t,["category"]);if(n!=null&&d(e,["category"],n),l(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["threshold"]);return o!=null&&d(e,["threshold"],o),e}function DF(t){const e={},n=l(t,["handle"]);if(n!=null&&d(e,["handle"],n),l(t,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function $F(t){const e={};if(l(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=l(t,["computerUse"]);n!=null&&d(e,["computerUse"],n);const o=l(t,["fileSearch"]);o!=null&&d(e,["fileSearch"],o);const i=l(t,["googleSearch"]);i!=null&&d(e,["googleSearch"],EF(i));const s=l(t,["googleMaps"]);s!=null&&d(e,["googleMaps"],TF(s));const r=l(t,["codeExecution"]);if(r!=null&&d(e,["codeExecution"],r),l(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const a=l(t,["functionDeclarations"]);if(a!=null){let f=a;Array.isArray(f)&&(f=f.map(h=>h)),d(e,["functionDeclarations"],f)}const u=l(t,["googleSearchRetrieval"]);if(u!=null&&d(e,["googleSearchRetrieval"],u),l(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const c=l(t,["urlContext"]);c!=null&&d(e,["urlContext"],c);const p=l(t,["mcpServers"]);if(p!=null){let f=p;Array.isArray(f)&&(f=f.map(h=>h)),d(e,["mcpServers"],f)}return e}function UF(t){const e={},n=l(t,["retrieval"]);n!=null&&d(e,["retrieval"],n);const o=l(t,["computerUse"]);if(o!=null&&d(e,["computerUse"],o),l(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const i=l(t,["googleSearch"]);i!=null&&d(e,["googleSearch"],i);const s=l(t,["googleMaps"]);s!=null&&d(e,["googleMaps"],s);const r=l(t,["codeExecution"]);r!=null&&d(e,["codeExecution"],r);const a=l(t,["enterpriseWebSearch"]);a!=null&&d(e,["enterpriseWebSearch"],a);const u=l(t,["functionDeclarations"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(m=>m)),d(e,["functionDeclarations"],h)}const c=l(t,["googleSearchRetrieval"]);c!=null&&d(e,["googleSearchRetrieval"],c);const p=l(t,["parallelAiSearch"]);p!=null&&d(e,["parallelAiSearch"],p);const f=l(t,["urlContext"]);if(f!=null&&d(e,["urlContext"],f),l(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return e}function OF(t){const e={},n=l(t,["promptTokenCount"]);n!=null&&d(e,["promptTokenCount"],n);const o=l(t,["cachedContentTokenCount"]);o!=null&&d(e,["cachedContentTokenCount"],o);const i=l(t,["candidatesTokenCount"]);i!=null&&d(e,["responseTokenCount"],i);const s=l(t,["toolUsePromptTokenCount"]);s!=null&&d(e,["toolUsePromptTokenCount"],s);const r=l(t,["thoughtsTokenCount"]);r!=null&&d(e,["thoughtsTokenCount"],r);const a=l(t,["totalTokenCount"]);a!=null&&d(e,["totalTokenCount"],a);const u=l(t,["promptTokensDetails"]);if(u!=null){let m=u;Array.isArray(m)&&(m=m.map(v=>v)),d(e,["promptTokensDetails"],m)}const c=l(t,["cacheTokensDetails"]);if(c!=null){let m=c;Array.isArray(m)&&(m=m.map(v=>v)),d(e,["cacheTokensDetails"],m)}const p=l(t,["candidatesTokensDetails"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(v=>v)),d(e,["responseTokensDetails"],m)}const f=l(t,["toolUsePromptTokensDetails"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(v=>v)),d(e,["toolUsePromptTokensDetails"],m)}const h=l(t,["trafficType"]);return h!=null&&d(e,["trafficType"],h),e}function LF(t){const e={},n=l(t,["type"]);return n!=null&&d(e,["voiceActivityType"],n),e}/**
198
+ * @license
199
+ * Copyright 2025 Google LLC
200
+ * SPDX-License-Identifier: Apache-2.0
201
+ */function GF(t,e){const n={},o=l(t,["apiKey"]);if(o!=null&&d(n,["apiKey"],o),l(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function zF(t,e){const n={},o=l(t,["data"]);if(o!=null&&d(n,["data"],o),l(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const i=l(t,["mimeType"]);return i!=null&&d(n,["mimeType"],i),n}function FF(t,e){const n={},o=l(t,["content"]);o!=null&&d(n,["content"],o);const i=l(t,["citationMetadata"]);i!=null&&d(n,["citationMetadata"],VF(i));const s=l(t,["tokenCount"]);s!=null&&d(n,["tokenCount"],s);const r=l(t,["finishReason"]);r!=null&&d(n,["finishReason"],r);const a=l(t,["groundingMetadata"]);a!=null&&d(n,["groundingMetadata"],a);const u=l(t,["avgLogprobs"]);u!=null&&d(n,["avgLogprobs"],u);const c=l(t,["index"]);c!=null&&d(n,["index"],c);const p=l(t,["logprobsResult"]);p!=null&&d(n,["logprobsResult"],p);const f=l(t,["safetyRatings"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(v=>v)),d(n,["safetyRatings"],m)}const h=l(t,["urlContextMetadata"]);return h!=null&&d(n,["urlContextMetadata"],h),n}function VF(t,e){const n={},o=l(t,["citationSources"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>s)),d(n,["citations"],i)}return n}function qF(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["contents"]);if(s!=null){let r=Ut(s);Array.isArray(r)&&(r=r.map(a=>is(a))),d(o,["contents"],r)}return o}function BF(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["tokensInfo"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>r)),d(n,["tokensInfo"],s)}return n}function HF(t,e){const n={},o=l(t,["values"]);o!=null&&d(n,["values"],o);const i=l(t,["statistics"]);return i!=null&&d(n,["statistics"],ZF(i)),n}function ZF(t,e){const n={},o=l(t,["truncated"]);o!=null&&d(n,["truncated"],o);const i=l(t,["token_count"]);return i!=null&&d(n,["tokenCount"],i),n}function ra(t,e){const n={},o=l(t,["parts"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(r=>eq(r))),d(n,["parts"],s)}const i=l(t,["role"]);return i!=null&&d(n,["role"],i),n}function is(t,e){const n={},o=l(t,["parts"]);if(o!=null){let s=o;Array.isArray(s)&&(s=s.map(r=>tq(r))),d(n,["parts"],s)}const i=l(t,["role"]);return i!=null&&d(n,["role"],i),n}function JF(t,e){const n={},o=l(t,["controlType"]);o!=null&&d(n,["controlType"],o);const i=l(t,["enableControlImageComputation"]);return i!=null&&d(n,["computeControl"],i),n}function WF(t,e){const n={};if(l(t,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function KF(t,e,n){const o={},i=l(t,["systemInstruction"]);e!==void 0&&i!=null&&d(e,["systemInstruction"],is(_t(i)));const s=l(t,["tools"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(u=>_E(u))),d(e,["tools"],a)}const r=l(t,["generationConfig"]);return e!==void 0&&r!=null&&d(e,["generationConfig"],GV(r)),o}function YF(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["contents"]);if(s!=null){let a=Ut(s);Array.isArray(a)&&(a=a.map(u=>ra(u))),d(o,["contents"],a)}const r=l(e,["config"]);return r!=null&&WF(r),o}function XF(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["contents"]);if(s!=null){let a=Ut(s);Array.isArray(a)&&(a=a.map(u=>is(u))),d(o,["contents"],a)}const r=l(e,["config"]);return r!=null&&KF(r,o),o}function QF(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["totalTokens"]);i!=null&&d(n,["totalTokens"],i);const s=l(t,["cachedContentTokenCount"]);return s!=null&&d(n,["cachedContentTokenCount"],s),n}function jF(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["totalTokens"]);return i!=null&&d(n,["totalTokens"],i),n}function eV(t,e,n){const o={},i=l(e,["model"]);return i!=null&&d(o,["_url","name"],Pe(t,i)),o}function tV(t,e,n){const o={},i=l(e,["model"]);return i!=null&&d(o,["_url","name"],Pe(t,i)),o}function nV(t,e){const n={},o=l(t,["sdkHttpResponse"]);return o!=null&&d(n,["sdkHttpResponse"],o),n}function oV(t,e){const n={},o=l(t,["sdkHttpResponse"]);return o!=null&&d(n,["sdkHttpResponse"],o),n}function iV(t,e,n){const o={},i=l(t,["outputGcsUri"]);e!==void 0&&i!=null&&d(e,["parameters","storageUri"],i);const s=l(t,["negativePrompt"]);e!==void 0&&s!=null&&d(e,["parameters","negativePrompt"],s);const r=l(t,["numberOfImages"]);e!==void 0&&r!=null&&d(e,["parameters","sampleCount"],r);const a=l(t,["aspectRatio"]);e!==void 0&&a!=null&&d(e,["parameters","aspectRatio"],a);const u=l(t,["guidanceScale"]);e!==void 0&&u!=null&&d(e,["parameters","guidanceScale"],u);const c=l(t,["seed"]);e!==void 0&&c!=null&&d(e,["parameters","seed"],c);const p=l(t,["safetyFilterLevel"]);e!==void 0&&p!=null&&d(e,["parameters","safetySetting"],p);const f=l(t,["personGeneration"]);e!==void 0&&f!=null&&d(e,["parameters","personGeneration"],f);const h=l(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&d(e,["parameters","includeSafetyAttributes"],h);const m=l(t,["includeRaiReason"]);e!==void 0&&m!=null&&d(e,["parameters","includeRaiReason"],m);const v=l(t,["language"]);e!==void 0&&v!=null&&d(e,["parameters","language"],v);const _=l(t,["outputMimeType"]);e!==void 0&&_!=null&&d(e,["parameters","outputOptions","mimeType"],_);const w=l(t,["outputCompressionQuality"]);e!==void 0&&w!=null&&d(e,["parameters","outputOptions","compressionQuality"],w);const C=l(t,["addWatermark"]);e!==void 0&&C!=null&&d(e,["parameters","addWatermark"],C);const E=l(t,["labels"]);e!==void 0&&E!=null&&d(e,["labels"],E);const A=l(t,["editMode"]);e!==void 0&&A!=null&&d(e,["parameters","editMode"],A);const R=l(t,["baseSteps"]);return e!==void 0&&R!=null&&d(e,["parameters","editConfig","baseSteps"],R),o}function sV(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["prompt"]);s!=null&&d(o,["instances[0]","prompt"],s);const r=l(e,["referenceImages"]);if(r!=null){let u=r;Array.isArray(u)&&(u=u.map(c=>aq(c))),d(o,["instances[0]","referenceImages"],u)}const a=l(e,["config"]);return a!=null&&iV(a,o),o}function rV(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>Zl(r))),d(n,["generatedImages"],s)}return n}function aV(t,e,n){const o={},i=l(t,["taskType"]);e!==void 0&&i!=null&&d(e,["requests[]","taskType"],i);const s=l(t,["title"]);e!==void 0&&s!=null&&d(e,["requests[]","title"],s);const r=l(t,["outputDimensionality"]);if(e!==void 0&&r!=null&&d(e,["requests[]","outputDimensionality"],r),l(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function lV(t,e,n){const o={};let i=l(n,["embeddingApiType"]);if(i===void 0&&(i="PREDICT"),i==="PREDICT"){const f=l(t,["taskType"]);e!==void 0&&f!=null&&d(e,["instances[]","task_type"],f)}else if(i==="EMBED_CONTENT"){const f=l(t,["taskType"]);e!==void 0&&f!=null&&d(e,["embedContentConfig","taskType"],f)}let s=l(n,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){const f=l(t,["title"]);e!==void 0&&f!=null&&d(e,["instances[]","title"],f)}else if(s==="EMBED_CONTENT"){const f=l(t,["title"]);e!==void 0&&f!=null&&d(e,["embedContentConfig","title"],f)}let r=l(n,["embeddingApiType"]);if(r===void 0&&(r="PREDICT"),r==="PREDICT"){const f=l(t,["outputDimensionality"]);e!==void 0&&f!=null&&d(e,["parameters","outputDimensionality"],f)}else if(r==="EMBED_CONTENT"){const f=l(t,["outputDimensionality"]);e!==void 0&&f!=null&&d(e,["embedContentConfig","outputDimensionality"],f)}let a=l(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="PREDICT"){const f=l(t,["mimeType"]);e!==void 0&&f!=null&&d(e,["instances[]","mimeType"],f)}let u=l(n,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="PREDICT"){const f=l(t,["autoTruncate"]);e!==void 0&&f!=null&&d(e,["parameters","autoTruncate"],f)}else if(u==="EMBED_CONTENT"){const f=l(t,["autoTruncate"]);e!==void 0&&f!=null&&d(e,["embedContentConfig","autoTruncate"],f)}let c=l(n,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="EMBED_CONTENT"){const f=l(t,["documentOcr"]);e!==void 0&&f!=null&&d(e,["embedContentConfig","documentOcr"],f)}let p=l(n,["embeddingApiType"]);if(p===void 0&&(p="PREDICT"),p==="EMBED_CONTENT"){const f=l(t,["audioTrackExtraction"]);e!==void 0&&f!=null&&d(e,["embedContentConfig","audioTrackExtraction"],f)}return o}function uV(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["contents"]);if(s!=null){let c=cd(t,s);Array.isArray(c)&&(c=c.map(p=>p)),d(o,["requests[]","content"],c)}const r=l(e,["content"]);r!=null&&ra(_t(r));const a=l(e,["config"]);a!=null&&aV(a,o);const u=l(e,["model"]);return u!==void 0&&d(o,["requests[]","model"],Pe(t,u)),o}function cV(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));let s=l(n,["embeddingApiType"]);if(s===void 0&&(s="PREDICT"),s==="PREDICT"){const u=l(e,["contents"]);if(u!=null){let c=cd(t,u);Array.isArray(c)&&(c=c.map(p=>p)),d(o,["instances[]","content"],c)}}let r=l(n,["embeddingApiType"]);if(r===void 0&&(r="PREDICT"),r==="EMBED_CONTENT"){const u=l(e,["content"]);u!=null&&d(o,["content"],is(_t(u)))}const a=l(e,["config"]);return a!=null&&lV(a,o,n),o}function dV(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["embeddings"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>a)),d(n,["embeddings"],r)}const s=l(t,["metadata"]);return s!=null&&d(n,["metadata"],s),n}function pV(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["predictions[]","embeddings"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>HF(a))),d(n,["embeddings"],r)}const s=l(t,["metadata"]);if(s!=null&&d(n,["metadata"],s),e&&l(e,["embeddingApiType"])==="EMBED_CONTENT"){const r=l(t,["embedding"]),a=l(t,["usageMetadata"]),u=l(t,["truncated"]);if(r){const c={};a&&a.promptTokenCount&&(c.tokenCount=a.promptTokenCount),u&&(c.truncated=u),r.statistics=c,d(n,["embeddings"],[r])}}return n}function fV(t,e){const n={},o=l(t,["endpoint"]);o!=null&&d(n,["name"],o);const i=l(t,["deployedModelId"]);return i!=null&&d(n,["deployedModelId"],i),n}function hV(t,e){const n={};if(l(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["fileUri"]);o!=null&&d(n,["fileUri"],o);const i=l(t,["mimeType"]);return i!=null&&d(n,["mimeType"],i),n}function mV(t,e){const n={},o=l(t,["id"]);o!=null&&d(n,["id"],o);const i=l(t,["args"]);i!=null&&d(n,["args"],i);const s=l(t,["name"]);if(s!=null&&d(n,["name"],s),l(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function gV(t,e){const n={},o=l(t,["allowedFunctionNames"]);o!=null&&d(n,["allowedFunctionNames"],o);const i=l(t,["mode"]);if(i!=null&&d(n,["mode"],i),l(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function vV(t,e,n,o){const i={},s=l(e,["systemInstruction"]);n!==void 0&&s!=null&&d(n,["systemInstruction"],ra(_t(s)));const r=l(e,["temperature"]);r!=null&&d(i,["temperature"],r);const a=l(e,["topP"]);a!=null&&d(i,["topP"],a);const u=l(e,["topK"]);u!=null&&d(i,["topK"],u);const c=l(e,["candidateCount"]);c!=null&&d(i,["candidateCount"],c);const p=l(e,["maxOutputTokens"]);p!=null&&d(i,["maxOutputTokens"],p);const f=l(e,["stopSequences"]);f!=null&&d(i,["stopSequences"],f);const h=l(e,["responseLogprobs"]);h!=null&&d(i,["responseLogprobs"],h);const m=l(e,["logprobs"]);m!=null&&d(i,["logprobs"],m);const v=l(e,["presencePenalty"]);v!=null&&d(i,["presencePenalty"],v);const _=l(e,["frequencyPenalty"]);_!=null&&d(i,["frequencyPenalty"],_);const w=l(e,["seed"]);w!=null&&d(i,["seed"],w);const C=l(e,["responseMimeType"]);C!=null&&d(i,["responseMimeType"],C);const E=l(e,["responseSchema"]);E!=null&&d(i,["responseSchema"],dd(E));const A=l(e,["responseJsonSchema"]);if(A!=null&&d(i,["responseJsonSchema"],A),l(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const R=l(e,["safetySettings"]);if(n!==void 0&&R!=null){let ue=R;Array.isArray(ue)&&(ue=ue.map(we=>lq(we))),d(n,["safetySettings"],ue)}const k=l(e,["tools"]);if(n!==void 0&&k!=null){let ue=ns(k);Array.isArray(ue)&&(ue=ue.map(we=>gq(ts(we)))),d(n,["tools"],ue)}const b=l(e,["toolConfig"]);if(n!==void 0&&b!=null&&d(n,["toolConfig"],hq(b)),l(e,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const U=l(e,["cachedContent"]);n!==void 0&&U!=null&&d(n,["cachedContent"],jn(t,U));const J=l(e,["responseModalities"]);J!=null&&d(i,["responseModalities"],J);const G=l(e,["mediaResolution"]);G!=null&&d(i,["mediaResolution"],G);const L=l(e,["speechConfig"]);if(L!=null&&d(i,["speechConfig"],pd(L)),l(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const B=l(e,["thinkingConfig"]);B!=null&&d(i,["thinkingConfig"],B);const ve=l(e,["imageConfig"]);ve!=null&&d(i,["imageConfig"],BV(ve));const Ae=l(e,["enableEnhancedCivicAnswers"]);if(Ae!=null&&d(i,["enableEnhancedCivicAnswers"],Ae),l(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const ye=l(e,["serviceTier"]);return n!==void 0&&ye!=null&&d(n,["serviceTier"],ye),i}function yV(t,e,n,o){const i={},s=l(e,["systemInstruction"]);n!==void 0&&s!=null&&d(n,["systemInstruction"],is(_t(s)));const r=l(e,["temperature"]);r!=null&&d(i,["temperature"],r);const a=l(e,["topP"]);a!=null&&d(i,["topP"],a);const u=l(e,["topK"]);u!=null&&d(i,["topK"],u);const c=l(e,["candidateCount"]);c!=null&&d(i,["candidateCount"],c);const p=l(e,["maxOutputTokens"]);p!=null&&d(i,["maxOutputTokens"],p);const f=l(e,["stopSequences"]);f!=null&&d(i,["stopSequences"],f);const h=l(e,["responseLogprobs"]);h!=null&&d(i,["responseLogprobs"],h);const m=l(e,["logprobs"]);m!=null&&d(i,["logprobs"],m);const v=l(e,["presencePenalty"]);v!=null&&d(i,["presencePenalty"],v);const _=l(e,["frequencyPenalty"]);_!=null&&d(i,["frequencyPenalty"],_);const w=l(e,["seed"]);w!=null&&d(i,["seed"],w);const C=l(e,["responseMimeType"]);C!=null&&d(i,["responseMimeType"],C);const E=l(e,["responseSchema"]);E!=null&&d(i,["responseSchema"],dd(E));const A=l(e,["responseJsonSchema"]);A!=null&&d(i,["responseJsonSchema"],A);const R=l(e,["routingConfig"]);R!=null&&d(i,["routingConfig"],R);const k=l(e,["modelSelectionConfig"]);k!=null&&d(i,["modelConfig"],k);const b=l(e,["safetySettings"]);if(n!==void 0&&b!=null){let x=b;Array.isArray(x)&&(x=x.map(ce=>ce)),d(n,["safetySettings"],x)}const U=l(e,["tools"]);if(n!==void 0&&U!=null){let x=ns(U);Array.isArray(x)&&(x=x.map(ce=>_E(ts(ce)))),d(n,["tools"],x)}const J=l(e,["toolConfig"]);n!==void 0&&J!=null&&d(n,["toolConfig"],mq(J));const G=l(e,["labels"]);n!==void 0&&G!=null&&d(n,["labels"],G);const L=l(e,["cachedContent"]);n!==void 0&&L!=null&&d(n,["cachedContent"],jn(t,L));const B=l(e,["responseModalities"]);B!=null&&d(i,["responseModalities"],B);const ve=l(e,["mediaResolution"]);ve!=null&&d(i,["mediaResolution"],ve);const Ae=l(e,["speechConfig"]);Ae!=null&&d(i,["speechConfig"],pd(Ae));const ye=l(e,["audioTimestamp"]);ye!=null&&d(i,["audioTimestamp"],ye);const ue=l(e,["thinkingConfig"]);ue!=null&&d(i,["thinkingConfig"],ue);const we=l(e,["imageConfig"]);if(we!=null&&d(i,["imageConfig"],HV(we)),l(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const j=l(e,["modelArmorConfig"]);n!==void 0&&j!=null&&d(n,["modelArmorConfig"],j);const re=l(e,["serviceTier"]);return n!==void 0&&re!=null&&d(n,["serviceTier"],re),i}function Sm(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["contents"]);if(s!=null){let a=Ut(s);Array.isArray(a)&&(a=a.map(u=>ra(u))),d(o,["contents"],a)}const r=l(e,["config"]);return r!=null&&d(o,["generationConfig"],vV(t,r,o)),o}function Cm(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["contents"]);if(s!=null){let a=Ut(s);Array.isArray(a)&&(a=a.map(u=>is(u))),d(o,["contents"],a)}const r=l(e,["config"]);return r!=null&&d(o,["generationConfig"],yV(t,r,o)),o}function Am(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["candidates"]);if(i!=null){let p=i;Array.isArray(p)&&(p=p.map(f=>FF(f))),d(n,["candidates"],p)}const s=l(t,["modelVersion"]);s!=null&&d(n,["modelVersion"],s);const r=l(t,["promptFeedback"]);r!=null&&d(n,["promptFeedback"],r);const a=l(t,["responseId"]);a!=null&&d(n,["responseId"],a);const u=l(t,["usageMetadata"]);u!=null&&d(n,["usageMetadata"],u);const c=l(t,["modelStatus"]);return c!=null&&d(n,["modelStatus"],c),n}function bm(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["candidates"]);if(i!=null){let p=i;Array.isArray(p)&&(p=p.map(f=>f)),d(n,["candidates"],p)}const s=l(t,["createTime"]);s!=null&&d(n,["createTime"],s);const r=l(t,["modelVersion"]);r!=null&&d(n,["modelVersion"],r);const a=l(t,["promptFeedback"]);a!=null&&d(n,["promptFeedback"],a);const u=l(t,["responseId"]);u!=null&&d(n,["responseId"],u);const c=l(t,["usageMetadata"]);return c!=null&&d(n,["usageMetadata"],c),n}function _V(t,e,n){const o={};if(l(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const i=l(t,["numberOfImages"]);e!==void 0&&i!=null&&d(e,["parameters","sampleCount"],i);const s=l(t,["aspectRatio"]);e!==void 0&&s!=null&&d(e,["parameters","aspectRatio"],s);const r=l(t,["guidanceScale"]);if(e!==void 0&&r!=null&&d(e,["parameters","guidanceScale"],r),l(t,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const a=l(t,["safetyFilterLevel"]);e!==void 0&&a!=null&&d(e,["parameters","safetySetting"],a);const u=l(t,["personGeneration"]);e!==void 0&&u!=null&&d(e,["parameters","personGeneration"],u);const c=l(t,["includeSafetyAttributes"]);e!==void 0&&c!=null&&d(e,["parameters","includeSafetyAttributes"],c);const p=l(t,["includeRaiReason"]);e!==void 0&&p!=null&&d(e,["parameters","includeRaiReason"],p);const f=l(t,["language"]);e!==void 0&&f!=null&&d(e,["parameters","language"],f);const h=l(t,["outputMimeType"]);e!==void 0&&h!=null&&d(e,["parameters","outputOptions","mimeType"],h);const m=l(t,["outputCompressionQuality"]);if(e!==void 0&&m!=null&&d(e,["parameters","outputOptions","compressionQuality"],m),l(t,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const v=l(t,["imageSize"]);if(e!==void 0&&v!=null&&d(e,["parameters","sampleImageSize"],v),l(t,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function TV(t,e,n){const o={},i=l(t,["outputGcsUri"]);e!==void 0&&i!=null&&d(e,["parameters","storageUri"],i);const s=l(t,["negativePrompt"]);e!==void 0&&s!=null&&d(e,["parameters","negativePrompt"],s);const r=l(t,["numberOfImages"]);e!==void 0&&r!=null&&d(e,["parameters","sampleCount"],r);const a=l(t,["aspectRatio"]);e!==void 0&&a!=null&&d(e,["parameters","aspectRatio"],a);const u=l(t,["guidanceScale"]);e!==void 0&&u!=null&&d(e,["parameters","guidanceScale"],u);const c=l(t,["seed"]);e!==void 0&&c!=null&&d(e,["parameters","seed"],c);const p=l(t,["safetyFilterLevel"]);e!==void 0&&p!=null&&d(e,["parameters","safetySetting"],p);const f=l(t,["personGeneration"]);e!==void 0&&f!=null&&d(e,["parameters","personGeneration"],f);const h=l(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&d(e,["parameters","includeSafetyAttributes"],h);const m=l(t,["includeRaiReason"]);e!==void 0&&m!=null&&d(e,["parameters","includeRaiReason"],m);const v=l(t,["language"]);e!==void 0&&v!=null&&d(e,["parameters","language"],v);const _=l(t,["outputMimeType"]);e!==void 0&&_!=null&&d(e,["parameters","outputOptions","mimeType"],_);const w=l(t,["outputCompressionQuality"]);e!==void 0&&w!=null&&d(e,["parameters","outputOptions","compressionQuality"],w);const C=l(t,["addWatermark"]);e!==void 0&&C!=null&&d(e,["parameters","addWatermark"],C);const E=l(t,["labels"]);e!==void 0&&E!=null&&d(e,["labels"],E);const A=l(t,["imageSize"]);e!==void 0&&A!=null&&d(e,["parameters","sampleImageSize"],A);const R=l(t,["enhancePrompt"]);return e!==void 0&&R!=null&&d(e,["parameters","enhancePrompt"],R),o}function EV(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["prompt"]);s!=null&&d(o,["instances[0]","prompt"],s);const r=l(e,["config"]);return r!=null&&_V(r,o),o}function wV(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["prompt"]);s!=null&&d(o,["instances[0]","prompt"],s);const r=l(e,["config"]);return r!=null&&TV(r,o),o}function IV(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["predictions"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>$V(a))),d(n,["generatedImages"],r)}const s=l(t,["positivePromptSafetyAttributes"]);return s!=null&&d(n,["positivePromptSafetyAttributes"],vE(s)),n}function SV(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["predictions"]);if(i!=null){let r=i;Array.isArray(r)&&(r=r.map(a=>Zl(a))),d(n,["generatedImages"],r)}const s=l(t,["positivePromptSafetyAttributes"]);return s!=null&&d(n,["positivePromptSafetyAttributes"],yE(s)),n}function CV(t,e,n){const o={},i=l(t,["numberOfVideos"]);if(e!==void 0&&i!=null&&d(e,["parameters","sampleCount"],i),l(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=l(t,["durationSeconds"]);if(e!==void 0&&s!=null&&d(e,["parameters","durationSeconds"],s),l(t,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=l(t,["aspectRatio"]);e!==void 0&&r!=null&&d(e,["parameters","aspectRatio"],r);const a=l(t,["resolution"]);e!==void 0&&a!=null&&d(e,["parameters","resolution"],a);const u=l(t,["personGeneration"]);if(e!==void 0&&u!=null&&d(e,["parameters","personGeneration"],u),l(t,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const c=l(t,["negativePrompt"]);e!==void 0&&c!=null&&d(e,["parameters","negativePrompt"],c);const p=l(t,["enhancePrompt"]);if(e!==void 0&&p!=null&&d(e,["parameters","enhancePrompt"],p),l(t,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const f=l(t,["lastFrame"]);e!==void 0&&f!=null&&d(e,["instances[0]","lastFrame"],Jl(f));const h=l(t,["referenceImages"]);if(e!==void 0&&h!=null){let v=h;Array.isArray(v)&&(v=v.map(_=>kq(_))),d(e,["instances[0]","referenceImages"],v)}if(l(t,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const m=l(t,["webhookConfig"]);if(e!==void 0&&m!=null&&d(e,["webhookConfig"],m),l(t,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function AV(t,e,n){const o={},i=l(t,["numberOfVideos"]);e!==void 0&&i!=null&&d(e,["parameters","sampleCount"],i);const s=l(t,["outputGcsUri"]);e!==void 0&&s!=null&&d(e,["parameters","storageUri"],s);const r=l(t,["fps"]);e!==void 0&&r!=null&&d(e,["parameters","fps"],r);const a=l(t,["durationSeconds"]);e!==void 0&&a!=null&&d(e,["parameters","durationSeconds"],a);const u=l(t,["seed"]);e!==void 0&&u!=null&&d(e,["parameters","seed"],u);const c=l(t,["aspectRatio"]);e!==void 0&&c!=null&&d(e,["parameters","aspectRatio"],c);const p=l(t,["resolution"]);e!==void 0&&p!=null&&d(e,["parameters","resolution"],p);const f=l(t,["personGeneration"]);e!==void 0&&f!=null&&d(e,["parameters","personGeneration"],f);const h=l(t,["pubsubTopic"]);e!==void 0&&h!=null&&d(e,["parameters","pubsubTopic"],h);const m=l(t,["negativePrompt"]);e!==void 0&&m!=null&&d(e,["parameters","negativePrompt"],m);const v=l(t,["enhancePrompt"]);e!==void 0&&v!=null&&d(e,["parameters","enhancePrompt"],v);const _=l(t,["generateAudio"]);e!==void 0&&_!=null&&d(e,["parameters","generateAudio"],_);const w=l(t,["lastFrame"]);e!==void 0&&w!=null&&d(e,["instances[0]","lastFrame"],bn(w));const C=l(t,["referenceImages"]);if(e!==void 0&&C!=null){let b=C;Array.isArray(b)&&(b=b.map(U=>Pq(U))),d(e,["instances[0]","referenceImages"],b)}const E=l(t,["mask"]);e!==void 0&&E!=null&&d(e,["instances[0]","mask"],Rq(E));const A=l(t,["compressionQuality"]);e!==void 0&&A!=null&&d(e,["parameters","compressionQuality"],A);const R=l(t,["labels"]);if(e!==void 0&&R!=null&&d(e,["labels"],R),l(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const k=l(t,["resizeMode"]);return e!==void 0&&k!=null&&d(e,["parameters","resizeMode"],k),o}function bV(t,e){const n={},o=l(t,["name"]);o!=null&&d(n,["name"],o);const i=l(t,["metadata"]);i!=null&&d(n,["metadata"],i);const s=l(t,["done"]);s!=null&&d(n,["done"],s);const r=l(t,["error"]);r!=null&&d(n,["error"],r);const a=l(t,["response","generateVideoResponse"]);return a!=null&&d(n,["response"],NV(a)),n}function RV(t,e){const n={},o=l(t,["name"]);o!=null&&d(n,["name"],o);const i=l(t,["metadata"]);i!=null&&d(n,["metadata"],i);const s=l(t,["done"]);s!=null&&d(n,["done"],s);const r=l(t,["error"]);r!=null&&d(n,["error"],r);const a=l(t,["response"]);return a!=null&&d(n,["response"],MV(a)),n}function kV(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["prompt"]);s!=null&&d(o,["instances[0]","prompt"],s);const r=l(e,["image"]);r!=null&&d(o,["instances[0]","image"],Jl(r));const a=l(e,["video"]);a!=null&&d(o,["instances[0]","video"],TE(a));const u=l(e,["source"]);u!=null&&xV(u,o);const c=l(e,["config"]);return c!=null&&CV(c,o),o}function PV(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["prompt"]);s!=null&&d(o,["instances[0]","prompt"],s);const r=l(e,["image"]);r!=null&&d(o,["instances[0]","image"],bn(r));const a=l(e,["video"]);a!=null&&d(o,["instances[0]","video"],EE(a));const u=l(e,["source"]);u!=null&&DV(u,o);const c=l(e,["config"]);return c!=null&&AV(c,o),o}function NV(t,e){const n={},o=l(t,["generatedSamples"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>OV(a))),d(n,["generatedVideos"],r)}const i=l(t,["raiMediaFilteredCount"]);i!=null&&d(n,["raiMediaFilteredCount"],i);const s=l(t,["raiMediaFilteredReasons"]);return s!=null&&d(n,["raiMediaFilteredReasons"],s),n}function MV(t,e){const n={},o=l(t,["videos"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(a=>LV(a))),d(n,["generatedVideos"],r)}const i=l(t,["raiMediaFilteredCount"]);i!=null&&d(n,["raiMediaFilteredCount"],i);const s=l(t,["raiMediaFilteredReasons"]);return s!=null&&d(n,["raiMediaFilteredReasons"],s),n}function xV(t,e,n){const o={},i=l(t,["prompt"]);e!==void 0&&i!=null&&d(e,["instances[0]","prompt"],i);const s=l(t,["image"]);e!==void 0&&s!=null&&d(e,["instances[0]","image"],Jl(s));const r=l(t,["video"]);return e!==void 0&&r!=null&&d(e,["instances[0]","video"],TE(r)),o}function DV(t,e,n){const o={},i=l(t,["prompt"]);e!==void 0&&i!=null&&d(e,["instances[0]","prompt"],i);const s=l(t,["image"]);e!==void 0&&s!=null&&d(e,["instances[0]","image"],bn(s));const r=l(t,["video"]);return e!==void 0&&r!=null&&d(e,["instances[0]","video"],EE(r)),o}function $V(t,e){const n={},o=l(t,["_self"]);o!=null&&d(n,["image"],ZV(o));const i=l(t,["raiFilteredReason"]);i!=null&&d(n,["raiFilteredReason"],i);const s=l(t,["_self"]);return s!=null&&d(n,["safetyAttributes"],vE(s)),n}function Zl(t,e){const n={},o=l(t,["_self"]);o!=null&&d(n,["image"],gE(o));const i=l(t,["raiFilteredReason"]);i!=null&&d(n,["raiFilteredReason"],i);const s=l(t,["_self"]);s!=null&&d(n,["safetyAttributes"],yE(s));const r=l(t,["prompt"]);return r!=null&&d(n,["enhancedPrompt"],r),n}function UV(t,e){const n={},o=l(t,["_self"]);o!=null&&d(n,["mask"],gE(o));const i=l(t,["labels"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>r)),d(n,["labels"],s)}return n}function OV(t,e){const n={},o=l(t,["video"]);return o!=null&&d(n,["video"],Aq(o)),n}function LV(t,e){const n={},o=l(t,["_self"]);return o!=null&&d(n,["video"],bq(o)),n}function GV(t,e){const n={},o=l(t,["modelSelectionConfig"]);o!=null&&d(n,["modelConfig"],o);const i=l(t,["responseJsonSchema"]);i!=null&&d(n,["responseJsonSchema"],i);const s=l(t,["audioTimestamp"]);s!=null&&d(n,["audioTimestamp"],s);const r=l(t,["candidateCount"]);r!=null&&d(n,["candidateCount"],r);const a=l(t,["enableAffectiveDialog"]);a!=null&&d(n,["enableAffectiveDialog"],a);const u=l(t,["frequencyPenalty"]);u!=null&&d(n,["frequencyPenalty"],u);const c=l(t,["logprobs"]);c!=null&&d(n,["logprobs"],c);const p=l(t,["maxOutputTokens"]);p!=null&&d(n,["maxOutputTokens"],p);const f=l(t,["mediaResolution"]);f!=null&&d(n,["mediaResolution"],f);const h=l(t,["presencePenalty"]);h!=null&&d(n,["presencePenalty"],h);const m=l(t,["responseLogprobs"]);m!=null&&d(n,["responseLogprobs"],m);const v=l(t,["responseMimeType"]);v!=null&&d(n,["responseMimeType"],v);const _=l(t,["responseModalities"]);_!=null&&d(n,["responseModalities"],_);const w=l(t,["responseSchema"]);w!=null&&d(n,["responseSchema"],w);const C=l(t,["routingConfig"]);C!=null&&d(n,["routingConfig"],C);const E=l(t,["seed"]);E!=null&&d(n,["seed"],E);const A=l(t,["speechConfig"]);A!=null&&d(n,["speechConfig"],A);const R=l(t,["stopSequences"]);R!=null&&d(n,["stopSequences"],R);const k=l(t,["temperature"]);k!=null&&d(n,["temperature"],k);const b=l(t,["thinkingConfig"]);b!=null&&d(n,["thinkingConfig"],b);const U=l(t,["topK"]);U!=null&&d(n,["topK"],U);const J=l(t,["topP"]);if(J!=null&&d(n,["topP"],J),l(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function zV(t,e,n){const o={},i=l(e,["model"]);return i!=null&&d(o,["_url","name"],Pe(t,i)),o}function FV(t,e,n){const o={},i=l(e,["model"]);return i!=null&&d(o,["_url","name"],Pe(t,i)),o}function VV(t,e){const n={},o=l(t,["authConfig"]);o!=null&&d(n,["authConfig"],GF(o));const i=l(t,["enableWidget"]);return i!=null&&d(n,["enableWidget"],i),n}function qV(t,e){const n={},o=l(t,["searchTypes"]);if(o!=null&&d(n,["searchTypes"],o),l(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const i=l(t,["timeRangeFilter"]);return i!=null&&d(n,["timeRangeFilter"],i),n}function BV(t,e){const n={},o=l(t,["aspectRatio"]);o!=null&&d(n,["aspectRatio"],o);const i=l(t,["imageSize"]);if(i!=null&&d(n,["imageSize"],i),l(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return n}function HV(t,e){const n={},o=l(t,["aspectRatio"]);o!=null&&d(n,["aspectRatio"],o);const i=l(t,["imageSize"]);i!=null&&d(n,["imageSize"],i);const s=l(t,["personGeneration"]);s!=null&&d(n,["personGeneration"],s);const r=l(t,["prominentPeople"]);r!=null&&d(n,["prominentPeople"],r);const a=l(t,["outputMimeType"]);a!=null&&d(n,["imageOutputOptions","mimeType"],a);const u=l(t,["outputCompressionQuality"]);u!=null&&d(n,["imageOutputOptions","compressionQuality"],u);const c=l(t,["imageOutputOptions"]);return c!=null&&d(n,["imageOutputOptions"],c),n}function ZV(t,e){const n={},o=l(t,["bytesBase64Encoded"]);o!=null&&d(n,["imageBytes"],No(o));const i=l(t,["mimeType"]);return i!=null&&d(n,["mimeType"],i),n}function gE(t,e){const n={},o=l(t,["gcsUri"]);o!=null&&d(n,["gcsUri"],o);const i=l(t,["bytesBase64Encoded"]);i!=null&&d(n,["imageBytes"],No(i));const s=l(t,["mimeType"]);return s!=null&&d(n,["mimeType"],s),n}function Jl(t,e){const n={};if(l(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["imageBytes"]);o!=null&&d(n,["bytesBase64Encoded"],No(o));const i=l(t,["mimeType"]);return i!=null&&d(n,["mimeType"],i),n}function bn(t,e){const n={},o=l(t,["gcsUri"]);o!=null&&d(n,["gcsUri"],o);const i=l(t,["imageBytes"]);i!=null&&d(n,["bytesBase64Encoded"],No(i));const s=l(t,["mimeType"]);return s!=null&&d(n,["mimeType"],s),n}function JV(t,e,n,o){const i={},s=l(e,["pageSize"]);n!==void 0&&s!=null&&d(n,["_query","pageSize"],s);const r=l(e,["pageToken"]);n!==void 0&&r!=null&&d(n,["_query","pageToken"],r);const a=l(e,["filter"]);n!==void 0&&a!=null&&d(n,["_query","filter"],a);const u=l(e,["queryBase"]);return n!==void 0&&u!=null&&d(n,["_url","models_url"],uE(t,u)),i}function WV(t,e,n,o){const i={},s=l(e,["pageSize"]);n!==void 0&&s!=null&&d(n,["_query","pageSize"],s);const r=l(e,["pageToken"]);n!==void 0&&r!=null&&d(n,["_query","pageToken"],r);const a=l(e,["filter"]);n!==void 0&&a!=null&&d(n,["_query","filter"],a);const u=l(e,["queryBase"]);return n!==void 0&&u!=null&&d(n,["_url","models_url"],uE(t,u)),i}function KV(t,e,n){const o={},i=l(e,["config"]);return i!=null&&JV(t,i,o),o}function YV(t,e,n){const o={},i=l(e,["config"]);return i!=null&&WV(t,i,o),o}function XV(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["nextPageToken"]);i!=null&&d(n,["nextPageToken"],i);const s=l(t,["_self"]);if(s!=null){let r=cE(s);Array.isArray(r)&&(r=r.map(a=>uc(a))),d(n,["models"],r)}return n}function QV(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["nextPageToken"]);i!=null&&d(n,["nextPageToken"],i);const s=l(t,["_self"]);if(s!=null){let r=cE(s);Array.isArray(r)&&(r=r.map(a=>cc(a))),d(n,["models"],r)}return n}function jV(t,e){const n={},o=l(t,["maskMode"]);o!=null&&d(n,["maskMode"],o);const i=l(t,["segmentationClasses"]);i!=null&&d(n,["maskClasses"],i);const s=l(t,["maskDilation"]);return s!=null&&d(n,["dilation"],s),n}function uc(t,e){const n={},o=l(t,["name"]);o!=null&&d(n,["name"],o);const i=l(t,["displayName"]);i!=null&&d(n,["displayName"],i);const s=l(t,["description"]);s!=null&&d(n,["description"],s);const r=l(t,["version"]);r!=null&&d(n,["version"],r);const a=l(t,["_self"]);a!=null&&d(n,["tunedModelInfo"],vq(a));const u=l(t,["inputTokenLimit"]);u!=null&&d(n,["inputTokenLimit"],u);const c=l(t,["outputTokenLimit"]);c!=null&&d(n,["outputTokenLimit"],c);const p=l(t,["supportedGenerationMethods"]);p!=null&&d(n,["supportedActions"],p);const f=l(t,["temperature"]);f!=null&&d(n,["temperature"],f);const h=l(t,["maxTemperature"]);h!=null&&d(n,["maxTemperature"],h);const m=l(t,["topP"]);m!=null&&d(n,["topP"],m);const v=l(t,["topK"]);v!=null&&d(n,["topK"],v);const _=l(t,["thinking"]);return _!=null&&d(n,["thinking"],_),n}function cc(t,e){const n={},o=l(t,["name"]);o!=null&&d(n,["name"],o);const i=l(t,["displayName"]);i!=null&&d(n,["displayName"],i);const s=l(t,["description"]);s!=null&&d(n,["description"],s);const r=l(t,["versionId"]);r!=null&&d(n,["version"],r);const a=l(t,["deployedModels"]);if(a!=null){let h=a;Array.isArray(h)&&(h=h.map(m=>fV(m))),d(n,["endpoints"],h)}const u=l(t,["labels"]);u!=null&&d(n,["labels"],u);const c=l(t,["_self"]);c!=null&&d(n,["tunedModelInfo"],yq(c));const p=l(t,["defaultCheckpointId"]);p!=null&&d(n,["defaultCheckpointId"],p);const f=l(t,["checkpoints"]);if(f!=null){let h=f;Array.isArray(h)&&(h=h.map(m=>m)),d(n,["checkpoints"],h)}return n}function eq(t,e){const n={},o=l(t,["mediaResolution"]);o!=null&&d(n,["mediaResolution"],o);const i=l(t,["codeExecutionResult"]);i!=null&&d(n,["codeExecutionResult"],i);const s=l(t,["executableCode"]);s!=null&&d(n,["executableCode"],s);const r=l(t,["fileData"]);r!=null&&d(n,["fileData"],hV(r));const a=l(t,["functionCall"]);a!=null&&d(n,["functionCall"],mV(a));const u=l(t,["functionResponse"]);u!=null&&d(n,["functionResponse"],u);const c=l(t,["inlineData"]);c!=null&&d(n,["inlineData"],zF(c));const p=l(t,["text"]);p!=null&&d(n,["text"],p);const f=l(t,["thought"]);f!=null&&d(n,["thought"],f);const h=l(t,["thoughtSignature"]);h!=null&&d(n,["thoughtSignature"],h);const m=l(t,["videoMetadata"]);m!=null&&d(n,["videoMetadata"],m);const v=l(t,["toolCall"]);v!=null&&d(n,["toolCall"],v);const _=l(t,["toolResponse"]);_!=null&&d(n,["toolResponse"],_);const w=l(t,["partMetadata"]);return w!=null&&d(n,["partMetadata"],w),n}function tq(t,e){const n={},o=l(t,["mediaResolution"]);o!=null&&d(n,["mediaResolution"],o);const i=l(t,["codeExecutionResult"]);i!=null&&d(n,["codeExecutionResult"],i);const s=l(t,["executableCode"]);s!=null&&d(n,["executableCode"],s);const r=l(t,["fileData"]);r!=null&&d(n,["fileData"],r);const a=l(t,["functionCall"]);a!=null&&d(n,["functionCall"],a);const u=l(t,["functionResponse"]);u!=null&&d(n,["functionResponse"],u);const c=l(t,["inlineData"]);c!=null&&d(n,["inlineData"],c);const p=l(t,["text"]);p!=null&&d(n,["text"],p);const f=l(t,["thought"]);f!=null&&d(n,["thought"],f);const h=l(t,["thoughtSignature"]);h!=null&&d(n,["thoughtSignature"],h);const m=l(t,["videoMetadata"]);if(m!=null&&d(n,["videoMetadata"],m),l(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(l(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function nq(t,e){const n={},o=l(t,["productImage"]);return o!=null&&d(n,["image"],bn(o)),n}function oq(t,e,n){const o={},i=l(t,["numberOfImages"]);e!==void 0&&i!=null&&d(e,["parameters","sampleCount"],i);const s=l(t,["baseSteps"]);e!==void 0&&s!=null&&d(e,["parameters","baseSteps"],s);const r=l(t,["outputGcsUri"]);e!==void 0&&r!=null&&d(e,["parameters","storageUri"],r);const a=l(t,["seed"]);e!==void 0&&a!=null&&d(e,["parameters","seed"],a);const u=l(t,["safetyFilterLevel"]);e!==void 0&&u!=null&&d(e,["parameters","safetySetting"],u);const c=l(t,["personGeneration"]);e!==void 0&&c!=null&&d(e,["parameters","personGeneration"],c);const p=l(t,["addWatermark"]);e!==void 0&&p!=null&&d(e,["parameters","addWatermark"],p);const f=l(t,["outputMimeType"]);e!==void 0&&f!=null&&d(e,["parameters","outputOptions","mimeType"],f);const h=l(t,["outputCompressionQuality"]);e!==void 0&&h!=null&&d(e,["parameters","outputOptions","compressionQuality"],h);const m=l(t,["enhancePrompt"]);e!==void 0&&m!=null&&d(e,["parameters","enhancePrompt"],m);const v=l(t,["labels"]);return e!==void 0&&v!=null&&d(e,["labels"],v),o}function iq(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["source"]);s!=null&&rq(s,o);const r=l(e,["config"]);return r!=null&&oq(r,o),o}function sq(t,e){const n={},o=l(t,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>Zl(s))),d(n,["generatedImages"],i)}return n}function rq(t,e,n){const o={},i=l(t,["prompt"]);e!==void 0&&i!=null&&d(e,["instances[0]","prompt"],i);const s=l(t,["personImage"]);e!==void 0&&s!=null&&d(e,["instances[0]","personImage","image"],bn(s));const r=l(t,["productImages"]);if(e!==void 0&&r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>nq(u))),d(e,["instances[0]","productImages"],a)}return o}function aq(t,e){const n={},o=l(t,["referenceImage"]);o!=null&&d(n,["referenceImage"],bn(o));const i=l(t,["referenceId"]);i!=null&&d(n,["referenceId"],i);const s=l(t,["referenceType"]);s!=null&&d(n,["referenceType"],s);const r=l(t,["maskImageConfig"]);r!=null&&d(n,["maskImageConfig"],jV(r));const a=l(t,["controlImageConfig"]);a!=null&&d(n,["controlImageConfig"],JF(a));const u=l(t,["styleImageConfig"]);u!=null&&d(n,["styleImageConfig"],u);const c=l(t,["subjectImageConfig"]);return c!=null&&d(n,["subjectImageConfig"],c),n}function vE(t,e){const n={},o=l(t,["safetyAttributes","categories"]);o!=null&&d(n,["categories"],o);const i=l(t,["safetyAttributes","scores"]);i!=null&&d(n,["scores"],i);const s=l(t,["contentType"]);return s!=null&&d(n,["contentType"],s),n}function yE(t,e){const n={},o=l(t,["safetyAttributes","categories"]);o!=null&&d(n,["categories"],o);const i=l(t,["safetyAttributes","scores"]);i!=null&&d(n,["scores"],i);const s=l(t,["contentType"]);return s!=null&&d(n,["contentType"],s),n}function lq(t,e){const n={},o=l(t,["category"]);if(o!=null&&d(n,["category"],o),l(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const i=l(t,["threshold"]);return i!=null&&d(n,["threshold"],i),n}function uq(t,e){const n={},o=l(t,["image"]);return o!=null&&d(n,["image"],bn(o)),n}function cq(t,e,n){const o={},i=l(t,["mode"]);e!==void 0&&i!=null&&d(e,["parameters","mode"],i);const s=l(t,["maxPredictions"]);e!==void 0&&s!=null&&d(e,["parameters","maxPredictions"],s);const r=l(t,["confidenceThreshold"]);e!==void 0&&r!=null&&d(e,["parameters","confidenceThreshold"],r);const a=l(t,["maskDilation"]);e!==void 0&&a!=null&&d(e,["parameters","maskDilation"],a);const u=l(t,["binaryColorThreshold"]);e!==void 0&&u!=null&&d(e,["parameters","binaryColorThreshold"],u);const c=l(t,["labels"]);return e!==void 0&&c!=null&&d(e,["labels"],c),o}function dq(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["source"]);s!=null&&fq(s,o);const r=l(e,["config"]);return r!=null&&cq(r,o),o}function pq(t,e){const n={},o=l(t,["predictions"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>UV(s))),d(n,["generatedMasks"],i)}return n}function fq(t,e,n){const o={},i=l(t,["prompt"]);e!==void 0&&i!=null&&d(e,["instances[0]","prompt"],i);const s=l(t,["image"]);e!==void 0&&s!=null&&d(e,["instances[0]","image"],bn(s));const r=l(t,["scribbleImage"]);return e!==void 0&&r!=null&&d(e,["instances[0]","scribble"],uq(r)),o}function hq(t,e){const n={},o=l(t,["retrievalConfig"]);o!=null&&d(n,["retrievalConfig"],o);const i=l(t,["functionCallingConfig"]);i!=null&&d(n,["functionCallingConfig"],gV(i));const s=l(t,["includeServerSideToolInvocations"]);return s!=null&&d(n,["includeServerSideToolInvocations"],s),n}function mq(t,e){const n={},o=l(t,["retrievalConfig"]);o!=null&&d(n,["retrievalConfig"],o);const i=l(t,["functionCallingConfig"]);if(i!=null&&d(n,["functionCallingConfig"],i),l(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function gq(t,e){const n={};if(l(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["computerUse"]);o!=null&&d(n,["computerUse"],o);const i=l(t,["fileSearch"]);i!=null&&d(n,["fileSearch"],i);const s=l(t,["googleSearch"]);s!=null&&d(n,["googleSearch"],qV(s));const r=l(t,["googleMaps"]);r!=null&&d(n,["googleMaps"],VV(r));const a=l(t,["codeExecution"]);if(a!=null&&d(n,["codeExecution"],a),l(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=l(t,["functionDeclarations"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(m=>m)),d(n,["functionDeclarations"],h)}const c=l(t,["googleSearchRetrieval"]);if(c!=null&&d(n,["googleSearchRetrieval"],c),l(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const p=l(t,["urlContext"]);p!=null&&d(n,["urlContext"],p);const f=l(t,["mcpServers"]);if(f!=null){let h=f;Array.isArray(h)&&(h=h.map(m=>m)),d(n,["mcpServers"],h)}return n}function _E(t,e){const n={},o=l(t,["retrieval"]);o!=null&&d(n,["retrieval"],o);const i=l(t,["computerUse"]);if(i!=null&&d(n,["computerUse"],i),l(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const s=l(t,["googleSearch"]);s!=null&&d(n,["googleSearch"],s);const r=l(t,["googleMaps"]);r!=null&&d(n,["googleMaps"],r);const a=l(t,["codeExecution"]);a!=null&&d(n,["codeExecution"],a);const u=l(t,["enterpriseWebSearch"]);u!=null&&d(n,["enterpriseWebSearch"],u);const c=l(t,["functionDeclarations"]);if(c!=null){let m=c;Array.isArray(m)&&(m=m.map(v=>v)),d(n,["functionDeclarations"],m)}const p=l(t,["googleSearchRetrieval"]);p!=null&&d(n,["googleSearchRetrieval"],p);const f=l(t,["parallelAiSearch"]);f!=null&&d(n,["parallelAiSearch"],f);const h=l(t,["urlContext"]);if(h!=null&&d(n,["urlContext"],h),l(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function vq(t,e){const n={},o=l(t,["baseModel"]);o!=null&&d(n,["baseModel"],o);const i=l(t,["createTime"]);i!=null&&d(n,["createTime"],i);const s=l(t,["updateTime"]);return s!=null&&d(n,["updateTime"],s),n}function yq(t,e){const n={},o=l(t,["labels","google-vertex-llm-tuning-base-model-id"]);o!=null&&d(n,["baseModel"],o);const i=l(t,["createTime"]);i!=null&&d(n,["createTime"],i);const s=l(t,["updateTime"]);return s!=null&&d(n,["updateTime"],s),n}function _q(t,e,n){const o={},i=l(t,["displayName"]);e!==void 0&&i!=null&&d(e,["displayName"],i);const s=l(t,["description"]);e!==void 0&&s!=null&&d(e,["description"],s);const r=l(t,["defaultCheckpointId"]);return e!==void 0&&r!=null&&d(e,["defaultCheckpointId"],r),o}function Tq(t,e,n){const o={},i=l(t,["displayName"]);e!==void 0&&i!=null&&d(e,["displayName"],i);const s=l(t,["description"]);e!==void 0&&s!=null&&d(e,["description"],s);const r=l(t,["defaultCheckpointId"]);return e!==void 0&&r!=null&&d(e,["defaultCheckpointId"],r),o}function Eq(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","name"],Pe(t,i));const s=l(e,["config"]);return s!=null&&_q(s,o),o}function wq(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["config"]);return s!=null&&Tq(s,o),o}function Iq(t,e,n){const o={},i=l(t,["outputGcsUri"]);e!==void 0&&i!=null&&d(e,["parameters","storageUri"],i);const s=l(t,["safetyFilterLevel"]);e!==void 0&&s!=null&&d(e,["parameters","safetySetting"],s);const r=l(t,["personGeneration"]);e!==void 0&&r!=null&&d(e,["parameters","personGeneration"],r);const a=l(t,["includeRaiReason"]);e!==void 0&&a!=null&&d(e,["parameters","includeRaiReason"],a);const u=l(t,["outputMimeType"]);e!==void 0&&u!=null&&d(e,["parameters","outputOptions","mimeType"],u);const c=l(t,["outputCompressionQuality"]);e!==void 0&&c!=null&&d(e,["parameters","outputOptions","compressionQuality"],c);const p=l(t,["enhanceInputImage"]);e!==void 0&&p!=null&&d(e,["parameters","upscaleConfig","enhanceInputImage"],p);const f=l(t,["imagePreservationFactor"]);e!==void 0&&f!=null&&d(e,["parameters","upscaleConfig","imagePreservationFactor"],f);const h=l(t,["labels"]);e!==void 0&&h!=null&&d(e,["labels"],h);const m=l(t,["numberOfImages"]);e!==void 0&&m!=null&&d(e,["parameters","sampleCount"],m);const v=l(t,["mode"]);return e!==void 0&&v!=null&&d(e,["parameters","mode"],v),o}function Sq(t,e,n){const o={},i=l(e,["model"]);i!=null&&d(o,["_url","model"],Pe(t,i));const s=l(e,["image"]);s!=null&&d(o,["instances[0]","image"],bn(s));const r=l(e,["upscaleFactor"]);r!=null&&d(o,["parameters","upscaleConfig","upscaleFactor"],r);const a=l(e,["config"]);return a!=null&&Iq(a,o),o}function Cq(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["predictions"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>Zl(r))),d(n,["generatedImages"],s)}return n}function Aq(t,e){const n={},o=l(t,["uri"]);o!=null&&d(n,["uri"],o);const i=l(t,["encodedVideo"]);i!=null&&d(n,["videoBytes"],No(i));const s=l(t,["encoding"]);return s!=null&&d(n,["mimeType"],s),n}function bq(t,e){const n={},o=l(t,["gcsUri"]);o!=null&&d(n,["uri"],o);const i=l(t,["bytesBase64Encoded"]);i!=null&&d(n,["videoBytes"],No(i));const s=l(t,["mimeType"]);return s!=null&&d(n,["mimeType"],s),n}function Rq(t,e){const n={},o=l(t,["image"]);o!=null&&d(n,["_self"],bn(o));const i=l(t,["maskMode"]);return i!=null&&d(n,["maskMode"],i),n}function kq(t,e){const n={},o=l(t,["image"]);o!=null&&d(n,["image"],Jl(o));const i=l(t,["referenceType"]);return i!=null&&d(n,["referenceType"],i),n}function Pq(t,e){const n={},o=l(t,["image"]);o!=null&&d(n,["image"],bn(o));const i=l(t,["referenceType"]);return i!=null&&d(n,["referenceType"],i),n}function TE(t,e){const n={},o=l(t,["uri"]);o!=null&&d(n,["uri"],o);const i=l(t,["videoBytes"]);i!=null&&d(n,["encodedVideo"],No(i));const s=l(t,["mimeType"]);return s!=null&&d(n,["encoding"],s),n}function EE(t,e){const n={},o=l(t,["uri"]);o!=null&&d(n,["gcsUri"],o);const i=l(t,["videoBytes"]);i!=null&&d(n,["bytesBase64Encoded"],No(i));const s=l(t,["mimeType"]);return s!=null&&d(n,["mimeType"],s),n}/**
202
+ * @license
203
+ * Copyright 2025 Google LLC
204
+ * SPDX-License-Identifier: Apache-2.0
205
+ */function Nq(t,e,n){const o={},i=l(e,["displayName"]);n!==void 0&&i!=null&&d(n,["displayName"],i);const s=l(e,["embeddingModel"]);return n!==void 0&&s!=null&&d(n,["embeddingModel"],Pe(t,s)),o}function Mq(t,e){const n={},o=l(e,["config"]);return o!=null&&Nq(t,o,n),n}function xq(t,e){const n={},o=l(t,["force"]);return e!==void 0&&o!=null&&d(e,["_query","force"],o),n}function Dq(t){const e={},n=l(t,["name"]);n!=null&&d(e,["_url","name"],n);const o=l(t,["config"]);return o!=null&&xq(o,e),e}function $q(t){const e={},n=l(t,["name"]);return n!=null&&d(e,["_url","name"],n),e}function Uq(t,e){const n={},o=l(t,["customMetadata"]);if(e!==void 0&&o!=null){let s=o;Array.isArray(s)&&(s=s.map(r=>r)),d(e,["customMetadata"],s)}const i=l(t,["chunkingConfig"]);return e!==void 0&&i!=null&&d(e,["chunkingConfig"],i),n}function Oq(t){const e={},n=l(t,["name"]);n!=null&&d(e,["name"],n);const o=l(t,["metadata"]);o!=null&&d(e,["metadata"],o);const i=l(t,["done"]);i!=null&&d(e,["done"],i);const s=l(t,["error"]);s!=null&&d(e,["error"],s);const r=l(t,["response"]);return r!=null&&d(e,["response"],Gq(r)),e}function Lq(t){const e={},n=l(t,["fileSearchStoreName"]);n!=null&&d(e,["_url","file_search_store_name"],n);const o=l(t,["fileName"]);o!=null&&d(e,["fileName"],o);const i=l(t,["config"]);return i!=null&&Uq(i,e),e}function Gq(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["parent"]);o!=null&&d(e,["parent"],o);const i=l(t,["documentName"]);return i!=null&&d(e,["documentName"],i),e}function zq(t,e){const n={},o=l(t,["pageSize"]);e!==void 0&&o!=null&&d(e,["_query","pageSize"],o);const i=l(t,["pageToken"]);return e!==void 0&&i!=null&&d(e,["_query","pageToken"],i),n}function Fq(t){const e={},n=l(t,["config"]);return n!=null&&zq(n,e),e}function Vq(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["nextPageToken"]);o!=null&&d(e,["nextPageToken"],o);const i=l(t,["fileSearchStores"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>r)),d(e,["fileSearchStores"],s)}return e}function wE(t,e){const n={},o=l(t,["mimeType"]);e!==void 0&&o!=null&&d(e,["mimeType"],o);const i=l(t,["displayName"]);e!==void 0&&i!=null&&d(e,["displayName"],i);const s=l(t,["customMetadata"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(u=>u)),d(e,["customMetadata"],a)}const r=l(t,["chunkingConfig"]);return e!==void 0&&r!=null&&d(e,["chunkingConfig"],r),n}function qq(t){const e={},n=l(t,["fileSearchStoreName"]);n!=null&&d(e,["_url","file_search_store_name"],n);const o=l(t,["config"]);return o!=null&&wE(o,e),e}function Bq(t){const e={},n=l(t,["sdkHttpResponse"]);return n!=null&&d(e,["sdkHttpResponse"],n),e}/**
206
+ * @license
207
+ * Copyright 2025 Google LLC
208
+ * SPDX-License-Identifier: Apache-2.0
209
+ */const Hq="Content-Type",Zq="X-Server-Timeout",Jq="User-Agent",dc="x-goog-api-client",Wq="2.3.0",Kq=`google-genai-sdk/${Wq}`,Yq="v1beta1",Xq="v1beta",Qq=new Set(["us","eu"]),jq=5,eB=[408,429,500,502,503,504];class tB{constructor(e){var n,o,i;this.clientOptions=Object.assign({},e),this.customBaseUrl=(n=e.httpOptions)===null||n===void 0?void 0:n.baseUrl,this.clientOptions.vertexai&&(this.clientOptions.project&&this.clientOptions.location?this.clientOptions.apiKey=void 0:this.clientOptions.apiKey&&(this.clientOptions.project=void 0,this.clientOptions.location=void 0));const s={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");const a=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!a?(s.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey||this.clientOptions.location==="global"?s.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&Qq.has(this.clientOptions.location)?s.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(s.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),s.apiVersion=(o=this.clientOptions.apiVersion)!==null&&o!==void 0?o:Yq}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),s.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:Xq,s.baseUrl="https://generativelanguage.googleapis.com/";s.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=s,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(s,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){const e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");const o=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&o.push(e.apiVersion),o.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const e=this.getBaseUrl(),n=new URL(e);return n.protocol=n.protocol=="http:"?"ws":"wss",n.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}constructUrl(e,n,o){const i=[this.getRequestUrlInternal(n)];return o&&i.push(this.getBaseResourcePath()),e!==""&&i.push(e),new URL(`${i.join("/")}`)}shouldPrependVertexProjectPath(e,n){return!(n.baseUrl&&n.baseUrlResourceScope===rc.COLLECTION||this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const o=this.shouldPrependVertexProjectPath(e,n),i=this.constructUrl(e.path,n,o);if(e.queryParams)for(const[r,a]of Object.entries(e.queryParams))i.searchParams.append(r,String(a));let s={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else s.body=e.body;return s=await this.includeExtraHttpOptionsToRequestInit(s,n,i.toString(),e.abortSignal),this.unaryApiCall(i,s,e.httpMethod)}patchHttpOptions(e,n){const o=JSON.parse(JSON.stringify(e));for(const[i,s]of Object.entries(n))typeof s=="object"?o[i]=Object.assign(Object.assign({},o[i]),s):s!==void 0&&(o[i]=s);return o}async requestStream(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const o=this.shouldPrependVertexProjectPath(e,n),i=this.constructUrl(e.path,n,o);(!i.searchParams.has("alt")||i.searchParams.get("alt")!=="sse")&&i.searchParams.set("alt","sse");let s={};return s.body=e.body,s=await this.includeExtraHttpOptionsToRequestInit(s,n,i.toString(),e.abortSignal),this.streamApiCall(i,s,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,n,o,i){if(n&&n.timeout||i){const s=new AbortController,r=s.signal;if(n.timeout&&(n==null?void 0:n.timeout)>0){const a=Symbol.for("undici.globalDispatcher.1"),u=globalThis[a];if(u){const p=Object.getOwnPropertySymbols(u);for(const f of p){const h=f.description;if(h!=null&&h.includes("headers timeout")||h!=null&&h.includes("body timeout")){const m=u[f];typeof m=="number"&&(u[f]=Math.max(m,n.timeout))}}}const c=setTimeout(()=>s.abort(),n.timeout);c&&typeof c.unref=="function"&&c.unref()}i&&i.addEventListener("abort",()=>{s.abort()}),e.signal=r}return n&&n.extraBody!==null&&nB(e,n.extraBody),e.headers=await this.getHeadersInternal(n,o),e}async unaryApiCall(e,n,o){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:o})).then(async i=>(await Rm(i),new il(i))).catch(i=>{throw i instanceof Error?i:new Error(`exception ${i} sending request`,{cause:i})})}async streamApiCall(e,n,o){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:o})).then(async i=>(await Rm(i),this.processStreamResponse(i))).catch(i=>{throw i instanceof Error?i:new Error(`exception ${i} sending request`,{cause:i})})}processStreamResponse(e){return ln(this,arguments,function*(){var o;const i=(o=e==null?void 0:e.body)===null||o===void 0?void 0:o.getReader(),s=new TextDecoder("utf-8");if(!i)throw new Error("Response body is empty");try{let r="";const a="data:",u=[`
210
+
211
+ `,"\r\r",`\r
212
+ \r
213
+ `];for(;;){const{done:c,value:p}=yield pe(i.read());if(c){if(r.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}const f=s.decode(p,{stream:!0});try{const v=JSON.parse(f);if("error"in v){const _=JSON.parse(JSON.stringify(v.error)),w=_.status,C=_.code,E=`got status: ${w}. ${JSON.stringify(v)}`;if(C>=400&&C<600)throw new Hl({message:E,status:C})}}catch(v){if(v.name==="ApiError")throw v}r+=f;let h=-1,m=0;for(;;){h=-1,m=0;for(const w of u){const C=r.indexOf(w);C!==-1&&(h===-1||C<h)&&(h=C,m=w.length)}if(h===-1)break;const v=r.substring(0,h);r=r.substring(h+m);const _=v.trim();if(_.startsWith(a)){const w=_.substring(a.length).trim();try{const C=new Response(w,{headers:e==null?void 0:e.headers,status:e==null?void 0:e.status,statusText:e==null?void 0:e.statusText});yield yield pe(new il(C))}catch(C){throw new Error(`exception parsing stream chunk ${w}. ${C}`)}}}}}finally{i.releaseLock()}})}async apiCall(e,n){var o;if(!this.clientOptions.httpOptions||!this.clientOptions.httpOptions.retryOptions)return fetch(e,n);const i=this.clientOptions.httpOptions.retryOptions;return M1(async()=>{const r=await fetch(e,n);if(r.ok)return r;throw eB.includes(r.status)?new Error(`Retryable HTTP Error: ${r.statusText}`):new eE.AbortError(`Non-retryable exception ${r.statusText} sending request`)},{retries:((o=i.attempts)!==null&&o!==void 0?o:jq)-1})}getDefaultHeaders(){const e={},n=Kq+" "+this.clientOptions.userAgentExtra;return e[Jq]=n,e[dc]=n,e[Hq]="application/json",e}async getHeadersInternal(e,n){const o=new Headers;if(e&&e.headers)for(const[i,s]of Object.entries(e.headers))o.append(i,s);return e!=null&&e.timeout&&e.timeout>0&&o.append(Zq,String(Math.ceil(e.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(o,n),o}getFileName(e){var n;let o="";return typeof e=="string"&&(o=e.replace(/[/\\]+$/,""),o=(n=o.split(/[/\\]/).pop())!==null&&n!==void 0?n:""),o}async uploadFile(e,n){var o;const i={};n!=null&&(i.mimeType=n.mimeType,i.name=n.name,i.displayName=n.displayName),i.name&&!i.name.startsWith("files/")&&(i.name=`files/${i.name}`);const s=this.clientOptions.uploader,r=await s.stat(e);i.sizeBytes=String(r.size);const a=(o=n==null?void 0:n.mimeType)!==null&&o!==void 0?o:r.type;if(a===void 0||a==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");i.mimeType=a;const u={file:i},c=this.getFileName(e),p=Q("upload/v1beta/files",u._url),f=await this.fetchUploadUrl(p,i.sizeBytes,i.mimeType,c,u,n==null?void 0:n.httpOptions);return s.upload(e,f,this)}async uploadFileToFileSearchStore(e,n,o){var i;const s=this.clientOptions.uploader,r=await s.stat(n),a=String(r.size),u=(i=o==null?void 0:o.mimeType)!==null&&i!==void 0?i:r.type;if(u===void 0||u==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");const c=`upload/v1beta/${e}:uploadToFileSearchStore`,p=this.getFileName(n),f={};o!=null&&wE(o,f);const h=await this.fetchUploadUrl(c,a,u,p,f,o==null?void 0:o.httpOptions);return s.uploadToFileSearchStore(n,h,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,o,i,s,r){var a;let u={};r?u=r:u={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${o}`},i?{"X-Goog-Upload-File-Name":i}:{})};const c=await this.request({path:e,body:JSON.stringify(s),httpMethod:"POST",httpOptions:u});if(!c||!(c!=null&&c.headers))throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");const p=(a=c==null?void 0:c.headers)===null||a===void 0?void 0:a["x-goog-upload-url"];if(p===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return p}}async function Rm(t){var e;if(t===void 0)throw new Error("response is undefined");if(!t.ok){const n=t.status;let o;!((e=t.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?o=await t.json():o={error:{message:await t.text(),code:t.status,status:t.statusText}};const i=JSON.stringify(o);throw n>=400&&n<600?new Hl({message:i,status:n}):new Error(i)}}function nB(t,e){if(!e||Object.keys(e).length===0)return;if(t.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof t.body=="string"&&t.body.length>0)try{const s=JSON.parse(t.body);if(typeof s=="object"&&s!==null&&!Array.isArray(s))n=s;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function o(s,r){const a=Object.assign({},s);for(const u in r)if(Object.prototype.hasOwnProperty.call(r,u)){const c=r[u],p=a[u];c&&typeof c=="object"&&!Array.isArray(c)&&p&&typeof p=="object"&&!Array.isArray(p)?a[u]=o(p,c):(p&&c&&typeof p!=typeof c&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${u}". Original type: ${typeof p}, New type: ${typeof c}. Overwriting.`),a[u]=c)}return a}const i=o(n,e);t.body=JSON.stringify(i)}/**
214
+ * @license
215
+ * Copyright 2025 Google LLC
216
+ * SPDX-License-Identifier: Apache-2.0
217
+ */const oB="mcp_used/unknown";let iB=!1;function IE(t){for(const e of t)if(sB(e)||typeof e=="object"&&"inputSchema"in e)return!0;return iB}function SE(t){var e;const n=(e=t[dc])!==null&&e!==void 0?e:"";t[dc]=(n+` ${oB}`).trimStart()}function sB(t){return t!==null&&typeof t=="object"&&t instanceof hd}function rB(t){return ln(this,arguments,function*(n,o=100){let i,s=0;for(;s<o;){const r=yield pe(n.listTools({cursor:i}));for(const a of r.tools)yield yield pe(a),s++;if(!r.nextCursor)break;i=r.nextCursor}})}class hd{constructor(e=[],n){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=n}static create(e,n){return new hd(e,n)}async initialize(){var e,n,o,i;if(this.mcpTools.length>0)return;const s={},r=[];for(const p of this.mcpClients)try{for(var a=!0,u=(n=void 0,un(rB(p))),c;c=await u.next(),e=c.done,!e;a=!0){i=c.value,a=!1;const f=i;r.push(f);const h=f.name;if(s[h])throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`);s[h]=p}}catch(f){n={error:f}}finally{try{!a&&!e&&(o=u.return)&&await o.call(u)}finally{if(n)throw n.error}}this.mcpTools=r,this.functionNameToMcpClient=s}async tool(){return await this.initialize(),EG(this.mcpTools,this.config)}async callTool(e){await this.initialize();const n=[];for(const o of e)if(o.name in this.functionNameToMcpClient){const i=this.functionNameToMcpClient[o.name];let s;this.config.timeout&&(s={timeout:this.config.timeout});const r=await i.callTool({name:o.name,arguments:o.args},void 0,s);n.push({functionResponse:{name:o.name,response:r.isError?{error:r}:r}})}return n}}/**
218
+ * @license
219
+ * Copyright 2025 Google LLC
220
+ * SPDX-License-Identifier: Apache-2.0
221
+ */async function aB(t,e,n){const o=new fG;let i;n.data instanceof Blob?i=JSON.parse(await n.data.text()):i=JSON.parse(n.data),Object.assign(o,i),e(o)}class lB{constructor(e,n,o){this.apiClient=e,this.auth=n,this.webSocketFactory=o}async connect(e){var n,o;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");const i=this.apiClient.getWebsocketBaseUrl(),s=this.apiClient.getApiVersion(),r=dB(this.apiClient.getDefaultHeaders()),a=this.apiClient.getApiKey(),u=`${i}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${a}`;let c=()=>{};const p=new Promise(A=>{c=A}),f=e.callbacks,h=function(){c({})},m=this.apiClient,v={onopen:h,onmessage:A=>{aB(m,f.onmessage,A)},onerror:(n=f==null?void 0:f.onerror)!==null&&n!==void 0?n:function(A){},onclose:(o=f==null?void 0:f.onclose)!==null&&o!==void 0?o:function(A){}},_=this.webSocketFactory.create(u,cB(r),v);_.connect(),await p;const E={setup:{model:Pe(this.apiClient,e.model)}};return _.send(JSON.stringify(E)),new uB(_,this.apiClient)}}class uB{constructor(e,n){this.conn=e,this.apiClient=n}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");const n=bF(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});const n=AF(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){const n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(gi.PLAY)}pause(){this.sendPlaybackControl(gi.PAUSE)}stop(){this.sendPlaybackControl(gi.STOP)}resetContext(){this.sendPlaybackControl(gi.RESET_CONTEXT)}close(){this.conn.close()}}function cB(t){const e={};return t.forEach((n,o)=>{e[o]=n}),e}function dB(t){const e=new Headers;for(const[n,o]of Object.entries(t))e.append(n,o);return e}/**
222
+ * @license
223
+ * Copyright 2025 Google LLC
224
+ * SPDX-License-Identifier: Apache-2.0
225
+ */const pB="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function fB(t,e,n){const o=new pG;let i;n.data instanceof Blob?i=await n.data.text():n.data instanceof ArrayBuffer?i=new TextDecoder().decode(n.data):i=n.data;const s=JSON.parse(i);if(t.isVertexAI()){const r=PF(s);Object.assign(o,r)}else Object.assign(o,s);e(o)}class hB{constructor(e,n,o){this.apiClient=e,this.auth=n,this.webSocketFactory=o,this.music=new lB(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,o,i,s,r,a;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");const u=this.apiClient.getWebsocketBaseUrl(),c=this.apiClient.getApiVersion();let p;const f=this.apiClient.getHeaders();e.config&&e.config.tools&&IE(e.config.tools)&&SE(f);const h=yB(f);if(this.apiClient.isVertexAI()){const G=this.apiClient.getProject(),L=this.apiClient.getLocation(),B=this.apiClient.getApiKey(),ve=!!G&&!!L||!!B;this.apiClient.getCustomBaseUrl()&&!ve?p=u:(p=`${u}/ws/google.cloud.aiplatform.${c}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(h,p))}else{const G=this.apiClient.getApiKey();let L="BidiGenerateContent",B="key";G!=null&&G.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),c!=="v1alpha"&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),L="BidiGenerateContentConstrained",B="access_token"),p=`${u}/ws/google.ai.generativelanguage.${c}.GenerativeService.${L}?${B}=${G}`}let m=()=>{};const v=new Promise(G=>{m=G}),_=e.callbacks,w=function(){var G;(G=_==null?void 0:_.onopen)===null||G===void 0||G.call(_),m({})},C=this.apiClient,E={onopen:w,onmessage:G=>{fB(C,_.onmessage,G)},onerror:(n=_==null?void 0:_.onerror)!==null&&n!==void 0?n:function(G){},onclose:(o=_==null?void 0:_.onclose)!==null&&o!==void 0?o:function(G){}},A=this.webSocketFactory.create(p,vB(h),E);A.connect(),await v;let R=Pe(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&R.startsWith("publishers/")){const G=this.apiClient.getProject(),L=this.apiClient.getLocation();G&&L&&(R=`projects/${G}/locations/${L}/`+R)}let k={};this.apiClient.isVertexAI()&&((i=e.config)===null||i===void 0?void 0:i.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[nl.AUDIO]}:e.config.responseModalities=[nl.AUDIO]),!((s=e.config)===null||s===void 0)&&s.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");const b=(a=(r=e.config)===null||r===void 0?void 0:r.tools)!==null&&a!==void 0?a:[],U=[];for(const G of b)if(this.isCallableTool(G)){const L=G;U.push(await L.tool())}else U.push(G);U.length>0&&(e.config.tools=U);const J={model:R,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?k=CF(this.apiClient,J):k=SF(this.apiClient,J),delete k.config,A.send(JSON.stringify(k)),new gB(A,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}}const mB={turnComplete:!0};class gB{constructor(e,n){this.conn=e,this.apiClient=n}tLiveClientContent(e,n){if(n.turns!==null&&n.turns!==void 0){let o=[];try{o=Ut(n.turns),e.isVertexAI()||(o=o.map(i=>ra(i)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof n.turns}'`)}return{clientContent:{turns:o,turnComplete:n.turnComplete}}}return{clientContent:{turnComplete:n.turnComplete}}}tLiveClienttToolResponse(e,n){let o=[];if(n.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(n.functionResponses)?o=n.functionResponses:o=[n.functionResponses],o.length===0)throw new Error("functionResponses is required.");for(const s of o){if(typeof s!="object"||s===null||!("name"in s)||!("response"in s))throw new Error(`Could not parse function response, type '${typeof s}'.`);if(!e.isVertexAI()&&!("id"in s))throw new Error(pB)}return{toolResponse:{functionResponses:o}}}sendClientContent(e){e=Object.assign(Object.assign({},mB),e);const n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:kF(e)}:n={realtimeInput:RF(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");const n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}}function vB(t){const e={};return t.forEach((n,o)=>{e[o]=n}),e}function yB(t){const e=new Headers;for(const[n,o]of Object.entries(t))e.append(n,o);return e}/**
226
+ * @license
227
+ * Copyright 2025 Google LLC
228
+ * SPDX-License-Identifier: Apache-2.0
229
+ */const km=10;function Pm(t){var e,n,o;if(!((e=t==null?void 0:t.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let i=!1;for(const r of(n=t==null?void 0:t.tools)!==null&&n!==void 0?n:[])if(Ei(r)){i=!0;break}if(!i)return!0;const s=(o=t==null?void 0:t.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls;return s&&(s<0||!Number.isInteger(s))||s==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",s),!0):!1}function Ei(t){return"callTool"in t&&typeof t.callTool=="function"}function _B(t){var e,n,o;return(o=(n=(e=t.config)===null||e===void 0?void 0:e.tools)===null||n===void 0?void 0:n.some(i=>Ei(i)))!==null&&o!==void 0?o:!1}function Nm(t){var e;const n=[];return!((e=t==null?void 0:t.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((o,i)=>{if(Ei(o))return;const s=o;s.functionDeclarations&&s.functionDeclarations.length>0&&n.push(i)}),n}function Mm(t){var e;return!(!((e=t==null?void 0:t.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}/**
230
+ * @license
231
+ * Copyright 2025 Google LLC
232
+ * SPDX-License-Identifier: Apache-2.0
233
+ */class TB extends Qn{constructor(e){super(),this.apiClient=e,this.embedContent=async n=>{if(!this.apiClient.isVertexAI())return n.model.includes("gemini-embedding-2")&&(n.contents=Ut(n.contents)),await this.embedContentInternal(n);if(n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas")){const i=Ut(n.contents);if(i.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");const s=Object.assign(Object.assign({},n),{content:i[0],embeddingApiType:ol.EMBED_CONTENT});return await this.embedContentInternal(s)}else{const i=Object.assign(Object.assign({},n),{embeddingApiType:ol.PREDICT});return await this.embedContentInternal(i)}},this.generateContent=async n=>{var o,i,s,r,a;const u=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchem(n),!_B(n)||Pm(n.config))return await this.generateContentInternal(u);const c=Nm(n);if(c.length>0){const _=c.map(w=>`tools[${w}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${_}.`)}let p,f;const h=Ut(u.contents),m=(s=(i=(o=u.config)===null||o===void 0?void 0:o.automaticFunctionCalling)===null||i===void 0?void 0:i.maximumRemoteCalls)!==null&&s!==void 0?s:km;let v=0;for(;v<m&&(p=await this.generateContentInternal(u),!(!p.functionCalls||p.functionCalls.length===0));){const _=p.candidates[0].content,w=[];for(const C of(a=(r=n.config)===null||r===void 0?void 0:r.tools)!==null&&a!==void 0?a:[])if(Ei(C)){const A=await C.callTool(p.functionCalls);w.push(...A)}v++,f={role:"user",parts:w},u.contents=Ut(u.contents),u.contents.push(_),u.contents.push(f),Mm(u.config)&&(h.push(_),h.push(f))}return Mm(u.config)&&(p.automaticFunctionCallingHistory=h),p},this.generateContentStream=async n=>{var o,i,s,r,a;if(this.maybeMoveToResponseJsonSchem(n),Pm(n.config)){const f=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(f)}const u=Nm(n);if(u.length>0){const f=u.map(h=>`tools[${h}]`).join(", ");throw new Error(`Incompatible tools found at ${f}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}const c=(s=(i=(o=n==null?void 0:n.config)===null||o===void 0?void 0:o.toolConfig)===null||i===void 0?void 0:i.functionCallingConfig)===null||s===void 0?void 0:s.streamFunctionCallArguments,p=(a=(r=n==null?void 0:n.config)===null||r===void 0?void 0:r.automaticFunctionCalling)===null||a===void 0?void 0:a.disable;if(c&&!p)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(n)},this.generateImages=async n=>await this.generateImagesInternal(n).then(o=>{var i;let s;const r=[];if(o!=null&&o.generatedImages)for(const u of o.generatedImages)u&&(u!=null&&u.safetyAttributes)&&((i=u==null?void 0:u.safetyAttributes)===null||i===void 0?void 0:i.contentType)==="Positive Prompt"?s=u==null?void 0:u.safetyAttributes:r.push(u);let a;return s?a={generatedImages:r,positivePromptSafetyAttributes:s,sdkHttpResponse:o.sdkHttpResponse}:a={generatedImages:r,sdkHttpResponse:o.sdkHttpResponse},a}),this.list=async n=>{var o;const r={config:Object.assign(Object.assign({},{queryBase:!0}),n==null?void 0:n.config)};if(this.apiClient.isVertexAI()&&!r.config.queryBase){if(!((o=r.config)===null||o===void 0)&&o.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");r.config.filter="labels.tune-type:*"}return new ai(Yn.PAGED_ITEM_MODELS,a=>this.listInternal(a),await this.listInternal(r),r)},this.editImage=async n=>{const o={model:n.model,prompt:n.prompt,referenceImages:[],config:n.config};return n.referenceImages&&n.referenceImages&&(o.referenceImages=n.referenceImages.map(i=>i.toReferenceImageAPI())),await this.editImageInternal(o)},this.upscaleImage=async n=>{let o={numberOfImages:1,mode:"upscale"};n.config&&(o=Object.assign(Object.assign({},o),n.config));const i={model:n.model,image:n.image,upscaleFactor:n.upscaleFactor,config:o};return await this.upscaleImageInternal(i)},this.generateVideos=async n=>{var o,i,s,r,a,u;if((n.prompt||n.image||n.video)&&n.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return this.apiClient.isVertexAI()||(!((o=n.video)===null||o===void 0)&&o.uri&&(!((i=n.video)===null||i===void 0)&&i.videoBytes)?n.video={uri:n.video.uri,mimeType:n.video.mimeType}:!((r=(s=n.source)===null||s===void 0?void 0:s.video)===null||r===void 0)&&r.uri&&(!((u=(a=n.source)===null||a===void 0?void 0:a.video)===null||u===void 0)&&u.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var n,o,i;const s=(n=e.config)===null||n===void 0?void 0:n.tools;if(!s)return e;const r=await Promise.all(s.map(async u=>Ei(u)?await u.tool():u)),a={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:r})};if(a.config.tools=r,e.config&&e.config.tools&&IE(e.config.tools)){const u=(i=(o=e.config.httpOptions)===null||o===void 0?void 0:o.headers)!==null&&i!==void 0?i:{};let c=Object.assign({},u);Object.keys(c).length===0&&(c=this.apiClient.getDefaultHeaders()),SE(c),a.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:c})}return a}async initAfcToolsMap(e){var n,o,i;const s=new Map;for(const r of(o=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&o!==void 0?o:[])if(Ei(r)){const a=r,u=await a.tool();for(const c of(i=u.functionDeclarations)!==null&&i!==void 0?i:[]){if(!c.name)throw new Error("Function declaration name is required.");if(s.has(c.name))throw new Error(`Duplicate tool declaration name: ${c.name}`);s.set(c.name,a)}}return s}async processAfcStream(e){var n,o,i;const s=(i=(o=(n=e.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&i!==void 0?i:km;let r=!1,a=0;const u=await this.initAfcToolsMap(e);return(function(c,p,f){return ln(this,arguments,function*(){for(var h,m,v,_,w,C;a<s;){r&&(a++,r=!1);const k=yield pe(c.processParamsMaybeAddMcpUsage(f)),b=yield pe(c.generateContentStreamInternal(k)),U=[],J=[];try{for(var E=!0,A=(m=void 0,un(b)),R;R=yield pe(A.next()),h=R.done,!h;E=!0){_=R.value,E=!1;const G=_;if(yield yield pe(G),G.candidates&&(!((w=G.candidates[0])===null||w===void 0)&&w.content)){J.push(G.candidates[0].content);for(const L of(C=G.candidates[0].content.parts)!==null&&C!==void 0?C:[])if(a<s&&L.functionCall){if(!L.functionCall.name)throw new Error("Function call name was not returned by the model.");if(p.has(L.functionCall.name)){const B=yield pe(p.get(L.functionCall.name).callTool([L.functionCall]));U.push(...B)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${p.keys()}, mising tool: ${L.functionCall.name}`)}}}}catch(G){m={error:G}}finally{try{!E&&!h&&(v=A.return)&&(yield pe(v.call(A)))}finally{if(m)throw m.error}}if(U.length>0){r=!0;const G=new ds;G.candidates=[{content:{role:"user",parts:U}}],yield yield pe(G);const L=[];L.push(...J),L.push({role:"user",parts:U});const B=Ut(f.contents).concat(L);f.contents=B}else break}})})(this,u,e)}async generateContentInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=Cm(this.apiClient,e);return a=Q("{model}:generateContent",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=bm(p),h=new ds;return Object.assign(h,f),h})}else{const c=Sm(this.apiClient,e);return a=Q("{model}:generateContent",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=Am(p),h=new ds;return Object.assign(h,f),h})}}async generateContentStreamInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=Cm(this.apiClient,e);return a=Q("{model}:streamGenerateContent?alt=sse",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.requestStream({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}),r.then(function(f){return ln(this,arguments,function*(){var h,m,v,_;try{for(var w=!0,C=un(f),E;E=yield pe(C.next()),h=E.done,!h;w=!0){_=E.value,w=!1;const A=_,R=bm(yield pe(A.json()),e);R.sdkHttpResponse={headers:A.headers};const k=new ds;Object.assign(k,R),yield yield pe(k)}}catch(A){m={error:A}}finally{try{!w&&!h&&(v=C.return)&&(yield pe(v.call(C)))}finally{if(m)throw m.error}}})})}else{const c=Sm(this.apiClient,e);return a=Q("{model}:streamGenerateContent?alt=sse",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.requestStream({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}),r.then(function(f){return ln(this,arguments,function*(){var h,m,v,_;try{for(var w=!0,C=un(f),E;E=yield pe(C.next()),h=E.done,!h;w=!0){_=E.value,w=!1;const A=_,R=Am(yield pe(A.json()),e);R.sdkHttpResponse={headers:A.headers};const k=new ds;Object.assign(k,R),yield yield pe(k)}}catch(A){m={error:A}}finally{try{!w&&!h&&(v=C.return)&&(yield pe(v.call(C)))}finally{if(m)throw m.error}}})})}}async embedContentInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=cV(this.apiClient,e,e),p=IG(e.model)?"{model}:embedContent":"{model}:predict";return a=Q(p,c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(h=>{const m=h;return m.sdkHttpResponse={headers:f.headers},m})),r.then(f=>{const h=pV(f,e),m=new rm;return Object.assign(m,h),m})}else{const c=uV(this.apiClient,e);return a=Q("{model}:batchEmbedContents",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=dV(p),h=new rm;return Object.assign(h,f),h})}}async generateImagesInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=wV(this.apiClient,e);return a=Q("{model}:predict",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=SV(p),h=new am;return Object.assign(h,f),h})}else{const c=EV(this.apiClient,e);return a=Q("{model}:predict",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=IV(p),h=new am;return Object.assign(h,f),h})}}async editImageInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI()){const a=sV(this.apiClient,e);return s=Q("{model}:predict",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json().then(c=>{const p=c;return p.sdkHttpResponse={headers:u.headers},p})),i.then(u=>{const c=rV(u),p=new j1;return Object.assign(p,c),p})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI()){const a=Sq(this.apiClient,e);return s=Q("{model}:predict",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json().then(c=>{const p=c;return p.sdkHttpResponse={headers:u.headers},p})),i.then(u=>{const c=Cq(u),p=new eG;return Object.assign(p,c),p})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI()){const a=iq(this.apiClient,e);return s=Q("{model}:predict",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>{const c=sq(u),p=new tG;return Object.assign(p,c),p})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI()){const a=dq(this.apiClient,e);return s=Q("{model}:predict",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>{const c=pq(u),p=new nG;return Object.assign(p,c),p})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=FV(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),r.then(p=>cc(p))}else{const c=zV(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json()),r.then(p=>uc(p))}}async listInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=YV(this.apiClient,e);return a=Q("{models_url}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=QV(p),h=new lm;return Object.assign(h,f),h})}else{const c=KV(this.apiClient,e);return a=Q("{models_url}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=XV(p),h=new lm;return Object.assign(h,f),h})}}async update(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=wq(this.apiClient,e);return a=Q("{model}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),r.then(p=>cc(p))}else{const c=Eq(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"PATCH",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json()),r.then(p=>uc(p))}}async delete(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=tV(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=oV(p),h=new um;return Object.assign(h,f),h})}else{const c=eV(this.apiClient,e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"DELETE",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=nV(p),h=new um;return Object.assign(h,f),h})}}async countTokens(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=XF(this.apiClient,e);return a=Q("{model}:countTokens",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=jF(p),h=new cm;return Object.assign(h,f),h})}else{const c=YF(this.apiClient,e);return a=Q("{model}:countTokens",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=QF(p),h=new cm;return Object.assign(h,f),h})}}async computeTokens(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI()){const a=qF(this.apiClient,e);return s=Q("{model}:computeTokens",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json().then(c=>{const p=c;return p.sdkHttpResponse={headers:u.headers},p})),i.then(u=>{const c=BF(u),p=new oG;return Object.assign(p,c),p})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=PV(this.apiClient,e);return a=Q("{model}:predictLongRunning",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),r.then(p=>{const f=RV(p),h=new sl;return Object.assign(h,f),h})}else{const c=kV(this.apiClient,e);return a=Q("{model}:predictLongRunning",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json()),r.then(p=>{const f=bV(p),h=new sl;return Object.assign(h,f),h})}}}/**
234
+ * @license
235
+ * Copyright 2025 Google LLC
236
+ * SPDX-License-Identifier: Apache-2.0
237
+ */class EB extends Qn{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){const n=e.operation,o=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const i=n.name.split("/operations/")[0];let s;o&&"httpOptions"in o&&(s=o.httpOptions);const r=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:s}});return n._fromAPIResponse({apiResponse:r,_isVertexAI:!0})}else{const i=await this.getVideosOperationInternal({operationName:n.name,config:o});return n._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async get(e){const n=e.operation,o=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const i=n.name.split("/operations/")[0];let s;o&&"httpOptions"in o&&(s=o.httpOptions);const r=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:i,config:{httpOptions:s}});return n._fromAPIResponse({apiResponse:r,_isVertexAI:!0})}else{const i=await this.getVideosOperationInternal({operationName:n.name,config:o});return n._fromAPIResponse({apiResponse:i,_isVertexAI:!1})}}async getVideosOperationInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=J1(e);return a=Q("{operationName}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json()),r}else{const c=Z1(e);return a=Q("{operationName}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json()),r}}async fetchPredictVideosOperationInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI()){const a=G1(e);return s=Q("{resourceName}:fetchPredictOperation",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}/**
238
+ * @license
239
+ * Copyright 2025 Google LLC
240
+ * SPDX-License-Identifier: Apache-2.0
241
+ */function xm(t){const e={};if(l(t,["languageCodes"])!==void 0)throw new Error("languageCodes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function wB(t){const e={},n=l(t,["apiKey"]);if(n!=null&&d(e,["apiKey"],n),l(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function IB(t){const e={},n=l(t,["data"]);if(n!=null&&d(e,["data"],n),l(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["mimeType"]);return o!=null&&d(e,["mimeType"],o),e}function SB(t){const e={},n=l(t,["parts"]);if(n!=null){let i=n;Array.isArray(i)&&(i=i.map(s=>xB(s))),d(e,["parts"],i)}const o=l(t,["role"]);return o!=null&&d(e,["role"],o),e}function CB(t,e,n){const o={},i=l(e,["expireTime"]);n!==void 0&&i!=null&&d(n,["expireTime"],i);const s=l(e,["newSessionExpireTime"]);n!==void 0&&s!=null&&d(n,["newSessionExpireTime"],s);const r=l(e,["uses"]);n!==void 0&&r!=null&&d(n,["uses"],r);const a=l(e,["liveConnectConstraints"]);n!==void 0&&a!=null&&d(n,["bidiGenerateContentSetup"],MB(t,a));const u=l(e,["lockAdditionalFields"]);return n!==void 0&&u!=null&&d(n,["fieldMask"],u),o}function AB(t,e){const n={},o=l(e,["config"]);return o!=null&&d(n,["config"],CB(t,o,n)),n}function bB(t){const e={};if(l(t,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=l(t,["fileUri"]);n!=null&&d(e,["fileUri"],n);const o=l(t,["mimeType"]);return o!=null&&d(e,["mimeType"],o),e}function RB(t){const e={},n=l(t,["id"]);n!=null&&d(e,["id"],n);const o=l(t,["args"]);o!=null&&d(e,["args"],o);const i=l(t,["name"]);if(i!=null&&d(e,["name"],i),l(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function kB(t){const e={},n=l(t,["authConfig"]);n!=null&&d(e,["authConfig"],wB(n));const o=l(t,["enableWidget"]);return o!=null&&d(e,["enableWidget"],o),e}function PB(t){const e={},n=l(t,["searchTypes"]);if(n!=null&&d(e,["searchTypes"],n),l(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["timeRangeFilter"]);return o!=null&&d(e,["timeRangeFilter"],o),e}function NB(t,e){const n={},o=l(t,["generationConfig"]);e!==void 0&&o!=null&&d(e,["setup","generationConfig"],o);const i=l(t,["responseModalities"]);e!==void 0&&i!=null&&d(e,["setup","generationConfig","responseModalities"],i);const s=l(t,["temperature"]);e!==void 0&&s!=null&&d(e,["setup","generationConfig","temperature"],s);const r=l(t,["topP"]);e!==void 0&&r!=null&&d(e,["setup","generationConfig","topP"],r);const a=l(t,["topK"]);e!==void 0&&a!=null&&d(e,["setup","generationConfig","topK"],a);const u=l(t,["maxOutputTokens"]);e!==void 0&&u!=null&&d(e,["setup","generationConfig","maxOutputTokens"],u);const c=l(t,["mediaResolution"]);e!==void 0&&c!=null&&d(e,["setup","generationConfig","mediaResolution"],c);const p=l(t,["seed"]);e!==void 0&&p!=null&&d(e,["setup","generationConfig","seed"],p);const f=l(t,["speechConfig"]);e!==void 0&&f!=null&&d(e,["setup","generationConfig","speechConfig"],fd(f));const h=l(t,["thinkingConfig"]);e!==void 0&&h!=null&&d(e,["setup","generationConfig","thinkingConfig"],h);const m=l(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&d(e,["setup","generationConfig","enableAffectiveDialog"],m);const v=l(t,["systemInstruction"]);e!==void 0&&v!=null&&d(e,["setup","systemInstruction"],SB(_t(v)));const _=l(t,["tools"]);if(e!==void 0&&_!=null){let G=ns(_);Array.isArray(G)&&(G=G.map(L=>UB(ts(L)))),d(e,["setup","tools"],G)}const w=l(t,["sessionResumption"]);e!==void 0&&w!=null&&d(e,["setup","sessionResumption"],$B(w));const C=l(t,["inputAudioTranscription"]);e!==void 0&&C!=null&&d(e,["setup","inputAudioTranscription"],xm(C));const E=l(t,["outputAudioTranscription"]);e!==void 0&&E!=null&&d(e,["setup","outputAudioTranscription"],xm(E));const A=l(t,["realtimeInputConfig"]);e!==void 0&&A!=null&&d(e,["setup","realtimeInputConfig"],A);const R=l(t,["contextWindowCompression"]);e!==void 0&&R!=null&&d(e,["setup","contextWindowCompression"],R);const k=l(t,["proactivity"]);if(e!==void 0&&k!=null&&d(e,["setup","proactivity"],k),l(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const b=l(t,["avatarConfig"]);e!==void 0&&b!=null&&d(e,["setup","avatarConfig"],b);const U=l(t,["safetySettings"]);if(e!==void 0&&U!=null){let G=U;Array.isArray(G)&&(G=G.map(L=>DB(L))),d(e,["setup","safetySettings"],G)}const J=l(t,["streamTranslationConfig"]);return e!==void 0&&J!=null&&d(e,["setup","generationConfig","streamTranslationConfig"],J),n}function MB(t,e){const n={},o=l(e,["model"]);o!=null&&d(n,["setup","model"],Pe(t,o));const i=l(e,["config"]);return i!=null&&d(n,["config"],NB(i,n)),n}function xB(t){const e={},n=l(t,["mediaResolution"]);n!=null&&d(e,["mediaResolution"],n);const o=l(t,["codeExecutionResult"]);o!=null&&d(e,["codeExecutionResult"],o);const i=l(t,["executableCode"]);i!=null&&d(e,["executableCode"],i);const s=l(t,["fileData"]);s!=null&&d(e,["fileData"],bB(s));const r=l(t,["functionCall"]);r!=null&&d(e,["functionCall"],RB(r));const a=l(t,["functionResponse"]);a!=null&&d(e,["functionResponse"],a);const u=l(t,["inlineData"]);u!=null&&d(e,["inlineData"],IB(u));const c=l(t,["text"]);c!=null&&d(e,["text"],c);const p=l(t,["thought"]);p!=null&&d(e,["thought"],p);const f=l(t,["thoughtSignature"]);f!=null&&d(e,["thoughtSignature"],f);const h=l(t,["videoMetadata"]);h!=null&&d(e,["videoMetadata"],h);const m=l(t,["toolCall"]);m!=null&&d(e,["toolCall"],m);const v=l(t,["toolResponse"]);v!=null&&d(e,["toolResponse"],v);const _=l(t,["partMetadata"]);return _!=null&&d(e,["partMetadata"],_),e}function DB(t){const e={},n=l(t,["category"]);if(n!=null&&d(e,["category"],n),l(t,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["threshold"]);return o!=null&&d(e,["threshold"],o),e}function $B(t){const e={},n=l(t,["handle"]);if(n!=null&&d(e,["handle"],n),l(t,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return e}function UB(t){const e={};if(l(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=l(t,["computerUse"]);n!=null&&d(e,["computerUse"],n);const o=l(t,["fileSearch"]);o!=null&&d(e,["fileSearch"],o);const i=l(t,["googleSearch"]);i!=null&&d(e,["googleSearch"],PB(i));const s=l(t,["googleMaps"]);s!=null&&d(e,["googleMaps"],kB(s));const r=l(t,["codeExecution"]);if(r!=null&&d(e,["codeExecution"],r),l(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const a=l(t,["functionDeclarations"]);if(a!=null){let f=a;Array.isArray(f)&&(f=f.map(h=>h)),d(e,["functionDeclarations"],f)}const u=l(t,["googleSearchRetrieval"]);if(u!=null&&d(e,["googleSearchRetrieval"],u),l(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const c=l(t,["urlContext"]);c!=null&&d(e,["urlContext"],c);const p=l(t,["mcpServers"]);if(p!=null){let f=p;Array.isArray(f)&&(f=f.map(h=>h)),d(e,["mcpServers"],f)}return e}/**
242
+ * @license
243
+ * Copyright 2025 Google LLC
244
+ * SPDX-License-Identifier: Apache-2.0
245
+ */function OB(t){const e=[];for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(typeof o=="object"&&o!=null&&Object.keys(o).length>0){const i=Object.keys(o).map(s=>`${n}.${s}`);e.push(...i)}else e.push(n)}return e.join(",")}function LB(t,e){let n=null;const o=t.bidiGenerateContentSetup;if(typeof o=="object"&&o!==null&&"setup"in o){const s=o.setup;typeof s=="object"&&s!==null?(t.bidiGenerateContentSetup=s,n=s):delete t.bidiGenerateContentSetup}else o!==void 0&&delete t.bidiGenerateContentSetup;const i=t.fieldMask;if(n){const s=OB(n);if(Array.isArray(e==null?void 0:e.lockAdditionalFields)&&(e==null?void 0:e.lockAdditionalFields.length)===0)s?t.fieldMask=s:delete t.fieldMask;else if(e!=null&&e.lockAdditionalFields&&e.lockAdditionalFields.length>0&&i!==null&&Array.isArray(i)&&i.length>0){const r=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let a=[];i.length>0&&(a=i.map(c=>r.includes(c)?`generationConfig.${c}`:c));const u=[];s&&u.push(s),a.length>0&&u.push(...a),u.length>0?t.fieldMask=u.join(","):delete t.fieldMask}else delete t.fieldMask}else i!==null&&Array.isArray(i)&&i.length>0?t.fieldMask=i.join(","):delete t.fieldMask;return t}class GB extends Qn{constructor(e){super(),this.apiClient=e}async create(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{const a=AB(this.apiClient,e);s=Q("auth_tokens",a._url),r=a._query,delete a.config,delete a._url,delete a._query;const u=LB(a,e.config);return i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),i.then(c=>c)}}}/**
246
+ * @license
247
+ * Copyright 2025 Google LLC
248
+ * SPDX-License-Identifier: Apache-2.0
249
+ */function zB(t,e){const n={},o=l(t,["force"]);return e!==void 0&&o!=null&&d(e,["_query","force"],o),n}function FB(t){const e={},n=l(t,["name"]);n!=null&&d(e,["_url","name"],n);const o=l(t,["config"]);return o!=null&&zB(o,e),e}function VB(t){const e={},n=l(t,["name"]);return n!=null&&d(e,["_url","name"],n),e}function qB(t,e){const n={},o=l(t,["pageSize"]);e!==void 0&&o!=null&&d(e,["_query","pageSize"],o);const i=l(t,["pageToken"]);return e!==void 0&&i!=null&&d(e,["_query","pageToken"],i),n}function BB(t){const e={},n=l(t,["parent"]);n!=null&&d(e,["_url","parent"],n);const o=l(t,["config"]);return o!=null&&qB(o,e),e}function HB(t){const e={},n=l(t,["sdkHttpResponse"]);n!=null&&d(e,["sdkHttpResponse"],n);const o=l(t,["nextPageToken"]);o!=null&&d(e,["nextPageToken"],o);const i=l(t,["documents"]);if(i!=null){let s=i;Array.isArray(s)&&(s=s.map(r=>r)),d(e,["documents"],s)}return e}/**
250
+ * @license
251
+ * Copyright 2025 Google LLC
252
+ * SPDX-License-Identifier: Apache-2.0
253
+ */class ZB extends Qn{constructor(e){super(),this.apiClient=e,this.list=async n=>new ai(Yn.PAGED_ITEM_DOCUMENTS,o=>this.listInternal({parent:n.parent,config:o.config}),await this.listInternal(n),n)}async get(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=VB(e);return s=Q("{name}",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>u)}}async delete(e){var n,o;let i="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const r=FB(e);i=Q("{name}",r._url),s=r._query,delete r._url,delete r._query,await this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(r),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=BB(e);return s=Q("{parent}/documents",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>{const c=HB(u),p=new sG;return Object.assign(p,c),p})}}}/**
254
+ * @license
255
+ * Copyright 2025 Google LLC
256
+ * SPDX-License-Identifier: Apache-2.0
257
+ */class JB extends Qn{constructor(e,n=new ZB(e)){super(),this.apiClient=e,this.documents=n,this.list=async(o={})=>new ai(Yn.PAGED_ITEM_FILE_SEARCH_STORES,i=>this.listInternal(i),await this.listInternal(o),o)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async downloadMedia(e,n){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");const o=new URL(e,"http://dummy.com");let i=o.pathname;if(i.startsWith("/")&&(i=i.slice(1)),!i.includes("/media/"))throw new Error(`Invalid uri format: ${e}. Expected to contain /media/`);const s={};o.searchParams.forEach((u,c)=>{s[c]=u}),s.alt="media";const r=Object.assign({},n==null?void 0:n.httpOptions),a=await this.apiClient.request({path:i,httpMethod:"GET",queryParams:s,httpOptions:r});if(a instanceof il){const u=await a.responseInternal.arrayBuffer();return new Uint8Array(u)}else throw new Error("Unexpected response type from downloadMedia")}async create(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=Mq(this.apiClient,e);return s=Q("fileSearchStores",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>u)}}async get(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=$q(e);return s=Q("{name}",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>u)}}async delete(e){var n,o;let i="",s={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const r=Dq(e);i=Q("{name}",r._url),s=r._query,delete r._url,delete r._query,await this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(r),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=Fq(e);return s=Q("fileSearchStores",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>{const c=Vq(u),p=new rG;return Object.assign(p,c),p})}}async uploadToFileSearchStoreInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=qq(e);return s=Q("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>{const c=Bq(u),p=new aG;return Object.assign(p,c),p})}}async importFile(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=Lq(e);return s=Q("{file_search_store_name}:importFile",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json()),i.then(u=>{const c=Oq(u),p=new ld;return Object.assign(p,c),p})}}}/**
258
+ * @license
259
+ * Copyright 2025 Google LLC
260
+ * SPDX-License-Identifier: Apache-2.0
261
+ */let CE=function(){const{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return CE=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,o=>(+o^n()&15>>+o/4).toString(16))};const WB=()=>CE();/**
262
+ * @license
263
+ * Copyright 2025 Google LLC
264
+ * SPDX-License-Identifier: Apache-2.0
265
+ */function pc(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const fc=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};/**
266
+ * @license
267
+ * Copyright 2025 Google LLC
268
+ * SPDX-License-Identifier: Apache-2.0
269
+ */class dn extends Error{}class $t extends dn{constructor(e,n,o,i){super(`${$t.makeMessage(e,n,o)}`),this.status=e,this.headers=i,this.error=n}static makeMessage(e,n,o){const i=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):o;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,n,o,i){if(!e||!i)return new Wl({message:o,cause:fc(n)});const s=n;return e===400?new bE(e,s,o,i):e===401?new RE(e,s,o,i):e===403?new kE(e,s,o,i):e===404?new PE(e,s,o,i):e===409?new NE(e,s,o,i):e===422?new ME(e,s,o,i):e===429?new xE(e,s,o,i):e>=500?new DE(e,s,o,i):new $t(e,s,o,i)}}class hc extends $t{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Wl extends $t{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class AE extends Wl{constructor({message:e}={}){super({message:e??"Request timed out."})}}class bE extends $t{}class RE extends $t{}class kE extends $t{}class PE extends $t{}class NE extends $t{}class ME extends $t{}class xE extends $t{}class DE extends $t{}/**
270
+ * @license
271
+ * Copyright 2025 Google LLC
272
+ * SPDX-License-Identifier: Apache-2.0
273
+ */const KB=/^[a-z][a-z0-9+.-]*:/i,YB=t=>KB.test(t);let mc=t=>(mc=Array.isArray,mc(t));const XB=mc;let QB=XB;const Dm=QB;function $m(t){if(!t)return!0;for(const e in t)return!1;return!0}function jB(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const eH=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new dn(`${t} must be an integer`);if(e<0)throw new dn(`${t} must be a positive integer`);return e},tH=t=>{try{return JSON.parse(t)}catch{return}};/**
274
+ * @license
275
+ * Copyright 2025 Google LLC
276
+ * SPDX-License-Identifier: Apache-2.0
277
+ */const nH=t=>new Promise(e=>setTimeout(e,t));/**
278
+ * @license
279
+ * Copyright 2025 Google LLC
280
+ * SPDX-License-Identifier: Apache-2.0
281
+ */function oH(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function $E(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function iH(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return $E({start(){},async pull(n){const{done:o,value:i}=await e.next();o?n.close():n.enqueue(i)},async cancel(){var n;await((n=e.return)===null||n===void 0?void 0:n.call(e))}})}function UE(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n!=null&&n.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function sH(t){var e,n;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((n=(e=t[Symbol.asyncIterator]()).return)===null||n===void 0?void 0:n.call(e));return}const o=t.getReader(),i=o.cancel();o.releaseLock(),await i}/**
282
+ * @license
283
+ * Copyright 2025 Google LLC
284
+ * SPDX-License-Identifier: Apache-2.0
285
+ */const rH=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});/**
286
+ * @license
287
+ * Copyright 2025 Google LLC
288
+ * SPDX-License-Identifier: Apache-2.0
289
+ */function aH(t){return Object.entries(t).filter(([e,n])=>typeof n<"u").map(([e,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(e)}=`;throw new dn(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}/**
290
+ * @license
291
+ * Copyright 2025 Google LLC
292
+ * SPDX-License-Identifier: Apache-2.0
293
+ */const lH="0.0.1";/**
294
+ * @license
295
+ * Copyright 2025 Google LLC
296
+ * SPDX-License-Identifier: Apache-2.0
297
+ */const OE=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e==null?void 0:e.versions)===null||t===void 0?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Tu(t,e,n){return OE(),new File(t,e??"unknown_file",n)}function uH(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const cH=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";/**
298
+ * @license
299
+ * Copyright 2025 Google LLC
300
+ * SPDX-License-Identifier: Apache-2.0
301
+ */const LE=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",dH=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&LE(t),pH=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function fH(t,e,n){if(OE(),t=await t,dH(t))return t instanceof File?t:Tu([await t.arrayBuffer()],t.name);if(pH(t)){const i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Tu(await gc(i),e,n)}const o=await gc(t);if(e||(e=uH(t)),!(n!=null&&n.type)){const i=o.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(n=Object.assign(Object.assign({},n),{type:i}))}return Tu(o,e,n)}async function gc(t){var e,n,o,i,s;let r=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)r.push(t);else if(LE(t))r.push(t instanceof Blob?t:await t.arrayBuffer());else if(cH(t))try{for(var a=!0,u=un(t),c;c=await u.next(),e=c.done,!e;a=!0){i=c.value,a=!1;const p=i;r.push(...await gc(p))}}catch(p){n={error:p}}finally{try{!a&&!e&&(o=u.return)&&await o.call(u)}finally{if(n)throw n.error}}else{const p=(s=t==null?void 0:t.constructor)===null||s===void 0?void 0:s.name;throw new Error(`Unexpected data type: ${typeof t}${p?`; constructor: ${p}`:""}${hH(t)}`)}return r}function hH(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}/**
302
+ * @license
303
+ * Copyright 2025 Google LLC
304
+ * SPDX-License-Identifier: Apache-2.0
305
+ */class md{constructor(e){this._client=e}}md._key=[];/**
306
+ * @license
307
+ * Copyright 2025 Google LLC
308
+ * SPDX-License-Identifier: Apache-2.0
309
+ */function mH(t){let e=0;for(const i of t)e+=i.length;const n=new Uint8Array(e);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}let Ia;function gd(t){let e;return(Ia??(e=new globalThis.TextEncoder,Ia=e.encode.bind(e)))(t)}let Sa;function Um(t){let e;return(Sa??(e=new globalThis.TextDecoder,Sa=e.decode.bind(e)))(t)}/**
310
+ * @license
311
+ * Copyright 2025 Google LLC
312
+ * SPDX-License-Identifier: Apache-2.0
313
+ */class Kl{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null,this.searchIndex=0}decode(e){var n;if(e==null)return[];const o=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gd(e):e;this.buffer=mH([this.buffer,o]);const i=[];let s;for(;(s=gH(this.buffer,(n=this.carriageReturnIndex)!==null&&n!==void 0?n:this.searchIndex))!=null;){if(s.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=s.index;continue}if(this.carriageReturnIndex!=null&&(s.index!==this.carriageReturnIndex+1||s.carriage)){i.push(Um(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null,this.searchIndex=0;continue}const r=this.carriageReturnIndex!==null?s.preceding-1:s.preceding,a=Um(this.buffer.subarray(0,r));i.push(a),this.buffer=this.buffer.subarray(s.index),this.carriageReturnIndex=null,this.searchIndex=0}return this.searchIndex=Math.max(0,this.buffer.length-1),i}flush(){return this.buffer.length?this.decode(`
314
+ `):[]}}Kl.NEWLINE_CHARS=new Set([`
315
+ `,"\r"]);Kl.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function gH(t,e){const i=e??0,s=t.indexOf(10,i),r=t.indexOf(13,i);if(s===-1&&r===-1)return null;let a;return s!==-1&&r!==-1?a=Math.min(s,r):a=s!==-1?s:r,t[a]===10?{preceding:a,index:a+1,carriage:!1}:{preceding:a,index:a+1,carriage:!0}}/**
316
+ * @license
317
+ * Copyright 2025 Google LLC
318
+ * SPDX-License-Identifier: Apache-2.0
319
+ */const al={off:0,error:200,warn:300,info:400,debug:500},Om=(t,e,n)=>{if(t){if(jB(al,t))return t;Mt(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(al))}`)}};function _s(){}function Ca(t,e,n){return!e||al[t]>al[n]?_s:e[t].bind(e)}const vH={error:_s,warn:_s,info:_s,debug:_s};let Lm=new WeakMap;function Mt(t){var e;const n=t.logger,o=(e=t.logLevel)!==null&&e!==void 0?e:"off";if(!n)return vH;const i=Lm.get(n);if(i&&i[0]===o)return i[1];const s={error:Ca("error",n,o),warn:Ca("warn",n,o),info:Ca("info",n,o),debug:Ca("debug",n,o)};return Lm.set(n,[o,s]),s}const Lo=t=>(t.options&&(t.options=Object.assign({},t.options),delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-goog-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);/**
320
+ * @license
321
+ * Copyright 2025 Google LLC
322
+ * SPDX-License-Identifier: Apache-2.0
323
+ */class _o{constructor(e,n,o){this.iterator=e,this.controller=n,this.client=o}static fromSSEResponse(e,n,o){let i=!1;const s=o?Mt(o):console;function r(){return ln(this,arguments,function*(){var u,c,p,f;if(i)throw new dn("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let h=!1;try{try{for(var m=!0,v=un(yH(e,n)),_;_=yield pe(v.next()),u=_.done,!u;m=!0){f=_.value,m=!1;const w=f;if(!h)if(w.data.startsWith("[DONE]")){h=!0;continue}else try{yield yield pe(JSON.parse(w.data))}catch(C){throw s.error("Could not parse message into JSON:",w.data),s.error("From chunk:",w.raw),C}}}catch(w){c={error:w}}finally{try{!m&&!u&&(p=v.return)&&(yield pe(p.call(v)))}finally{if(c)throw c.error}}h=!0}catch(w){if(pc(w))return yield pe(void 0);throw w}finally{h||n.abort()}})}return new _o(r,n,o)}static fromReadableStream(e,n,o){let i=!1;function s(){return ln(this,arguments,function*(){var u,c,p,f;const h=new Kl,m=UE(e);try{for(var v=!0,_=un(m),w;w=yield pe(_.next()),u=w.done,!u;v=!0){f=w.value,v=!1;const C=f;for(const E of h.decode(C))yield yield pe(E)}}catch(C){c={error:C}}finally{try{!v&&!u&&(p=_.return)&&(yield pe(p.call(_)))}finally{if(c)throw c.error}}for(const C of h.flush())yield yield pe(C)})}function r(){return ln(this,arguments,function*(){var u,c,p,f;if(i)throw new dn("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let h=!1;try{try{for(var m=!0,v=un(s()),_;_=yield pe(v.next()),u=_.done,!u;m=!0){f=_.value,m=!1;const w=f;h||w&&(yield yield pe(JSON.parse(w)))}}catch(w){c={error:w}}finally{try{!m&&!u&&(p=v.return)&&(yield pe(p.call(v)))}finally{if(c)throw c.error}}h=!0}catch(w){if(pc(w))return yield pe(void 0);throw w}finally{h||n.abort()}})}return new _o(r,n,o)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],n=[],o=this.iterator(),i=s=>({next:()=>{if(s.length===0){const r=o.next();e.push(r),n.push(r)}return s.shift()}});return[new _o(()=>i(e),this.controller,this.client),new _o(()=>i(n),this.controller,this.client)]}toReadableStream(){const e=this;let n;return $E({async start(){n=e[Symbol.asyncIterator]()},async pull(o){try{const{value:i,done:s}=await n.next();if(s)return o.close();const r=gd(JSON.stringify(i)+`
324
+ `);o.enqueue(r)}catch(i){o.error(i)}},async cancel(){var o;await((o=n.return)===null||o===void 0?void 0:o.call(n))}})}}function yH(t,e){return ln(this,arguments,function*(){var o,i,s,r;if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new dn("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new dn("Attempted to iterate over a response with no body");const a=new TH,u=new Kl,c=UE(t.body);try{for(var p=!0,f=un(_H(c)),h;h=yield pe(f.next()),o=h.done,!o;p=!0){r=h.value,p=!1;const m=r;for(const v of u.decode(m)){const _=a.decode(v);_&&(yield yield pe(_))}}}catch(m){i={error:m}}finally{try{!p&&!o&&(s=f.return)&&(yield pe(s.call(f)))}finally{if(i)throw i.error}}for(const m of u.flush()){const v=a.decode(m);v&&(yield yield pe(v))}})}function _H(t){return ln(this,arguments,function*(){var n,o,i,s;try{for(var r=!0,a=un(t),u;u=yield pe(a.next()),n=u.done,!n;r=!0){s=u.value,r=!1;const c=s;if(c==null)continue;const p=c instanceof ArrayBuffer?new Uint8Array(c):typeof c=="string"?gd(c):c;yield yield pe(p)}}catch(c){o={error:c}}finally{try{!r&&!n&&(i=a.return)&&(yield pe(i.call(a)))}finally{if(o)throw o.error}}})}class TH{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const s={event:this.event,data:this.data.join(`
325
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,o,i]=EH(e,":");return i.startsWith(" ")&&(i=i.substring(1)),n==="event"?this.event=i:n==="data"&&this.data.push(i),null}}function EH(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}/**
326
+ * @license
327
+ * Copyright 2025 Google LLC
328
+ * SPDX-License-Identifier: Apache-2.0
329
+ */const wH=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]),Gm={"interaction.start":"interaction.created","content.start":"step.start","content.delta":"step.delta","content.stop":"step.stop","interaction.complete":"interaction.completed"};function IH({isVertex:t,model:e}){return!!t&&typeof e=="string"&&wH.has(e)}function SH(t){const e=t.clientAdapter;return!!(e&&e.isVertexAI())}function vc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function GE(t){if(!("outputs"in t)||"steps"in t)return t;const{outputs:e}=t,n=Un(t,["outputs"]);return Object.assign(Object.assign({},n),{steps:[{type:"model_output",content:e}]})}function CH(t){return vc(t)?GE(t):t}function AH(t){if(!vc(t))return t;const e=t.event_type;if(typeof e!="string"||!(e in Gm))return t;const n=Object.assign(Object.assign({},t),{event_type:Gm[e]});if(e==="content.start"){const{content:o}=n,i=Un(n,["content"]);let s;return o==null?s=[]:Array.isArray(o)?s=o:s=[o],Object.assign(Object.assign({},i),{step:{type:"model_output",content:s}})}if(e==="interaction.start"||e==="interaction.complete"){const o=n.interaction;vc(o)&&(n.interaction=GE(o))}return n}class vd extends _o{static fromSSEResponse(e,n,o){const i=_o.fromSSEResponse(e,n,o);function s(){return ln(this,arguments,function*(){var a,u,c,p;try{for(var f=!0,h=un(i),m;m=yield pe(h.next()),a=m.done,!a;f=!0)p=m.value,f=!1,yield yield pe(AH(p))}catch(v){u={error:v}}finally{try{!f&&!a&&(c=h.return)&&(yield pe(c.call(h)))}finally{if(u)throw u.error}}})}return new vd(s,n,o)}}/**
330
+ * @license
331
+ * Copyright 2025 Google LLC
332
+ * SPDX-License-Identifier: Apache-2.0
333
+ */function zE(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const zm=Object.freeze(Object.create(null)),bH=(t=zE)=>(function(n,...o){if(n.length===1)return n[0];let i=!1;const s=[],r=n.reduce((p,f,h)=>{var m,v,_;/[?#]/.test(f)&&(i=!0);const w=o[h];let C=(i?encodeURIComponent:t)(""+w);return h!==o.length&&(w==null||typeof w=="object"&&w.toString===((_=Object.getPrototypeOf((v=Object.getPrototypeOf((m=w.hasOwnProperty)!==null&&m!==void 0?m:zm))!==null&&v!==void 0?v:zm))===null||_===void 0?void 0:_.toString))&&(C=w+"",s.push({start:p.length+f.length,length:C.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`})),p+f+(h===o.length?"":C)},""),a=r.split(/[?#]/,1)[0],u=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;(c=u.exec(a))!==null;){const p=c[0].startsWith("/"),f=p?1:0,h=p?c[0].slice(1):c[0];s.push({start:c.index+f,length:h.length,error:`Value "${h}" can't be safely passed as a path parameter`})}if(s.sort((p,f)=>p.start-f.start),s.length>0){let p=0;const f=s.reduce((h,m)=>{const v=" ".repeat(m.start-p),_="^".repeat(m.length);return p=m.start+m.length,h+v+_},"");throw new dn(`Path parameters result in path with invalid segments:
334
+ ${s.map(h=>h.error).join(`
335
+ `)}
336
+ ${r}
337
+ ${f}`)}return r}),wn=bH(zE);/**
338
+ * @license
339
+ * Copyright 2025 Google LLC
340
+ * SPDX-License-Identifier: Apache-2.0
341
+ */class FE extends md{create(e,n){var o;const{api_version:i=this._client.apiVersion}=e,s=Un(e,["api_version"]);if("model"in s&&"agent_config"in s)throw new dn("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in s&&"generation_config"in s)throw new dn("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");const r=IH({isVertex:SH(this._client),model:"model"in s?s.model:void 0}),a=(o=e.stream)!==null&&o!==void 0?o:!1,u=this._client.post(wn`/${i}/interactions`,Object.assign(Object.assign(Object.assign({body:s},n),{stream:a}),r&&a?{__streamClass:vd}:{}));if(a)return u;let c=u;return r&&(c=c._thenUnwrap(p=>CH(p))),c._thenUnwrap(Eu)}delete(e,n={},o){const{api_version:i=this._client.apiVersion}=n??{};return this._client.delete(wn`/${i}/interactions/${e}`,o)}cancel(e,n={},o){const{api_version:i=this._client.apiVersion}=n??{};return this._client.post(wn`/${i}/interactions/${e}/cancel`,o)._thenUnwrap(Eu)}get(e,n={},o){var i;const s=n??{},{api_version:r=this._client.apiVersion}=s,a=Un(s,["api_version"]),u=this._client.get(wn`/${r}/interactions/${e}`,Object.assign(Object.assign({query:a},o),{stream:(i=n==null?void 0:n.stream)!==null&&i!==void 0?i:!1}));return n!=null&&n.stream?u:u._thenUnwrap(Eu)}}FE._key=Object.freeze(["interactions"]);class VE extends FE{}function Eu(t){var e,n;const o=(e=t.steps)!==null&&e!==void 0?e:[];let i=o.length;for(;i>0&&o[i-1].type==="model_output";)i--;const r=o.slice(i).flatMap(h=>{var m;return(m=h.content)!==null&&m!==void 0?m:[]}),a=[];for(let h=r.length-1;h>=0;h--){const m=r[h];if(m.type!=="text")break;a.push((n=m.text)!==null&&n!==void 0?n:"")}const u=a.reverse().join("");let c,p,f;for(let h=o.length-1;h>=0;h--){const v=o[h];if(v.type==="user_input")break;if(v.type==="model_output"&&v.content)for(let _=v.content.length-1;_>=0;_--){const w=v.content[_];w.type==="image"&&!c&&(c=w),w.type==="audio"&&!p&&(p=w),w.type==="video"&&!f&&(f=w)}}return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},t),u&&{output_text:u}),c&&{output_image:c}),p&&{output_audio:p}),f&&{output_video:f})}/**
342
+ * @license
343
+ * Copyright 2025 Google LLC
344
+ * SPDX-License-Identifier: Apache-2.0
345
+ */class qE extends md{create(e,n){const{api_version:o=this._client.apiVersion}=e,i=Un(e,["api_version"]);return this._client.post(wn`/${o}/webhooks`,Object.assign({body:i},n))}update(e,n={},o){const i=n??{},{api_version:s=this._client.apiVersion,update_mask:r}=i,a=Un(i,["api_version","update_mask"]);return this._client.patch(wn`/${s}/webhooks/${e}`,Object.assign({query:{update_mask:r},body:a},o))}list(e={},n){const o=e??{},{api_version:i=this._client.apiVersion}=o,s=Un(o,["api_version"]);return this._client.get(wn`/${i}/webhooks`,Object.assign({query:s},n))}delete(e,n={},o){const{api_version:i=this._client.apiVersion}=n??{};return this._client.delete(wn`/${i}/webhooks/${e}`,o)}get(e,n={},o){const{api_version:i=this._client.apiVersion}=n??{};return this._client.get(wn`/${i}/webhooks/${e}`,o)}ping(e,n=void 0,o){const{api_version:i=this._client.apiVersion,body:s}=n??{};return this._client.post(wn`/${i}/webhooks/${e}:ping`,Object.assign({body:s},o))}rotateSigningSecret(e,n={},o){const i=n??{},{api_version:s=this._client.apiVersion}=i,r=Un(i,["api_version"]);return this._client.post(wn`/${s}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:r},o))}}qE._key=Object.freeze(["webhooks"]);class BE extends qE{}/**
346
+ * @license
347
+ * Copyright 2025 Google LLC
348
+ * SPDX-License-Identifier: Apache-2.0
349
+ */async function RH(t,e){const{response:n,requestLogID:o,retryOfRequestLogID:i,startTime:s}=e,r=await(async()=>{var a;if(e.options.stream)return Mt(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):_o.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const u=n.headers.get("content-type"),c=(a=u==null?void 0:u.split(";")[0])===null||a===void 0?void 0:a.trim();return(c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))?n.headers.get("content-length")==="0"?void 0:await n.json():await n.text()})();return Mt(t).debug(`[${o}] response parsed`,Lo({retryOfRequestLogID:i,url:n.url,status:n.status,body:r,durationMs:Date.now()-s})),r}/**
350
+ * @license
351
+ * Copyright 2025 Google LLC
352
+ * SPDX-License-Identifier: Apache-2.0
353
+ */class yd extends Promise{constructor(e,n,o=RH){super(i=>{i(null)}),this.responsePromise=n,this.parseResponse=o,this.client=e}_thenUnwrap(e){return new yd(this.client,this.responsePromise,async(n,o)=>e(await this.parseResponse(n,o),o))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}/**
354
+ * @license
355
+ * Copyright 2025 Google LLC
356
+ * SPDX-License-Identifier: Apache-2.0
357
+ */const HE=Symbol("brand.privateNullableHeaders");function*kH(t){if(!t)return;if(HE in t){const{values:o,nulls:i}=t;yield*o.entries();for(const s of i)yield[s,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Dm(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let o of n){const i=o[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");const s=Dm(o[1])?o[1]:[o[1]];let r=!1;for(const a of s)a!==void 0&&(e&&!r&&(r=!0,yield[i,null]),yield[i,a])}}const ps=t=>{const e=new Headers,n=new Set;for(const o of t){const i=new Set;for(const[s,r]of kH(o)){const a=s.toLowerCase();i.has(a)||(e.delete(s),i.add(a)),r===null?(e.delete(s),n.add(a)):(e.append(s,r),n.delete(a))}}return{[HE]:!0,values:e,nulls:n}};/**
358
+ * @license
359
+ * Copyright 2025 Google LLC
360
+ * SPDX-License-Identifier: Apache-2.0
361
+ */const wu=t=>{var e,n,o,i,s;if(typeof globalThis.process<"u")return((n=(e=x1)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())||void 0;if(typeof globalThis.Deno<"u")return((s=(i=(o=globalThis.Deno.env)===null||o===void 0?void 0:o.get)===null||i===void 0?void 0:i.call(o,t))===null||s===void 0?void 0:s.trim())||void 0};/**
362
+ * @license
363
+ * Copyright 2025 Google LLC
364
+ * SPDX-License-Identifier: Apache-2.0
365
+ */var ZE;class Yl{constructor(e){var n,o,i,s,r,a,u,{baseURL:c=wu("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:p=(n=wu("GEMINI_API_KEY"))!==null&&n!==void 0?n:null,apiVersion:f="v1beta"}=e,h=Un(e,["baseURL","apiKey","apiVersion"]);const m=Object.assign(Object.assign({apiKey:p,apiVersion:f},h),{baseURL:c||"https://generativelanguage.googleapis.com"});this.baseURL=m.baseURL,this.timeout=(o=m.timeout)!==null&&o!==void 0?o:Yl.DEFAULT_TIMEOUT,this.logger=(i=m.logger)!==null&&i!==void 0?i:console;const v="warn";this.logLevel=v,this.logLevel=(r=(s=Om(m.logLevel,"ClientOptions.logLevel",this))!==null&&s!==void 0?s:Om(wu("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&r!==void 0?r:v,this.fetchOptions=m.fetchOptions,this.maxRetries=(a=m.maxRetries)!==null&&a!==void 0?a:2,this.fetch=(u=m.fetch)!==null&&u!==void 0?u:oH(),this.encoder=rH,this._options=m,this.apiKey=p,this.apiVersion=f,this.clientAdapter=m.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.has("authorization")||e.has("x-goog-api-key"))&&!(this.apiKey&&e.get("x-goog-api-key"))&&!n.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){const n=ps([e.headers]);if(!(n.values.has("authorization")||n.values.has("x-goog-api-key"))){if(this.apiKey)return ps([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter&&this.clientAdapter.isVertexAI())return ps([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return aH(e)}getUserAgent(){return`${this.constructor.name}/JS ${lH}`}defaultIdempotencyKey(){return`stainless-node-retry-${WB()}`}makeStatusError(e,n,o,i){return $t.generate(e,n,o,i)}buildURL(e,n,o){const i=!this.baseURLOverridden()&&o||this.baseURL,s=YB(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),r=this.defaultQuery(),a=Object.fromEntries(s.searchParams);return(!$m(r)||!$m(a))&&(n=Object.assign(Object.assign(Object.assign({},a),r),n)),typeof n=="object"&&n&&!Array.isArray(n)&&(s.search=this.stringifyQuery(n)),s.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){const n=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${n}`}}async prepareRequest(e,{url:n,options:o}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,o){return this.request(Promise.resolve(o).then(i=>Object.assign({method:e,path:n},i)))}request(e,n=null){return new yd(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,o){var i,s,r;const a=await e,u=(i=a.maxRetries)!==null&&i!==void 0?i:this.maxRetries;n==null&&(n=u),await this.prepareOptions(a);const{req:c,url:p,timeout:f}=await this.buildRequest(a,{retryCount:u-n});await this.prepareRequest(c,{url:p,options:a});const h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=o===void 0?"":`, retryOf: ${o}`,v=Date.now();if(Mt(this).debug(`[${h}] sending request`,Lo({retryOfRequestLogID:o,method:a.method,url:p,options:a,headers:c.headers})),!((s=a.signal)===null||s===void 0)&&s.aborted)throw new hc;const _=new AbortController,w=await this.fetchWithTimeout(p,c,f,_).catch(fc),C=Date.now();if(w instanceof globalThis.Error){const A=`retrying, ${n} attempts remaining`;if(!((r=a.signal)===null||r===void 0)&&r.aborted)throw new hc;const R=pc(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(n)return Mt(this).info(`[${h}] connection ${R?"timed out":"failed"} - ${A}`),Mt(this).debug(`[${h}] connection ${R?"timed out":"failed"} (${A})`,Lo({retryOfRequestLogID:o,url:p,durationMs:C-v,message:w.message})),this.retryRequest(a,n,o??h);throw Mt(this).info(`[${h}] connection ${R?"timed out":"failed"} - error; no more retries left`),Mt(this).debug(`[${h}] connection ${R?"timed out":"failed"} (error; no more retries left)`,Lo({retryOfRequestLogID:o,url:p,durationMs:C-v,message:w.message})),R?new AE:new Wl({cause:w})}const E=`[${h}${m}] ${c.method} ${p} ${w.ok?"succeeded":"failed"} with status ${w.status} in ${C-v}ms`;if(!w.ok){const A=await this.shouldRetry(w);if(n&&A){const G=`retrying, ${n} attempts remaining`;return await sH(w.body),Mt(this).info(`${E} - ${G}`),Mt(this).debug(`[${h}] response error (${G})`,Lo({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,durationMs:C-v})),this.retryRequest(a,n,o??h,w.headers)}const R=A?"error; no more retries left":"error; not retryable";Mt(this).info(`${E} - ${R}`);const k=await w.text().catch(G=>fc(G).message),b=tH(k),U=b?void 0:k;throw Mt(this).debug(`[${h}] response error (${R})`,Lo({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,message:U,durationMs:Date.now()-v})),this.makeStatusError(w.status,b,U,w.headers)}return Mt(this).info(E),Mt(this).debug(`[${h}] response start`,Lo({retryOfRequestLogID:o,url:w.url,status:w.status,headers:w.headers,durationMs:C-v})),{response:w,options:a,controller:_,requestLogID:h,retryOfRequestLogID:o,startTime:v}}async fetchWithTimeout(e,n,o,i){const s=n||{},{signal:r,method:a}=s,u=Un(s,["signal","method"]),c=this._makeAbort(i);r&&r.addEventListener("abort",c,{once:!0});const p=setTimeout(c,o),f=globalThis.ReadableStream&&u.body instanceof globalThis.ReadableStream||typeof u.body=="object"&&u.body!==null&&Symbol.asyncIterator in u.body,h=Object.assign(Object.assign(Object.assign({signal:i.signal},f?{duplex:"half"}:{}),{method:"GET"}),u);a&&(h.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(p)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,o,i){var s;let r;const a=i==null?void 0:i.get("retry-after-ms");if(a){const c=parseFloat(a);Number.isNaN(c)||(r=c)}const u=i==null?void 0:i.get("retry-after");if(u&&!r){const c=parseFloat(u);Number.isNaN(c)?r=Date.parse(u)-Date.now():r=c*1e3}if(r===void 0){const c=(s=e.maxRetries)!==null&&s!==void 0?s:this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(n,c)}return await nH(r),this.makeRequest(e,n-1,o)}calculateDefaultRetryTimeoutMillis(e,n){const s=n-e,r=Math.min(.5*Math.pow(2,s),8),a=1-Math.random()*.25;return r*a*1e3}async buildRequest(e,{retryCount:n=0}={}){var o,i,s;const r=Object.assign({},e),{method:a,path:u,query:c,defaultBaseURL:p}=r,f=this.buildURL(u,c,p);"timeout"in r&&eH("timeout",r.timeout),r.timeout=(o=r.timeout)!==null&&o!==void 0?o:this.timeout;const{bodyHeaders:h,body:m}=this.buildBody({options:r}),v=await this.buildHeaders({options:e,method:a,bodyHeaders:h,retryCount:n});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:a,headers:v},r.signal&&{signal:r.signal}),globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"}),m&&{body:m}),(i=this.fetchOptions)!==null&&i!==void 0?i:{}),(s=r.fetchOptions)!==null&&s!==void 0?s:{}),url:f,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:o,retryCount:i}){let s={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);const r=await this.authHeaders(e);let a=ps([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"Api-Revision":"2026-05-20"},this._options.defaultHeaders,o,e.headers,r]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const o=ps([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&o.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:iH(e)}:typeof e=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:o})}}Yl.DEFAULT_TIMEOUT=6e4;class yt extends Yl{constructor(){super(...arguments),this.interactions=new VE(this),this.webhooks=new BE(this)}}ZE=yt;yt.GeminiNextGenAPIClient=ZE;yt.GeminiNextGenAPIClientError=dn;yt.APIError=$t;yt.APIConnectionError=Wl;yt.APIConnectionTimeoutError=AE;yt.APIUserAbortError=hc;yt.NotFoundError=PE;yt.ConflictError=NE;yt.RateLimitError=xE;yt.BadRequestError=bE;yt.AuthenticationError=RE;yt.InternalServerError=DE;yt.PermissionDeniedError=kE;yt.UnprocessableEntityError=ME;yt.toFile=fH;yt.Interactions=VE;yt.Webhooks=BE;/**
366
+ * @license
367
+ * Copyright 2025 Google LLC
368
+ * SPDX-License-Identifier: Apache-2.0
369
+ */function PH(t,e){const n={},o=l(t,["name"]);return o!=null&&d(n,["_url","name"],o),n}function NH(t,e){const n={},o=l(t,["name"]);return o!=null&&d(n,["_url","name"],o),n}function MH(t,e){const n={},o=l(t,["sdkHttpResponse"]);return o!=null&&d(n,["sdkHttpResponse"],o),n}function xH(t,e){const n={},o=l(t,["sdkHttpResponse"]);return o!=null&&d(n,["sdkHttpResponse"],o),n}function DH(t,e,n){const o={};if(l(t,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const i=l(t,["tunedModelDisplayName"]);if(e!==void 0&&i!=null&&d(e,["displayName"],i),l(t,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=l(t,["epochCount"]);e!==void 0&&s!=null&&d(e,["tuningTask","hyperparameters","epochCount"],s);const r=l(t,["learningRateMultiplier"]);if(r!=null&&d(o,["tuningTask","hyperparameters","learningRateMultiplier"],r),l(t,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const a=l(t,["batchSize"]);e!==void 0&&a!=null&&d(e,["tuningTask","hyperparameters","batchSize"],a);const u=l(t,["learningRate"]);if(e!==void 0&&u!=null&&d(e,["tuningTask","hyperparameters","learningRate"],u),l(t,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return o}function $H(t,e,n){const o={};let i=l(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){const b=l(t,["validationDataset"]);e!==void 0&&b!=null&&d(e,["supervisedTuningSpec"],Iu(b))}else if(i==="PREFERENCE_TUNING"){const b=l(t,["validationDataset"]);e!==void 0&&b!=null&&d(e,["preferenceOptimizationSpec"],Iu(b))}else if(i==="DISTILLATION"){const b=l(t,["validationDataset"]);e!==void 0&&b!=null&&d(e,["distillationSpec"],Iu(b))}const s=l(t,["tunedModelDisplayName"]);e!==void 0&&s!=null&&d(e,["tunedModelDisplayName"],s);const r=l(t,["description"]);e!==void 0&&r!=null&&d(e,["description"],r);let a=l(n,["config","method"]);if(a===void 0&&(a="SUPERVISED_FINE_TUNING"),a==="SUPERVISED_FINE_TUNING"){const b=l(t,["epochCount"]);e!==void 0&&b!=null&&d(e,["supervisedTuningSpec","hyperParameters","epochCount"],b)}else if(a==="PREFERENCE_TUNING"){const b=l(t,["epochCount"]);e!==void 0&&b!=null&&d(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],b)}else if(a==="DISTILLATION"){const b=l(t,["epochCount"]);e!==void 0&&b!=null&&d(e,["distillationSpec","hyperParameters","epochCount"],b)}let u=l(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){const b=l(t,["learningRateMultiplier"]);e!==void 0&&b!=null&&d(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],b)}else if(u==="PREFERENCE_TUNING"){const b=l(t,["learningRateMultiplier"]);e!==void 0&&b!=null&&d(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],b)}else if(u==="DISTILLATION"){const b=l(t,["learningRateMultiplier"]);e!==void 0&&b!=null&&d(e,["distillationSpec","hyperParameters","learningRateMultiplier"],b)}let c=l(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){const b=l(t,["exportLastCheckpointOnly"]);e!==void 0&&b!=null&&d(e,["supervisedTuningSpec","exportLastCheckpointOnly"],b)}else if(c==="PREFERENCE_TUNING"){const b=l(t,["exportLastCheckpointOnly"]);e!==void 0&&b!=null&&d(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],b)}else if(c==="DISTILLATION"){const b=l(t,["exportLastCheckpointOnly"]);e!==void 0&&b!=null&&d(e,["distillationSpec","exportLastCheckpointOnly"],b)}let p=l(n,["config","method"]);if(p===void 0&&(p="SUPERVISED_FINE_TUNING"),p==="SUPERVISED_FINE_TUNING"){const b=l(t,["adapterSize"]);e!==void 0&&b!=null&&d(e,["supervisedTuningSpec","hyperParameters","adapterSize"],b)}else if(p==="PREFERENCE_TUNING"){const b=l(t,["adapterSize"]);e!==void 0&&b!=null&&d(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],b)}else if(p==="DISTILLATION"){const b=l(t,["adapterSize"]);e!==void 0&&b!=null&&d(e,["distillationSpec","hyperParameters","adapterSize"],b)}let f=l(n,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){const b=l(t,["tuningMode"]);e!==void 0&&b!=null&&d(e,["supervisedTuningSpec","tuningMode"],b)}else if(f==="DISTILLATION"){const b=l(t,["tuningMode"]);e!==void 0&&b!=null&&d(e,["distillationSpec","tuningMode"],b)}const h=l(t,["customBaseModel"]);e!==void 0&&h!=null&&d(e,["customBaseModel"],h);let m=l(n,["config","method"]);if(m===void 0&&(m="SUPERVISED_FINE_TUNING"),m==="SUPERVISED_FINE_TUNING"){const b=l(t,["batchSize"]);e!==void 0&&b!=null&&d(e,["supervisedTuningSpec","hyperParameters","batchSize"],b)}else if(m==="DISTILLATION"){const b=l(t,["batchSize"]);e!==void 0&&b!=null&&d(e,["distillationSpec","hyperParameters","batchSize"],b)}let v=l(n,["config","method"]);if(v===void 0&&(v="SUPERVISED_FINE_TUNING"),v==="SUPERVISED_FINE_TUNING"){const b=l(t,["learningRate"]);e!==void 0&&b!=null&&d(e,["supervisedTuningSpec","hyperParameters","learningRate"],b)}else if(v==="DISTILLATION"){const b=l(t,["learningRate"]);e!==void 0&&b!=null&&d(e,["distillationSpec","hyperParameters","learningRate"],b)}const _=l(t,["labels"]);e!==void 0&&_!=null&&d(e,["labels"],_);const w=l(t,["beta"]);e!==void 0&&w!=null&&d(e,["preferenceOptimizationSpec","hyperParameters","beta"],w);const C=l(t,["baseTeacherModel"]);e!==void 0&&C!=null&&d(e,["distillationSpec","baseTeacherModel"],C);const E=l(t,["tunedTeacherModelSource"]);e!==void 0&&E!=null&&d(e,["distillationSpec","tunedTeacherModelSource"],E);const A=l(t,["sftLossWeightMultiplier"]);e!==void 0&&A!=null&&d(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],A);const R=l(t,["outputUri"]);e!==void 0&&R!=null&&d(e,["outputUri"],R);const k=l(t,["encryptionSpec"]);return e!==void 0&&k!=null&&d(e,["encryptionSpec"],k),o}function UH(t,e){const n={},o=l(t,["baseModel"]);o!=null&&d(n,["baseModel"],o);const i=l(t,["preTunedModel"]);i!=null&&d(n,["preTunedModel"],i);const s=l(t,["trainingDataset"]);s!=null&&BH(s);const r=l(t,["config"]);return r!=null&&DH(r,n),n}function OH(t,e){const n={},o=l(t,["baseModel"]);o!=null&&d(n,["baseModel"],o);const i=l(t,["preTunedModel"]);i!=null&&d(n,["preTunedModel"],i);const s=l(t,["trainingDataset"]);s!=null&&HH(s,n,e);const r=l(t,["config"]);return r!=null&&$H(r,n,e),n}function LH(t,e){const n={},o=l(t,["name"]);return o!=null&&d(n,["_url","name"],o),n}function GH(t,e){const n={},o=l(t,["name"]);return o!=null&&d(n,["_url","name"],o),n}function zH(t,e,n){const o={},i=l(t,["pageSize"]);e!==void 0&&i!=null&&d(e,["_query","pageSize"],i);const s=l(t,["pageToken"]);e!==void 0&&s!=null&&d(e,["_query","pageToken"],s);const r=l(t,["filter"]);return e!==void 0&&r!=null&&d(e,["_query","filter"],r),o}function FH(t,e){const n={},o=l(t,["config"]);return o!=null&&zH(o,n),n}function VH(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["nextPageToken"]);i!=null&&d(n,["nextPageToken"],i);const s=l(t,["tuningJobs"]);if(s!=null){let r=s;Array.isArray(r)&&(r=r.map(a=>yc(a))),d(n,["tuningJobs"],r)}return n}function qH(t,e){const n={},o=l(t,["name"]);o!=null&&d(n,["model"],o);const i=l(t,["name"]);return i!=null&&d(n,["endpoint"],i),n}function BH(t,e){const n={};if(l(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(l(t,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=l(t,["examples"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(s=>s)),d(n,["examples","examples"],i)}return n}function HH(t,e,n){const o={};let i=l(n,["config","method"]);if(i===void 0&&(i="SUPERVISED_FINE_TUNING"),i==="SUPERVISED_FINE_TUNING"){const r=l(t,["gcsUri"]);e!==void 0&&r!=null&&d(e,["supervisedTuningSpec","trainingDatasetUri"],r)}else if(i==="PREFERENCE_TUNING"){const r=l(t,["gcsUri"]);e!==void 0&&r!=null&&d(e,["preferenceOptimizationSpec","trainingDatasetUri"],r)}else if(i==="DISTILLATION"){const r=l(t,["gcsUri"]);e!==void 0&&r!=null&&d(e,["distillationSpec","promptDatasetUri"],r)}let s=l(n,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){const r=l(t,["vertexDatasetResource"]);e!==void 0&&r!=null&&d(e,["supervisedTuningSpec","trainingDatasetUri"],r)}else if(s==="PREFERENCE_TUNING"){const r=l(t,["vertexDatasetResource"]);e!==void 0&&r!=null&&d(e,["preferenceOptimizationSpec","trainingDatasetUri"],r)}else if(s==="DISTILLATION"){const r=l(t,["vertexDatasetResource"]);e!==void 0&&r!=null&&d(e,["distillationSpec","promptDatasetUri"],r)}if(l(t,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return o}function ZH(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["name"]);i!=null&&d(n,["name"],i);const s=l(t,["state"]);s!=null&&d(n,["state"],aE(s));const r=l(t,["createTime"]);r!=null&&d(n,["createTime"],r);const a=l(t,["tuningTask","startTime"]);a!=null&&d(n,["startTime"],a);const u=l(t,["tuningTask","completeTime"]);u!=null&&d(n,["endTime"],u);const c=l(t,["updateTime"]);c!=null&&d(n,["updateTime"],c);const p=l(t,["description"]);p!=null&&d(n,["description"],p);const f=l(t,["baseModel"]);f!=null&&d(n,["baseModel"],f);const h=l(t,["_self"]);return h!=null&&d(n,["tunedModel"],qH(h)),n}function yc(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["name"]);i!=null&&d(n,["name"],i);const s=l(t,["state"]);s!=null&&d(n,["state"],aE(s));const r=l(t,["createTime"]);r!=null&&d(n,["createTime"],r);const a=l(t,["startTime"]);a!=null&&d(n,["startTime"],a);const u=l(t,["endTime"]);u!=null&&d(n,["endTime"],u);const c=l(t,["updateTime"]);c!=null&&d(n,["updateTime"],c);const p=l(t,["error"]);p!=null&&d(n,["error"],p);const f=l(t,["description"]);f!=null&&d(n,["description"],f);const h=l(t,["baseModel"]);h!=null&&d(n,["baseModel"],h);const m=l(t,["tunedModel"]);m!=null&&d(n,["tunedModel"],m);const v=l(t,["preTunedModel"]);v!=null&&d(n,["preTunedModel"],v);const _=l(t,["supervisedTuningSpec"]);_!=null&&d(n,["supervisedTuningSpec"],_);const w=l(t,["preferenceOptimizationSpec"]);w!=null&&d(n,["preferenceOptimizationSpec"],w);const C=l(t,["distillationSpec"]);C!=null&&d(n,["distillationSpec"],C);const E=l(t,["tuningDataStats"]);E!=null&&d(n,["tuningDataStats"],E);const A=l(t,["encryptionSpec"]);A!=null&&d(n,["encryptionSpec"],A);const R=l(t,["partnerModelTuningSpec"]);R!=null&&d(n,["partnerModelTuningSpec"],R);const k=l(t,["customBaseModel"]);k!=null&&d(n,["customBaseModel"],k);const b=l(t,["evaluateDatasetRuns"]);if(b!=null){let re=b;Array.isArray(re)&&(re=re.map(x=>x)),d(n,["evaluateDatasetRuns"],re)}const U=l(t,["experiment"]);U!=null&&d(n,["experiment"],U);const J=l(t,["fullFineTuningSpec"]);J!=null&&d(n,["fullFineTuningSpec"],J);const G=l(t,["labels"]);G!=null&&d(n,["labels"],G);const L=l(t,["outputUri"]);L!=null&&d(n,["outputUri"],L);const B=l(t,["pipelineJob"]);B!=null&&d(n,["pipelineJob"],B);const ve=l(t,["serviceAccount"]);ve!=null&&d(n,["serviceAccount"],ve);const Ae=l(t,["tunedModelDisplayName"]);Ae!=null&&d(n,["tunedModelDisplayName"],Ae);const ye=l(t,["tuningJobState"]);ye!=null&&d(n,["tuningJobState"],ye);const ue=l(t,["veoTuningSpec"]);ue!=null&&d(n,["veoTuningSpec"],ue);const we=l(t,["distillationSamplingSpec"]);we!=null&&d(n,["distillationSamplingSpec"],we);const j=l(t,["tuningJobMetadata"]);return j!=null&&d(n,["tuningJobMetadata"],j),n}function JH(t,e){const n={},o=l(t,["sdkHttpResponse"]);o!=null&&d(n,["sdkHttpResponse"],o);const i=l(t,["name"]);i!=null&&d(n,["name"],i);const s=l(t,["metadata"]);s!=null&&d(n,["metadata"],s);const r=l(t,["done"]);r!=null&&d(n,["done"],r);const a=l(t,["error"]);return a!=null&&d(n,["error"],a),n}function Iu(t,e){const n={},o=l(t,["gcsUri"]);o!=null&&d(n,["validationDatasetUri"],o);const i=l(t,["vertexDatasetResource"]);return i!=null&&d(n,["validationDatasetUri"],i),n}/**
370
+ * @license
371
+ * Copyright 2025 Google LLC
372
+ * SPDX-License-Identifier: Apache-2.0
373
+ */class WH extends Qn{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ai(Yn.PAGED_ITEM_TUNING_JOBS,o=>this.listInternal(o),await this.listInternal(n),n),this.get=async n=>await this.getInternal(n),this.tune=async n=>{var o;if(this.apiClient.isVertexAI())if(n.baseModel.startsWith("projects/")){const i={tunedModelName:n.baseModel};!((o=n.config)===null||o===void 0)&&o.preTunedModelCheckpointId&&(i.checkpointId=n.config.preTunedModelCheckpointId);const s=Object.assign(Object.assign({},n),{preTunedModel:i});return s.baseModel=void 0,await this.tuneInternal(s)}else{const i=Object.assign({},n);return await this.tuneInternal(i)}else{const i=Object.assign({},n),s=await this.tuneMldevInternal(i);let r="";return s.metadata!==void 0&&s.metadata.tunedModel!==void 0?r=s.metadata.tunedModel:s.name!==void 0&&s.name.includes("/operations/")&&(r=s.name.split("/operations/")[0]),{name:r,state:sc.JOB_STATE_QUEUED}}}}async getInternal(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=GH(e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>yc(p))}else{const c=LH(e);return a=Q("{name}",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"GET",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>ZH(p))}}async listInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI()){const a=FH(e);return s=Q("tuningJobs",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json().then(c=>{const p=c;return p.sdkHttpResponse={headers:u.headers},p})),i.then(u=>{const c=VH(u),p=new iG;return Object.assign(p,c),p})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var n,o,i,s;let r,a="",u={};if(this.apiClient.isVertexAI()){const c=NH(e);return a=Q("{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=xH(p),h=new dm;return Object.assign(h,f),h})}else{const c=PH(e);return a=Q("{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,r=this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(i=e.config)===null||i===void 0?void 0:i.httpOptions,abortSignal:(s=e.config)===null||s===void 0?void 0:s.abortSignal}).then(p=>p.json().then(f=>{const h=f;return h.sdkHttpResponse={headers:p.headers},h})),r.then(p=>{const f=MH(p),h=new dm;return Object.assign(h,f),h})}}async tuneInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI()){const a=OH(e,e);return s=Q("tuningJobs",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json().then(c=>{const p=c;return p.sdkHttpResponse={headers:u.headers},p})),i.then(u=>yc(u))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var n,o;let i,s="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=UH(e);return s=Q("tunedModels",a._url),r=a._query,delete a._url,delete a._query,i=this.apiClient.request({path:s,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(u=>u.json().then(c=>{const p=c;return p.sdkHttpResponse={headers:u.headers},p})),i.then(u=>JH(u))}}}/**
374
+ * @license
375
+ * Copyright 2025 Google LLC
376
+ * SPDX-License-Identifier: Apache-2.0
377
+ */class KH{async download(e,n){throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.")}}const YH=1024*1024*8,XH=3,QH=1e3,jH=2,ll="x-goog-upload-status";async function eZ(t,e,n,o){var i;const s=await JE(t,e,n,o),r=await(s==null?void 0:s.json());if(((i=s==null?void 0:s.headers)===null||i===void 0?void 0:i[ll])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return r.file}async function tZ(t,e,n,o){var i;const s=await JE(t,e,n,o),r=await(s==null?void 0:s.json());if(((i=s==null?void 0:s.headers)===null||i===void 0?void 0:i[ll])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");const a=tE(r),u=new ud;return Object.assign(u,a),u}async function JE(t,e,n,o){var i,s,r;let a=e;const u=(o==null?void 0:o.baseUrl)||((i=n.clientOptions.httpOptions)===null||i===void 0?void 0:i.baseUrl);if(u){const m=new URL(u),v=new URL(e);v.protocol=m.protocol,v.host=m.host,v.port=m.port,a=v.toString()}let c=0,p=0,f=new il(new Response),h="upload";for(c=t.size;p<c;){const m=Math.min(YH,c-p),v=t.slice(p,p+m);p+m>=c&&(h+=", finalize");let _=0,w=QH;for(;_<XH;){const C=Object.assign(Object.assign({},(o==null?void 0:o.headers)||{}),{"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":String(p),"Content-Length":String(m)});if(f=await n.request({path:"",body:v,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},o),{apiVersion:"",baseUrl:a,headers:C})}),!((s=f==null?void 0:f.headers)===null||s===void 0)&&s[ll])break;_++,await oZ(w),w=w*jH}if(p+=m,((r=f==null?void 0:f.headers)===null||r===void 0?void 0:r[ll])!=="active")break;if(c<=p)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return f}async function nZ(t){return{size:t.size,type:t.type}}function oZ(t){return new Promise(e=>setTimeout(e,t))}class iZ{async upload(e,n,o,i){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await eZ(e,n,o,i)}async uploadToFileSearchStore(e,n,o,i){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await tZ(e,n,o,i)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await nZ(e)}}/**
378
+ * @license
379
+ * Copyright 2025 Google LLC
380
+ * SPDX-License-Identifier: Apache-2.0
381
+ */class sZ{create(e,n,o){return new rZ(e,n,o)}}class rZ{constructor(e,n,o){this.url=e,this.headers=n,this.callbacks=o}connect(){this.ws=new WebSocket(this.url),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}}/**
382
+ * @license
383
+ * Copyright 2025 Google LLC
384
+ * SPDX-License-Identifier: Apache-2.0
385
+ */const Fm="x-goog-api-key";class aZ{constructor(e){this.apiKey=e}async addAuthHeaders(e,n){if(e.get(Fm)===null){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");if(!this.apiKey)throw new Error("API key is missing. Please provide a valid API key.");e.append(Fm,this.apiKey)}}}/**
386
+ * @license
387
+ * Copyright 2025 Google LLC
388
+ * SPDX-License-Identifier: Apache-2.0
389
+ */const lZ="gl-node/";class uZ{getNextGenClient(){var e;const n=this.httpOptions;if(this._nextGenClient===void 0){const o=this.httpOptions;this._nextGenClient=new yt({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:o==null?void 0:o.timeout,maxRetries:(e=o==null?void 0:o.retryOptions)===null||e===void 0?void 0:e.attempts})}return n!=null&&n.extraBody&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions."),this._interactions=this.getNextGenClient().interactions,this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=this.getNextGenClient().webhooks,this._webhooks)}constructor(e){var n;if(e.apiKey==null)throw new Error("An API Key must be set when running in a browser");if(e.project||e.location)throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.");this.vertexai=(n=e.vertexai)!==null&&n!==void 0?n:!1,this.apiKey=e.apiKey;const o=O1(e.httpOptions,e.vertexai,void 0,void 0);o&&(e.httpOptions?e.httpOptions.baseUrl=o:e.httpOptions={baseUrl:o}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;const i=new aZ(this.apiKey);this.apiClient=new tB({auth:i,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:lZ+"web",uploader:new iZ,downloader:new KH}),this.models=new TB(this.apiClient),this.live=new hB(this.apiClient,i,new sZ),this.batches=new yz(this.apiClient),this.chats=new tF(this.models,this.apiClient),this.caches=new Qz(this.apiClient),this.files=new fF(this.apiClient),this.operations=new EB(this.apiClient),this.authTokens=new GB(this.apiClient),this.tunings=new WH(this.apiClient),this.fileSearchStores=new JB(this.apiClient)}}function WE(t,e){return jT({apiKey:"browser-placeholder",baseURL:An("/proxy/google/v1beta"),headers:e})(t)}function KE(){return new uZ({apiKey:"browser-placeholder",httpOptions:{baseUrl:An("/proxy/google/")}})}const cZ={format:"pcm",async synthesize(t){const e=t.voiceId||"Kore",n=await KE().models.generateContentStream({model:t.modelId??"gemini-3.1-flash-tts-preview",contents:[{parts:[{text:t.text}]}],config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}},abortSignal:t.signal}});return new ReadableStream({async start(o){var i,s,r,a,u,c;try{for await(const p of n){const f=(c=(u=(a=(r=(s=(i=p.candidates)==null?void 0:i[0])==null?void 0:s.content)==null?void 0:r.parts)==null?void 0:a[0])==null?void 0:u.inlineData)==null?void 0:c.data;f&&o.enqueue(LN(f))}o.close()}catch(p){o.error(p)}},cancel(){}})}};function YE(t,e,n){return t==="google"?{provider:cZ,voiceId:n??Og,modelId:"gemini-3.1-flash-tts-preview"}:{provider:jN,voiceId:e,modelId:"eleven_v3"}}const dZ=5e3;var so,xn,Ji,QE,jE;class XE{constructor(){D(this,Ji);D(this,so,new Map);D(this,xn,null)}async prepareSegment(e,n,o,i){const s=new Audio,r=new MediaSource;s.src=URL.createObjectURL(r);const a={segmentId:e,audio:s,mediaSource:r,sourceBuffer:null,abortController:o,state:"loading",messageId:i==null?void 0:i.messageId,textHash:i==null?void 0:i.textHash};g(this,so).set(e,a),await new Promise((u,c)=>{const p=setTimeout(()=>{c(new Error(`sourceopen timeout for segment ${e}`))},dZ);if(r.readyState==="open"){clearTimeout(p),a.sourceBuffer=r.addSourceBuffer("audio/mpeg"),u();return}r.addEventListener("sourceopen",()=>{clearTimeout(p);try{a.sourceBuffer=r.addSourceBuffer("audio/mpeg")}catch(f){c(f);return}u()},{once:!0})}).catch(u=>{throw a.state="cancelled",u}),(async()=>{const u=n.getReader();try{for(;;){const{value:c,done:p}=await u.read();if(p||a.state==="cancelled")break;a.sourceBuffer&&c&&await $(this,Ji,QE).call(this,a.sourceBuffer,c)}a.state!=="cancelled"&&r.readyState==="open"&&(r.endOfStream(),a.state="ready")}catch{a.state!=="cancelled"&&(a.state="cancelled")}})().catch(()=>{})}async play(e){const n=g(this,so).get(e);if(!n)throw new Error(`no segment ${e}`);if(g(this,xn)&&g(this,xn).segmentId!==e&&g(this,xn).audio.pause(),O(this,xn,n),n.state==="loading"&&await $(this,Ji,jE).call(this,n),n.state==="cancelled")throw new Error(`segment ${e} was cancelled`);return n.state="playing",new Promise((o,i)=>{n.audio.addEventListener("ended",()=>{n.state="ended",o()},{once:!0}),n.audio.addEventListener("error",i,{once:!0}),n.audio.play().catch(i)})}cancel(e){var o;const n=g(this,so).get(e);if(n){n.state="cancelled",n.abortController.abort(),n.audio.pause();try{URL.revokeObjectURL(n.audio.src)}catch{}if(n.mediaSource.readyState==="open")try{n.mediaSource.endOfStream()}catch{}g(this,so).delete(e),((o=g(this,xn))==null?void 0:o.segmentId)===e&&O(this,xn,null)}}clear(){for(const e of g(this,so).values())this.cancel(e.segmentId);O(this,xn,null)}}so=new WeakMap,xn=new WeakMap,Ji=new WeakSet,QE=function(e,n){return new Promise((o,i)=>{const s=()=>{e.removeEventListener("updateend",s),o()};e.addEventListener("updateend",s);try{const r=new ArrayBuffer(n.byteLength);new Uint8Array(r).set(n),e.appendBuffer(r)}catch(r){e.removeEventListener("updateend",s),i(r)}})},jE=function(e){return new Promise(n=>{const o=()=>{e.state!=="loading"?n():setTimeout(o,50)};o()})};function Vm(t,e){const n=new Uint8Array(t.length+e.length);n.set(t,0),n.set(e,t.length);const o=n.length,i=Math.floor(o/2),s=i*2,r=new Int16Array(i);for(let u=0;u<i;u++){const c=n[u*2]??0,p=n[u*2+1]??0,f=c|p<<8;r[u]=f>=32768?f-65536:f}const a=s<o?n.slice(s):new Uint8Array(0);return{samples:r,rest:a}}function qm(t){const e=new Float32Array(t.length);for(let n=0;n<t.length;n++)e[n]=(t[n]??0)/32768;return e}const Su=24e3;var Ri,ro,ao,Xn,_c,tw,nw;class ew{constructor(){D(this,Xn);D(this,Ri,null);D(this,ro,new Map);D(this,ao,0)}async prepareSegment(e,n,o,i){const s=$(this,Xn,_c).call(this),r={segmentId:e,state:"loading",abortController:o,buffers:[],activeSources:[],streamDone:!1};g(this,ro).set(e,r),$(this,Xn,tw).call(this,s,r,n)}async play(e){const n=g(this,ro).get(e);if(!n)throw new Error(`PcmAudioStream: no segment ${e}`);const o=$(this,Xn,_c).call(this);if(o.state==="suspended"&&await o.resume(),await $(this,Xn,nw).call(this,n),n.state==="cancelled")throw new Error(`PcmAudioStream: segment ${e} was cancelled`);return n.state="playing",g(this,ao)<o.currentTime&&O(this,ao,o.currentTime),new Promise((i,s)=>{let r=0,a=0,u=!1;const c=()=>{if(n.state==="cancelled"){u||(u=!0,s(new Error("cancelled")));return}const p=n.buffers.splice(0);for(const f of p){const h=o.createBufferSource();h.buffer=f,h.connect(o.destination),h.start(g(this,ao)),O(this,ao,g(this,ao)+f.duration),r++,n.activeSources.push(h),h.onended=()=>{n.activeSources=n.activeSources.filter(m=>m!==h),a++,a>=r&&n.streamDone?u||(u=!0,n.state="ended",i()):n.streamDone||c()}}!n.streamDone&&p.length===0?setTimeout(c,20):(n.streamDone&&p.length===0&&r===0||n.streamDone&&a>=r)&&(u||(u=!0,n.state="ended",i()))};c()})}cancel(e){const n=g(this,ro).get(e);if(n){n.state="cancelled",n.abortController.abort();for(const o of n.activeSources)try{o.stop()}catch{}n.activeSources=[],g(this,ro).delete(e)}}clear(){for(const e of[...g(this,ro).keys()])this.cancel(e);O(this,ao,0)}}Ri=new WeakMap,ro=new WeakMap,ao=new WeakMap,Xn=new WeakSet,_c=function(){return g(this,Ri)||O(this,Ri,new AudioContext({sampleRate:Su})),g(this,Ri)},tw=async function(e,n,o){const i=o.getReader();let s=new Uint8Array(0);try{for(;n.state!=="cancelled";){const{value:r,done:a}=await i.read();if(a||!r||n.state==="cancelled")break;const{samples:u,rest:c}=Vm(s,r);if(s=c.length>0?new Uint8Array(c):new Uint8Array(0),u.length>0){const p=qm(u),f=new Float32Array(p),h=e.createBuffer(1,f.length,Su);h.copyToChannel(f,0),n.buffers.push(h)}}if(s.length>0&&n.state!=="cancelled"){const r=s[0],a=new Uint8Array([r!==void 0?r:0,0]),{samples:u}=Vm(new Uint8Array(0),a);if(u.length>0){const c=qm(u),p=new Float32Array(c),f=e.createBuffer(1,p.length,Su);f.copyToChannel(p,0),n.buffers.push(f)}}}catch{n.state==="loading"&&(n.state="cancelled")}finally{i.releaseLock()}n.state!=="cancelled"&&(n.streamDone=!0,n.state==="loading"&&(n.state="ready"))},nw=function(e){return new Promise(n=>{const o=()=>{e.state!=="loading"||e.buffers.length>0?n():setTimeout(o,20)};o()})};var lo;class ow{constructor(e,n){D(this,lo,new Map);this.mp3=e,this.pcm=n}async prepareSegment(e,n,o,i){const s=(i==null?void 0:i.format)==="pcm"?this.pcm:this.mp3;return g(this,lo).set(e,s),s.prepareSegment(e,n,o,i)}play(e){return(g(this,lo).get(e)??this.mp3).play(e)}cancel(e){const n=g(this,lo).get(e);n&&(n.cancel(e),g(this,lo).delete(e))}clear(){this.mp3.clear(),this.pcm.clear(),g(this,lo).clear()}}lo=new WeakMap;var cr,ki,Fn,uo,Vn,Pi,co;class pZ{constructor(e){D(this,cr,se(null));D(this,ki);D(this,Fn);D(this,uo,null);D(this,Vn,null);D(this,Pi,new ow(new XE,new ew));D(this,co,null);O(this,ki,e.session),O(this,Fn,e.settings)}get playingBubbleId(){return Y(g(this,cr))}set playingBubbleId(e){te(g(this,cr),e,!0)}toggle(e){if(g(this,ki).turnState!=="idle")return;if(this.playingBubbleId===e){this.stop();return}this.stop();const n=g(this,ki).bubbles.find(r=>r.id===e);if(!n||n.kind==="tool")return;this.playingBubbleId=e,O(this,Vn,new AbortController);const o=g(this,Vn),i=new Audio;O(this,uo,i);const s=()=>{this.playingBubbleId=null,O(this,uo,null),O(this,Vn,null),O(this,co,null)};if(n.kind==="user"){const r=n.recordingId;if(!r){s();return}FN(r,i).then(s).catch(s)}else{const r=n.segments.map(f=>f.text).join("");if(!r.trim()){s();return}const{provider:a,voiceId:u,modelId:c}=YE(g(this,Fn).ttsProvider,g(this,Fn).voiceId,g(this,Fn).geminiVoice);if(!Is.isAvailable(g(this,Fn).ttsProvider)){s(),console.warn("[BubblePlayer] TTS provider unavailable, skipping bubble",{provider:g(this,Fn).ttsProvider,bubbleId:e});return}O(this,co,e),(async()=>{const f=await a.synthesize({text:r,voiceId:u,modelId:c,signal:o.signal});await g(this,Pi).prepareSegment(e,f,o,{format:a.format}),await g(this,Pi).play(e)})().then(s).catch(s)}}stop(){if(g(this,Vn)&&(g(this,Vn).abort(),O(this,Vn,null)),g(this,co)&&(g(this,Pi).cancel(g(this,co)),O(this,co,null)),g(this,uo)){try{g(this,uo).pause()}catch{}O(this,uo,null)}this.playingBubbleId=null}}cr=new WeakMap,ki=new WeakMap,Fn=new WeakMap,uo=new WeakMap,Vn=new WeakMap,Pi=new WeakMap,co=new WeakMap;var po,Jo,dr;class fZ{constructor(e){D(this,po);D(this,Jo);D(this,dr,ws(()=>g(this,Jo).state==="speaking"?"speaking":g(this,po).turnState==="calling-tool"?"calling-tool":g(this,po).turnState==="responding"?"responding":g(this,po).turnState==="thinking"?"thinking":g(this,po).turnState==="waiting"?"waiting":g(this,Jo).enabled&&g(this,Jo).hasPendingNarration?"pending-tts":null));O(this,po,e.session),O(this,Jo,e.speaker)}get phase(){return Y(g(this,dr))}set phase(e){te(g(this,dr),e)}}po=new WeakMap,Jo=new WeakMap,dr=new WeakMap;var fo,Wo,Ko,pr,fr;class hZ{constructor(e){D(this,fo);D(this,Wo);D(this,Ko);D(this,pr,se(!1));D(this,fr,ws(()=>this.isCancelling?"cancelling":g(this,fo).state==="recording"?"recording":g(this,fo).state==="transcribing"?"transcribing":g(this,Ko).state==="speaking"?"speaking":g(this,Wo).turnState!=="idle"?"thinking":"idle"));O(this,fo,e.mic),O(this,Wo,e.session),O(this,Ko,e.speaker),Ga(()=>{this.isCancelling&&g(this,fo).state==="idle"&&g(this,Wo).turnState==="idle"&&g(this,Ko).state==="idle"&&(this.isCancelling=!1)})}get isCancelling(){return Y(g(this,pr))}set isCancelling(e){te(g(this,pr),e,!0)}get state(){return Y(g(this,fr))}set state(e){te(g(this,fr),e)}cancel(){this.isCancelling=!0,g(this,fo).cancel(),g(this,Ko).stop(),g(this,Wo).cancelTurn()}}fo=new WeakMap,Wo=new WeakMap,Ko=new WeakMap,pr=new WeakMap,fr=new WeakMap;const mZ={"connect.title":"drive-coding v2","connect.subtitle":"Connect to a CLI agent","connect.cli.label":"CLI","connect.cwd.label":"Working directory","connect.cwd.placeholder":"/home/user/projects/X","connect.submit":"Connect","connect.submitting":"Connecting…","connect.error.prefix":"Error:","chat.bubble.user":"Me","chat.bubble.thought":"Thought","chat.bubble.agent":"Agent","chat.empty":"Start typing below…","chat.prompt.placeholder":"Type a prompt…","chat.send":"Send","chat.disconnect":"Disconnect","chat.audioToggle":"Audio","chat.voicePicker.label":"Voice","chat.voicePicker.loading":"Loading voices…","chat.voicePicker.error":"Failed to load voices","mic.error.permission":"Microphone access denied. Allow access in browser settings.","mic.error.notFound":"No microphone found. Connect a microphone and try again.","mic.error.transcribe":"Transcription failed. Please try again.","mic.error.generic":"Microphone error. Please try again.","mic.retry":"Try again","voiceMode.status.idle":"Microphone","voiceMode.status.recording":"Recording…","voiceMode.status.transcribing":"Transcribing…","voiceMode.status.thinking":"Thinking…","voiceMode.status.speaking":"Speaking…","voiceMode.status.cancelling":"Cancelling…","chat.tool.status.pending":"Pending","chat.tool.status.in_progress":"In progress","chat.tool.status.completed":"Completed","chat.tool.status.failed":"Failed","chat.tool.args":"Input","chat.tool.result":"Output","chat.tool.loading_narration":"...","chat.tool.raw":"Raw output","chat.tool.locations":"Files","chat.tool.content":"Content","chat.tool.terminal":"Terminal","chat.tool.diff.added":"Added","chat.tool.diff.removed":"Removed","sessions.loadButton":"Load recent sessions","sessions.loading":"Loading…","sessions.label":"Select session","sessions.startNew":"New","sessions.error":"Failed to load","sessions.refresh":"Refresh","settings.title":"Settings","settings.beUrl.label":"Backend URL","settings.beUrl.help":"Leave empty in dev mode. In production (Cloudflare) enter the full BE URL.","settings.beUrl.invalid":"Invalid URL","settings.beUrl.saved":"Saved ✓","settings.back":"Back","agentOptions.title":"Session options","agentOptions.model.label":"Model","agentOptions.model.other":"Other","agentOptions.agent.label":"Agent","agentOptions.mode.label":"Mode","configName.agent":"Agent","configName.mode":"Mode","configName.sessionMode":"Session Mode","configName.approvalPreset":"Approval Preset","configName.model":"Model","configName.effort":"Effort","configName.reasoningEffort":"Reasoning Effort","chat.jumpDown":"New messages","modal.sessions.title":"Recent sessions","modal.sessions.refresh":"Refresh","modal.sessions.new":"New session","modal.sessions.loading":"Loading sessions…","modal.sessions.error":"Failed to load sessions","modal.sessions.empty":"No sessions","modal.folder.title":"Select folder","modal.folder.pick":"Choose this folder","modal.folder.up":"Up","modal.folder.loading":"Loading…","modal.folder.error":"Failed to load folders","modal.folder.showHidden":"Show hidden folders","modal.close":"Close","record.tab.record":"Record","record.tab.type":"Type","record.tab.hide":"Hidden","record.status.idle":"Tap to record","record.send":"Send","record.placeholder":"Type a prompt…","record.reconnect":"Reconnect","record.reconnecting":"Reconnecting…","record.reconnectAttempt":"attempt","mic.stop":"Stop","settings.connection":"Connection","settings.voiceSpeech":"Voice & Speech","settings.folder.label":"Working directory","settings.folder.pick":"Browse…","settings.model.label":"Model","settings.session.label":"Session","settings.voice.label":"TTS Voice","settings.toggle.speakThoughts":"Speak model thoughts","settings.toggle.narrateTools":"Narrate tool actions","settings.toggle.translateThoughts":"Translate thoughts to Hebrew","settings.toggle.carMode":"Car mode (Play on Bluetooth = record)","settings.reset":"Reset","settings.saveOpen":"Save & Open","settings.version":"Version:","settings.language.label":"Interface language","settings.language.he":"Hebrew","settings.language.en":"English","header.menu":"Menu","header.settings":"Settings","header.connected":"Connected","header.disconnect":"Disconnect","header.audioOn":"Mute audio","header.audioOff":"Unmute audio","sidebar.collapse":"Collapse panel","sidebar.agentOptions":"Agent options","sidebar.sessions":"Sessions","sidebar.refresh":"Refresh","sidebar.newSession":"New session","sidebar.runningOn":"Running on","sheet.handle":"Drag to open","bubble.play":"Play","bubble.stop":"Stop playback","bubble.copy":"Copy","bubble.copied":"Copied!","modelStatus.waiting":"Waiting…","modelStatus.thinking":"Thinking…","modelStatus.responding":"Responding…","modelStatus.callingTool":"Running tool…","modelStatus.pendingTts":"Preparing audio…","modelStatus.speaking":"Speaking…","settings.theme.label":"Theme","settings.theme.ember":"Ember","settings.theme.forest":"Forest","settings.theme.plum":"Plum","settings.theme.teal":"Teal","settings.theme.midnight":"Midnight","settings.theme.rose":"Rose","settings.theme.slate":"Slate","settings.theme.daylight":"Daylight","connect.agents.title":"Active processes","connect.agents.empty":"No active processes","connect.agents.refresh":"Refresh","connect.agents.reconnect":"Reconnect","connect.agents.kill":"Kill","connect.agents.killConfirm":"Sure?","connect.agents.inUse":"Open in another tab","connect.agents.working":"working…","connect.agents.lastMessage":"Last activity","settings.screen.label":"Screen","settings.toggle.keepScreenOn":"Keep screen on","settings.chatDisplay":"Chat display","settings.toggle.showThoughts":"Show thoughts by default","settings.toggle.showTools":"Show tools by default","settings.toggle.enterToSend":"Enter sends message","contentViewer.title":"View","contentViewer.expand":"Expand","contentViewer.close":"Close","settings.ttsProvider.label":"TTS provider","settings.ttsProvider.elevenlabs":"ElevenLabs","settings.ttsProvider.gemini":"Gemini","attach.addImage":"Add image","attach.remove":"Remove","chat.content.attachedFile":"Attached file","chat.content.unsupported":"Unsupported content","connect.recent.title":"Recent folders","connect.recent.empty":"No recent folders","connect.recent.refresh":"Refresh","connect.recent.remove":"Remove from list","connect.recent.collapse":"Collapse","connect.recent.expand":"Expand","session.leaveRunning":"Leave — keep running","session.closeSession":"Shut the process down completely","session.leaveWarning.title":"Agent will keep running","session.leaveWarning.body":"The run will stall when a permission request arrives, because the browser is the ACP client. To prevent stalling: switch to bypass-permissions mode before leaving.","session.leaveWarning.confirm":"Leave anyway","session.leaveWarning.cancel":"Cancel","session.leaveWarning.dontShowAgain":"Don't show this message again","agentOptions.thinking.label":"Thinking","agentOptions.thinking.off":"Off","agentOptions.thinking.low":"Low","agentOptions.thinking.medium":"Medium","agentOptions.thinking.high":"High","settings.geminiVoice.label":"Gemini voice","settings.geminiVoice.desc.Zephyr":"Bright","settings.geminiVoice.desc.Puck":"Upbeat","settings.geminiVoice.desc.Charon":"Informative","settings.geminiVoice.desc.Kore":"Firm","settings.geminiVoice.desc.Fenrir":"Excitable","settings.geminiVoice.desc.Leda":"Youthful","settings.geminiVoice.desc.Orus":"Firm","settings.geminiVoice.desc.Aoede":"Breezy","settings.geminiVoice.desc.Callirrhoe":"Easy-going","settings.geminiVoice.desc.Autonoe":"Bright","settings.geminiVoice.desc.Enceladus":"Breathy","settings.geminiVoice.desc.Iapetus":"Clear","settings.geminiVoice.desc.Umbriel":"Easy-going","settings.geminiVoice.desc.Algieba":"Smooth","settings.geminiVoice.desc.Despina":"Smooth","settings.geminiVoice.desc.Erinome":"Clear","settings.geminiVoice.desc.Algenib":"Gravelly","settings.geminiVoice.desc.Rasalgethi":"Informative","settings.geminiVoice.desc.Laomedeia":"Upbeat","settings.geminiVoice.desc.Achernar":"Soft","settings.geminiVoice.desc.Alnilam":"Firm","settings.geminiVoice.desc.Schedar":"Even","settings.geminiVoice.desc.Gacrux":"Mature","settings.geminiVoice.desc.Pulcherrima":"Forward","settings.geminiVoice.desc.Achird":"Friendly","settings.geminiVoice.desc.Zubenelgenubi":"Casual","settings.geminiVoice.desc.Vindemiatrix":"Gentle","settings.geminiVoice.desc.Sadachbia":"Lively","settings.geminiVoice.desc.Sadaltager":"Knowledgeable","settings.geminiVoice.desc.Sulafat":"Warm","settings.ttsProvider.unavailable":"This provider is unavailable (missing or invalid key)","settings.ttsProvider.fallbackNotice":"Switched to the available provider","settings.ttsProvider.allUnavailable":"No TTS provider available — check your keys","settings.ttsStatus.title":"TTS Status","settings.ttsStatus.loading":"Loading...","settings.ttsStatus.reason.quota":"Quota exhausted","settings.ttsStatus.reason.noKey":"Missing API key","settings.ttsStatus.reason.forbidden":"Key not authorized","settings.ttsStatus.reason.error":"Connection error","settings.ttsStatus.quota.label":"ElevenLabs quota","settings.ttsStatus.quota.exhausted":"Exhausted","settings.ttsStatus.quota.used":"Used","settings.ttsStatus.quota.limitLabel":"Limit","settings.ttsStatus.quota.overage":"Overage","settings.ttsStatus.usage.label":"Usage (total since startup)","settings.ttsStatus.usage.elevenlabs":"ElevenLabs","settings.ttsStatus.usage.gemini":"Gemini","settings.ttsStatus.usage.cache":"Cache hits","settings.ttsStatus.usage.cost":"Est. cost","settings.ttsStatus.usage.notAvailable":"—","settings.ttsStatus.refresh":"Refresh","session.copyId":"Copy session ID","modal.loading.session":"Loading session…","appTitle.settings":"Settings","appTitle.sessions":"Sessions","slash.commandsList":"Slash commands"},gZ={"connect.title":"drive-coding v2","connect.subtitle":"חבר ל-CLI agent","connect.cli.label":"CLI","connect.cwd.label":"תיקיית עבודה","connect.cwd.placeholder":"/home/user/projects/X","connect.submit":"חבר","connect.submitting":"מתחבר…","connect.error.prefix":"שגיאה:","chat.bubble.user":"אני","chat.bubble.thought":"מחשבה","chat.bubble.agent":"סוכן","chat.empty":"התחל לכתוב למטה…","chat.prompt.placeholder":"כתוב prompt…","chat.send":"שלח","chat.disconnect":"נתק","chat.audioToggle":"אודיו","chat.voicePicker.label":"קול","chat.voicePicker.loading":"טוען קולות…","chat.voicePicker.error":"שגיאה בטעינת קולות","mic.error.permission":"הגישה למיקרופון נדחתה. אפשר גישה בהגדרות הדפדפן.","mic.error.notFound":"לא נמצא מיקרופון. חבר מיקרופון ונסה שוב.","mic.error.transcribe":"התמלול נכשל. נסה שוב.","mic.error.generic":"שגיאה במיקרופון. נסה שוב.","mic.retry":"נסה שוב","voiceMode.status.idle":"מיקרופון","voiceMode.status.recording":"מקליט…","voiceMode.status.transcribing":"מתמלל…","voiceMode.status.thinking":"חושב…","voiceMode.status.speaking":"מדבר…","voiceMode.status.cancelling":"מבטל…","chat.tool.status.pending":"ממתין","chat.tool.status.in_progress":"בתהליך","chat.tool.status.completed":"הושלם","chat.tool.status.failed":"נכשל","chat.tool.args":"קלט","chat.tool.result":"פלט","chat.tool.loading_narration":"...","chat.tool.raw":"פלט גולמי","chat.tool.locations":"קבצים","chat.tool.content":"תוכן","chat.tool.terminal":"טרמינל","chat.tool.diff.added":"נוסף","chat.tool.diff.removed":"הוסר","sessions.loadButton":"טען סשנים אחרונים","sessions.loading":"טוען…","sessions.label":"בחירת סשן","sessions.startNew":"חדש","sessions.error":"שגיאה בטעינה","sessions.refresh":"רענן","settings.title":"הגדרות","settings.beUrl.label":"כתובת השרת (BE URL)","settings.beUrl.help":"השאר ריק במצב פיתוח. בפרודקשן (Cloudflare) הזן את הכתובת המלאה של ה-BE.","settings.beUrl.invalid":"כתובת לא תקינה","settings.beUrl.saved":"נשמר ✓","settings.back":"חזרה","agentOptions.title":"הגדרות סשן","agentOptions.model.label":"מודל","agentOptions.model.other":"אחר","agentOptions.agent.label":"סוכן","agentOptions.mode.label":"מצב","configName.agent":"סוכן","configName.mode":"מצב","configName.sessionMode":"מצב סשן","configName.approvalPreset":"רמת אישורים","configName.model":"מודל","configName.effort":"מאמץ","configName.reasoningEffort":"מאמץ חשיבה","chat.jumpDown":"הודעות חדשות","modal.sessions.title":"סשנים אחרונים","modal.sessions.refresh":"רענן","modal.sessions.new":"סשן חדש","modal.sessions.loading":"טוען סשנים…","modal.sessions.error":"שגיאה בטעינת סשנים","modal.sessions.empty":"אין סשנים","modal.folder.title":"בחר תיקייה","modal.folder.pick":"בחר תיקייה זו","modal.folder.up":"עלה","modal.folder.loading":"טוען…","modal.folder.error":"שגיאה בטעינת תיקיות","modal.folder.showHidden":"הצג תיקיות מוסתרות","modal.close":"סגור","record.tab.record":"הקלטה","record.tab.type":"הקלדה","record.tab.hide":"מוסתר","record.status.idle":"לחץ להקלטה","record.send":"שלח","record.placeholder":"כתוב prompt…","record.reconnect":"התחבר מחדש","record.reconnecting":"מתחבר מחדש…","record.reconnectAttempt":"ניסיון","mic.stop":"עצור","settings.connection":"חיבור","settings.voiceSpeech":"קול ודיבור","settings.folder.label":"תיקיית עבודה","settings.folder.pick":"בחר…","settings.model.label":"מודל","settings.session.label":"Session","settings.voice.label":"קול ה-TTS","settings.toggle.speakThoughts":"הקראת מחשבות המודל","settings.toggle.narrateTools":"קריינות פעולות (כלים)","settings.toggle.translateThoughts":"תרגום מחשבות לעברית","settings.toggle.carMode":"מצב רכב (Play בבלוטוס = הקלטה)","settings.reset":"איפוס","settings.saveOpen":"שמור ופתח","settings.version":"גרסה:","settings.language.label":"שפת ממשק","settings.language.he":"עברית","settings.language.en":"English","header.menu":"תפריט","header.settings":"הגדרות","header.connected":"מחובר","header.disconnect":"נתק","header.audioOn":"השתק שמע","header.audioOff":"הפעל שמע","sidebar.collapse":"קפל פאנל","sidebar.agentOptions":"אפשרויות סוכן","sidebar.sessions":"סשנים","sidebar.refresh":"רענן","sidebar.newSession":"סשן חדש","sidebar.runningOn":"פועל על","sheet.handle":"גרור לפתיחה","bubble.play":"השמע","bubble.stop":"עצור השמעה","bubble.copy":"העתק","bubble.copied":"הועתק!","modelStatus.waiting":"ממתין…","modelStatus.thinking":"חושב…","modelStatus.responding":"מגיב…","modelStatus.callingTool":"מריץ כלי…","modelStatus.pendingTts":"מכין השמעה…","modelStatus.speaking":"מדבר…","settings.theme.label":"ערכת נושא","settings.theme.ember":"גחלת","settings.theme.forest":"יער","settings.theme.plum":"שזיף","settings.theme.teal":"טורקיז","settings.theme.midnight":"חצות","settings.theme.rose":"ורד","settings.theme.slate":"צפחה","settings.theme.daylight":"אור יום","connect.agents.title":"תהליכים פעילים","connect.agents.empty":"אין תהליכים פעילים","connect.agents.refresh":"רענן","connect.agents.reconnect":"התחבר מחדש","connect.agents.kill":"הרוג","connect.agents.killConfirm":"בטוח?","connect.agents.inUse":"פעיל בכרטיסייה אחרת","connect.agents.working":"עובד…","connect.agents.lastMessage":"פעילות אחרונה","settings.screen.label":"מסך","settings.toggle.keepScreenOn":"השאר מסך דלוק","settings.chatDisplay":"תצוגת צ'אט","settings.toggle.showThoughts":"הצג מחשבות כברירת מחדל","settings.toggle.showTools":"הצג כלים כברירת מחדל","settings.toggle.enterToSend":"Enter שולח הודעה","contentViewer.title":"תצוגה","contentViewer.expand":"הרחב","contentViewer.close":"סגור","settings.ttsProvider.label":"ספק TTS","settings.ttsProvider.elevenlabs":"ElevenLabs","settings.ttsProvider.gemini":"Gemini","attach.addImage":"הוסף תמונה","attach.remove":"הסר","chat.content.attachedFile":"קובץ מצורף","chat.content.unsupported":"תוכן לא-נתמך","connect.recent.title":"תיקיות אחרונות","connect.recent.empty":"אין תיקיות אחרונות","connect.recent.refresh":"רענן","connect.recent.remove":"הסר מהרשימה","connect.recent.collapse":"כווץ","connect.recent.expand":"הרחב","session.leaveRunning":"צא — השאר רץ","session.closeSession":"כבה לגמרי את התהליך","session.leaveWarning.title":"הסוכן ימשיך לרוץ","session.leaveWarning.body":"הריצה תיעצר ברגע שתגיע בקשת-הרשאה, כי הדפדפן הוא ה-ACP client. למנוע תקיעה: עבור למצב עקיפת-הרשאות לפני שתצא.","session.leaveWarning.confirm":"צא בכל זאת","session.leaveWarning.cancel":"ביטול","session.leaveWarning.dontShowAgain":"אל תציג הודעה זו שוב","agentOptions.thinking.label":"חשיבה","agentOptions.thinking.off":"כבוי","agentOptions.thinking.low":"נמוך","agentOptions.thinking.medium":"בינוני","agentOptions.thinking.high":"גבוה","settings.geminiVoice.label":"קול Gemini","settings.geminiVoice.desc.Zephyr":"Bright · בהיר","settings.geminiVoice.desc.Puck":"Upbeat · עליז","settings.geminiVoice.desc.Charon":"Informative · אינפורמטיבי","settings.geminiVoice.desc.Kore":"Firm · תקיף","settings.geminiVoice.desc.Fenrir":"Excitable · נלהב","settings.geminiVoice.desc.Leda":"Youthful · צעיר","settings.geminiVoice.desc.Orus":"Firm · תקיף","settings.geminiVoice.desc.Aoede":"Breezy · קליל","settings.geminiVoice.desc.Callirrhoe":"Easy-going · נינוח","settings.geminiVoice.desc.Autonoe":"Bright · בהיר","settings.geminiVoice.desc.Enceladus":"Breathy · נשימתי","settings.geminiVoice.desc.Iapetus":"Clear · צלול","settings.geminiVoice.desc.Umbriel":"Easy-going · נינוח","settings.geminiVoice.desc.Algieba":"Smooth · חלק","settings.geminiVoice.desc.Despina":"Smooth · חלק","settings.geminiVoice.desc.Erinome":"Clear · צלול","settings.geminiVoice.desc.Algenib":"Gravelly · גרגרי","settings.geminiVoice.desc.Rasalgethi":"Informative · אינפורמטיבי","settings.geminiVoice.desc.Laomedeia":"Upbeat · עליז","settings.geminiVoice.desc.Achernar":"Soft · עדין","settings.geminiVoice.desc.Alnilam":"Firm · תקיף","settings.geminiVoice.desc.Schedar":"Even · מאוזן","settings.geminiVoice.desc.Gacrux":"Mature · בוגר","settings.geminiVoice.desc.Pulcherrima":"Forward · ישיר","settings.geminiVoice.desc.Achird":"Friendly · ידידותי","settings.geminiVoice.desc.Zubenelgenubi":"Casual · ספונטני","settings.geminiVoice.desc.Vindemiatrix":"Gentle · עדין","settings.geminiVoice.desc.Sadachbia":"Lively · חי","settings.geminiVoice.desc.Sadaltager":"Knowledgeable · בקיא","settings.geminiVoice.desc.Sulafat":"Warm · חם","settings.ttsProvider.unavailable":"ספק זה אינו זמין (חסר מפתח או מפתח לא תקף)","settings.ttsProvider.fallbackNotice":"עברנו לספק הזמין","settings.ttsProvider.allUnavailable":"אין ספק TTS זמין — בדוק מפתחות","settings.ttsStatus.title":"מצב TTS","settings.ttsStatus.loading":"טוען...","settings.ttsStatus.reason.quota":"המכסה מוצתה","settings.ttsStatus.reason.noKey":"חסר מפתח","settings.ttsStatus.reason.forbidden":"מפתח לא מורשה","settings.ttsStatus.reason.error":"שגיאת חיבור","settings.ttsStatus.quota.label":"מכסת ElevenLabs","settings.ttsStatus.quota.exhausted":"מוצה","settings.ttsStatus.quota.used":"נוצל","settings.ttsStatus.quota.limitLabel":"מכסה","settings.ttsStatus.quota.overage":"חריגה","settings.ttsStatus.usage.label":'שימוש (סה"כ מאז ההפעלה)',"settings.ttsStatus.usage.elevenlabs":"ElevenLabs","settings.ttsStatus.usage.gemini":"Gemini","settings.ttsStatus.usage.cache":"מטמון","settings.ttsStatus.usage.cost":"עלות משוערת","settings.ttsStatus.usage.notAvailable":"—","settings.ttsStatus.refresh":"רענן","session.copyId":"העתק מזהה סשן","modal.loading.session":"טוען סשן…","appTitle.settings":"הגדרות","appTitle.sessions":"סשנים","slash.commandsList":"רשימת פקודות slash"},Bm={he:gZ,en:mZ},_d="he";function vZ(t){const e=Bm[t.locale],n=Bm[_d];return{locale:t.locale,t:o=>e[o]??n[o]}}function Cu(){return typeof navigator>"u"?_d:(navigator.language??"").toLowerCase().startsWith("he")?"he":"en"}var Ni,yl;class yZ{constructor(e){D(this,Ni);D(this,yl,ws(()=>vZ({locale:this.locale})));Z(this,"t",e=>Y(g(this,yl)).t(e));Z(this,"setLocale",e=>{g(this,Ni).setLocale(e)});O(this,Ni,e.settings)}get locale(){return g(this,Ni).locale}}Ni=new WeakMap,yl=new WeakMap;class _Z{constructor(){Z(this,"mr",null);Z(this,"chunks",[])}async start(){console.info("[recorder] start");let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(o){throw console.warn("[recorder] mic permission denied",String(o)),o}const n=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm";this.mr=new MediaRecorder(e,{mimeType:n}),this.chunks=[],this.mr.ondataavailable=o=>{o.data.size>0&&this.chunks.push(o.data)},this.mr.start()}stop(){return new Promise(e=>{if(!this.mr){e({blob:new Blob,mimeType:"audio/webm"});return}const n=this.mr.mimeType||"audio/webm";this.mr.onstop=()=>{var i;const o=new Blob(this.chunks,{type:n});console.info("[recorder] stop",{bytes:o.size,mimeType:n}),(i=this.mr)==null||i.stream.getTracks().forEach(s=>{s.stop()}),this.mr=null,e({blob:o,mimeType:n})},this.mr.stop()})}get isRecording(){return this.mr!==null&&this.mr.state==="recording"}}async function TZ(t,e){const n=e==null?void 0:e.retries,o=e==null?void 0:e.baseDelayMs,i=e==null?void 0:e.maxDelayMs,s=e==null?void 0:e.signal,r=(e==null?void 0:e.shouldRetry)??(()=>!0),a=e==null?void 0:e.label;if(s!=null&&s.aborted)throw new DOMException(`${a} aborted`,"AbortError");let u;for(let c=0;c<n;c++)try{return await t(c)}catch(p){if(u=p,s!=null&&s.aborted||!r(p))throw p;if(c>=n-1)break;const f=Math.min(o*2**c,i);if(await new Promise((h,m)=>{let v;const _=()=>{clearTimeout(v),m(new DOMException(`${a} aborted during retry sleep`,"AbortError"))};if(s!=null&&s.aborted){m(new DOMException(`${a} aborted`,"AbortError"));return}s==null||s.addEventListener("abort",_,{once:!0}),v=setTimeout(()=>{s==null||s.removeEventListener("abort",_),h()},f)}),s!=null&&s.aborted)throw new DOMException(`${a} aborted`,"AbortError")}throw u}const EZ=3e4;async function wZ(t,e={}){const n=new Uint8Array(await t.arrayBuffer()),o=t.type||"audio/webm",i=GN(t).catch(()=>({id:""})),s="Output in the original script of the language spoken. If Hebrew, output Hebrew letters.",r=e.previousAssistantText?`Transcribe the user's audio. Context: previous assistant said: "${e.previousAssistantText}". Transcribe ONLY user's audio. ${s}`:`Transcribe the audio. ${s}`,a=Qy(n),u=await TZ(()=>Ln(f=>KE().models.generateContent({model:"gemini-flash-latest",contents:[{role:"user",parts:[{text:r},{inlineData:{mimeType:o,data:a}}]}],config:{abortSignal:f}}),EZ,{signal:e.signal,label:"transcribe"}),{retries:3,baseDelayMs:800,maxDelayMs:4e3,signal:e.signal,label:"transcribe"}),{id:c}=await i;return{text:u.text??"",recordingId:c}}var hr,mr,gr,Yo,Mi,ho,vr;class IZ{constructor(e){D(this,hr,se("idle"));D(this,mr,se(null));D(this,gr);D(this,Yo);D(this,Mi);D(this,ho,null);Z(this,"toggle",async()=>{var e,n;if(this.state==="idle"){this.state="recording",this.error=null;try{await g(this,Yo).start()}catch(o){this.state="idle",o instanceof DOMException&&o.name==="NotAllowedError"?this.error="mic.error.permission":o instanceof DOMException&&o.name==="NotFoundError"?this.error="mic.error.notFound":this.error="mic.error.generic";return}(e=g(this,Mi))==null||e.play("recordingStart");return}if(this.state==="recording"){this.state="transcribing",(n=g(this,Mi))==null||n.play("recordingStop");let o;try{o=(await g(this,Yo).stop()).blob}catch(i){this.state="idle",console.warn("[mic] recorder.stop() failed",i),this.error="mic.error.generic";return}O(this,ho,o),await g(this,vr).call(this,o);return}});Z(this,"retryTranscribe",async()=>{g(this,ho)!==null&&this.state==="idle"&&(this.state="transcribing",this.error=null,await g(this,vr).call(this,g(this,ho)))});D(this,vr,async e=>{let n,o;try{const i=await wZ(e);n=i.text,o=i.recordingId}catch(i){this.state="idle",console.warn("[mic] transcribe() failed",i),this.error="mic.error.transcribe";return}O(this,ho,null),n.trim().length>0&&g(this,gr).sendPrompt(n,{recordingId:o}),this.state="idle"});O(this,gr,e.session),O(this,Yo,new _Z),O(this,Mi,e.cues)}get state(){return Y(g(this,hr))}set state(e){te(g(this,hr),e,!0)}get error(){return Y(g(this,mr))}set error(e){te(g(this,mr),e,!0)}get canRetry(){return g(this,ho)!==null}cancel(){this.state==="recording"&&(g(this,Yo).stop().catch(()=>{}),this.state="idle",this.error=null)}}hr=new WeakMap,mr=new WeakMap,gr=new WeakMap,Yo=new WeakMap,Mi=new WeakMap,ho=new WeakMap,vr=new WeakMap;var yr;class SZ{constructor(){D(this,yr,se(null))}get payload(){return Y(g(this,yr))}set payload(e){te(g(this,yr),e,!0)}get open(){return this.payload!==null}show(e){this.payload=e}close(){this.payload=null}}yr=new WeakMap;var _r;class CZ{constructor(){D(this,_r,se(!1))}get folderOpen(){return Y(g(this,_r))}set folderOpen(e){te(g(this,_r),e,!0)}openFolder(){this.folderOpen=!0}closeFolder(){this.folderOpen=!1}}_r=new WeakMap;var Tr,xi;class AZ{constructor(){D(this,Tr,se(!1));D(this,xi);typeof window>"u"||(O(this,xi,window.matchMedia("(max-width: 767px)")),this.isMobile=g(this,xi).matches,g(this,xi).addEventListener("change",e=>{this.isMobile=e.matches}))}get isMobile(){return Y(g(this,Tr))}set isMobile(e){te(g(this,Tr),e,!0)}}Tr=new WeakMap,xi=new WeakMap;const bZ=8e3;async function RZ(t){const e=await Ln(o=>fetch(An("/proxy/elevenlabs/v1/voices"),{method:"GET",headers:{"xi-api-key":"browser-placeholder",accept:"application/json"},signal:o}),bZ,{signal:t,label:"listVoices"});if(!e.ok){const o=await e.text().catch(()=>"");throw new Error(`listVoices failed: ${e.status} ${o}`)}return(await e.json()).voices??[]}const iw="drive-coding-v2-settings",kZ="EXAVITQu4vr4xnSDxMaL",tt={cliKind:"opencode",lastCwd:"",voiceId:kZ,beUrl:"",speakThoughts:!0,narrateTools:!0,translateThoughts:!0,carMode:!1,locale:_d,muted:!1,screenWakeLock:!1,showThoughts:!0,showTools:!1,enterToSend:!0,lastConfig:{},ttsProvider:"elevenlabs",recentCollapsed:!1,suppressLeaveWarning:!1,geminiVoice:Og};function PZ(){if(typeof localStorage>"u")return{...tt,locale:Cu()};try{const t=localStorage.getItem(iw);if(!t)return{...tt,locale:Cu()};const e=JSON.parse(t);return e.showThoughts===void 0&&e.collapseThoughts!==void 0&&(e.showThoughts=!e.collapseThoughts),e.showTools===void 0&&e.expandTools!==void 0&&(e.showTools=e.expandTools),{...tt,...e}}catch{return{...tt,locale:Cu()}}}function NZ(t){if(!(typeof localStorage>"u"))try{localStorage.setItem(iw,JSON.stringify(t))}catch{}}var Er,wr,Ir,Sr,Cr,Ar,mo,qn,br,Rr,kr,Pr,Nr,Mr,xr,Dr,$r,Ur,Or,Lr,Gr,zr,Fr,Vr,_l,Tl,El,Le,sw,Ua,ut;const to=class to{constructor(){D(this,Le);D(this,Er,se(qe(tt.cliKind)));D(this,wr,se(qe(tt.lastCwd)));D(this,Ir,se(qe(tt.voiceId)));D(this,Sr,se(qe([])));D(this,Cr,se(!1));D(this,Ar,se(null));D(this,mo,0);D(this,qn,null);D(this,br,se(qe(tt.beUrl)));D(this,Rr,se(qe(tt.speakThoughts)));D(this,kr,se(qe(tt.narrateTools)));D(this,Pr,se(qe(tt.translateThoughts)));D(this,Nr,se(qe(tt.carMode)));D(this,Mr,se(qe(tt.locale)));D(this,xr,se(qe(tt.muted)));D(this,Dr,se(qe(tt.screenWakeLock)));D(this,$r,se(qe(tt.showThoughts)));D(this,Ur,se(qe(tt.showTools)));D(this,Or,se(qe(tt.enterToSend)));D(this,Lr,se(qe(tt.lastConfig)));D(this,Gr,se(qe(tt.ttsProvider)));D(this,zr,se(qe(tt.recentCollapsed)));D(this,Fr,se(qe(tt.suppressLeaveWarning)));D(this,Vr,se(qe(tt.geminiVoice)));Z(this,"setCliKind",e=>{this.cliKind=e,$(this,Le,ut).call(this)});Z(this,"setLastCwd",e=>{this.lastCwd=e,$(this,Le,ut).call(this)});Z(this,"setVoiceId",e=>{this.voiceId=e,$(this,Le,ut).call(this)});Z(this,"loadVoices",async(e=!1)=>{if(!Is.isAvailable("elevenlabs")){$(this,Le,Ua).call(this);return}if(!this.voicesLoading&&!(this.availableVoices.length>0&&this.voicesError===null)){if(e)$(this,Le,Ua).call(this),O(this,mo,0);else if(g(this,qn)!==null)return;this.voicesLoading=!0,this.voicesError=null;try{const n=await RZ();this.availableVoices=n,O(this,mo,0)}catch(n){this.voicesError=n instanceof Error?n.message:String(n),$(this,Le,sw).call(this)}finally{this.voicesLoading=!1}}});Z(this,"setBeUrl",e=>{const n=e.trim().replace(/\/$/,"");if(n==="")return this.beUrl="",iu(this.beUrl),$(this,Le,ut).call(this),{ok:!0};try{const o=new URL(n);return o.protocol!=="http:"&&o.protocol!=="https:"?{ok:!1,error:"scheme must be http or https"}:(this.beUrl=n,iu(this.beUrl),$(this,Le,ut).call(this),{ok:!0})}catch{return{ok:!1,error:"malformed URL"}}});Z(this,"setSpeakThoughts",e=>{this.speakThoughts=e,$(this,Le,ut).call(this)});Z(this,"setNarrateTools",e=>{this.narrateTools=e,$(this,Le,ut).call(this)});Z(this,"setTranslateThoughts",e=>{this.translateThoughts=e,$(this,Le,ut).call(this)});Z(this,"setCarMode",e=>{this.carMode=e,$(this,Le,ut).call(this)});Z(this,"setLocale",e=>{this.locale=e,$(this,Le,ut).call(this)});Z(this,"setMuted",e=>{this.muted=e,$(this,Le,ut).call(this)});Z(this,"setScreenWakeLock",e=>{this.screenWakeLock=e,$(this,Le,ut).call(this)});Z(this,"setShowThoughts",e=>{this.showThoughts=e,$(this,Le,ut).call(this)});Z(this,"setShowTools",e=>{this.showTools=e,$(this,Le,ut).call(this)});Z(this,"setEnterToSend",e=>{this.enterToSend=e,$(this,Le,ut).call(this)});Z(this,"setLastConfig",(e,n,o)=>{this.lastConfig={...this.lastConfig,[e]:{...this.lastConfig[e]??{},[n]:o}},$(this,Le,ut).call(this)});Z(this,"setTtsProvider",e=>{this.ttsProvider=e,$(this,Le,ut).call(this)});Z(this,"setRecentCollapsed",e=>{this.recentCollapsed=e,$(this,Le,ut).call(this)});Z(this,"setSuppressLeaveWarning",e=>{this.suppressLeaveWarning=e,$(this,Le,ut).call(this)});Z(this,"setGeminiVoice",e=>{this.geminiVoice=e,$(this,Le,ut).call(this)});const e=PZ();this.cliKind=e.cliKind,this.lastCwd=e.lastCwd,this.voiceId=e.voiceId,this.beUrl=e.beUrl,iu(this.beUrl),this.speakThoughts=e.speakThoughts,this.narrateTools=e.narrateTools,this.translateThoughts=e.translateThoughts,this.carMode=e.carMode,this.locale=e.locale,this.muted=e.muted,this.screenWakeLock=e.screenWakeLock,this.showThoughts=e.showThoughts,this.showTools=e.showTools,this.enterToSend=e.enterToSend,this.lastConfig=e.lastConfig,this.ttsProvider=e.ttsProvider,this.recentCollapsed=e.recentCollapsed,this.suppressLeaveWarning=e.suppressLeaveWarning,this.geminiVoice=e.geminiVoice}get cliKind(){return Y(g(this,Er))}set cliKind(e){te(g(this,Er),e,!0)}get lastCwd(){return Y(g(this,wr))}set lastCwd(e){te(g(this,wr),e,!0)}get voiceId(){return Y(g(this,Ir))}set voiceId(e){te(g(this,Ir),e,!0)}get availableVoices(){return Y(g(this,Sr))}set availableVoices(e){te(g(this,Sr),e,!0)}get voicesLoading(){return Y(g(this,Cr))}set voicesLoading(e){te(g(this,Cr),e,!0)}get voicesError(){return Y(g(this,Ar))}set voicesError(e){te(g(this,Ar),e,!0)}get beUrl(){return Y(g(this,br))}set beUrl(e){te(g(this,br),e,!0)}get speakThoughts(){return Y(g(this,Rr))}set speakThoughts(e){te(g(this,Rr),e,!0)}get narrateTools(){return Y(g(this,kr))}set narrateTools(e){te(g(this,kr),e,!0)}get translateThoughts(){return Y(g(this,Pr))}set translateThoughts(e){te(g(this,Pr),e,!0)}get carMode(){return Y(g(this,Nr))}set carMode(e){te(g(this,Nr),e,!0)}get locale(){return Y(g(this,Mr))}set locale(e){te(g(this,Mr),e,!0)}get muted(){return Y(g(this,xr))}set muted(e){te(g(this,xr),e,!0)}get screenWakeLock(){return Y(g(this,Dr))}set screenWakeLock(e){te(g(this,Dr),e,!0)}get showThoughts(){return Y(g(this,$r))}set showThoughts(e){te(g(this,$r),e,!0)}get showTools(){return Y(g(this,Ur))}set showTools(e){te(g(this,Ur),e,!0)}get enterToSend(){return Y(g(this,Or))}set enterToSend(e){te(g(this,Or),e,!0)}get lastConfig(){return Y(g(this,Lr))}set lastConfig(e){te(g(this,Lr),e,!0)}get ttsProvider(){return Y(g(this,Gr))}set ttsProvider(e){te(g(this,Gr),e,!0)}get recentCollapsed(){return Y(g(this,zr))}set recentCollapsed(e){te(g(this,zr),e,!0)}get suppressLeaveWarning(){return Y(g(this,Fr))}set suppressLeaveWarning(e){te(g(this,Fr),e,!0)}get geminiVoice(){return Y(g(this,Vr))}set geminiVoice(e){te(g(this,Vr),e,!0)}};Er=new WeakMap,wr=new WeakMap,Ir=new WeakMap,Sr=new WeakMap,Cr=new WeakMap,Ar=new WeakMap,mo=new WeakMap,qn=new WeakMap,br=new WeakMap,Rr=new WeakMap,kr=new WeakMap,Pr=new WeakMap,Nr=new WeakMap,Mr=new WeakMap,xr=new WeakMap,Dr=new WeakMap,$r=new WeakMap,Ur=new WeakMap,Or=new WeakMap,Lr=new WeakMap,Gr=new WeakMap,zr=new WeakMap,Fr=new WeakMap,Vr=new WeakMap,_l=new WeakMap,Tl=new WeakMap,El=new WeakMap,Le=new WeakSet,sw=function(){if(!Is.isAvailable("elevenlabs")||g(this,mo)>=g(to,_l))return;const e=Math.min(g(to,Tl)*2**g(this,mo),g(to,El));O(this,mo,g(this,mo)+1),$(this,Le,Ua).call(this),O(this,qn,setTimeout(()=>{O(this,qn,null),this.loadVoices()},e))},Ua=function(){g(this,qn)!==null&&(clearTimeout(g(this,qn)),O(this,qn,null))},ut=function(){NZ({cliKind:this.cliKind,lastCwd:this.lastCwd,voiceId:this.voiceId,beUrl:this.beUrl,speakThoughts:this.speakThoughts,narrateTools:this.narrateTools,translateThoughts:this.translateThoughts,carMode:this.carMode,locale:this.locale,muted:this.muted,screenWakeLock:this.screenWakeLock,showThoughts:this.showThoughts,showTools:this.showTools,enterToSend:this.enterToSend,lastConfig:this.lastConfig,ttsProvider:this.ttsProvider,recentCollapsed:this.recentCollapsed,suppressLeaveWarning:this.suppressLeaveWarning,geminiVoice:this.geminiVoice})},D(to,_l,6),D(to,Tl,2e3),D(to,El,3e4);let Tc=to;const MZ=ti("'google' | 'openai' | 'elevenlabs'"),Aa=ti({provider:MZ,model:"string"});ti("'translate' | 'narrate' | 'stt' | 'tts'");ti({translate:Aa,narrate:Aa,stt:Aa,tts:Aa});const Hm={translate:{provider:"google",model:"gemini-flash-lite-latest"},narrate:{provider:"google",model:"gemini-flash-lite-latest"},stt:{provider:"google",model:"gemini-flash-latest"},tts:{provider:"elevenlabs",model:"eleven_v3"}};function Zm(t,e){return e[t]}function xZ(t,e){const n=t.seq-e.seq;return n!==0?n:t.segmentIndex-e.segmentIndex}var Dn;class DZ{constructor(){D(this,Dn,[])}get size(){return g(this,Dn).length}insert(e,n){let o=g(this,Dn).length;for(;o>0&&xZ(e,g(this,Dn)[o-1].key)<0;)o--;g(this,Dn).splice(o,0,{key:e,value:n})}takeNext(){return g(this,Dn).shift()}peekNext(){return g(this,Dn)[0]}clear(){O(this,Dn,[])}}Dn=new WeakMap;var wl,Di;class $Z{constructor(){D(this,wl,0);D(this,Di,new Map)}next(e){let n=g(this,Di).get(e);n===void 0&&(n={seq:sp(this,wl)._++,nextSegmentIndex:0},g(this,Di).set(e,n));const o={seq:n.seq,segmentIndex:n.nextSegmentIndex};return n.nextSegmentIndex++,o}clear(){g(this,Di).clear()}}wl=new WeakMap,Di=new WeakMap;var Au,Jm;function UZ(){if(Jm)return Au;Jm=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,i=(p,f)=>{for(var h in f)t(p,h,{get:f[h],enumerable:!0})},s=(p,f,h,m)=>{if(f&&typeof f=="object"||typeof f=="function")for(let v of n(f))!o.call(p,v)&&v!==h&&t(p,v,{get:()=>f[v],enumerable:!(m=e(f,v))||m.enumerable});return p},r=p=>s(t({},"__esModule",{value:!0}),p),a={};i(a,{SYMBOL_FOR_REQ_CONTEXT:()=>u,getContext:()=>c}),Au=r(a);const u=Symbol.for("@vercel/request-context");function c(){var f,h;return((h=(f=globalThis[u])==null?void 0:f.get)==null?void 0:h.call(f))??{}}return Au}var bu,Wm;function OZ(){if(Wm)return bu;Wm=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,i=(p,f)=>{for(var h in f)t(p,h,{get:f[h],enumerable:!0})},s=(p,f,h,m)=>{if(f&&typeof f=="object"||typeof f=="function")for(let v of n(f))!o.call(p,v)&&v!==h&&t(p,v,{get:()=>f[v],enumerable:!(m=e(f,v))||m.enumerable});return p},r=p=>s(t({},"__esModule",{value:!0}),p),a={};i(a,{AccessTokenMissingError:()=>u,RefreshAccessTokenFailedError:()=>c}),bu=r(a);class u extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login)."),this.name="AccessTokenMissingError"}}class c extends Error{constructor(f){super("Failed to refresh authentication token.",{cause:f}),this.name="RefreshAccessTokenFailedError"}}return bu}var Ru,Km;function LZ(){if(Km)return Ru;Km=1;var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,i=(m,v)=>{for(var _ in v)t(m,_,{get:v[_],enumerable:!0})},s=(m,v,_,w)=>{if(v&&typeof v=="object"||typeof v=="function")for(let C of n(v))!o.call(m,C)&&C!==_&&t(m,C,{get:()=>v[C],enumerable:!(w=e(v,C))||w.enumerable});return m},r=m=>s(t({},"__esModule",{value:!0}),m),a={};i(a,{AccessTokenMissingError:()=>c.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>c.RefreshAccessTokenFailedError,getContext:()=>u.getContext,getVercelOidcToken:()=>p,getVercelOidcTokenSync:()=>f,getVercelToken:()=>h}),Ru=r(a);var u=UZ(),c=OZ();async function p(){return""}function f(){return""}async function h(){throw new Error("getVercelToken is not supported in browser environments")}return Ru}var rw=LZ(),GZ="vercel.ai.gateway.error",ku=Symbol.for(GZ),Ym,Xm,bt=class aw extends(Xm=Error,Ym=ku,Xm){constructor({message:e,statusCode:n=500,cause:o,generationId:i,isRetryable:s=n!=null&&(n===408||n===409||n===429||n>=500)}){super(i?`${e} [${i}]`:e),this[Ym]=!0,this.statusCode=n,this.cause=o,this.generationId=i,this.isRetryable=s}static isInstance(e){return aw.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&ku in e&&e[ku]===!0}},lw="GatewayAuthenticationError",zZ=`vercel.ai.gateway.error.${lw}`,Qm=Symbol.for(zZ),jm,eg,Td=class uw extends(eg=bt,jm=Qm,eg){constructor({message:e="Authentication failed",statusCode:n=401,cause:o,generationId:i}={}){super({message:e,statusCode:n,cause:o,generationId:i}),this[jm]=!0,this.name=lw,this.type="authentication_error"}static isInstance(e){return bt.hasMarker(e)&&Qm in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:n,message:o="Authentication failed",statusCode:i=401,cause:s,generationId:r}){let a;return e?a=`AI Gateway authentication failed: Invalid API key.
390
+
391
+ Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
392
+
393
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?a=`AI Gateway authentication failed: Invalid OIDC token.
394
+
395
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
396
+
397
+ Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:a=`AI Gateway authentication failed: No authentication provided.
398
+
399
+ Option 1 - API key:
400
+ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
401
+ Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
402
+
403
+ Option 2 - OIDC token:
404
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new uw({message:a,statusCode:i,cause:s,generationId:r})}},cw="GatewayInvalidRequestError",FZ=`vercel.ai.gateway.error.${cw}`,tg=Symbol.for(FZ),ng,og,VZ=class extends(og=bt,ng=tg,og){constructor({message:t="Invalid request",statusCode:e=400,cause:n,generationId:o}={}){super({message:t,statusCode:e,cause:n,generationId:o}),this[ng]=!0,this.name=cw,this.type="invalid_request_error"}static isInstance(t){return bt.hasMarker(t)&&tg in t}},dw="GatewayRateLimitError",qZ=`vercel.ai.gateway.error.${dw}`,ig=Symbol.for(qZ),sg,rg,BZ=class extends(rg=bt,sg=ig,rg){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:n,generationId:o}={}){super({message:t,statusCode:e,cause:n,generationId:o}),this[sg]=!0,this.name=dw,this.type="rate_limit_exceeded"}static isInstance(t){return bt.hasMarker(t)&&ig in t}},pw="GatewayModelNotFoundError",HZ=`vercel.ai.gateway.error.${pw}`,ag=Symbol.for(HZ),ZZ=xe(()=>Me(M({modelId:I()}))),lg,ug,JZ=class extends(ug=bt,lg=ag,ug){constructor({message:t="Model not found",statusCode:e=404,modelId:n,cause:o,generationId:i}={}){super({message:t,statusCode:e,cause:o,generationId:i}),this[lg]=!0,this.name=pw,this.type="model_not_found",this.modelId=n}static isInstance(t){return bt.hasMarker(t)&&ag in t}},fw="GatewayInternalServerError",WZ=`vercel.ai.gateway.error.${fw}`,cg=Symbol.for(WZ),dg,pg,fg=class extends(pg=bt,dg=cg,pg){constructor({message:t="Internal server error",statusCode:e=500,cause:n,generationId:o}={}){super({message:t,statusCode:e,cause:n,generationId:o}),this[dg]=!0,this.name=fw,this.type="internal_server_error"}static isInstance(t){return bt.hasMarker(t)&&cg in t}},hw="GatewayResponseError",KZ=`vercel.ai.gateway.error.${hw}`,hg=Symbol.for(KZ),mg,gg,YZ=class extends(gg=bt,mg=hg,gg){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:n,validationError:o,cause:i,generationId:s}={}){super({message:t,statusCode:e,cause:i,generationId:s}),this[mg]=!0,this.name=hw,this.type="response_error",this.response=n,this.validationError=o}static isInstance(t){return bt.hasMarker(t)&&hg in t}};async function vg({response:t,statusCode:e,defaultMessage:n="Gateway request failed",cause:o,authMethod:i}){var s;const r=await Gt({value:t,schema:XZ});if(!r.success){const f=typeof t=="object"&&t!==null&&"generationId"in t?t.generationId:void 0;return new YZ({message:`Invalid error response format: ${n}`,statusCode:e,response:t,validationError:r.error,cause:o,generationId:f})}const a=r.value,u=a.error.type,c=a.error.message,p=(s=a.generationId)!=null?s:void 0;switch(u){case"authentication_error":return Td.createContextualError({apiKeyProvided:i==="api-key",oidcTokenProvided:i==="oidc",statusCode:e,cause:o,generationId:p});case"invalid_request_error":return new VZ({message:c,statusCode:e,cause:o,generationId:p});case"rate_limit_exceeded":return new BZ({message:c,statusCode:e,cause:o,generationId:p});case"model_not_found":{const f=await Gt({value:a.error.param,schema:ZZ});return new JZ({message:c,statusCode:e,modelId:f.success?f.value.modelId:void 0,cause:o,generationId:p})}case"internal_server_error":return new fg({message:c,statusCode:e,cause:o,generationId:p});default:return new fg({message:c,statusCode:e,cause:o,generationId:p})}}var XZ=xe(()=>Me(M({error:M({message:I(),type:I().nullish(),param:at().nullish(),code:$e([I(),W()]).nullish()}),generationId:I().nullish()})));function QZ(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var mw="GatewayTimeoutError",jZ=`vercel.ai.gateway.error.${mw}`,yg=Symbol.for(jZ),_g,Tg,Eg=class gw extends(Tg=bt,_g=yg,Tg){constructor({message:e="Request timed out",statusCode:n=408,cause:o,generationId:i}={}){super({message:e,statusCode:n,cause:o,generationId:i}),this[_g]=!0,this.name=mw,this.type="timeout_error"}static isInstance(e){return bt.hasMarker(e)&&yg in e}static createTimeoutError({originalMessage:e,statusCode:n=408,cause:o,generationId:i}){const s=`Gateway request timed out: ${e}
405
+
406
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new gw({message:s,statusCode:n,cause:o,generationId:i})}};function wg(t){if(!(t instanceof Error))return!1;const e=t.code;return typeof e=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(e):!1}async function Lt(t,e){var n;return bt.isInstance(t)?t:wg(t)?Eg.createTimeoutError({originalMessage:t instanceof Error?t.message:"Unknown error",cause:t}):rt.isInstance(t)?t.cause&&wg(t.cause)?Eg.createTimeoutError({originalMessage:t.message,cause:t}):await vg({response:QZ(t),statusCode:(n=t.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):await vg({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}var vw="ai-gateway-auth-method";async function On(t){const e=await Gt({value:t[vw],schema:e4});return e.success?e.value:void 0}var e4=xe(()=>Me($e([ne("api-key"),ne("oidc")]))),t4=["embedding","image","language","reranking","video"],Ig=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await oi({url:`${this.config.baseURL}/config`,headers:await He(this.config.headers()),successfulResponseHandler:Ct(n4),failedResponseHandler:Cn({errorSchema:rn(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await Lt(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await oi({url:`${t.origin}/v1/credits`,headers:await He(this.config.headers()),successfulResponseHandler:Ct(o4),failedResponseHandler:Cn({errorSchema:rn(),errorToMessage:n=>n}),fetch:this.config.fetch});return e}catch(t){throw await Lt(t)}}},n4=xe(()=>Me(M({models:ee(M({id:I(),name:I(),description:I().nullish(),pricing:M({input:I(),output:I(),input_cache_read:I().nullish(),input_cache_write:I().nullish()}).transform(({input:t,output:e,input_cache_read:n,input_cache_write:o})=>({input:t,output:e,...n?{cachedInputTokens:n}:{},...o?{cacheCreationInputTokens:o}:{}})).nullish(),specification:M({specificationVersion:ne("v3"),provider:I(),modelId:I()}),modelType:I().nullish()})).transform(t=>t.filter(e=>e.modelType==null||t4.includes(e.modelType)))}))),o4=xe(()=>Me(M({balance:I(),total_used:I()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),i4=class{constructor(t){this.config=t}async getSpendReport(t){try{const e=new URL(this.config.baseURL),n=new URLSearchParams;n.set("start_date",t.startDate),n.set("end_date",t.endDate),t.groupBy&&n.set("group_by",t.groupBy),t.datePart&&n.set("date_part",t.datePart),t.userId&&n.set("user_id",t.userId),t.model&&n.set("model",t.model),t.provider&&n.set("provider",t.provider),t.credentialType&&n.set("credential_type",t.credentialType),t.tags&&t.tags.length>0&&n.set("tags",t.tags.join(","));const{value:o}=await oi({url:`${e.origin}/v1/report?${n.toString()}`,headers:await He(this.config.headers()),successfulResponseHandler:Ct(s4),failedResponseHandler:Cn({errorSchema:rn(),errorToMessage:i=>i}),fetch:this.config.fetch});return o}catch(e){throw await Lt(e)}}},s4=xe(()=>Me(M({results:ee(M({day:I().optional(),hour:I().optional(),user:I().optional(),model:I().optional(),tag:I().optional(),provider:I().optional(),credential_type:Te(["byok","system"]).optional(),total_cost:W(),market_cost:W().optional(),input_tokens:W().optional(),output_tokens:W().optional(),cached_input_tokens:W().optional(),cache_creation_input_tokens:W().optional(),reasoning_tokens:W().optional(),request_count:W().optional()}).transform(({credential_type:t,total_cost:e,market_cost:n,input_tokens:o,output_tokens:i,cached_input_tokens:s,cache_creation_input_tokens:r,reasoning_tokens:a,request_count:u,...c})=>({...c,...t!==void 0?{credentialType:t}:{},totalCost:e,...n!==void 0?{marketCost:n}:{},...o!==void 0?{inputTokens:o}:{},...i!==void 0?{outputTokens:i}:{},...s!==void 0?{cachedInputTokens:s}:{},...r!==void 0?{cacheCreationInputTokens:r}:{},...a!==void 0?{reasoningTokens:a}:{},...u!==void 0?{requestCount:u}:{}})))}))),r4=class{constructor(t){this.config=t}async getGenerationInfo(t){try{const e=new URL(this.config.baseURL),{value:n}=await oi({url:`${e.origin}/v1/generation?id=${encodeURIComponent(t.id)}`,headers:await He(this.config.headers()),successfulResponseHandler:Ct(a4),failedResponseHandler:Cn({errorSchema:rn(),errorToMessage:o=>o}),fetch:this.config.fetch});return n}catch(e){throw await Lt(e)}}},a4=xe(()=>Me(M({data:M({id:I(),total_cost:W(),upstream_inference_cost:W(),usage:W(),created_at:I(),model:I(),is_byok:ht(),provider_name:I(),streamed:ht(),finish_reason:I(),latency:W(),generation_time:W(),native_tokens_prompt:W(),native_tokens_completion:W(),native_tokens_reasoning:W(),native_tokens_cached:W(),native_tokens_cache_creation:W(),billable_web_search_calls:W()}).transform(({total_cost:t,upstream_inference_cost:e,created_at:n,is_byok:o,provider_name:i,finish_reason:s,generation_time:r,native_tokens_prompt:a,native_tokens_completion:u,native_tokens_reasoning:c,native_tokens_cached:p,native_tokens_cache_creation:f,billable_web_search_calls:h,...m})=>({...m,totalCost:t,upstreamInferenceCost:e,createdAt:n,isByok:o,providerName:i,finishReason:s,generationTime:r,promptTokens:a,completionTokens:u,reasoningTokens:c,cachedTokens:p,cacheCreationTokens:f,billableWebSearchCalls:h}))}).transform(({data:t})=>t))),l4=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...n}=t;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(t){const{args:e,warnings:n}=await this.getArgs(t),{abortSignal:o}=t,i=await He(this.config.headers());try{const{responseHeaders:s,value:r,rawValue:a}=await xt({url:this.getUrl(),headers:Dt(i,t.headers,this.getModelConfigHeaders(this.modelId,!1),await He(this.config.o11yHeaders)),body:e,successfulResponseHandler:Ct(rn()),failedResponseHandler:Cn({errorSchema:rn(),errorToMessage:u=>u}),...o&&{abortSignal:o},fetch:this.config.fetch});return{...r,request:{body:e},response:{headers:s,body:a},warnings:n}}catch(s){throw await Lt(s,await On(i))}}async doStream(t){const{args:e,warnings:n}=await this.getArgs(t),{abortSignal:o}=t,i=await He(this.config.headers());try{const{value:s,responseHeaders:r}=await xt({url:this.getUrl(),headers:Dt(i,t.headers,this.getModelConfigHeaders(this.modelId,!0),await He(this.config.o11yHeaders)),body:e,successfulResponseHandler:Bl(rn()),failedResponseHandler:Cn({errorSchema:rn(),errorToMessage:a=>a}),...o&&{abortSignal:o},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(a){n.length>0&&a.enqueue({type:"stream-start",warnings:n})},transform(a,u){if(a.success){const c=a.value;if(c.type==="raw"&&!t.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),u.enqueue(c)}else u.error(a.error)}})),request:{body:e},response:{headers:r}}}catch(s){throw await Lt(s,await On(i))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const n of e.content)if(this.isFilePart(n)){const o=n;if(o.data instanceof Uint8Array){const i=Uint8Array.from(o.data),s=Buffer.from(i).toString("base64");o.data=new URL(`data:${o.mediaType||"application/octet-stream"};base64,${s}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"3","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},u4=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:n,providerOptions:o}){var i;const s=await He(this.config.headers());try{const{responseHeaders:r,value:a,rawValue:u}=await xt({url:this.getUrl(),headers:Dt(s,e??{},this.getModelConfigHeaders(),await He(this.config.o11yHeaders)),body:{values:t,...o?{providerOptions:o}:{}},successfulResponseHandler:Ct(c4),failedResponseHandler:Cn({errorSchema:rn(),errorToMessage:c=>c}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:a.embeddings,usage:(i=a.usage)!=null?i:void 0,providerMetadata:a.providerMetadata,response:{headers:r,body:u},warnings:[]}}catch(r){throw await Lt(r,await On(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},c4=xe(()=>Me(M({embeddings:ee(ee(W())),usage:M({tokens:W()}).nullish(),providerMetadata:Et(I(),Et(I(),at())).optional()}))),d4=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:n,aspectRatio:o,seed:i,files:s,mask:r,providerOptions:a,headers:u,abortSignal:c}){var p,f,h,m;const v=await He(this.config.headers());try{const{responseHeaders:_,value:w,rawValue:C}=await xt({url:this.getUrl(),headers:Dt(v,u??{},this.getModelConfigHeaders(),await He(this.config.o11yHeaders)),body:{prompt:t,n:e,...n&&{size:n},...o&&{aspectRatio:o},...i&&{seed:i},...a&&{providerOptions:a},...s&&{files:s.map(E=>Sg(E))},...r&&{mask:Sg(r)}},successfulResponseHandler:Ct(m4),failedResponseHandler:Cn({errorSchema:rn(),errorToMessage:E=>E}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:w.images,warnings:(p=w.warnings)!=null?p:[],providerMetadata:w.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:_},...w.usage!=null&&{usage:{inputTokens:(f=w.usage.inputTokens)!=null?f:void 0,outputTokens:(h=w.usage.outputTokens)!=null?h:void 0,totalTokens:(m=w.usage.totalTokens)!=null?m:void 0}}}}catch(_){throw await Lt(_,await On(v))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function Sg(t){return t.type==="file"&&t.data instanceof Uint8Array?{...t,data:ni(t.data)}:t}var p4=M({images:ee(at()).optional()}).catchall(at()),f4=Vl("type",[M({type:ne("unsupported"),feature:I(),details:I().optional()}),M({type:ne("compatibility"),feature:I(),details:I().optional()}),M({type:ne("other"),message:I()})]),h4=M({inputTokens:W().nullish(),outputTokens:W().nullish(),totalTokens:W().nullish()}),m4=M({images:ee(I()),warnings:ee(f4).optional(),providerMetadata:Et(I(),p4).optional(),usage:h4.optional()}),g4=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,aspectRatio:n,resolution:o,duration:i,fps:s,seed:r,image:a,providerOptions:u,headers:c,abortSignal:p}){var f;const h=await He(this.config.headers());try{const{responseHeaders:m,value:v}=await xt({url:this.getUrl(),headers:Dt(h,c??{},this.getModelConfigHeaders(),await He(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:t,n:e,...n&&{aspectRatio:n},...o&&{resolution:o},...i&&{duration:i},...s&&{fps:s},...r&&{seed:r},...u&&{providerOptions:u},...a&&{image:v4(a)}},successfulResponseHandler:async({response:_,url:w,requestBodyValues:C})=>{if(_.body==null)throw new rt({message:"SSE response body is empty",url:w,requestBodyValues:C,statusCode:_.status});const A=MT({stream:_.body,schema:E4}).getReader(),{done:R,value:k}=await A.read();if(A.releaseLock(),R||!k)throw new rt({message:"SSE stream ended without a data event",url:w,requestBodyValues:C,statusCode:_.status});if(!k.success)throw new rt({message:"Failed to parse video SSE event",cause:k.error,url:w,requestBodyValues:C,statusCode:_.status});const b=k.value;if(b.type==="error")throw new rt({message:b.message,statusCode:b.statusCode,url:w,requestBodyValues:C,responseHeaders:Object.fromEntries([..._.headers]),responseBody:JSON.stringify(b),data:{error:{message:b.message,type:b.errorType,param:b.param}}});return{value:{videos:b.videos,warnings:b.warnings,providerMetadata:b.providerMetadata},responseHeaders:Object.fromEntries([..._.headers])}},failedResponseHandler:Cn({errorSchema:rn(),errorToMessage:_=>_}),...p&&{abortSignal:p},fetch:this.config.fetch});return{videos:v.videos,warnings:(f=v.warnings)!=null?f:[],providerMetadata:v.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:m}}}catch(m){throw await Lt(m,await On(h))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function v4(t){return t.type==="file"&&t.data instanceof Uint8Array?{...t,data:ni(t.data)}:t}var y4=M({videos:ee(at()).optional()}).catchall(at()),_4=$e([M({type:ne("url"),url:I(),mediaType:I()}),M({type:ne("base64"),data:I(),mediaType:I()})]),T4=Vl("type",[M({type:ne("unsupported"),feature:I(),details:I().optional()}),M({type:ne("compatibility"),feature:I(),details:I().optional()}),M({type:ne("other"),message:I()})]),E4=Vl("type",[M({type:ne("result"),videos:ee(_4),warnings:ee(T4).optional(),providerMetadata:Et(I(),y4).optional()}),M({type:ne("error"),message:I(),errorType:I(),statusCode:W(),param:at().nullable()})]),w4=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v3"}get provider(){return this.config.provider}async doRerank({documents:t,query:e,topN:n,headers:o,abortSignal:i,providerOptions:s}){const r=await He(this.config.headers());try{const{responseHeaders:a,value:u,rawValue:c}=await xt({url:this.getUrl(),headers:Dt(r,o??{},this.getModelConfigHeaders(),await He(this.config.o11yHeaders)),body:{documents:t,query:e,...n!=null?{topN:n}:{},...s?{providerOptions:s}:{}},successfulResponseHandler:Ct(I4),failedResponseHandler:Cn({errorSchema:rn(),errorToMessage:p=>p}),...i&&{abortSignal:i},fetch:this.config.fetch});return{ranking:u.ranking,providerMetadata:u.providerMetadata,response:{headers:a,body:c},warnings:[]}}catch(a){throw await Lt(a,await On(r))}}getUrl(){return`${this.config.baseURL}/reranking-model`}getModelConfigHeaders(){return{"ai-reranking-model-specification-version":"3","ai-model-id":this.modelId}}},I4=xe(()=>Me(M({ranking:ee(M({index:W(),relevanceScore:W()})),providerMetadata:Et(I(),Et(I(),at())).optional()}))),S4=xe(()=>Me(M({objective:I().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:ee(I()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Te(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:W().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:M({include_domains:ee(I()).optional().describe("List of domains to include in search results."),exclude_domains:ee(I()).optional().describe("List of domains to exclude from search results."),after_date:I().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:M({max_chars_per_result:W().optional().describe("Maximum characters per result."),max_chars_total:W().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:M({max_age_seconds:W().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),C4=xe(()=>Me($e([M({searchId:I(),results:ee(M({url:I(),title:I(),excerpt:I(),publishDate:I().nullable().optional(),relevanceScore:W().optional()}))}),M({error:Te(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:W().optional(),message:I()})]))),A4=id({id:"gateway.parallel_search",inputSchema:S4,outputSchema:C4}),b4=(t={})=>A4(t),R4=xe(()=>Me(M({query:$e([I(),ee(I())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:W().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:W().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:W().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:I().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:ee(I()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:ee(I()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:I().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:I().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:I().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:I().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Te(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),k4=xe(()=>Me($e([M({results:ee(M({title:I(),url:I(),snippet:I(),date:I().optional(),lastUpdated:I().optional()})),id:I()}),M({error:Te(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:W().optional(),message:I()})]))),P4=id({id:"gateway.perplexity_search",inputSchema:R4,outputSchema:k4}),N4=(t={})=>P4(t),M4={parallelSearch:b4,perplexitySearch:N4};async function x4(){var t;return(t=rw.getContext().headers)==null?void 0:t["x-vercel-id"]}var D4="3.0.115",$4="0.0.1";function U4(t={}){var e,n;let o=null,i=null;const s=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let r=0;const a=(n=xT(t.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v3/ai",u=async()=>{try{const E=await L4(t);return Po({Authorization:`Bearer ${E.token}`,"ai-gateway-protocol-version":$4,[vw]:E.authMethod,...t.headers},`ai-sdk/gateway/${D4}`)}catch(E){throw Td.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:E})}},c=()=>{const E=ys({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),A=ys({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),R=ys({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),k=ys({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const b=await x4();return{...E&&{"ai-o11y-deployment-id":E},...A&&{"ai-o11y-environment":A},...R&&{"ai-o11y-region":R},...b&&{"ai-o11y-request-id":b},...k&&{"ai-o11y-project-id":k}}}},p=E=>new l4(E,{provider:"gateway",baseURL:a,headers:u,fetch:t.fetch,o11yHeaders:c()}),f=async()=>{var E,A,R;const k=(R=(A=(E=t._internal)==null?void 0:E.currentDate)==null?void 0:A.call(E).getTime())!=null?R:Date.now();return(!o||k-r>s)&&(r=k,o=new Ig({baseURL:a,headers:u,fetch:t.fetch}).getAvailableModels().then(b=>(i=b,b)).catch(async b=>{throw await Lt(b,await On(await u()))})),i?Promise.resolve(i):o},h=async()=>new Ig({baseURL:a,headers:u,fetch:t.fetch}).getCredits().catch(async E=>{throw await Lt(E,await On(await u()))}),m=async E=>new i4({baseURL:a,headers:u,fetch:t.fetch}).getSpendReport(E).catch(async A=>{throw await Lt(A,await On(await u()))}),v=async E=>new r4({baseURL:a,headers:u,fetch:t.fetch}).getGenerationInfo(E).catch(async A=>{throw await Lt(A,await On(await u()))}),_=function(E){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return p(E)};_.specificationVersion="v3",_.getAvailableModels=f,_.getCredits=h,_.getSpendReport=m,_.getGenerationInfo=v,_.imageModel=E=>new d4(E,{provider:"gateway",baseURL:a,headers:u,fetch:t.fetch,o11yHeaders:c()}),_.languageModel=p;const w=E=>new u4(E,{provider:"gateway",baseURL:a,headers:u,fetch:t.fetch,o11yHeaders:c()});_.embeddingModel=w,_.textEmbeddingModel=w,_.videoModel=E=>new g4(E,{provider:"gateway",baseURL:a,headers:u,fetch:t.fetch,o11yHeaders:c()});const C=E=>new w4(E,{provider:"gateway",baseURL:a,headers:u,fetch:t.fetch,o11yHeaders:c()});return _.rerankingModel=C,_.reranking=C,_.chat=_.languageModel,_.embedding=_.embeddingModel,_.image=_.imageModel,_.video=_.videoModel,_.tools=M4,_}var O4=U4();async function L4(t){const e=ys({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return e?{token:e,authMethod:"api-key"}:{token:await rw.getVercelOidcToken(),authMethod:"oidc"}}const Go="1.9.1",Cg=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function G4(t){const e=new Set([t]),n=new Set,o=t.match(Cg);if(!o)return()=>!1;const i={major:+o[1],minor:+o[2],patch:+o[3],prerelease:o[4]};if(i.prerelease!=null)return function(u){return u===t};function s(a){return n.add(a),!1}function r(a){return e.add(a),!0}return function(u){if(e.has(u))return!0;if(n.has(u))return!1;const c=u.match(Cg);if(!c)return s(u);const p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return p.prerelease!=null||i.major!==p.major?s(u):i.major===0?i.minor===p.minor&&i.patch<=p.patch?r(u):s(u):i.minor<=p.minor?r(u):s(u)}}const z4=G4(Go),F4=Go.split(".")[0],Ns=Symbol.for(`opentelemetry.js.api.${F4}`),Ms=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function Ed(t,e,n,o=!1){var i;const s=Ms[Ns]=(i=Ms[Ns])!==null&&i!==void 0?i:{version:Go};if(!o&&s[t]){const r=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return n.error(r.stack||r.message),!1}if(s.version!==Go){const r=new Error(`@opentelemetry/api: Registration of version v${s.version} for ${t} does not match previously registered API v${Go}`);return n.error(r.stack||r.message),!1}return s[t]=e,n.debug(`@opentelemetry/api: Registered a global for ${t} v${Go}.`),!0}function xs(t){var e,n;const o=(e=Ms[Ns])===null||e===void 0?void 0:e.version;if(!(!o||!z4(o)))return(n=Ms[Ns])===null||n===void 0?void 0:n[t]}function wd(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${Go}.`);const n=Ms[Ns];n&&delete n[t]}class V4{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return fs("debug",this._namespace,e)}error(...e){return fs("error",this._namespace,e)}info(...e){return fs("info",this._namespace,e)}warn(...e){return fs("warn",this._namespace,e)}verbose(...e){return fs("verbose",this._namespace,e)}}function fs(t,e,n){const o=xs("diag");if(o)return o[t](e,...n)}var Wt;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(Wt||(Wt={}));function q4(t,e){t<Wt.NONE?t=Wt.NONE:t>Wt.ALL&&(t=Wt.ALL),e=e||{};function n(o,i){const s=e[o];return typeof s=="function"&&t>=i?s.bind(e):function(){}}return{error:n("error",Wt.ERROR),warn:n("warn",Wt.WARN),info:n("info",Wt.INFO),debug:n("debug",Wt.DEBUG),verbose:n("verbose",Wt.VERBOSE)}}const B4="diag";class Zi{static instance(){return this._instance||(this._instance=new Zi),this._instance}constructor(){function e(i){return function(...s){const r=xs("diag");if(r)return r[i](...s)}}const n=this,o=(i,s={logLevel:Wt.INFO})=>{var r,a,u;if(i===n){const f=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((r=f.stack)!==null&&r!==void 0?r:f.message),!1}typeof s=="number"&&(s={logLevel:s});const c=xs("diag"),p=q4((a=s.logLevel)!==null&&a!==void 0?a:Wt.INFO,i);if(c&&!s.suppressOverrideMessage){const f=(u=new Error().stack)!==null&&u!==void 0?u:"<failed to generate stacktrace>";c.warn(`Current logger will be overwritten from ${f}`),p.warn(`Current logger will overwrite one already registered from ${f}`)}return Ed("diag",p,n,!0)};n.setLogger=o,n.disable=()=>{wd(B4,n)},n.createComponentLogger=i=>new V4(i),n.verbose=e("verbose"),n.debug=e("debug"),n.info=e("info"),n.warn=e("warn"),n.error=e("error")}}function H4(t){return Symbol.for(t)}class ul{constructor(e){const n=this;n._currentContext=e?new Map(e):new Map,n.getValue=o=>n._currentContext.get(o),n.setValue=(o,i)=>{const s=new ul(n._currentContext);return s._currentContext.set(o,i),s},n.deleteValue=o=>{const i=new ul(n._currentContext);return i._currentContext.delete(o),i}}}const Z4=new ul;class J4{active(){return Z4}with(e,n,o,...i){return n.call(o,...i)}bind(e,n){return n}enable(){return this}disable(){return this}}const Pu="context",W4=new J4;class aa{constructor(){}static getInstance(){return this._instance||(this._instance=new aa),this._instance}setGlobalContextManager(e){return Ed(Pu,e,Zi.instance())}active(){return this._getContextManager().active()}with(e,n,o,...i){return this._getContextManager().with(e,n,o,...i)}bind(e,n){return this._getContextManager().bind(e,n)}_getContextManager(){return xs(Pu)||W4}disable(){this._getContextManager().disable(),wd(Pu,Zi.instance())}}var Ec;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Ec||(Ec={}));const yw="0000000000000000",_w="00000000000000000000000000000000",K4={traceId:_w,spanId:yw,traceFlags:Ec.NONE};class Es{constructor(e=K4){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,n){return this}setAttributes(e){return this}addEvent(e,n){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,n){}}const Id=H4("OpenTelemetry Context Key SPAN");function Sd(t){return t.getValue(Id)||void 0}function Y4(){return Sd(aa.getInstance().active())}function Cd(t,e){return t.setValue(Id,e)}function X4(t){return t.deleteValue(Id)}function Q4(t,e){return Cd(t,new Es(e))}function Tw(t){var e;return(e=Sd(t))===null||e===void 0?void 0:e.spanContext()}const ba=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function Ew(t,e){if(typeof t!="string"||t.length!==e)return!1;let n=0;for(let o=0;o<t.length;o+=4)n+=(ba[t.charCodeAt(o)]|0)+(ba[t.charCodeAt(o+1)]|0)+(ba[t.charCodeAt(o+2)]|0)+(ba[t.charCodeAt(o+3)]|0);return n===e}function j4(t){return Ew(t,32)&&t!==_w}function eJ(t){return Ew(t,16)&&t!==yw}function ww(t){return j4(t.traceId)&&eJ(t.spanId)}function tJ(t){return new Es(t)}const Nu=aa.getInstance();class Iw{startSpan(e,n,o=Nu.active()){if(!!(n!=null&&n.root))return new Es;const s=o&&Tw(o);return nJ(s)&&ww(s)?new Es(s):new Es}startActiveSpan(e,n,o,i){let s,r,a;if(arguments.length<2)return;arguments.length===2?a=n:arguments.length===3?(s=n,a=o):(s=n,r=o,a=i);const u=r??Nu.active(),c=this.startSpan(e,s,u),p=Cd(u,c);return Nu.with(p,a,void 0,c)}}function nJ(t){return t!==null&&typeof t=="object"&&"spanId"in t&&typeof t.spanId=="string"&&"traceId"in t&&typeof t.traceId=="string"&&"traceFlags"in t&&typeof t.traceFlags=="number"}const oJ=new Iw;class iJ{constructor(e,n,o,i){this._provider=e,this.name=n,this.version=o,this.options=i}startSpan(e,n,o){return this._getTracer().startSpan(e,n,o)}startActiveSpan(e,n,o,i){const s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)}_getTracer(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):oJ}}class sJ{getTracer(e,n,o){return new Iw}}const rJ=new sJ;class Ag{getTracer(e,n,o){var i;return(i=this.getDelegateTracer(e,n,o))!==null&&i!==void 0?i:new iJ(this,e,n,o)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:rJ}setDelegate(e){this._delegate=e}getDelegateTracer(e,n,o){var i;return(i=this._delegate)===null||i===void 0?void 0:i.getTracer(e,n,o)}}var cl;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(cl||(cl={}));const bg=aa.getInstance(),Mu="trace";class Ad{constructor(){this._proxyTracerProvider=new Ag,this.wrapSpanContext=tJ,this.isSpanContextValid=ww,this.deleteSpan=X4,this.getSpan=Sd,this.getActiveSpan=Y4,this.getSpanContext=Tw,this.setSpan=Cd,this.setSpanContext=Q4}static getInstance(){return this._instance||(this._instance=new Ad),this._instance}setGlobalTracerProvider(e){const n=Ed(Mu,this._proxyTracerProvider,Zi.instance());return n&&this._proxyTracerProvider.setDelegate(e),n}getTracerProvider(){return xs(Mu)||this._proxyTracerProvider}getTracer(e,n){return this.getTracerProvider().getTracer(e,n)}disable(){wd(Mu,Zi.instance()),this._proxyTracerProvider=new Ag}}const aJ=Ad.getInstance();var lJ=Object.defineProperty,uJ=(t,e)=>{for(var n in e)lJ(t,n,{get:e[n],enumerable:!0})},Sw="AI_InvalidArgumentError",Cw=`vercel.ai.error.${Sw}`,cJ=Symbol.for(Cw),Aw,Qe=class extends de{constructor({parameter:t,value:e,message:n}){super({name:Sw,message:`Invalid argument for parameter ${t}: ${n}`}),this[Aw]=!0,this.parameter=t,this.value=e}static isInstance(t){return de.hasMarker(t,Cw)}};Aw=cJ;var bw="AI_InvalidToolApprovalError",Rw=`vercel.ai.error.${bw}`,dJ=Symbol.for(Rw),kw,pJ=class extends de{constructor({approvalId:t}){super({name:bw,message:`Tool approval response references unknown approvalId: "${t}". No matching tool-approval-request found in message history.`}),this[kw]=!0,this.approvalId=t}static isInstance(t){return de.hasMarker(t,Rw)}};kw=dJ;var Pw="AI_InvalidToolInputError",Nw=`vercel.ai.error.${Pw}`,fJ=Symbol.for(Nw),Mw,bd=class extends de{constructor({toolInput:t,toolName:e,cause:n,message:o=`Invalid input for tool ${e}: ${ta(n)}`}){super({name:Pw,message:o,cause:n}),this[Mw]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return de.hasMarker(t,Nw)}};Mw=fJ;var xw="AI_ToolCallNotFoundForApprovalError",Dw=`vercel.ai.error.${xw}`,hJ=Symbol.for(Dw),$w,Uw=class extends de{constructor({toolCallId:t,approvalId:e}){super({name:xw,message:`Tool call "${t}" not found for approval request "${e}".`}),this[$w]=!0,this.toolCallId=t,this.approvalId=e}static isInstance(t){return de.hasMarker(t,Dw)}};$w=hJ;var Ow="AI_MissingToolResultsError",Lw=`vercel.ai.error.${Ow}`,mJ=Symbol.for(Lw),Gw,Rg=class extends de{constructor({toolCallIds:t}){super({name:Ow,message:`Tool result${t.length>1?"s are":" is"} missing for tool call${t.length>1?"s":""} ${t.join(", ")}.`}),this[Gw]=!0,this.toolCallIds=t}static isInstance(t){return de.hasMarker(t,Lw)}};Gw=mJ;var zw="AI_NoObjectGeneratedError",Fw=`vercel.ai.error.${zw}`,gJ=Symbol.for(Fw),Vw,Kt=class extends de{constructor({message:t="No object generated.",cause:e,text:n,response:o,usage:i,finishReason:s}){super({name:zw,message:t,cause:e}),this[Vw]=!0,this.text=n,this.response=o,this.usage=i,this.finishReason=s}static isInstance(t){return de.hasMarker(t,Fw)}};Vw=gJ;var qw="AI_NoOutputGeneratedError",Bw=`vercel.ai.error.${qw}`,vJ=Symbol.for(Bw),Hw,yJ=class extends de{constructor({message:t="No output generated.",cause:e}={}){super({name:qw,message:t,cause:e}),this[Hw]=!0}static isInstance(t){return de.hasMarker(t,Bw)}};Hw=vJ;var Zw="AI_NoSuchToolError",Jw=`vercel.ai.error.${Zw}`,_J=Symbol.for(Jw),Ww,wc=class extends de{constructor({toolName:t,availableTools:e=void 0,message:n=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:Zw,message:n}),this[Ww]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return de.hasMarker(t,Jw)}};Ww=_J;var Kw="AI_ToolCallRepairError",Yw=`vercel.ai.error.${Kw}`,TJ=Symbol.for(Yw),Xw,EJ=class extends de{constructor({cause:t,originalError:e,message:n=`Error repairing tool call: ${ta(t)}`}){super({name:Kw,message:n,cause:t}),this[Xw]=!0,this.originalError=e}static isInstance(t){return de.hasMarker(t,Yw)}};Xw=TJ;var wJ=class extends de{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},Qw="AI_InvalidMessageRoleError",jw=`vercel.ai.error.${Qw}`,IJ=Symbol.for(jw),eI,SJ=class extends de{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Qw,message:e}),this[eI]=!0,this.role=t}static isInstance(t){return de.hasMarker(t,jw)}};eI=IJ;var tI="AI_RetryError",nI=`vercel.ai.error.${tI}`,CJ=Symbol.for(nI),oI,kg=class extends de{constructor({message:t,reason:e,errors:n}){super({name:tI,message:t}),this[oI]=!0,this.reason=e,this.errors=n,this.lastError=n[n.length-1]}static isInstance(t){return de.hasMarker(t,nI)}};oI=CJ;function la(t){return t===void 0?[]:Array.isArray(t)?t:[t]}async function zo(t){for(const e of la(t.callbacks))if(e!=null)try{await e(t.event)}catch{}}function AJ({warning:t,provider:e,model:n}){const o=`AI SDK Warning (${e} / ${n}):`;switch(t.type){case"unsupported":{let i=`${o} The feature "${t.feature}" is not supported.`;return t.details&&(i+=` ${t.details}`),i}case"compatibility":{let i=`${o} The feature "${t.feature}" is used in a compatibility mode.`;return t.details&&(i+=` ${t.details}`),i}case"other":return`${o} ${t.message}`;default:return`${o} ${JSON.stringify(t,null,2)}`}}var bJ="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Pg=!1,Rd=t=>{if(t.warnings.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}Pg||(Pg=!0,console.info(bJ));for(const n of t.warnings)console.warn(AJ({warning:n,provider:t.provider,model:t.model}))}};function RJ({provider:t,modelId:e}){Rd({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:t,model:e})}function kJ(t){return t.specificationVersion==="v3"?t:(RJ({provider:t.provider,modelId:t.modelId}),new Proxy(t,{get(e,n){switch(n){case"specificationVersion":return"v3";case"doGenerate":return async(...o)=>{const i=await e.doGenerate(...o);return{...i,finishReason:iI(i.finishReason),usage:sI(i.usage)}};case"doStream":return async(...o)=>{const i=await e.doStream(...o);return{...i,stream:PJ(i.stream)}};default:return e[n]}}}))}function PJ(t){return t.pipeThrough(new TransformStream({transform(e,n){switch(e.type){case"finish":n.enqueue({...e,finishReason:iI(e.finishReason),usage:sI(e.usage)});break;default:n.enqueue(e);break}}}))}function iI(t){return{unified:t==="unknown"?"other":t,raw:void 0}}function sI(t){return{inputTokens:{total:t.inputTokens,noCache:void 0,cacheRead:t.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:t.outputTokens,text:void 0,reasoning:t.reasoningTokens}}}function Ic(t){if(typeof t!="string"){if(t.specificationVersion!=="v3"&&t.specificationVersion!=="v2"){const e=t;throw new wJ({version:e.specificationVersion,provider:e.provider,modelId:e.modelId})}return kJ(t)}return NJ().languageModel(t)}function NJ(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:O4}function rI(t){if(t!=null)return typeof t=="number"?t:t.totalMs}function MJ(t){if(!(t==null||typeof t=="number"))return t.stepMs}var xJ=[{mediaType:"image/gif",bytesPrefix:[71,73,70]},{mediaType:"image/png",bytesPrefix:[137,80,78,71]},{mediaType:"image/jpeg",bytesPrefix:[255,216]},{mediaType:"image/webp",bytesPrefix:[82,73,70,70,null,null,null,null,87,69,66,80]},{mediaType:"image/bmp",bytesPrefix:[66,77]},{mediaType:"image/tiff",bytesPrefix:[73,73,42,0]},{mediaType:"image/tiff",bytesPrefix:[77,77,0,42]},{mediaType:"image/avif",bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102]},{mediaType:"image/heic",bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99]}],DJ=t=>{const e=typeof t=="string"?nd(t):t,n=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(n+10)};function $J(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?DJ(t):t}function UJ({data:t,signatures:e}){const n=$J(t),o=typeof n=="string"?nd(n.substring(0,Math.min(n.length,24))):n;for(const i of e)if(o.length>=i.bytesPrefix.length&&i.bytesPrefix.every((s,r)=>s===null||o[r]===s))return i.mediaType}var kd="6.0.184",OJ=async({url:t,maxBytes:e,abortSignal:n})=>{var o;const i=t.toString();xf(i);try{const s=await fetch(i,{headers:Po({},`ai-sdk/${kd}`,ql()),signal:n});if(s.redirected&&xf(s.url),!s.ok)throw new In({url:i,statusCode:s.status,statusText:s.statusText});return{data:await sO({response:s,url:i,maxBytes:e??wT}),mediaType:(o=s.headers.get("content-type"))!=null?o:void 0}}catch(s){throw In.isInstance(s)?s:new In({url:i,cause:s})}},LJ=(t=OJ)=>e=>Promise.all(e.map(async n=>n.isUrlSupportedByModel?null:t(n)));function GJ(t){try{const[e,n]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var aI=$e([I(),ja(Uint8Array),ja(ArrayBuffer),YU(t=>{var e,n;return(n=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?n:!1},{message:"Must be a Buffer"})]);function Pd(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:n}=GJ(t.toString());if(e==null||n==null)throw new de({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:n,mediaType:e}}return{data:t,mediaType:void 0}}function Sc(t){return typeof t=="string"?t:t instanceof ArrayBuffer?ni(new Uint8Array(t)):ni(t)}async function lI({prompt:t,supportedUrls:e,download:n=LJ()}){const o=await FJ(t.messages,n,e),i=new Map;for(const c of t.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const p of c.content)p.type==="tool-approval-request"&&"approvalId"in p&&"toolCallId"in p&&i.set(p.approvalId,p.toolCallId);const s=new Set;for(const c of t.messages)if(c.role==="tool"){for(const p of c.content)if(p.type==="tool-approval-response"){const f=i.get(p.approvalId);f&&s.add(f)}}const r=[...t.system!=null?typeof t.system=="string"?[{role:"system",content:t.system}]:la(t.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...t.messages.map(c=>zJ({message:c,downloadedAssets:o}))],a=[];for(const c of r){if(c.role!=="tool"){a.push(c);continue}const p=a.at(-1);(p==null?void 0:p.role)==="tool"?p.content.push(...c.content):a.push(c)}const u=new Set;for(const c of a)switch(c.role){case"assistant":{for(const p of c.content)p.type==="tool-call"&&!p.providerExecuted&&u.add(p.toolCallId);break}case"tool":{for(const p of c.content)p.type==="tool-result"&&u.delete(p.toolCallId);break}case"user":case"system":for(const p of s)u.delete(p);if(u.size>0)throw new Rg({toolCallIds:Array.from(u)});break}for(const c of s)u.delete(c);if(u.size>0)throw new Rg({toolCallIds:Array.from(u)});return a.filter(c=>c.role!=="tool"||c.content.length>0)}function zJ({message:t,downloadedAssets:e}){const n=t.role;switch(n){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(o=>VJ(o,e)).filter(o=>o.type!=="text"||o.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(o=>o.type!=="text"||o.text!==""||o.providerOptions!=null).filter(o=>o.type!=="tool-approval-request").map(o=>{const i=o.providerOptions;switch(o.type){case"file":{const{data:s,mediaType:r}=Pd(o.data);return{type:"file",data:s,filename:o.filename,mediaType:r??o.mediaType,providerOptions:i}}case"reasoning":return{type:"reasoning",text:o.text,providerOptions:i};case"text":return{type:"text",text:o.text,providerOptions:i};case"tool-call":return{type:"tool-call",toolCallId:o.toolCallId,toolName:o.toolName,input:o.input,providerExecuted:o.providerExecuted,providerOptions:i};case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Ng({output:o.output,downloadedAssets:e}),providerOptions:i}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.filter(o=>o.type!=="tool-approval-response"||o.providerExecuted).map(o=>{switch(o.type){case"tool-result":return{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:Ng({output:o.output,downloadedAssets:e}),providerOptions:o.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:o.approvalId,approved:o.approved,reason:o.reason}}}),providerOptions:t.providerOptions};default:{const o=n;throw new SJ({role:o})}}}async function FJ(t,e,n){var o;const i=[];for(const a of t){if(a.role==="user"&&Array.isArray(a.content))for(const u of a.content)(u.type==="image"||u.type==="file")&&i.push({data:u.type==="image"?u.image:u.data,mediaType:(o=u.mediaType)!=null?o:u.type==="image"?"image/*":void 0});if(a.role==="tool"||a.role==="assistant"){if(!Array.isArray(a.content))continue;for(const u of a.content)if(u.type==="tool-result"&&u.output.type==="content")for(const c of u.output.value)(c.type==="image-url"||c.type==="file-url")&&i.push({data:new URL(c.url),mediaType:c.type==="image-url"?"image/*":void 0})}}const s=i.map(a=>{const u=a.mediaType,{data:c}=Pd(a.data);return{mediaType:u,data:c}}).filter(a=>a.data instanceof URL).map(a=>({url:a.data,isUrlSupportedByModel:a.mediaType!=null&&pO({url:a.data.toString(),mediaType:a.mediaType,supportedUrls:n})})),r=await e(s);return Object.fromEntries(r.map((a,u)=>a==null?null:[s[u].url.toString(),{data:a.data,mediaType:a.mediaType}]).filter(a=>a!=null))}function VJ(t,e){var n;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let o;const i=t.type;switch(i){case"image":o=t.image;break;case"file":o=t.data;break;default:throw new Error(`Unsupported part type: ${i}`)}const{data:s,mediaType:r}=Pd(o);let a=r??t.mediaType,u=s;if(u instanceof URL){const c=e[u.toString()];c&&(u=c.data,a??(a=c.mediaType))}switch(i){case"image":return(u instanceof Uint8Array||typeof u=="string")&&(a=(n=UJ({data:u,signatures:xJ}))!=null?n:a),{type:"file",mediaType:a??"image/*",filename:void 0,data:u,providerOptions:t.providerOptions};case"file":{if(a==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:a,filename:t.filename,data:u,providerOptions:t.providerOptions}}}}function Ng({output:t,downloadedAssets:e}){return t.type!=="content"?t:{type:"content",value:t.value.map(n=>{var o,i;if(n.type==="image-url"){const s=e[new URL(n.url).toString()];return s?{type:"image-data",data:Sc(s.data),mediaType:(o=s.mediaType)!=null?o:"image/*",providerOptions:n.providerOptions}:n}if(n.type==="file-url"){const s=e[new URL(n.url).toString()];return s?{type:"file-data",data:Sc(s.data),mediaType:(i=s.mediaType)!=null?i:"application/octet-stream",providerOptions:n.providerOptions}:n}return n.type!=="media"?n:n.mediaType.startsWith("image/")?{type:"image-data",data:n.data,mediaType:n.mediaType}:{type:"file-data",data:n.data,mediaType:n.mediaType}})}}async function Oa({toolCallId:t,input:e,output:n,tool:o,errorMode:i}){return i==="text"?{type:"error-text",value:ta(n)}:i==="json"?{type:"error-json",value:Mg(n)}:o!=null&&o.toModelOutput?await o.toModelOutput({toolCallId:t,input:e,output:n}):typeof n=="string"?{type:"text",value:n}:{type:"json",value:Mg(n)}}function Mg(t){return t===void 0?null:t}function dl({maxOutputTokens:t,temperature:e,topP:n,topK:o,presencePenalty:i,frequencyPenalty:s,seed:r,stopSequences:a}){if(t!=null){if(!Number.isInteger(t))throw new Qe({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new Qe({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new Qe({parameter:"temperature",value:e,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new Qe({parameter:"topP",value:n,message:"topP must be a number"});if(o!=null&&typeof o!="number")throw new Qe({parameter:"topK",value:o,message:"topK must be a number"});if(i!=null&&typeof i!="number")throw new Qe({parameter:"presencePenalty",value:i,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Qe({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(r!=null&&!Number.isInteger(r))throw new Qe({parameter:"seed",value:r,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:n,topK:o,presencePenalty:i,frequencyPenalty:s,stopSequences:a,seed:r}}function qJ(t){return t!=null&&Object.keys(t).length>0}async function BJ({tools:t,toolChoice:e,activeTools:n}){if(!qJ(t))return{tools:void 0,toolChoice:void 0};const o=n!=null?Object.entries(t).filter(([s])=>n.includes(s)):Object.entries(t),i=[];for(const[s,r]of o){const a=r.type;switch(a){case void 0:case"dynamic":case"function":i.push({type:"function",name:s,description:r.description,inputSchema:await Co(r.inputSchema).jsonSchema,...r.inputExamples!=null?{inputExamples:r.inputExamples}:{},providerOptions:r.providerOptions,...r.strict!=null?{strict:r.strict}:{}});break;case"provider":i.push({type:"provider",name:s,id:r.id,args:r.args});break;default:{const u=a;throw new Error(`Unsupported tool type: ${u}`)}}}return{tools:i,toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}}var ii=KU(()=>$e([wU(),I(),W(),ht(),Et(I(),ii.optional()),ee(ii)])),nt=Et(I(),Et(I(),ii.optional())),uI=M({type:ne("text"),text:I(),providerOptions:nt.optional()}),HJ=M({type:ne("image"),image:$e([aI,ja(URL)]),mediaType:I().optional(),providerOptions:nt.optional()}),cI=M({type:ne("file"),data:$e([aI,ja(URL)]),filename:I().optional(),mediaType:I(),providerOptions:nt.optional()}),ZJ=M({type:ne("reasoning"),text:I(),providerOptions:nt.optional()}),JJ=M({type:ne("tool-call"),toolCallId:I(),toolName:I(),input:at(),providerOptions:nt.optional(),providerExecuted:ht().optional()}),WJ=Vl("type",[M({type:ne("text"),value:I(),providerOptions:nt.optional()}),M({type:ne("json"),value:ii,providerOptions:nt.optional()}),M({type:ne("execution-denied"),reason:I().optional(),providerOptions:nt.optional()}),M({type:ne("error-text"),value:I(),providerOptions:nt.optional()}),M({type:ne("error-json"),value:ii,providerOptions:nt.optional()}),M({type:ne("content"),value:ee($e([M({type:ne("text"),text:I(),providerOptions:nt.optional()}),M({type:ne("media"),data:I(),mediaType:I()}),M({type:ne("file-data"),data:I(),mediaType:I(),filename:I().optional(),providerOptions:nt.optional()}),M({type:ne("file-url"),url:I(),providerOptions:nt.optional()}),M({type:ne("file-id"),fileId:$e([I(),Et(I(),I())]),providerOptions:nt.optional()}),M({type:ne("image-data"),data:I(),mediaType:I(),providerOptions:nt.optional()}),M({type:ne("image-url"),url:I(),providerOptions:nt.optional()}),M({type:ne("image-file-id"),fileId:$e([I(),Et(I(),I())]),providerOptions:nt.optional()}),M({type:ne("custom"),providerOptions:nt.optional()})]))})]),dI=M({type:ne("tool-result"),toolCallId:I(),toolName:I(),output:WJ,providerOptions:nt.optional()}),KJ=M({type:ne("tool-approval-request"),approvalId:I(),toolCallId:I()}),YJ=M({type:ne("tool-approval-response"),approvalId:I(),approved:ht(),reason:I().optional()}),XJ=M({role:ne("system"),content:I(),providerOptions:nt.optional()}),QJ=M({role:ne("user"),content:$e([I(),ee($e([uI,HJ,cI]))]),providerOptions:nt.optional()}),jJ=M({role:ne("assistant"),content:$e([I(),ee($e([uI,cI,ZJ,JJ,dI,KJ]))]),providerOptions:nt.optional()}),e2=M({role:ne("tool"),content:ee($e([dI,YJ])),providerOptions:nt.optional()}),t2=$e([XJ,QJ,jJ,e2]);async function pI({allowSystemInMessages:t,system:e,prompt:n,messages:o}){if(n==null&&o==null)throw new Do({prompt:n,message:"prompt or messages must be defined"});if(n!=null&&o!=null)throw new Do({prompt:n,message:"prompt and messages cannot be defined at the same time"});if(typeof e!="string"&&!la(e).every(s=>s.role==="system"))throw new Do({prompt:n,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});if(n!=null&&typeof n=="string")o=[{role:"user",content:n}];else if(n!=null&&Array.isArray(n))o=n;else if(o==null)throw new Do({prompt:n,message:"prompt or messages must be defined"});if(o.length===0)throw new Do({prompt:n,message:"messages must not be empty"});if(o.some(s=>s.role==="system")){if(t===!1)throw new Do({prompt:n,message:"System messages are not allowed in the prompt or messages fields. Use the system option instead."});t===void 0&&console.warn("AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.")}const i=await Gt({value:o,schema:ee(t2)});if(!i.success)throw new Do({prompt:n,message:"The messages do not match the ModelMessage[] schema.",cause:i.error});return{messages:o,system:e}}function fI(t){if(!Td.isInstance(t))return t;const e=(process==null?void 0:"production")==="production",n="https://ai-sdk.dev/unauthenticated-ai-gateway";return e?new de({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
407
+
408
+ To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
409
+
410
+ Alternatively, you can use a provider module instead of the AI Gateway.
411
+
412
+ Learn more: \x1B[34m${n}\x1B[0m
413
+
414
+ `),{name:"GatewayAuthenticationError"})}function Ds({operationId:t,telemetry:e}){return{"operation.name":`${t}${(e==null?void 0:e.functionId)!=null?` ${e.functionId}`:""}`,"resource.name":e==null?void 0:e.functionId,"ai.operationId":t,"ai.telemetry.functionId":e==null?void 0:e.functionId}}function hI({model:t,settings:e,telemetry:n,headers:o}){var i;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((s,[r,a])=>{if(r==="timeout"){const u=rI(a);u!=null&&(s[`ai.settings.${r}`]=u)}else s[`ai.settings.${r}`]=a;return s},{}),...Object.entries((i=n==null?void 0:n.metadata)!=null?i:{}).reduce((s,[r,a])=>(s[`ai.telemetry.metadata.${r}`]=a,s),{}),...Object.entries(o??{}).reduce((s,[r,a])=>(a!==void 0&&(s[`ai.request.headers.${r}`]=a),s),{})}}var n2={startSpan(){return Ra},startActiveSpan(t,e,n,o){if(typeof e=="function")return e(Ra);if(typeof n=="function")return n(Ra);if(typeof o=="function")return o(Ra)}},Ra={spanContext(){return o2},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},o2={traceId:"",spanId:"",traceFlags:0};function mI({isEnabled:t=!1,tracer:e}={}){return t?e||aJ.getTracer("ai"):n2}async function $s({name:t,tracer:e,attributes:n,fn:o,endWhenDone:i=!0}){return e.startActiveSpan(t,{attributes:await n},async s=>{const r=bg.active();try{const a=await bg.with(r,()=>o(s));return i&&s.end(),a}catch(a){try{gI(s,a)}finally{s.end()}throw a}})}function gI(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:cl.ERROR,message:e.message})):t.setStatus({code:cl.ERROR})}async function Sn({telemetry:t,attributes:e}){if((t==null?void 0:t.isEnabled)!==!0)return{};const n={};for(const[o,i]of Object.entries(e))if(i!=null){if(typeof i=="object"&&"input"in i&&typeof i.input=="function"){if((t==null?void 0:t.recordInputs)===!1)continue;const s=await i.input();s!=null&&(n[o]=s);continue}if(typeof i=="object"&&"output"in i&&typeof i.output=="function"){if((t==null?void 0:t.recordOutputs)===!1)continue;const s=await i.output();s!=null&&(n[o]=s);continue}n[o]=i}return n}function vI(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?Sc(n.data):n.data}:n)})))}function i2(){var t;return(t=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?t:[]}function s2(){const t=i2();return e=>{const n=la(e),o=[...t,...n];function i(s){const r=o.map(s).filter(Boolean);return async a=>{for(const u of r)try{await u(a)}catch{}}}return{onStart:i(s=>s.onStart),onStepStart:i(s=>s.onStepStart),onToolCallStart:i(s=>s.onToolCallStart),onToolCallFinish:i(s=>s.onToolCallFinish),onStepFinish:i(s=>s.onStepFinish),onFinish:i(s=>s.onFinish)}}}function pl(t){return{inputTokens:t.inputTokens.total,inputTokenDetails:{noCacheTokens:t.inputTokens.noCache,cacheReadTokens:t.inputTokens.cacheRead,cacheWriteTokens:t.inputTokens.cacheWrite},outputTokens:t.outputTokens.total,outputTokenDetails:{textTokens:t.outputTokens.text,reasoningTokens:t.outputTokens.reasoning},totalTokens:yn(t.inputTokens.total,t.outputTokens.total),raw:t.raw,reasoningTokens:t.outputTokens.reasoning,cachedInputTokens:t.inputTokens.cacheRead}}function r2(t,e){var n,o,i,s,r,a,u,c,p,f;return{inputTokens:yn(t.inputTokens,e.inputTokens),inputTokenDetails:{noCacheTokens:yn((n=t.inputTokenDetails)==null?void 0:n.noCacheTokens,(o=e.inputTokenDetails)==null?void 0:o.noCacheTokens),cacheReadTokens:yn((i=t.inputTokenDetails)==null?void 0:i.cacheReadTokens,(s=e.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:yn((r=t.inputTokenDetails)==null?void 0:r.cacheWriteTokens,(a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens)},outputTokens:yn(t.outputTokens,e.outputTokens),outputTokenDetails:{textTokens:yn((u=t.outputTokenDetails)==null?void 0:u.textTokens,(c=e.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:yn((p=t.outputTokenDetails)==null?void 0:p.reasoningTokens,(f=e.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:yn(t.totalTokens,e.totalTokens),reasoningTokens:yn(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:yn(t.cachedInputTokens,e.cachedInputTokens)}}function yn(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function yI(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const n={...t};for(const o in e)if(!(o==="__proto__"||o==="constructor"||o==="prototype")&&Object.prototype.hasOwnProperty.call(e,o)){const i=e[o];if(i===void 0)continue;const s=o in t?t[o]:void 0,r=i!==null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),a=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);r&&a?n[o]=yI(s,i):n[o]=i}return n}function a2({error:t,exponentialBackoffDelay:e}){const n=rt.isInstance(t)?t.responseHeaders:rt.isInstance(t.cause)?t.cause.responseHeaders:void 0;if(!n)return e;let o;const i=n["retry-after-ms"];if(i){const r=parseFloat(i);Number.isNaN(r)||(o=r)}const s=n["retry-after"];if(s&&o===void 0){const r=parseFloat(s);Number.isNaN(r)?o=Date.parse(s)-Date.now():o=r*1e3}return o!=null&&!Number.isNaN(o)&&0<=o&&(o<60*1e3||o<e)?o:e}var l2=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:n=2,abortSignal:o}={})=>async i=>_I(i,{maxRetries:t,delayInMs:e,backoffFactor:n,abortSignal:o});async function _I(t,{maxRetries:e,delayInMs:n,backoffFactor:o,abortSignal:i},s=[]){try{return await t()}catch(r){if(Kn(r)||e===0)throw r;const a=ST(r),u=[...s,r],c=u.length;if(c>e)throw new kg({message:`Failed after ${c} attempts. Last error: ${a}`,reason:"maxRetriesExceeded",errors:u});if(r instanceof Error&&(rt.isInstance(r)&&r.isRetryable===!0||bt.isInstance(r)&&r.isRetryable===!0)&&c<=e)return await _i(a2({error:r,exponentialBackoffDelay:n}),{abortSignal:i}),_I(t,{maxRetries:e,delayInMs:o*n,backoffFactor:o,abortSignal:i},u);throw c===1?r:new kg({message:`Failed after ${c} attempts with non-retryable error: '${a}'`,reason:"errorNotRetryable",errors:u})}}function TI({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new Qe({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new Qe({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const n=t??2;return{maxRetries:n,retry:l2({maxRetries:n,abortSignal:e})}}function u2({messages:t}){const e=t.at(-1);if((e==null?void 0:e.role)!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const n={};for(const u of t)if(u.role==="assistant"&&typeof u.content!="string"){const c=u.content;for(const p of c)p.type==="tool-call"&&(n[p.toolCallId]=p)}const o={};for(const u of t)if(u.role==="assistant"&&typeof u.content!="string"){const c=u.content;for(const p of c)p.type==="tool-approval-request"&&(o[p.approvalId]=p)}const i={};for(const u of e.content)u.type==="tool-result"&&(i[u.toolCallId]=u);const s=[],r=[],a=e.content.filter(u=>u.type==="tool-approval-response");for(const u of a){const c=o[u.approvalId];if(c==null)throw new pJ({approvalId:u.approvalId});if(i[c.toolCallId]!=null)continue;const p=n[c.toolCallId];if(p==null)throw new Uw({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:u,toolCall:p};u.approved?s.push(f):r.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:r}}function xu(){var t,e;return(e=(t=globalThis==null?void 0:globalThis.performance)==null?void 0:t.now())!=null?e:Date.now()}async function c2({toolCall:t,tools:e,tracer:n,telemetry:o,messages:i,abortSignal:s,experimental_context:r,stepNumber:a,model:u,onPreliminaryToolResult:c,onToolCallStart:p,onToolCallFinish:f}){const{toolName:h,toolCallId:m,input:v}=t,_=e==null?void 0:e[h];if((_==null?void 0:_.execute)==null)return;const w={stepNumber:a,model:u,toolCall:t,messages:i,abortSignal:s,functionId:o==null?void 0:o.functionId,metadata:o==null?void 0:o.metadata,experimental_context:r};return $s({name:"ai.toolCall",attributes:Sn({telemetry:o,attributes:{...Ds({operationId:"ai.toolCall",telemetry:o}),"ai.toolCall.name":h,"ai.toolCall.id":m,"ai.toolCall.args":{output:()=>JSON.stringify(v)}}}),tracer:n,fn:async C=>{let E;await zo({event:w,callbacks:p});const A=xu();try{const k=fL({execute:_.execute.bind(_),input:v,options:{toolCallId:m,messages:i,abortSignal:s,experimental_context:r}});for await(const b of k)b.type==="preliminary"?c==null||c({...t,type:"tool-result",output:b.output,preliminary:!0}):E=b.output}catch(k){const b=xu()-A;return await zo({event:{...w,success:!1,error:k,durationMs:b},callbacks:f}),gI(C,k),{type:"tool-error",toolCallId:m,toolName:h,input:v,error:k,dynamic:_.type==="dynamic",...t.providerMetadata!=null?{providerMetadata:t.providerMetadata}:{},...t.toolMetadata!=null?{toolMetadata:t.toolMetadata}:{}}}const R=xu()-A;await zo({event:{...w,success:!0,output:E,durationMs:R},callbacks:f});try{C.setAttributes(await Sn({telemetry:o,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(E)}}}))}catch{}return{type:"tool-result",toolCallId:m,toolName:h,input:v,output:E,dynamic:_.type==="dynamic",...t.providerMetadata!=null?{providerMetadata:t.providerMetadata}:{},...t.toolMetadata!=null?{toolMetadata:t.toolMetadata}:{}}}})}function Cc(t){const e=t.filter(n=>n.type==="reasoning");return e.length===0?void 0:e.map(n=>n.text).join(`
415
+ `)}function Ac(t){const e=t.filter(n=>n.type==="text");if(e.length!==0)return e.map(n=>n.text).join("")}var d2=class{constructor({data:t,mediaType:e}){const n=t instanceof Uint8Array;this.base64Data=n?void 0:t,this.uint8ArrayData=n?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=ni(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=nd(this.base64Data)),this.uint8ArrayData}};async function p2({tool:t,toolCall:e,messages:n,experimental_context:o}){return t.needsApproval==null?!1:typeof t.needsApproval=="boolean"?t.needsApproval:await t.needsApproval(e.input,{toolCallId:e.toolCallId,messages:n,experimental_context:o})}var f2={};uJ(f2,{array:()=>g2,choice:()=>v2,json:()=>y2,object:()=>m2,text:()=>EI});function h2(t){const e=["ROOT"];let n=-1,o=null;function i(u,c,p){switch(u){case'"':{n=c,e.pop(),e.push(p),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,o=c,e.pop(),e.push(p),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(p),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,e.pop(),e.push(p),e.push("INSIDE_NUMBER");break}case"{":{n=c,e.pop(),e.push(p),e.push("INSIDE_OBJECT_START");break}case"[":{n=c,e.pop(),e.push(p),e.push("INSIDE_ARRAY_START");break}}}function s(u,c){switch(u){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,e.pop();break}}}function r(u,c){switch(u){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,e.pop();break}}}for(let u=0;u<t.length;u++){const c=t[u];switch(e[e.length-1]){case"ROOT":i(c,u,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{n=u,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{i(c,u,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,u);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),n=u;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:n=u}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=u,e.pop();break}default:{n=u,i(c,u,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,e.pop();break}default:{n=u;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{i(c,u,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),n=u;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&r(c,u),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,u);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,u);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&r(c,u);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const f=t.substring(o,u+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,u):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&r(c,u)):n=u;break}}}let a=t.slice(0,n+1);for(let u=e.length-1;u>=0;u--)switch(e[u]){case"INSIDE_STRING":{a+='"';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":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const p=t.substring(o,t.length);"true".startsWith(p)?a+="true".slice(p.length):"false".startsWith(p)?a+="false".slice(p.length):"null".startsWith(p)&&(a+="null".slice(p.length))}}return a}async function Xl(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await cn({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await cn({text:h2(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var EI=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:t}){return t},async parsePartialOutput({text:t}){return{partial:t}},createElementStreamTransform(){}}),m2=({schema:t,name:e,description:n})=>{const o=Co(t);return{name:"object",responseFormat:He(o.jsonSchema).then(i=>({type:"json",schema:i,...e!=null&&{name:e},...n!=null&&{description:n}})),async parseCompleteOutput({text:i},s){const r=await cn({text:i});if(!r.success)throw new Kt({message:"No object generated: could not parse the response.",cause:r.error,text:i,response:s.response,usage:s.usage,finishReason:s.finishReason});const a=await Gt({value:r.value,schema:o});if(!a.success)throw new Kt({message:"No object generated: response did not match schema.",cause:a.error,text:i,response:s.response,usage:s.usage,finishReason:s.finishReason});return a.value},async parsePartialOutput({text:i}){const s=await Xl(i);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},g2=({element:t,name:e,description:n})=>{const o=Co(t);return{name:"array",responseFormat:He(o.jsonSchema).then(i=>{const{$schema:s,...r}=i;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:r}},required:["elements"],additionalProperties:!1},...e!=null&&{name:e},...n!=null&&{description:n}}}),async parseCompleteOutput({text:i},s){const r=await cn({text:i});if(!r.success)throw new Kt({message:"No object generated: could not parse the response.",cause:r.error,text:i,response:s.response,usage:s.usage,finishReason:s.finishReason});const a=r.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))throw new Kt({message:"No object generated: response did not match schema.",cause:new Ot({value:a,cause:"response must be an object with an elements array"}),text:i,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const u of a.elements){const c=await Gt({value:u,schema:o});if(!c.success)throw new Kt({message:"No object generated: response did not match schema.",cause:c.error,text:i,response:s.response,usage:s.usage,finishReason:s.finishReason})}return a.elements},async parsePartialOutput({text:i}){const s=await Xl(i);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const r=s.value;if(r==null||typeof r!="object"||!("elements"in r)||!Array.isArray(r.elements))return;const a=s.state==="repaired-parse"&&r.elements.length>0?r.elements.slice(0,-1):r.elements,u=[];for(const c of a){const p=await Gt({value:c,schema:o});p.success&&u.push(p.value)}return{partial:u}}}},createElementStreamTransform(){let i=0;return new TransformStream({transform({partialOutput:s},r){if(s!=null)for(;i<s.length;i++)r.enqueue(s[i])}})}}},v2=({options:t,name:e,description:n})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:t}},required:["result"],additionalProperties:!1},...e!=null&&{name:e},...n!=null&&{description:n}}),async parseCompleteOutput({text:o},i){const s=await cn({text:o});if(!s.success)throw new Kt({message:"No object generated: could not parse the response.",cause:s.error,text:o,response:i.response,usage:i.usage,finishReason:i.finishReason});const r=s.value;if(r==null||typeof r!="object"||!("result"in r)||typeof r.result!="string"||!t.includes(r.result))throw new Kt({message:"No object generated: response did not match schema.",cause:new Ot({value:r,cause:"response must be an object that contains a choice value."}),text:o,response:i.response,usage:i.usage,finishReason:i.finishReason});return r.result},async parsePartialOutput({text:o}){const i=await Xl(o);switch(i.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=i.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const r=t.filter(a=>a.startsWith(s.result));return i.state==="successful-parse"?r.includes(s.result)?{partial:s.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),y2=({name:t,description:e}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...t!=null&&{name:t},...e!=null&&{description:e}}),async parseCompleteOutput({text:n},o){const i=await cn({text:n});if(!i.success)throw new Kt({message:"No object generated: could not parse the response.",cause:i.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return i.value},async parsePartialOutput({text:n}){const o=await Xl(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return o.value===void 0?void 0:{partial:o.value}}},createElementStreamTransform(){}});async function _2({toolCall:t,tools:e,repairToolCall:n,system:o,messages:i}){try{if(e==null){if(t.providerExecuted&&t.dynamic)return await wI(t);throw new wc({toolName:t.toolName})}try{return await xg({toolCall:t,tools:e})}catch(s){if(n==null||!(wc.isInstance(s)||bd.isInstance(s)))throw s;let r=null;try{r=await n({toolCall:t,tools:e,inputSchema:async({toolName:a})=>{const{inputSchema:u}=e[a];return await Co(u).jsonSchema},system:o,messages:i,error:s})}catch(a){throw new EJ({cause:a,originalError:s})}if(r==null)throw s;return await xg({toolCall:r,tools:e})}}catch(s){const r=await cn({text:t.input}),a=r.success?r.value:t.input,u=e==null?void 0:e[t.toolName];return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:a,dynamic:!0,invalid:!0,error:s,title:u==null?void 0:u.title,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,...(u==null?void 0:u.metadata)!=null?{toolMetadata:u.metadata}:{}}}}async function wI(t){const e=t.input.trim()===""?{success:!0,value:{}}:await cn({text:t.input});if(e.success===!1)throw new bd({toolName:t.toolName,toolInput:t.input,cause:e.error});return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:e.value,providerExecuted:!0,dynamic:!0,providerMetadata:t.providerMetadata}}async function xg({toolCall:t,tools:e}){const n=t.toolName,o=e[n];if(o==null){if(t.providerExecuted&&t.dynamic)return await wI(t);throw new wc({toolName:t.toolName,availableTools:Object.keys(e)})}const i=Co(o.inputSchema),s=t.input.trim()===""?await Gt({value:{},schema:i}):await cn({text:t.input,schema:i});if(s.success===!1)throw new bd({toolName:n,toolInput:t.input,cause:s.error});return o.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,...o.metadata!=null?{toolMetadata:o.metadata}:{},dynamic:!0,title:o.title}:{type:"tool-call",toolCallId:t.toolCallId,toolName:n,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,...o.metadata!=null?{toolMetadata:o.metadata}:{},title:o.title}}var T2=class{constructor({stepNumber:t,model:e,functionId:n,metadata:o,experimental_context:i,content:s,finishReason:r,rawFinishReason:a,usage:u,warnings:c,request:p,response:f,providerMetadata:h}){this.stepNumber=t,this.model=e,this.functionId=n,this.metadata=o,this.experimental_context=i,this.content=s,this.finishReason=r,this.rawFinishReason=a,this.usage=u,this.warnings=c,this.request=p,this.response=f,this.providerMetadata=h}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function E2(t){return({steps:e})=>e.length===t}async function w2({stopConditions:t,steps:e}){return(await Promise.all(t.map(n=>n({steps:e})))).some(n=>n)}async function I2({content:t,tools:e}){const n=[],o=[];for(const s of t)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":o.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":o.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":o.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":o.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.invalid&&typeof s.input!="object"?{}:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const r=await Oa({toolCallId:s.toolCallId,input:s.input,tool:e==null?void 0:e[s.toolName],output:s.output,errorMode:"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:r,providerOptions:s.providerMetadata});break}case"tool-error":{const r=await Oa({toolCallId:s.toolCallId,input:s.input,tool:e==null?void 0:e[s.toolName],output:s.error,errorMode:"json"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:r,providerOptions:s.providerMetadata});break}case"tool-approval-request":o.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}o.length>0&&n.push({role:"assistant",content:o});const i=[];for(const s of t){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const r=await Oa({toolCallId:s.toolCallId,input:s.input,tool:e==null?void 0:e[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});i.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:r,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return i.length>0&&n.push({role:"tool",content:i}),n}function S2(...t){const e=t.filter(o=>o!=null);if(e.length===0)return;if(e.length===1)return e[0];const n=new AbortController;for(const o of e){if(o.aborted)return n.abort(o.reason),n.signal;o.addEventListener("abort",()=>{n.abort(o.reason)},{once:!0})}return n.signal}var C2=ia({prefix:"aitxt",size:24});async function A2({model:t,tools:e,toolChoice:n,system:o,prompt:i,messages:s,allowSystemInMessages:r,maxRetries:a,abortSignal:u,timeout:c,headers:p,stopWhen:f=E2(1),experimental_output:h,output:m=h,experimental_telemetry:v,providerOptions:_,experimental_activeTools:w,activeTools:C=w,experimental_prepareStep:E,prepareStep:A=E,experimental_repairToolCall:R,experimental_download:k,experimental_context:b,experimental_include:U,_internal:{generateId:J=C2}={},experimental_onStart:G,experimental_onStepStart:L,experimental_onToolCallStart:B,experimental_onToolCallFinish:ve,onStepFinish:Ae,onFinish:ye,...ue}){const we=Ic(t),j=s2(),re=la(f),x=rI(c),ce=MJ(c),H=ce!=null?new AbortController:void 0,X=S2(u,x!=null?AbortSignal.timeout(x):void 0,H==null?void 0:H.signal),{maxRetries:ge,retry:oe}=TI({maxRetries:a,abortSignal:X}),_e=dl(ue),wt=Po(p??{},`ai/${kd}`),eo=hI({model:we,telemetry:v,headers:wt,settings:{..._e,maxRetries:ge}}),Qt={provider:we.provider,modelId:we.modelId},K=await pI({system:o,prompt:i,messages:s,allowSystemInMessages:r}),he=j(v==null?void 0:v.integrations);await zo({event:{model:Qt,system:o,prompt:i,messages:s,tools:e,toolChoice:n,activeTools:C,maxOutputTokens:_e.maxOutputTokens,temperature:_e.temperature,topP:_e.topP,topK:_e.topK,presencePenalty:_e.presencePenalty,frequencyPenalty:_e.frequencyPenalty,stopSequences:_e.stopSequences,seed:_e.seed,maxRetries:ge,timeout:c,headers:p,providerOptions:_,stopWhen:f,output:m,abortSignal:u,include:U,functionId:v==null?void 0:v.functionId,metadata:v==null?void 0:v.metadata,experimental_context:b},callbacks:[G,he.onStart]});const At=mI(v);try{return await $s({name:"ai.generateText",attributes:Sn({telemetry:v,attributes:{...Ds({operationId:"ai.generateText",telemetry:v}),...eo,"ai.model.provider":we.provider,"ai.model.id":we.modelId,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:i,messages:s})}}}),tracer:At,fn:async hn=>{var Mo,xo,De,gt,Ue,Rn,li,ua,Nd,Md,xd,Dd,$d,Ud,Od,Ld,Gd,zd,Fd,Vd;const Ql=K.messages,ca=[],{approvedToolApprovals:kI,deniedToolApprovals:qd}=u2({messages:Ql}),Bd=kI.filter(en=>!en.toolCall.providerExecuted);if(qd.length>0||Bd.length>0){const en=await Dg({toolCalls:Bd.map(Ie=>Ie.toolCall),tools:e,tracer:At,telemetry:v,messages:Ql,abortSignal:X,experimental_context:b,stepNumber:0,model:Qt,onToolCallStart:[B,he.onToolCallStart],onToolCallFinish:[ve,he.onToolCallFinish]}),qt=[];for(const Ie of en){const mn=await Oa({toolCallId:Ie.toolCallId,input:Ie.input,tool:e==null?void 0:e[Ie.toolName],output:Ie.type==="tool-result"?Ie.output:Ie.error,errorMode:Ie.type==="tool-error"?"text":"none"});qt.push({type:"tool-result",toolCallId:Ie.toolCallId,toolName:Ie.toolName,output:mn})}for(const Ie of qd)qt.push({type:"tool-result",toolCallId:Ie.toolCall.toolCallId,toolName:Ie.toolCall.toolName,output:{type:"execution-denied",reason:Ie.approvalResponse.reason,...Ie.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ie.approvalResponse.approvalId}}}}});ca.push({role:"tool",content:qt})}const PI=dl(ue);let dt,da=[],ss=[];const Vt=[],jl=new Map;do{const en=ce!=null?setTimeout(()=>H.abort(),ce):void 0;try{const qt=[...Ql,...ca],Ie=await(A==null?void 0:A({model:we,steps:Vt,stepNumber:Vt.length,messages:qt,experimental_context:b})),mn=Ic((Mo=Ie==null?void 0:Ie.model)!=null?Mo:we),rs={provider:mn.provider,modelId:mn.modelId},Zd=await lI({prompt:{system:(xo=Ie==null?void 0:Ie.system)!=null?xo:K.system,messages:(De=Ie==null?void 0:Ie.messages)!=null?De:qt},supportedUrls:await mn.supportedUrls,download:k});b=(gt=Ie==null?void 0:Ie.experimental_context)!=null?gt:b;const Jd=(Ue=Ie==null?void 0:Ie.activeTools)!=null?Ue:C,{toolChoice:pa,tools:eu}=await BJ({tools:e,toolChoice:(Rn=Ie==null?void 0:Ie.toolChoice)!=null?Rn:n,activeTools:Jd}),NI=(li=Ie==null?void 0:Ie.messages)!=null?li:qt,MI=(ua=Ie==null?void 0:Ie.system)!=null?ua:K.system,Wd=yI(_,Ie==null?void 0:Ie.providerOptions);await zo({event:{stepNumber:Vt.length,model:rs,system:MI,messages:NI,tools:e,toolChoice:pa,activeTools:Jd,steps:[...Vt],providerOptions:Wd,timeout:c,headers:p,stopWhen:f,output:m,abortSignal:u,include:U,functionId:v==null?void 0:v.functionId,metadata:v==null?void 0:v.metadata,experimental_context:b},callbacks:[L,he.onStepStart]}),dt=await oe(()=>{var Se;return $s({name:"ai.generateText.doGenerate",attributes:Sn({telemetry:v,attributes:{...Ds({operationId:"ai.generateText.doGenerate",telemetry:v}),...eo,"ai.model.provider":mn.provider,"ai.model.id":mn.modelId,"ai.prompt.messages":{input:()=>vI(Zd)},"ai.prompt.tools":{input:()=>eu==null?void 0:eu.map(Bt=>JSON.stringify(Bt))},"ai.prompt.toolChoice":{input:()=>pa!=null?JSON.stringify(pa):void 0},"gen_ai.system":mn.provider,"gen_ai.request.model":mn.modelId,"gen_ai.request.frequency_penalty":ue.frequencyPenalty,"gen_ai.request.max_tokens":ue.maxOutputTokens,"gen_ai.request.presence_penalty":ue.presencePenalty,"gen_ai.request.stop_sequences":ue.stopSequences,"gen_ai.request.temperature":(Se=ue.temperature)!=null?Se:void 0,"gen_ai.request.top_k":ue.topK,"gen_ai.request.top_p":ue.topP}}),tracer:At,fn:async Bt=>{var nu,ls,Xd,Qd,jd,ep,tp,np;const Xe=await mn.doGenerate({...PI,tools:eu,toolChoice:pa,responseFormat:await(m==null?void 0:m.responseFormat),prompt:Zd,providerOptions:Wd,abortSignal:X,headers:wt}),ui={id:(ls=(nu=Xe.response)==null?void 0:nu.id)!=null?ls:J(),timestamp:(Qd=(Xd=Xe.response)==null?void 0:Xd.timestamp)!=null?Qd:new Date,modelId:(ep=(jd=Xe.response)==null?void 0:jd.modelId)!=null?ep:mn.modelId,headers:(tp=Xe.response)==null?void 0:tp.headers,body:(np=Xe.response)==null?void 0:np.body},OI=pl(Xe.usage);return Bt.setAttributes(await Sn({telemetry:v,attributes:{"ai.response.finishReason":Xe.finishReason.unified,"ai.response.text":{output:()=>Ac(Xe.content)},"ai.response.reasoning":{output:()=>Cc(Xe.content)},"ai.response.toolCalls":{output:()=>{const op=$g(Xe.content);return op==null?void 0:JSON.stringify(op)}},"ai.response.id":ui.id,"ai.response.model":ui.modelId,"ai.response.timestamp":ui.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Xe.providerMetadata),"ai.usage.inputTokens":Xe.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":Xe.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":Xe.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":Xe.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":Xe.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":Xe.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":Xe.usage.outputTokens.reasoning,"ai.usage.totalTokens":OI.totalTokens,"ai.usage.reasoningTokens":Xe.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":Xe.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[Xe.finishReason.unified],"gen_ai.response.id":ui.id,"gen_ai.response.model":ui.modelId,"gen_ai.usage.input_tokens":Xe.usage.inputTokens.total,"gen_ai.usage.output_tokens":Xe.usage.outputTokens.total}})),{...Xe,response:ui}}})});const as=await Promise.all(dt.content.filter(Se=>Se.type==="tool-call").map(Se=>_2({toolCall:Se,tools:e,repairToolCall:R,system:o,messages:qt}))),tu={};for(const Se of as){if(Se.invalid)continue;const Bt=e==null?void 0:e[Se.toolName];Bt!=null&&((Bt==null?void 0:Bt.onInputAvailable)!=null&&await Bt.onInputAvailable({input:Se.input,toolCallId:Se.toolCallId,messages:qt,abortSignal:X,experimental_context:b}),await p2({tool:Bt,toolCall:Se,messages:qt,experimental_context:b})&&(tu[Se.toolCallId]={type:"tool-approval-request",approvalId:J(),toolCall:Se}))}const xI=as.filter(Se=>Se.invalid&&Se.dynamic);ss=[];for(const Se of xI)ss.push({type:"tool-error",toolCallId:Se.toolCallId,toolName:Se.toolName,input:Se.input,error:ST(Se.error),dynamic:!0});da=as.filter(Se=>!Se.providerExecuted),e!=null&&ss.push(...await Dg({toolCalls:da.filter(Se=>!Se.invalid&&tu[Se.toolCallId]==null),tools:e,tracer:At,telemetry:v,messages:qt,abortSignal:X,experimental_context:b,stepNumber:Vt.length,model:rs,onToolCallStart:[B,he.onToolCallStart],onToolCallFinish:[ve,he.onToolCallFinish]}));for(const Se of as){if(!Se.providerExecuted)continue;const Bt=e==null?void 0:e[Se.toolName];(Bt==null?void 0:Bt.type)==="provider"&&Bt.supportsDeferredResults&&(dt.content.some(ls=>ls.type==="tool-result"&&ls.toolCallId===Se.toolCallId)||jl.set(Se.toolCallId,{toolName:Se.toolName}))}for(const Se of dt.content)Se.type==="tool-result"&&jl.delete(Se.toolCallId);const Kd=R2({content:dt.content,toolCalls:as,toolOutputs:ss,toolApprovalRequests:Object.values(tu),tools:e});ca.push(...await I2({content:Kd,tools:e}));const DI=(Nd=U==null?void 0:U.requestBody)==null||Nd?(Md=dt.request)!=null?Md:{}:{...dt.request,body:void 0},$I={...dt.response,messages:structuredClone(ca),body:(xd=U==null?void 0:U.responseBody)==null||xd?(Dd=dt.response)==null?void 0:Dd.body:void 0},UI=Vt.length,Yd=new T2({stepNumber:UI,model:rs,functionId:v==null?void 0:v.functionId,metadata:v==null?void 0:v.metadata,experimental_context:b,content:Kd,finishReason:dt.finishReason.unified,rawFinishReason:dt.finishReason.raw,usage:pl(dt.usage),warnings:dt.warnings,providerMetadata:dt.providerMetadata,request:DI,response:$I});Rd({warnings:($d=dt.warnings)!=null?$d:[],provider:rs.provider,model:rs.modelId}),Vt.push(Yd),await zo({event:Yd,callbacks:[Ae,he.onStepFinish]})}finally{en!=null&&clearTimeout(en)}}while((da.length>0&&ss.length===da.length||jl.size>0)&&!await w2({stopConditions:re,steps:Vt}));hn.setAttributes(await Sn({telemetry:v,attributes:{"ai.response.finishReason":dt.finishReason.unified,"ai.response.text":{output:()=>Ac(dt.content)},"ai.response.reasoning":{output:()=>Cc(dt.content)},"ai.response.toolCalls":{output:()=>{const en=$g(dt.content);return en==null?void 0:JSON.stringify(en)}},"ai.response.providerMetadata":JSON.stringify(dt.providerMetadata)}}));const Oe=Vt[Vt.length-1],jt=Vt.reduce((en,qt)=>r2(en,qt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});hn.setAttributes(await Sn({telemetry:v,attributes:{"ai.usage.inputTokens":jt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Ud=jt.inputTokenDetails)==null?void 0:Ud.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Od=jt.inputTokenDetails)==null?void 0:Od.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Ld=jt.inputTokenDetails)==null?void 0:Ld.cacheWriteTokens,"ai.usage.outputTokens":jt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(Gd=jt.outputTokenDetails)==null?void 0:Gd.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(zd=jt.outputTokenDetails)==null?void 0:zd.reasoningTokens,"ai.usage.totalTokens":jt.totalTokens,"ai.usage.reasoningTokens":(Fd=jt.outputTokenDetails)==null?void 0:Fd.reasoningTokens,"ai.usage.cachedInputTokens":(Vd=jt.inputTokenDetails)==null?void 0:Vd.cacheReadTokens}})),await zo({event:{stepNumber:Oe.stepNumber,model:Oe.model,functionId:Oe.functionId,metadata:Oe.metadata,experimental_context:Oe.experimental_context,finishReason:Oe.finishReason,rawFinishReason:Oe.rawFinishReason,usage:Oe.usage,content:Oe.content,text:Oe.text,reasoningText:Oe.reasoningText,reasoning:Oe.reasoning,files:Oe.files,sources:Oe.sources,toolCalls:Oe.toolCalls,staticToolCalls:Oe.staticToolCalls,dynamicToolCalls:Oe.dynamicToolCalls,toolResults:Oe.toolResults,staticToolResults:Oe.staticToolResults,dynamicToolResults:Oe.dynamicToolResults,request:Oe.request,response:Oe.response,warnings:Oe.warnings,providerMetadata:Oe.providerMetadata,steps:Vt,totalUsage:jt},callbacks:[ye,he.onFinish]});let Hd;return Oe.finishReason==="stop"&&(Hd=await(m??EI()).parseCompleteOutput({text:Oe.text},{response:Oe.response,usage:Oe.usage,finishReason:Oe.finishReason})),new b2({steps:Vt,totalUsage:jt,output:Hd})}})}catch(hn){throw fI(hn)}}async function Dg({toolCalls:t,tools:e,tracer:n,telemetry:o,messages:i,abortSignal:s,experimental_context:r,stepNumber:a,model:u,onToolCallStart:c,onToolCallFinish:p}){return(await Promise.all(t.map(async h=>c2({toolCall:h,tools:e,tracer:n,telemetry:o,messages:i,abortSignal:s,experimental_context:r,stepNumber:a,model:u,onToolCallStart:c,onToolCallFinish:p})))).filter(h=>h!=null)}var b2=class{constructor(t){this.steps=t.steps,this._output=t.output,this.totalUsage=t.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new yJ;return this._output}};function $g(t){const e=t.filter(n=>n.type==="tool-call");if(e.length!==0)return e.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}function R2({content:t,toolCalls:e,toolOutputs:n,toolApprovalRequests:o,tools:i}){const s=[];for(const r of t)switch(r.type){case"text":case"reasoning":case"source":s.push(r);break;case"file":{s.push({type:"file",file:new d2(r),...r.providerMetadata!=null?{providerMetadata:r.providerMetadata}:{}});break}case"tool-call":{s.push(e.find(a=>a.toolCallId===r.toolCallId));break}case"tool-result":{const a=e.find(u=>u.toolCallId===r.toolCallId);if(a==null){const u=i==null?void 0:i[r.toolName];if(!((u==null?void 0:u.type)==="provider"&&u.supportsDeferredResults))throw new Error(`Tool call ${r.toolCallId} not found.`);r.isError?s.push({type:"tool-error",toolCallId:r.toolCallId,toolName:r.toolName,input:void 0,error:r.result,providerExecuted:!0,dynamic:r.dynamic,...r.providerMetadata!=null?{providerMetadata:r.providerMetadata}:{},...(u==null?void 0:u.metadata)!=null?{toolMetadata:u.metadata}:{}}):s.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,input:void 0,output:r.result,providerExecuted:!0,dynamic:r.dynamic,...r.providerMetadata!=null?{providerMetadata:r.providerMetadata}:{},...(u==null?void 0:u.metadata)!=null?{toolMetadata:u.metadata}:{}});break}r.isError?s.push({type:"tool-error",toolCallId:r.toolCallId,toolName:r.toolName,input:a.input,error:r.result,providerExecuted:!0,dynamic:a.dynamic,...r.providerMetadata!=null?{providerMetadata:r.providerMetadata}:{},...a.toolMetadata!=null?{toolMetadata:a.toolMetadata}:{}}):s.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,input:a.input,output:r.result,providerExecuted:!0,dynamic:a.dynamic,...r.providerMetadata!=null?{providerMetadata:r.providerMetadata}:{},...a.toolMetadata!=null?{toolMetadata:a.toolMetadata}:{}});break}case"tool-approval-request":{const a=e.find(u=>u.toolCallId===r.toolCallId);if(a==null)throw new Uw({toolCallId:r.toolCallId,approvalId:r.approvalId});s.push({type:"tool-approval-request",approvalId:r.approvalId,toolCall:a});break}}return[...s,...n,...o]}function k2(t,e){const n=new Headers(t??{});for(const[o,i]of Object.entries(e))n.has(o)||n.set(o,i);return n}(class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
416
+
417
+ `)},flush(t){t.enqueue(`data: [DONE]
418
+
419
+ `)}})}});Et(I(),ii.optional());function P2(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const n=this.getReader();let o=!1;async function i(s){var r;if(!o){o=!0;try{s&&await((r=n.cancel)==null?void 0:r.call(n))}finally{try{n.releaseLock()}catch{}}}}return{async next(){if(o)return{done:!0,value:void 0};const{done:s,value:r}=await n.read();return s?(await i(!0),{done:!0,value:void 0}):{done:!1,value:r}},async return(){return await i(!0),{done:!0,value:void 0}},async throw(s){throw await i(!0),s}}},e}ia({prefix:"aitxt",size:24});Et(I(),ii.optional());var N2={type:"no-schema",jsonSchema:async()=>{},async validatePartialResult({value:t,textDelta:e}){return{success:!0,value:{partial:t,textDelta:e}}},async validateFinalResult(t,e){return t===void 0?{success:!1,error:new Kt({message:"No object generated: response did not match schema.",text:e.text,response:e.response,usage:e.usage,finishReason:e.finishReason})}:{success:!0,value:t}},createElementStream(){throw new Vi({functionality:"element streams in no-schema mode"})}},M2=t=>({type:"object",jsonSchema:async()=>await t.jsonSchema,async validatePartialResult({value:e,textDelta:n}){return{success:!0,value:{partial:e,textDelta:n}}},async validateFinalResult(e){return Gt({value:e,schema:t})},createElementStream(){throw new Vi({functionality:"element streams in object mode"})}}),x2=t=>({type:"array",jsonSchema:async()=>{const{$schema:e,...n}=await t.jsonSchema;return{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:n}},required:["elements"],additionalProperties:!1}},async validatePartialResult({value:e,latestObject:n,isFirstDelta:o,isFinalDelta:i}){var s;if(!Za(e)||!jp(e.elements))return{success:!1,error:new Ot({value:e,cause:"value must be an object that contains an array of elements"})};const r=e.elements,a=[];for(let p=0;p<r.length;p++){const f=r[p],h=await Gt({value:f,schema:t});if(!(p===r.length-1&&!i)){if(!h.success)return h;a.push(h.value)}}const u=(s=n==null?void 0:n.length)!=null?s:0;let c="";return o&&(c+="["),u>0&&(c+=","),c+=a.slice(u).map(p=>JSON.stringify(p)).join(","),i&&(c+="]"),{success:!0,value:{partial:a,textDelta:c}}},async validateFinalResult(e){if(!Za(e)||!jp(e.elements))return{success:!1,error:new Ot({value:e,cause:"value must be an object that contains an array of elements"})};const n=e.elements;for(const o of n){const i=await Gt({value:o,schema:t});if(!i.success)return i}return{success:!0,value:n}},createElementStream(e){let n=0;return P2(e.pipeThrough(new TransformStream({transform(o,i){switch(o.type){case"object":{const s=o.object;for(;n<s.length;n++)i.enqueue(s[n]);break}case"text-delta":case"finish":case"error":break;default:{const s=o;throw new Error(`Unsupported chunk type: ${s}`)}}}})))}}),D2=t=>({type:"enum",jsonSchema:async()=>({$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:t}},required:["result"],additionalProperties:!1}),async validateFinalResult(e){if(!Za(e)||typeof e.result!="string")return{success:!1,error:new Ot({value:e,cause:'value must be an object that contains a string in the "result" property.'})};const n=e.result;return t.includes(n)?{success:!0,value:n}:{success:!1,error:new Ot({value:e,cause:"value must be a string in the enum"})}},async validatePartialResult({value:e,textDelta:n}){if(!Za(e)||typeof e.result!="string")return{success:!1,error:new Ot({value:e,cause:'value must be an object that contains a string in the "result" property.'})};const o=e.result,i=t.filter(s=>s.startsWith(o));return e.result.length===0||i.length===0?{success:!1,error:new Ot({value:e,cause:"value must be a string in the enum"})}:{success:!0,value:{partial:i.length>1?o:i[0],textDelta:n}}},createElementStream(){throw new Vi({functionality:"element streams in enum mode"})}});function $2({output:t,schema:e,enumValues:n}){switch(t){case"object":return M2(Co(e));case"array":return x2(Co(e));case"enum":return D2(n);case"no-schema":return N2;default:{const o=t;throw new Error(`Unsupported output: ${o}`)}}}async function Ug(t,e,n){const o=await cn({text:t});if(!o.success)throw new Kt({message:"No object generated: could not parse the response.",cause:o.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});const i=await e.validateFinalResult(o.value,{text:t,response:n.response,usage:n.usage});if(!i.success)throw new Kt({message:"No object generated: response did not match schema.",cause:i.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.value}async function U2(t,e,n,o){try{return await Ug(t,e,o)}catch(i){if(n!=null&&Kt.isInstance(i)&&(bs.isInstance(i.cause)||Ot.isInstance(i.cause))){const s=await n({text:t,error:i.cause});if(s===null)throw i;return await Ug(s,e,o)}throw i}}function O2({output:t,schema:e,schemaName:n,schemaDescription:o,enumValues:i}){if(t!=null&&t!=="object"&&t!=="array"&&t!=="enum"&&t!=="no-schema")throw new Qe({parameter:"output",value:t,message:"Invalid output type."});if(t==="no-schema"){if(e!=null)throw new Qe({parameter:"schema",value:e,message:"Schema is not supported for no-schema output."});if(o!=null)throw new Qe({parameter:"schemaDescription",value:o,message:"Schema description is not supported for no-schema output."});if(n!=null)throw new Qe({parameter:"schemaName",value:n,message:"Schema name is not supported for no-schema output."});if(i!=null)throw new Qe({parameter:"enumValues",value:i,message:"Enum values are not supported for no-schema output."})}if(t==="object"){if(e==null)throw new Qe({parameter:"schema",value:e,message:"Schema is required for object output."});if(i!=null)throw new Qe({parameter:"enumValues",value:i,message:"Enum values are not supported for object output."})}if(t==="array"){if(e==null)throw new Qe({parameter:"schema",value:e,message:"Element schema is required for array output."});if(i!=null)throw new Qe({parameter:"enumValues",value:i,message:"Enum values are not supported for array output."})}if(t==="enum"){if(e!=null)throw new Qe({parameter:"schema",value:e,message:"Schema is not supported for enum output."});if(o!=null)throw new Qe({parameter:"schemaDescription",value:o,message:"Schema description is not supported for enum output."});if(n!=null)throw new Qe({parameter:"schemaName",value:n,message:"Schema name is not supported for enum output."});if(i==null)throw new Qe({parameter:"enumValues",value:i,message:"Enum values are required for enum output."});for(const s of i)if(typeof s!="string")throw new Qe({parameter:"enumValues",value:s,message:"Enum values must be strings."})}}var L2=ia({prefix:"aiobj",size:24});async function G2(t){const{model:e,output:n="object",system:o,prompt:i,messages:s,allowSystemInMessages:r,maxRetries:a,abortSignal:u,headers:c,experimental_repairText:p,experimental_telemetry:f,experimental_download:h,providerOptions:m,_internal:{generateId:v=L2,currentDate:_=()=>new Date}={},...w}=t,C=Ic(e),E="enum"in t?t.enum:void 0,{schema:A,schemaDescription:R,schemaName:k}="schema"in t?t:{};O2({output:n,schema:A,schemaName:k,schemaDescription:R,enumValues:E});const{maxRetries:b,retry:U}=TI({maxRetries:a,abortSignal:u}),J=$2({output:n,schema:A,enumValues:E}),G=dl(w),L=Po(c??{},`ai/${kd}`),B=hI({model:C,telemetry:f,headers:L,settings:{...G,maxRetries:b}}),ve=mI(f),Ae=await J.jsonSchema();try{return await $s({name:"ai.generateObject",attributes:Sn({telemetry:f,attributes:{...Ds({operationId:"ai.generateObject",telemetry:f}),...B,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:i,messages:s})},"ai.schema":Ae!=null?{input:()=>JSON.stringify(Ae)}:void 0,"ai.schema.name":k,"ai.schema.description":R,"ai.settings.output":J.type}}),tracer:ve,fn:async ye=>{var ue;let we,j,re,x,ce,H,X,ge;const oe=await pI({system:o,prompt:i,messages:s,allowSystemInMessages:r}),_e=await lI({prompt:oe,supportedUrls:await C.supportedUrls,download:h}),wt=await U(()=>$s({name:"ai.generateObject.doGenerate",attributes:Sn({telemetry:f,attributes:{...Ds({operationId:"ai.generateObject.doGenerate",telemetry:f}),...B,"ai.prompt.messages":{input:()=>vI(_e)},"gen_ai.system":C.provider,"gen_ai.request.model":C.modelId,"gen_ai.request.frequency_penalty":G.frequencyPenalty,"gen_ai.request.max_tokens":G.maxOutputTokens,"gen_ai.request.presence_penalty":G.presencePenalty,"gen_ai.request.temperature":G.temperature,"gen_ai.request.top_k":G.topK,"gen_ai.request.top_p":G.topP}}),tracer:ve,fn:async Qt=>{var K,he,At,hn,Mo,xo,De,gt;const Ue=await C.doGenerate({responseFormat:{type:"json",schema:Ae,name:k,description:R},...dl(w),prompt:_e,providerOptions:m,abortSignal:u,headers:L}),Rn={id:(he=(K=Ue.response)==null?void 0:K.id)!=null?he:v(),timestamp:(hn=(At=Ue.response)==null?void 0:At.timestamp)!=null?hn:_(),modelId:(xo=(Mo=Ue.response)==null?void 0:Mo.modelId)!=null?xo:C.modelId,headers:(De=Ue.response)==null?void 0:De.headers,body:(gt=Ue.response)==null?void 0:gt.body},li=Ac(Ue.content),ua=Cc(Ue.content);if(li===void 0)throw new Kt({message:"No object generated: the model did not return a response.",response:Rn,usage:pl(Ue.usage),finishReason:Ue.finishReason.unified});return Qt.setAttributes(await Sn({telemetry:f,attributes:{"ai.response.finishReason":Ue.finishReason.unified,"ai.response.object":{output:()=>li},"ai.response.id":Rn.id,"ai.response.model":Rn.modelId,"ai.response.timestamp":Rn.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Ue.providerMetadata),"ai.usage.promptTokens":Ue.usage.inputTokens.total,"ai.usage.completionTokens":Ue.usage.outputTokens.total,"gen_ai.response.finish_reasons":[Ue.finishReason.unified],"gen_ai.response.id":Rn.id,"gen_ai.response.model":Rn.modelId,"gen_ai.usage.input_tokens":Ue.usage.inputTokens.total,"gen_ai.usage.output_tokens":Ue.usage.outputTokens.total}})),{...Ue,objectText:li,reasoning:ua,responseData:Rn}}}));we=wt.objectText,j=wt.finishReason.unified,re=pl(wt.usage),x=wt.warnings,X=wt.providerMetadata,H=(ue=wt.request)!=null?ue:{},ce=wt.responseData,ge=wt.reasoning,Rd({warnings:x,provider:C.provider,model:C.modelId});const eo=await U2(we,J,p,{response:ce,usage:re,finishReason:j});return ye.setAttributes(await Sn({telemetry:f,attributes:{"ai.response.finishReason":j,"ai.response.object":{output:()=>JSON.stringify(eo)},"ai.response.providerMetadata":JSON.stringify(X),"ai.usage.promptTokens":re.inputTokens,"ai.usage.completionTokens":re.outputTokens}})),new z2({object:eo,reasoning:ge,finishReason:j,usage:re,warnings:x,request:H,response:ce,providerMetadata:X})}})}catch(ye){throw fI(ye)}}var z2=class{constructor(t){this.object=t.object,this.finishReason=t.finishReason,this.usage=t.usage,this.warnings=t.warnings,this.providerMetadata=t.providerMetadata,this.response=t.response,this.request=t.request,this.reasoning=t.reasoning}toJsonResponse(t){var e;return new Response(JSON.stringify(this.object),{status:(e=t==null?void 0:t.status)!=null?e:200,headers:k2(t==null?void 0:t.headers,{"content-type":"application/json; charset=utf-8"})})}};ia({prefix:"aiobj",size:24});const F2=3e3;async function V2(t,e,n,o){const i=BN(t,e),s=await KN(e.toolCallId,e.kind);try{const a=(await Ln(u=>A2({model:WE(n.model,s),prompt:i,abortSignal:u}),F2,{signal:o,label:"narrate"})).text.trim();return a.length===0?null:a}catch(r){return console.warn("narrate failed",{err:r instanceof Error?r.message:String(r)}),null}}const q2=2500,B2=sa({anyOf:[{type:"object",properties:{status:{type:"string",enum:["already_in_target"]}},required:["status"],additionalProperties:!1},{type:"object",properties:{status:{type:"string",enum:["translated"]},text:{type:"string"}},required:["status","text"],additionalProperties:!1}]});async function H2(t,e,n,o,i){const r=`${WN(t)}
420
+
421
+ Respond as JSON matching the schema:
422
+ - If the source is already in the target language, return {"status":"already_in_target"} (omit any text field).
423
+ - Otherwise, return {"status":"translated","text":"<the translated text>"}.`,a=await YN(t,e,i??null);try{const c=(await Ln(p=>G2({model:WE(n.model,a),schema:B2,prompt:r,abortSignal:p}),q2,{signal:o,label:"translate"})).object;return c.status==="translated"&&c.text.trim().length===0?(console.warn("translate returned empty text — treating as failure",{len:t.length}),null):c}catch(u){return console.warn("translate failed",{err:u instanceof Error?u.message:String(u),len:t.length}),null}}var qr,Br,$i,En,go,Hr,Zr,bc;class Z2{constructor(e,n){D(this,Zr);D(this,qr,se("idle"));D(this,Br,se(null));D(this,$i);D(this,En,new DZ);D(this,go,!1);D(this,Hr);O(this,$i,e),O(this,Hr,n)}get state(){return Y(g(this,qr))}set state(e){te(g(this,qr),e,!0)}get currentSegmentId(){return Y(g(this,Br))}set currentSegmentId(e){te(g(this,Br),e,!0)}addSegment(e,n){g(this,En).insert(n,e),!g(this,go)&&$(this,Zr,bc).call(this)}jumpToSegment(e){g(this,En).clear(),g(this,En).insert({seq:-1,segmentIndex:0},e),!g(this,go)&&$(this,Zr,bc).call(this)}stop(){const e=[];let n=g(this,En).takeNext();for(;n!==void 0;)e.push(n.value),n=g(this,En).takeNext();this.currentSegmentId!==null&&e.push(this.currentSegmentId),g(this,En).clear();for(const o of e)g(this,$i).cancel(o);O(this,go,!1),this.state="idle",this.currentSegmentId=null}}qr=new WeakMap,Br=new WeakMap,$i=new WeakMap,En=new WeakMap,go=new WeakMap,Hr=new WeakMap,Zr=new WeakSet,bc=async function(){var e;O(this,go,!0),this.state="playing",(e=g(this,Hr))==null||e.call(this);try{let n=g(this,En).takeNext();for(;n!==void 0;){const o=n.value;this.currentSegmentId=o;try{await g(this,$i).play(o)}catch{}n=g(this,En).takeNext()}}finally{O(this,go,!1),this.state="idle",this.currentSegmentId=null}};const J2="he",W2=20,K2=200,Y2=2;var Jr,pt,Jt,Xo,Qo,jo,ei,$n,vo,Ui,on,Il,Oi,Wr,Bn,Li,Gi,Je,II,SI,Rc,Ts,CI,AI,bI,RI,La;class X2{constructor(e){D(this,Je);D(this,Jr,se(!0));D(this,pt);D(this,Jt);D(this,Xo);D(this,Qo);D(this,jo);D(this,ei,!1);D(this,$n,new Map);D(this,vo,[]);D(this,Ui,0);D(this,on,se(0));D(this,Il,"idle");D(this,Oi,"idle");D(this,Wr,new Map);D(this,Bn,new Set);D(this,Li,new $Z);D(this,Gi,null);O(this,pt,e.session),O(this,Jt,e.settings),O(this,jo,e.cues),this.enabled=!e.settings.muted,e.cues&&(e.cues.enabled=!e.settings.muted),O(this,Xo,new ow(new XE,new ew)),O(this,Qo,new Z2(g(this,Xo),()=>{var n;g(this,ei)||(O(this,ei,!0),(n=g(this,jo))==null||n.play("speaking"))})),O(this,Gi,qI(()=>{Ga(()=>{const n=g(this,pt).status,o=g(this,pt).turnState,i=this.enabled,s=g(this,Jt).speakThoughts,r=g(this,Jt).narrateTools,a=g(this,pt).bubbles;a.filter(c=>c.kind==="message"||c.kind==="thought").map(c=>c.segments.length);const u=g(this,pt).isLoadingHistory;a.filter(c=>c.kind==="tool").map(c=>{const p=c.toolCall;return`${p.toolCallId}:${p.status}:${p.narration??""}`}),BI(()=>{$(this,Je,II).call(this,a,i,u,s),$(this,Je,AI).call(this,a,i,u,r),$(this,Je,SI).call(this,n,o,i,s),O(this,Il,n),O(this,Oi,o)})})}))}get enabled(){return Y(g(this,Jr))}set enabled(e){te(g(this,Jr),e,!0)}get state(){return g(this,Qo).state==="playing"?"speaking":"idle"}get hasPendingNarration(){return Y(g(this,on))>0}toggle(){this.enabled=!this.enabled,g(this,Jt).setMuted(!this.enabled),g(this,jo)&&(g(this,jo).enabled=this.enabled),this.enabled||$(this,Je,La).call(this)}stop(){$(this,Je,La).call(this)}destroy(){var e;(e=g(this,Gi))==null||e.call(this),O(this,Gi,null),$(this,Je,La).call(this)}}Jr=new WeakMap,pt=new WeakMap,Jt=new WeakMap,Xo=new WeakMap,Qo=new WeakMap,jo=new WeakMap,ei=new WeakMap,$n=new WeakMap,vo=new WeakMap,Ui=new WeakMap,on=new WeakMap,Il=new WeakMap,Oi=new WeakMap,Wr=new WeakMap,Bn=new WeakMap,Li=new WeakMap,Gi=new WeakMap,Je=new WeakSet,II=function(e,n,o,i){if(o){for(const s of e){if(s.kind!=="message"&&s.kind!=="thought")continue;let r=g(this,$n).get(s.id);r===void 0&&(r={processedSegments:0,buffer:""},g(this,$n).set(s.id,r)),r.processedSegments=s.segments.length,r.buffer=""}return}for(const s of e){if(s.kind!=="message"&&s.kind!=="thought")continue;const r=s.segments;let a=g(this,$n).get(s.id);if(a===void 0&&(a={processedSegments:0,buffer:""},g(this,$n).set(s.id,a)),s.kind==="thought"&&!i){a.processedSegments=r.length,a.buffer="";continue}if(a.processedSegments>=r.length)continue;const u=r.slice(a.processedSegments).map(f=>f.text).join("");if(a.processedSegments=r.length,!n){a.buffer="";continue}a.buffer+=u;const{sentences:c,remaining:p}=ZN(a.buffer,{minChars:W2,maxChars:K2});a.buffer=p;for(const f of c)$(this,Je,Rc).call(this,s.kind,s.messageId,f,s.id)}$(this,Je,Ts).call(this)},SI=function(e,n,o,i){if(n!=="idle"&&g(this,Oi)==="idle"&&O(this,ei,!1),g(this,Oi)!=="idle"&&n==="idle"&&o){for(const[r,a]of g(this,$n)){if(a.buffer.trim().length===0)continue;const u=g(this,pt).bubbles.find(c=>c.id===r);if(u!==void 0&&!(u.kind!=="message"&&u.kind!=="thought")){if(u.kind==="thought"&&!i){a.buffer="";continue}$(this,Je,Rc).call(this,u.kind,u.messageId,a.buffer.trim(),u.id),a.buffer=""}}$(this,Je,Ts).call(this)}},Rc=function(e,n,o,i){if(o.length===0)return;const s=i??n??crypto.randomUUID(),r=g(this,Li).next(s);g(this,vo).push({segmentId:crypto.randomUUID(),kind:e,messageId:n,text:o,status:"pending",abort:new AbortController,bubbleId:i,orderKey:r}),te(g(this,on),Y(g(this,on))+1)},Ts=function(){for(;g(this,Ui)<Y2;){const e=g(this,vo).find(n=>n.status==="pending");if(e===void 0)break;e.status="fetching",O(this,Ui,g(this,Ui)+1),$(this,Je,CI).call(this,e).finally(()=>{O(this,Ui,g(this,Ui)-1),$(this,Je,Ts).call(this)})}},CI=async function(e){try{let n=e.text;if(e.kind==="thought"){if(g(this,Jt).translateThoughts){const u=await H2(n,J2,Zm("translate",Hm),e.abort.signal,e.messageId);u!==null&&u.status==="translated"&&(e.bubbleId!==void 0&&$(this,Je,RI).call(this,e.bubbleId,e.text,u.text),n=u.text)}}else if(e.kind==="tool"){const u=await $(this,Je,bI).call(this,e);if(u===null){e.status="error";return}n=u}if(e.abort.signal.aborted){e.status="error";return}const{provider:o,voiceId:i,modelId:s}=YE(g(this,Jt).ttsProvider,g(this,Jt).voiceId,g(this,Jt).geminiVoice);if(!Is.isAvailable(g(this,Jt).ttsProvider)){e.status="error",console.warn("[Speaker] TTS provider unavailable, skipping segment",{provider:g(this,Jt).ttsProvider,id:e.segmentId});return}const r=await VN(n,i,s),a=await o.synthesize({text:n,voiceId:i,modelId:s,messageId:e.messageId,signal:e.abort.signal});await g(this,Xo).prepareSegment(e.segmentId,a,e.abort,{messageId:e.messageId,textHash:r,format:o.format}),g(this,Qo).addSegment(e.segmentId,e.orderKey),e.status="ready"}catch(n){e.status="error",console.warn("TTS job failed, skipping segment",{id:e.segmentId,err:n instanceof Error?n.message:String(n)})}finally{Y(g(this,on))>0&&te(g(this,on),Y(g(this,on))-1)}},AI=function(e,n,o,i){for(const s of e){if(s.kind!=="tool")continue;const r=s.toolCall;if(o){g(this,Bn).add(r.toolCallId);continue}if(r.status!=="completed")continue;if(r.narration!==void 0){g(this,Bn).add(r.toolCallId);continue}if(g(this,Bn).has(r.toolCallId))continue;if(!n){g(this,Bn).add(r.toolCallId);continue}if(!i){g(this,Bn).add(r.toolCallId);continue}g(this,Bn).add(r.toolCallId);const a=s.id,u=g(this,Li).next(a);g(this,vo).push({segmentId:crypto.randomUUID(),kind:"tool",messageId:null,text:"",status:"pending",abort:new AbortController,bubbleId:a,toolCallId:r.toolCallId,orderKey:u}),te(g(this,on),Y(g(this,on))+1),$(this,Je,Ts).call(this)}},bI=async function(e){if(e.toolCallId===void 0||e.bubbleId===void 0)return null;const n=g(this,pt).bubbles.findIndex(c=>c.id===e.bubbleId);if(n===-1)return null;const o=g(this,pt).bubbles[n];if(o===void 0||o.kind!=="tool")return null;const i=o.toolCall,s={userMessage:g(this,pt).lastUserMessage,recentMessages:g(this,pt).recentAssistantMessages(3)},r={toolCallId:i.toolCallId,kind:i.kind,title:i.title??i.name},a=await V2(s,r,Zm("narrate",Hm),e.abort.signal);if(a===null)return null;const u=g(this,pt).bubbles.findIndex(c=>c.id===e.bubbleId);if(u!==-1){const c=g(this,pt).bubbles[u];c!==void 0&&c.kind==="tool"&&(g(this,pt).bubbles[u]={...c,toolCall:{...c.toolCall,narration:a}})}return a},RI=function(e,n,o){const i=g(this,pt).bubbles.findIndex(c=>c.id===e);if(i===-1)return;const s=g(this,pt).bubbles[i];if(s===void 0||s.kind!=="thought")return;const r=s,a=g(this,Wr).get(e)??0;if(a>=r.segments.length)return;const u=r.segments.map((c,p)=>p===a?{...c,text:o,originalText:n}:c);g(this,pt).bubbles[i]={...r,segments:u},g(this,Wr).set(e,a+1)},La=function(){O(this,ei,!1);for(const e of g(this,vo))if(e.status==="fetching"||e.status==="pending")try{e.abort.abort()}catch{}O(this,vo,[]),te(g(this,on),0),g(this,Qo).stop(),g(this,Xo).clear(),g(this,Li).clear();for(const e of g(this,pt).bubbles){if(e.kind!=="message"&&e.kind!=="thought")continue;const n=g(this,$n).get(e.id)??{processedSegments:0,buffer:""};n.processedSegments=e.segments.length,n.buffer="",g(this,$n).set(e.id,n)}};var Kr,Yr,Xr;class Q2{constructor(){D(this,Kr,se(!1));D(this,Yr,se("peek"));D(this,Xr,se(null))}get sidebarCollapsed(){return Y(g(this,Kr))}set sidebarCollapsed(e){te(g(this,Kr),e,!0)}get sheetDetent(){return Y(g(this,Yr))}set sheetDetent(e){te(g(this,Yr),e,!0)}get sheetDragPx(){return Y(g(this,Xr))}set sheetDragPx(e){te(g(this,Xr),e,!0)}get sheetOpen(){return this.sheetDetent!=="peek"}toggleSidebar(){this.sidebarCollapsed=!this.sidebarCollapsed}setDetent(e){this.sheetDetent=e,this.sheetDragPx=null}openSheet(){this.setDetent("full")}closeSheet(){this.setDetent("peek")}toggleSheet(){this.setDetent(this.sheetDetent==="peek"?"full":"peek")}}Kr=new WeakMap,Yr=new WeakMap,Xr=new WeakMap;function m9(t,e){HI(e,!0);const n=new Tc,o=new yZ({settings:n}),i=new IS,s=new qu({cues:i,settings:n}),r=new X2({session:s,settings:n,cues:i}),a=new IZ({session:s,cues:i}),u=new hZ({mic:a,session:s,speaker:r}),c=new fZ({session:s,speaker:r}),p=new pZ({session:s,settings:n}),f=new yS,h=new AZ,m=new Q2,v=new CZ,_=new SZ,w=new AS,C=new PS;Is.refresh();const E=new SS;Ga(()=>(E.setEnabled(n.screenWakeLock),()=>E.dispose()));const A=["he"];Ga(()=>{const L=o.locale,B=A.includes(L)?"rtl":"ltr";document.documentElement.dir=B,document.documentElement.lang=L});const R=wS.PUBLIC_APP_TITLE||"Drive Coding",k=ws(()=>{var B;const L=vS.url.pathname;return L.startsWith("/settings")?o.t("appTitle.settings"):L.startsWith("/chat")?((B=s.sessionTitle)==null?void 0:B.trim())||null:L==="/"?o.t("appTitle.sessions"):null}),b=ws(()=>Y(k)?`${R} • ${Y(k)}`:R);QI(o),jI(n),eS(i),tS(s),nS(r),oS(a),iS(u),sS(c),rS(p),aS(f),lS(h),uS(m),cS(v),dS(_),pS(w),fS(C);const U=qe({scrollEl:null,handle:null});hS(U);var J=zI();gS("12qhfyh",L=>{WI(()=>{YI.title=Y(b)??""})});var G=ZI(J);mS(G,()=>e.children??KI),FI(t,J),JI()}export{m9 as component,u9 as universal};