@hintergrund/ui 0.3.32 → 0.3.33

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.
@@ -1 +1 @@
1
- void 0===globalThis.process&&(globalThis.process={env:{},platform:"browser",version:"",versions:{},browser:!0,nextTick:function(e){return Promise.resolve().then(e)}});import{o as e,t}from"./rolldown-runtime-WNHmnFyz.js";import{$ as n,F as o,I as i,L as r,U as s,V as a,Y as l,Z as u,rt as c}from"./LanguageSelect-Bv8KWlDl.js";import{a as d,i as p,r as m,t as h}from"./provider-retry-DFO3RFBJ.js";import{_ as f,g as v,i as g,n as _,p as y}from"./transform-messages-D2LGinMz.js";var E=/* @__PURE__ */t((e,t)=>{function n(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.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))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=/* @__PURE__ */(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(/* @__PURE__ */new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(void 0===n){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1)}var o=this;return this._timer=setTimeout(function(){o._attempts++,o._operationTimeoutCb&&(o._timeout=setTimeout(function(){o._operationTimeoutCb(o._attempts)},o._operationTimeout),o._options.unref&&o._timeout.unref()),o._fn(o._attempts)},n),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=/* @__PURE__ */(new Date).getTime(),this._fn(this._attempts)},n.prototype.try=function(e){this.attempt(e)},n.prototype.start=function(e){this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,n=0,o=0;o<this._errors.length;o++){var i=this._errors[o],r=i.message,s=(e[r]||0)+1;e[r]=s,s>=n&&(t=i,n=s)}return t}}),T=/* @__PURE__ */t(e=>{var t=E();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],i=0;i<t.retries;i++)o.push(this.createTimeout(i,t));return e&&e.forever&&!o.length&&o.push(this.createTimeout(i,t)),o.sort(function(e,t){return e-t}),o},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,o=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(o,t.maxTimeout)},e.wrap=function(t,n,o){if(n instanceof Array&&(o=n,n=null),!o)for(var i in o=[],t)"function"==typeof t[i]&&o.push(i);for(var r=0;r<o.length;r++){var s=o[r],a=t[s];t[s]=function(o){var i=e.operation(n),r=Array.prototype.slice.call(arguments,1),s=r.pop();r.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),s.apply(this,arguments))}),i.attempt(function(){o.apply(t,r)})}.bind(t,a),t[s].options=n}}}),A=/* @__PURE__ */t((e,t)=>{t.exports=T()}),I=/* @__PURE__ */t((e,t)=>{var n=A(),o=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],i=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},r=(e,t)=>new Promise((r,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};const a=n.operation(t);a.attempt(async n=>{try{r(await e(n))}catch(u){if(!(u instanceof Error))return void s(/* @__PURE__ */new TypeError(`Non-error was thrown: "${u}". You should only throw errors.`));if(u instanceof i)a.stop(),s(u.originalError);else if(u instanceof TypeError&&(l=u.message,!o.includes(l)))a.stop(),s(u);else{((e,t,n)=>{const o=n.retries-(t-1);e.attemptNumber=t,e.retriesLeft=o})(u,n,t);try{await t.onFailedAttempt(u)}catch(u){return void s(u)}a.retry(u)||s(a.mainError())}}var l})});t.exports=r,t.exports.default=r,t.exports.AbortError=i}),C=/* @__PURE__ */e(I(),1);function S(e){if(!e)return"";try{return JSON.stringify(e)}catch(Rr){return String(e)}}var b=class extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}},O=class e extends b{constructor(t,n,o,i){super(e.makeMessage(t,n,o)),this.status=t,this.headers=i,this.error=n,this.statusCode=t,this.body=S(n),this.contentType=(null==i?void 0:i.get("content-type"))||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(e,t,n){var o;const i=t&&null!==(r=t)&&"object"==typeof r&&!Array.isArray(r)&&"string"==typeof t.message?t.message:void 0;var r;const s=S(t);return`${e?`${e} `:""}${null!==(o=null!=i?i:n)&&void 0!==o?o:s||"An error occurred"}`}static generate(t,n,o,i){return t&&i?new e(t,n,o,i):new w({message:o,cause:n instanceof Error?n:void 0})}},w=class extends O{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.cause=t}},R=class extends w{constructor(e={}){var t;super({message:null!==(t=e.message)&&void 0!==t?t:"WebSocket connection error."}),this.closeCode=e.closeCode,this.httpStatus=e.httpStatus,this.serverCode=e.serverCode}},P=class extends w{constructor(e={}){var t;super({message:null!==(t=e.message)&&void 0!==t?t:"WebRTC connection error."}),this.closeCode=e.closeCode,this.httpStatus=e.httpStatus,this.serverCode=e.serverCode}};function N(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(n[o[i]]=e[o[i]])}return n}function k(e){return this instanceof k?(this.v=e,this):new k(e)}function D(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o,i=n.apply(e,t||[]),r=[];return o=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),o[Symbol.asyncIterator]=function(){return this},o;function s(e,t){i[e]&&(o[e]=function(t){return new Promise(function(n,o){r.push([e,t,n,o])>1||a(e,t)})},t&&(o[e]=t(o[e])))}function a(e,t){try{(n=i[e](t)).value instanceof k?Promise.resolve(n.value.v).then(l,u):c(r[0][2],n)}catch(o){c(r[0][3],o)}var n}function l(e){a("next",e)}function u(e){a("throw",e)}function c(e,t){e(t),r.shift(),r.length&&a(r[0][0],r[0][1])}}function M(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],o=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&o>=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},o("next"),o("throw"),o("return"),t[Symbol.asyncIterator]=function(){return this},t);function o(n){t[n]=e[n]&&function(t){return new Promise(function(o,i){!function(e,t,n,o){Promise.resolve(o).then(function(t){e({value:t,done:n})},t)}(o,i,(t=e[n](t)).done,t.value)})}}}var x=!1;function G(){x||(x=!0)}var U=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};function L(e){return"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599?e:void 0}function q(e){var t,n,o;const i=null!==(n=null!==(t=L(e.httpStatus))&&void 0!==t?t:L(e.statusCode))&&void 0!==n?n:L(e.status);if(void 0!==i)return i;if(F(e.response)){const t=e.response,n=null!==(o=L(t.statusCode))&&void 0!==o?o:L(t.status);if(void 0!==n)return n}if("string"==typeof e.message){const t=/^Unexpected server response: (\d{3})$/.exec(e.message.trim());if(t)return L(Number(t[1]))}}function H(e){if(!F(e))return;const t=q(e);if(void 0!==t)return t;const n=e.error;return F(n)?q(n):void 0}var j=class{constructor(){this.values=[],this.readers=[],this.ended=!1}push(e){if(this.ended||this.failure)return;const t=this.readers.shift();t?t.resolve({done:!1,value:e}):this.values.push(e)}end(e=!1){if(!this.failure&&(e&&(this.values.length=0),!this.ended)){this.ended=!0;for(const e of this.readers.splice(0))e.resolve({done:!0,value:void 0})}}fail(e){if(!this.ended&&!this.failure){this.failure=e;for(const t of this.readers.splice(0))t.reject(e)}}next(){const e=this.values.shift();return void 0!==e?Promise.resolve({done:!1,value:e}):this.failure?Promise.reject(this.failure):this.ended?Promise.resolve({done:!0,value:void 0}):new Promise((e,t)=>{this.readers.push({resolve:e,reject:t})})}};function F(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function X(e){return"interaction.completed"===e||"interaction.canceled"===e||"interaction.cancelled"===e||"reconnection_required"===e}function B(e,t,n){V(e,t),e[t]=n}function V(e,t){for(const n of Object.keys(e))n.toLowerCase()===t.toLowerCase()&&delete e[n]}function J(e,t,n){var o,i,r,s,a,l,u,c;if(!t)throw new U("A non-empty interaction ID is required to connect.");const d=null!==(s=null!==(i=null!==(o=null==n?void 0:n.timeout_ms)&&void 0!==o?o:null==n?void 0:n.timeout)&&void 0!==i?i:null===(r=e.getTimeout)||void 0===r?void 0:r.call(e))&&void 0!==s?s:3e4;if(!Number.isFinite(d)||d<=0)throw new RangeError("timeout_ms must be positive and finite.");let p;const m=null!==(u=null!==(a=null==n?void 0:n.headers)&&void 0!==a?a:null===(l=null==n?void 0:n.fetch_options)||void 0===l?void 0:l.headers)&&void 0!==u?u:null===(c=null==n?void 0:n.fetchOptions)||void 0===c?void 0:c.headers;if(m)if(p={},m instanceof Headers)for(const[h,f]of Array.from(m.entries()))p[h]=f;else if(Array.isArray(m))for(const[h,f]of m)p[h]=f;else for(const h of Object.keys(m))p[h]=m[h];return{timeout:d,extraHeaders:p}}async function $(e,t,n,o){var i,r,s;const a=Object.assign(Object.assign({},o),null===(i=e.getDefaultHeaders)||void 0===i?void 0:i.call(e)),l=null===(r=e.getApiKey)||void 0===r?void 0:r.call(e);if(l)B(a,"x-goog-api-key",l);else for(const[u,c]of function(e){const t=[];return e.forEach((e,n)=>t.push([n,e])),t}(await e.getAuthHeaders(t)))B(a,u,c);for(const u of[null===(s=e.getHeaders)||void 0===s?void 0:s.call(e),n])for(const[e,t]of Object.entries(null!=u?u:{}))B(a,e,t);return(null==l?void 0:l.startsWith("auth_tokens/"))&&(V(a,"authorization"),B(a,"x-goog-api-key",l)),a}var W=class{constructor(e){this.queue=new j,this.detached=!1,this.terminal=!1,this.receiving=!1,G(),this.id=e}attach(e){this.socket=e}closeSocket(){const e=this.socket;this.socket=void 0;try{null==e||e.close()}catch(Rr){}}finishTerminal(){this.markTerminal(),this.closeSocket()}async finishClientCancel(){const e=this.socket;this.markTerminal(),(null==e?void 0:e.flush)?(this.pendingClose=e.flush().finally(()=>this.closeSocket()),await this.pendingClose):this.closeSocket()}handleMessage(e){if(this.detached||this.terminal||this.connectionError)return;const t=this.decodeFrameEvents(e);if(t)for(const n of t){if(!F(n)||"string"!=typeof n.event_type)return void this.failProtocol("Live interaction server events must have an event_type.");const e=n.event_type;if(this.queue.push(n),X(e))return void this.finishTerminal()}}markTerminal(){this.terminal=!0,this.queue.end()}decodeFrameEvents(e){const t=function(e){return"string"==typeof e?e:e instanceof ArrayBuffer?(new TextDecoder).decode(new Uint8Array(e)):ArrayBuffer.isView(e)?(new TextDecoder).decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):null}(e);if(null===t)return this.failProtocol("Live interaction server frames must contain UTF-8 JSON text."),null;let n;try{n=JSON.parse(t)}catch(Rr){return this.failProtocol("Live interaction server frames must contain valid JSON."),null}return F(n)&&Array.isArray(n.events)?n.events:[n]}newConnectionError(e){return new R(e)}failProtocol(e){const t=this.newConnectionError({message:e});this.connectionError=t,this.queue.fail(t),this.detach()}handleTransportError(){this.detached||this.terminal||this.connectionError||(this.connectionError=this.newConnectionError({message:"The live interaction connection closed with code 1006.",closeCode:1006}),this.queue.fail(this.connectionError),this.closeSocket())}handleClose(e=1006){this.detached||this.terminal?this.queue.end():this.connectionError||(this.connectionError=this.newConnectionError({message:`The live interaction connection closed with code ${e}.`,closeCode:e}),this.queue.fail(this.connectionError)),this.closeSocket()}ensureWritable(){if(this.connectionError)throw this.connectionError;if(this.terminal)throw new Error("This live interaction is already terminal.");if(this.detached)throw new Error("This live interaction is detached.");if(!this.socket)throw new Error("This live interaction is not connected.");return this.socket}sendEvent(e){var t;const n=this.ensureWritable(),o=JSON.stringify(e);try{n.send(o)}catch(i){if(i instanceof RangeError||i instanceof U)throw i;throw null!==(t=this.connectionError)&&void 0!==t||(this.connectionError=this.newConnectionError({message:"The live interaction connection closed with code 1006.",closeCode:1006})),this.queue.fail(this.connectionError),this.detach(),this.connectionError}}sendInitial(e){this.sendEvent(e)}async send(e){if("string"==typeof e)return void this.sendEvent({event_type:"input",content:[{type:"text",text:e}]});if(Array.isArray(e)){if(!e.length)throw new U("Empty client event batch.");const t=e.map(e=>z(e));return this.sendEvent({events:t}),void(t.some(e=>"interaction.cancel"===e.event_type)&&await this.finishClientCancel())}const t=z(e);"interaction.cancel"!==t.event_type||this.connectionError||!this.terminal?(this.sendEvent(t),"interaction.cancel"===t.event_type&&await this.finishClientCancel()):await this.pendingClose}receive(){return D(this,arguments,function*(){for(;;){if(this.receiving)throw new U("Only one receive iterator may be active at a time.");let e;this.receiving=!0;try{e=yield k(this.queue.next())}finally{this.receiving=!1}if(e.done)return yield k(void 0);yield yield k(e.value)}})}async complete(){if(this.connectionError)throw this.connectionError;this.terminal||this.sendEvent({event_type:"interaction.complete"})}async cancel(){await this.send({event_type:"interaction.cancel"})}detach(){var e;if(this.detached)return;const t=!this.terminal&&!this.connectionError;if(this.detached=!0,this.queue.end(!0),t)try{null===(e=this.socket)||void 0===e||e.send(JSON.stringify({event_type:"interaction.disconnect"}))}catch(n){}this.closeSocket()}},Y=Symbol.asyncDispose;Y&&(W.prototype[Y]=async function(){this.detach()});var K=class extends W{constructor(e){super(e)}};function z(e){if(!F(e))throw new U("Live client events must be JSON objects.");return e}var Z="events";function Q(e){return!!e&&("open"===e.readyState||void 0===e.readyState)}var ee=class extends W{constructor(e,t){super(e),this.transport=t}newConnectionError(e){return new P(e)}},te=class{get peerConnection(){return this._peerConnection}get dataChannel(){return this._dataChannel}constructor(e={}){var t,n,o;this._remoteTracks=[],this._audioEnabled=!0,this._videoEnabled=!0,this._audioMuteExplicitlySet=!1,this._videoMuteExplicitlySet=!1,this.audioSenders=[],this.videoSenders=[],this.connectGeneration=0,G(),this._mediaStream=null!==(t=e.mediaStream)&&void 0!==t?t:null,this._videoElement=null!==(n=e.videoElement)&&void 0!==n?n:null,this._audioElement=null!==(o=e.audioElement)&&void 0!==o?o:null,this._audioEnabled=this.computeInitialEnabled("audio"),this._videoEnabled=this.computeInitialEnabled("video"),this.onPeerConnectionCallback=e.onPeerConnection,this.rtcConfiguration=e.rtcConfiguration,this.peerConnectionFactory=e.peerConnectionFactory}computeInitialEnabled(e){if(!this._mediaStream)return!1;const t="audio"===e&&"function"==typeof this._mediaStream.getAudioTracks?this._mediaStream.getAudioTracks():"video"===e&&"function"==typeof this._mediaStream.getVideoTracks?this._mediaStream.getVideoTracks():this._mediaStream.getTracks().filter(t=>t.kind===e);return t.length>0&&t.some(e=>!1!==e.enabled)}get localMediaStream(){return this._mediaStream}get remoteMediaStream(){return this._remoteMediaStream}isAudioEnabled(){return this._audioEnabled}isVideoEnabled(){return this._videoEnabled}setVideoElement(e){const t=e;this._videoElement&&this._videoElement!==t&&(this._videoElement.srcObject=null),this._videoElement=t,this.syncMediaElements()}getVideoElement(){return this._videoElement}setAudioElement(e){const t=e;this._audioElement&&this._audioElement!==t&&(this._audioElement.srcObject=null),this._audioElement=t,this.syncMediaElements()}getAudioElement(){return this._audioElement}createStreamFromTracks(e){const t=globalThis;if("function"==typeof t.MediaStream)return new t.MediaStream(e);const n=[...e];return{getTracks:()=>[...n],getAudioTracks:()=>n.filter(e=>"audio"===e.kind),getVideoTracks:()=>n.filter(e=>"video"===e.kind),addTrack:e=>{n.includes(e)||n.push(e)}}}ensureStreamWithTracks(e,t){if(e&&"function"==typeof e.addTrack){const n=e.getTracks();for(const o of t)n.includes(o)||e.addTrack(o);return e}return this.createStreamFromTracks(t)}playMediaElement(e){var t;try{const n=null===(t=e.play)||void 0===t?void 0:t.call(e);null!=n&&"function"==typeof n.catch&&n.catch(()=>{})}catch(n){}}syncMediaElements(){if(0!==this._remoteTracks.length)if(this._audioElement){const e=this._remoteTracks.filter(e=>"audio"===e.kind);if(e.length>0&&(this._remoteAudioStream=this.ensureStreamWithTracks(this._remoteAudioStream,e),this._audioElement.srcObject!==this._remoteAudioStream&&(this._audioElement.srcObject=this._remoteAudioStream,this.playMediaElement(this._audioElement))),this._videoElement){const e=this._remoteTracks.filter(e=>"video"===e.kind);e.length>0?(this._remoteVideoStream=this.ensureStreamWithTracks(this._remoteVideoStream,e),this._videoElement.srcObject!==this._remoteVideoStream&&(this._videoElement.srcObject=this._remoteVideoStream,this.playMediaElement(this._videoElement))):null!==this._videoElement.srcObject&&void 0!==this._videoElement.srcObject&&(this._videoElement.srcObject=null)}}else this._videoElement&&this._remoteMediaStream&&this._videoElement.srcObject!==this._remoteMediaStream&&(this._videoElement.srcObject=this._remoteMediaStream,this.playMediaElement(this._videoElement));else this._videoElement&&this._remoteMediaStream&&!this._audioElement&&this._videoElement.srcObject!==this._remoteMediaStream&&(this._videoElement.srcObject=this._remoteMediaStream,this.playMediaElement(this._videoElement))}setAudioEnabled(e){if(this._audioMuteExplicitlySet=!0,this._audioEnabled=Boolean(e),this._mediaStream){const e="function"==typeof this._mediaStream.getAudioTracks?this._mediaStream.getAudioTracks():this._mediaStream.getTracks().filter(e=>"audio"===e.kind);for(const t of e)t.enabled=this._audioEnabled}for(const t of this.audioSenders)t.track&&(t.track.enabled=this._audioEnabled);return this._audioEnabled}setVideoEnabled(e){if(this._videoMuteExplicitlySet=!0,this._videoEnabled=Boolean(e),this._mediaStream){const e="function"==typeof this._mediaStream.getVideoTracks?this._mediaStream.getVideoTracks():this._mediaStream.getTracks().filter(e=>"video"===e.kind);for(const t of e)t.enabled=this._videoEnabled}for(const t of this.videoSenders)t.track&&(t.track.enabled=this._videoEnabled);return this._videoEnabled}validateAndSendOnChannel(e,t,n){var o;if(!e)throw new U("WebRTC data channel is not connected.");if(!Q(e))throw new U("WebRTC data channel is not open.");const i="number"==typeof(null===(o=null==t?void 0:t.sctp)||void 0===o?void 0:o.maxMessageSize)&&t.sctp.maxMessageSize>0?t.sctp.maxMessageSize:65536,r=(new TextEncoder).encode(n).byteLength;if(r>i)throw new RangeError(`WebRTC data channel message (${r} bytes) exceeds SCTP maxMessageSize (${i} bytes).`);e.send(n)}async connect(e,t,n,o={}){var i,r,s,a,l,u,c;if(!t)throw new U("A non-empty interaction ID is required to connect.");const d=null!==(i=o.timeoutMs)&&void 0!==i?i:3e4;if(!Number.isFinite(d)||d<=0)throw new RangeError("timeout_ms must be positive and finite.");const p=null!==(r=this.peerConnectionFactory)&&void 0!==r?r:function(){const e=globalThis;if("function"==typeof e.RTCPeerConnection){const t=e.RTCPeerConnection;return e=>new t(e)}}();if(!p)throw new U("Live Interactions WebRTC support requires a platform RTCPeerConnection or peerConnectionFactory.");const m=null!==(a=null===(s=e.getFetch)||void 0===s?void 0:s.call(e))&&void 0!==a?a:"function"==typeof globalThis.fetch?(e,t)=>null==t?globalThis.fetch(e):globalThis.fetch(e,t):void 0;if(!m)throw new U("Live Interactions WebRTC support requires a platform fetch implementation.");this.close();const h=++this.connectGeneration,f=function(e,t,n){if(e.isVertexAI())throw new U("Live Interactions WebRTC support is currently Gemini API only.");const o=e.getBaseUrl();if(!o)throw new U("Base URL must be set.");const i=new URL(o),r=(null!=n?n:e.getApiVersion()).replace(/^\/+|\/+$/g,"");return i.pathname=`${i.pathname.replace(/\/+$/g,"")}/${r}/interactions/${encodeURIComponent(t)}:webrtc`.replace(/\/{2,}/g,"/"),i.hash="",i.toString()}(e,t,o.apiVersion),v=p(this.rtcConfiguration);this._peerConnection=v,this.audioSenders=[],this.videoSenders=[];const g=/* @__PURE__ */new Set;let _,y,E,T=!1,A=!1,I=!1,C=!1;const S=new Promise((e,t)=>{y=e,E=t});S.catch(()=>{});const b=()=>{const e=this._dataChannel;if(e&&g.has(e)&&Q(e))return e;for(const t of g)if(Q(t))return t};let O;const R=(e=1e3,t=!0,o="The WebRTC connection attempt was superseded or closed.")=>{if(!T){T=!0,null==_||_.abort(),null==O||O(),O=void 0,this.activeAttemptCleanup===R&&(this.activeAttemptCleanup=void 0);for(const e of[...g])try{e.close()}catch(i){}if(g.clear(),this.connectGeneration===h)this.resetTransportState();else try{v.close()}catch(r){}C||(C=!0,E(new P({message:o,closeCode:e}))),t&&!A&&(A=!0,n.onclose({code:e}))}};this.activeAttemptCleanup=R;const N=e=>{if(g.has(e))return;g.add(e),e.binaryType="arraybuffer",this._dataChannel&&"open"===this._dataChannel.readyState||(this._dataChannel=e);const t=()=>{T||this.connectGeneration!==h||(this._dataChannel=e,C||(I=!0,C=!0,n.onopen(),y()))};e.onopen=t,e.onmessage=e=>{T||this.connectGeneration!==h||n.onmessage(e)},e.onerror=e=>{T||this.connectGeneration!==h||(I||C?n.onerror(e):(C=!0,E(new P({message:"WebRTC events data channel failed to open.",closeCode:1006}))))},e.onclose=()=>{if(g.delete(e),T||this.connectGeneration!==h)return;const t=b();t?this._dataChannel=t:R(1006,!0,"WebRTC events data channel closed before opening.")},"open"===e.readyState&&t()};try{let t;try{t=await async function(e,t,n){const o=await $(e,t,n);return B(o,"content-type","application/json"),o}(e,f,o.extraHeaders)}catch(k){throw new P({message:"Live authentication setup failed.",httpStatus:H(k)})}if(T||this.connectGeneration!==h)throw new P({message:"The WebRTC connection attempt was superseded or closed.",closeCode:1006});try{null===(l=this.onPeerConnectionCallback)||void 0===l||l.call(this,v)}catch(D){}const i=e=>{var t,n;if(this.connectGeneration===h){if(e.track&&!this._remoteTracks.includes(e.track))this._remoteTracks.push(e.track);else if(null===(t=e.streams)||void 0===t?void 0:t[0])for(const t of e.streams[0].getTracks())this._remoteTracks.includes(t)||this._remoteTracks.push(t);this._remoteTracks.length>0?(this._remoteMediaStream=this.ensureStreamWithTracks(this._remoteMediaStream,this._remoteTracks),this.syncMediaElements()):(null===(n=e.streams)||void 0===n?void 0:n[0])&&(this._remoteMediaStream=e.streams[0],this.syncMediaElements())}},r=e=>{if(this.connectGeneration!==h)return;const t=null==e?void 0:e.channel;t&&(void 0!==t.label&&""!==t.label&&t.label!==Z||N(t))},s=()=>{if(T||this.connectGeneration!==h)return;const e="failed"===v.connectionState||"failed"===v.iceConnectionState?"failed":"closed"===v.connectionState||"closed"===v.iceConnectionState?"closed":void 0;if(!e)return;const t="failed"===e&&I;R(1006,!t,`WebRTC peer connection ${e} during setup.`),t&&!A&&(A=!0,n.onerror(/* @__PURE__ */new Error("WebRTC peer connection failed.")),n.onclose({code:1006}))};v.addEventListener("track",i),v.addEventListener("connectionstatechange",s),v.addEventListener("iceconnectionstatechange",s),v.addEventListener("datachannel",r),O=()=>{v.removeEventListener("track",i),v.removeEventListener("connectionstatechange",s),v.removeEventListener("iceconnectionstatechange",s),v.removeEventListener("datachannel",r)};let a=!1,p=!1;if(this._mediaStream){const e=this._mediaStream.getTracks();for(const t of e){"audio"===t.kind?(a=!0,this._audioMuteExplicitlySet&&(t.enabled=this._audioEnabled)):"video"===t.kind&&(p=!0,this._videoMuteExplicitlySet&&(t.enabled=this._videoEnabled));const e=v.addTrack(t,this._mediaStream);e&&"object"==typeof e&&("audio"===t.kind?this.audioSenders.push(e):"video"===t.kind&&this.videoSenders.push(e))}}if("function"==typeof v.addTransceiver){if(!a){const e=v.addTransceiver("audio",{direction:"recvonly"});(null==e?void 0:e.sender)&&this.audioSenders.push(e.sender)}if(!p){const e=v.addTransceiver("video",{direction:"recvonly"});(null==e?void 0:e.sender)&&this.videoSenders.push(e.sender)}}N(v.createDataChannel(Z));const g=Date.now()+d,y=await v.createOffer();await v.setLocalDescription(y);const E=null!==(c=null===(u=v.localDescription)||void 0===u?void 0:u.sdp)&&void 0!==c?c:y.sdp;if(!E)throw new P({message:"RTCPeerConnection failed to produce an SDP offer."});if(T||this.connectGeneration!==h)throw new P({message:"The WebRTC connection attempt was superseded or closed.",closeCode:1006});const w=Math.max(1,g-Date.now());_="function"==typeof AbortController?new AbortController:void 0;const U=setTimeout(()=>{null==_||_.abort()},w);let L,q;try{L=await m(f,{method:"POST",headers:t,body:JSON.stringify({offer_sdp:E}),signal:null==_?void 0:_.signal})}catch(M){throw new P({message:"WebRTC SDP signaling request failed."})}finally{clearTimeout(U)}if(T||this.connectGeneration!==h)throw new P({message:"The WebRTC connection attempt was superseded or closed.",closeCode:1006});if(!L.ok){let e,t;try{const n=await L.json();F(n)&&F(n.error)&&(e=function(e){const t="number"==typeof e||"string"==typeof e?String(e):"";return/^[a-zA-Z0-9_.-]{1,64}$/.test(t)?t:void 0}(n.error.code),"string"==typeof n.error.message&&(t=n.error.message.trim()))}catch(x){}throw new P({message:t?`WebRTC SDP signaling failed with HTTP status ${L.status}: ${t}`:`WebRTC SDP signaling failed with HTTP status ${L.status}.`,httpStatus:L.status,serverCode:e})}try{q=await L.json()}catch(G){throw new P({message:"WebRTC SDP signaling response must be valid JSON."})}const j=F(q)&&"string"==typeof q.answer_sdp?q.answer_sdp:void 0;if(!j)throw new P({message:"WebRTC SDP signaling response is missing answer_sdp."});if(await v.setRemoteDescription({type:"answer",sdp:j}),T||this.connectGeneration!==h)throw new P({message:"The WebRTC connection attempt was superseded or closed.",closeCode:1006});if(!I){const e=Math.max(1,g-Date.now());await new Promise((t,n)=>{const o=setTimeout(()=>{C||(C=!0,n(new P({message:"Timed out waiting for WebRTC events data channel to open.",closeCode:1006})))},e);S.then(()=>{clearTimeout(o),t()},e=>{clearTimeout(o),n(e)})})}return{connect(){},send:e=>{var t;if(this.connectGeneration!==h)throw new Error("WebRTC data channel is not connected.");const n=null!==(t=b())&&void 0!==t?t:this._dataChannel;this.validateAndSendOnChannel(n,v,e)},flush:()=>{var e;return async function(e){if(!Q(e))return;const t=Date.now()+500;for(;Number(e.bufferedAmount)>0&&Q(e)&&Date.now()<t;)await new Promise(e=>setTimeout(e,10));Q(e)&&await new Promise(e=>setTimeout(e,50))}(null!==(e=b())&&void 0!==e?e:this._dataChannel)},close:()=>{R(1e3,!0)}}}catch(k){if(R(1006,!1),k instanceof w)throw k;throw new Error(k instanceof Error?k.message:"WebRTC live setup failed.")}}resetTransportState(){const e=this._peerConnection;this._dataChannel=void 0,this._peerConnection=void 0,this._remoteMediaStream=void 0,this._remoteAudioStream=void 0,this._remoteVideoStream=void 0,this._remoteTracks=[],this.audioSenders=[],this.videoSenders=[],this._videoElement&&(this._videoElement.srcObject=null),this._audioElement&&(this._audioElement.srcObject=null);try{null==e||e.close()}catch(Rr){}}close(){if(this.activeAttemptCleanup){const e=this.activeAttemptCleanup;this.activeAttemptCleanup=void 0,e(1e3,!0)}else this.resetTransportState();this.connectGeneration++}};var ne,oe,ie,re,se,ae,le,ue,ce,de,pe,me,he,fe,ve,ge,_e,ye,Ee,Te,Ae,Ie,Ce,Se,be,Oe,we,Re,Pe,Ne,ke,De,Me,xe,Ge,Ue,Le,qe,He,je,Fe,Xe,Be,Ve,Je,$e,We,Ye,Ke,ze,Ze,Qe,et,tt,nt,ot,it,rt,st,at,lt,ut,ct,dt,pt,mt,ht,ft,vt,gt,_t,yt,Et,Tt,At,It,Ct,St,bt,Ot,wt,Rt=class{};function Pt(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{if(t&&Object.prototype.hasOwnProperty.call(t,n)){const e=t[n];return null!=e?String(e):""}if("api_version"===n)return e;throw new Error(`Key '${n}' not found in valueMap.`)})}function Nt(e,t,n){for(let r=0;r<t.length-1;r++){const o=t[r];if(o.endsWith("[]")){const i=o.slice(0,-2);if(!(i in e)){if(!Array.isArray(n))throw new Error(`Value must be a list given an array path ${o}`);e[i]=Array.from({length:n.length},()=>({}))}if(Array.isArray(e[i])){const o=e[i];if(Array.isArray(n))for(let e=0;e<o.length;e++)Nt(o[e],t.slice(r+1),n[e]);else for(const e of o)Nt(e,t.slice(r+1),n)}return}if(o.endsWith("[0]")){const i=o.slice(0,-3);return i in e||(e[i]=[{}]),void Nt(e[i][0],t.slice(r+1),n)}e[o]&&"object"==typeof e[o]||(e[o]={}),e=e[o]}const o=t[t.length-1],i=e[o];if(void 0!==i){if(!n||"object"==typeof n&&0===Object.keys(n).length)return;if(n===i)return;if("object"!=typeof i||"object"!=typeof n||null===i||null===n)throw new Error(`Cannot set value for an existing key. Key: ${o}`);Object.assign(i,n)}else"_self"!==o||"object"!=typeof n||null===n||Array.isArray(n)?e[o]=n:Object.assign(e,n)}function kt(e,t,n=void 0){try{if(1===t.length&&"_self"===t[0])return e;for(let o=0;o<t.length;o++){if("object"!=typeof e||null===e)return n;const i=t[o];if(i.endsWith("[]")){const r=i.slice(0,-2);if(r in e){const i=e[r];return Array.isArray(i)?i.map(e=>kt(e,t.slice(o+1),n)):n}return n}e=e[i]}return e}catch(o){if(o instanceof TypeError)return n;throw o}}function Dt(e,t,n,o,i){if(o>=t.length)return;if("object"!=typeof e||null===e)return;const r=t[o];if(r.endsWith("[]")){const s=r.slice(0,-2),a=e;if(s in a&&Array.isArray(a[s]))for(const e of a[s])Dt(e,t,n,o+1,i)}else if("*"===r){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const t=e,r=Object.keys(t).filter(e=>!e.startsWith("_")&&!i.has(e)),s={};for(const e of r)s[e]=t[e];for(const[e,i]of Object.entries(s)){const r=[];for(const t of n.slice(o))"*"===t?r.push(e):r.push(t);Nt(t,r,i)}for(const e of r)delete t[e]}}else r in e&&Dt(e[r],t,n,o+1,i)}function Mt(e){if("string"!=typeof e)throw new Error("fromImageBytes must be a string");return e}function xt(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["parent"]);null!=o&&Nt(t,["parent"],o);const i=kt(e,["documentName"]);return null!=i&&Nt(t,["documentName"],i),t}(s)),t}!function(e){e.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",e.STATIC="STATIC",e.AGENTIC="AGENTIC"}(ne||(ne={})),function(e){e.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",e.OUTCOME_OK="OUTCOME_OK",e.OUTCOME_FAILED="OUTCOME_FAILED",e.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"}(oe||(oe={})),function(e){e.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",e.PYTHON="PYTHON"}(ie||(ie={})),function(e){e.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",e.SILENT="SILENT",e.WHEN_IDLE="WHEN_IDLE",e.INTERRUPT="INTERRUPT"}(re||(re={})),function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.STRING="STRING",e.NUMBER="NUMBER",e.INTEGER="INTEGER",e.BOOLEAN="BOOLEAN",e.ARRAY="ARRAY",e.OBJECT="OBJECT",e.NULL="NULL"}(se||(se={})),function(e){e.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",e.NO_AUTH="NO_AUTH",e.API_KEY_AUTH="API_KEY_AUTH",e.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",e.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",e.OAUTH="OAUTH",e.OIDC_AUTH="OIDC_AUTH"}(ae||(ae={})),function(e){e.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",e.HTTP_IN_QUERY="HTTP_IN_QUERY",e.HTTP_IN_HEADER="HTTP_IN_HEADER",e.HTTP_IN_PATH="HTTP_IN_PATH",e.HTTP_IN_BODY="HTTP_IN_BODY",e.HTTP_IN_COOKIE="HTTP_IN_COOKIE"}(le||(le={})),function(e){e.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",e.SIMPLE_SEARCH="SIMPLE_SEARCH",e.ELASTIC_SEARCH="ELASTIC_SEARCH"}(ue||(ue={})),function(e){e.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",e.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",e.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",e.COMMUNICATION_TOOL="COMMUNICATION_TOOL",e.ACCOUNT_CREATION="ACCOUNT_CREATION",e.DATA_MODIFICATION="DATA_MODIFICATION",e.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",e.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"}(ce||(ce={})),function(e){e.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",e.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",e.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",e.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"}(de||(de={})),function(e){e.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",e.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",e.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",e.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"}(pe||(pe={})),function(e){e.UNSPECIFIED="UNSPECIFIED",e.BLOCKING="BLOCKING",e.NON_BLOCKING="NON_BLOCKING"}(me||(me={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"}(he||(he={})),function(e){e.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH",e.XHIGH="XHIGH"}(fe||(fe={})),function(e){e.DONT_ALLOW="DONT_ALLOW",e.ALLOW_ADULT="ALLOW_ADULT",e.ALLOW_ALL="ALLOW_ALL"}(ve||(ve={})),function(e){e.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",e.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",e.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"}(ge||(ge={})),function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",e.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",e.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",e.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",e.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",e.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"}(_e||(_e={})),function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"}(ye||(ye={})),function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE",e.OFF="OFF"}(Ee||(Ee={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE",e.VALIDATED="VALIDATED"}(Te||(Te={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.VERBATIM="VERBATIM",e.SMART="SMART"}(Ae||(Ae={})),function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.IMAGE_SAFETY="IMAGE_SAFETY",e.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",e.IMAGE_OTHER="IMAGE_OTHER",e.NO_IMAGE="NO_IMAGE",e.IMAGE_RECITATION="IMAGE_RECITATION",e.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",e.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",e.MISSING_THOUGHT_SIGNATURE="MISSING_THOUGHT_SIGNATURE",e.MALFORMED_RESPONSE="MALFORMED_RESPONSE",e.ESCALATION="ESCALATION",e.PUP_LIMITED_DISABLED="PUP_LIMITED_DISABLED",e.CONTINUATION="CONTINUATION",e.MODEL_ARMOR="MODEL_ARMOR"}(Ie||(Ie={})),function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(Ce||(Ce={})),function(e){e.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"}(Se||(Se={})),function(e){e.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",e.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",e.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",e.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",e.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"}(be||(be={})),function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.IMAGE_SAFETY="IMAGE_SAFETY",e.MODEL_ARMOR="MODEL_ARMOR",e.JAILBREAK="JAILBREAK"}(Oe||(Oe={})),function(e){e.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",e.ON_DEMAND="ON_DEMAND",e.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",e.ON_DEMAND_FLEX="ON_DEMAND_FLEX",e.ON_DEMAND_OFFPEAK="ON_DEMAND_OFFPEAK",e.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"}(we||(we={})),function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"}(Re||(Re={})),function(e){e.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",e.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",e.EXPERIMENTAL="EXPERIMENTAL",e.PREVIEW="PREVIEW",e.STABLE="STABLE",e.LEGACY="LEGACY",e.DEPRECATED="DEPRECATED",e.RETIRED="RETIRED"}(Pe||(Pe={})),function(e){e.UNSPECIFIED="unspecified",e.FLEX="flex",e.STANDARD="standard",e.PRIORITY="priority"}(Ne||(Ne={})),function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"}(ke||(ke={})),function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.AUDIO="AUDIO",e.VIDEO="VIDEO"}(De||(De={})),function(e){e.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",e.INLINE="INLINE",e.URI="URI"}(Me||(Me={})),function(e){e.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",e.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",e.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",e.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",e.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",e.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",e.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",e.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",e.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",e.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",e.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",e.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",e.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"}(xe||(xe={})),function(e){e.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",e.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",e.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",e.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",e.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"}(Ge||(Ge={})),function(e){e.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",e.TUNING_MODE_FULL="TUNING_MODE_FULL",e.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"}(Ue||(Ue={})),function(e){e.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",e.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",e.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",e.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",e.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",e.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",e.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"}(Le||(Le={})),function(e){e.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",e.IDENTITY="IDENTITY",e.REGEX_EXTRACT="REGEX_EXTRACT"}(qe||(qe={})),function(e){e.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",e.REGEX_CONTAINS="REGEX_CONTAINS",e.PARTIAL_MATCH="PARTIAL_MATCH",e.EXACT_MATCH="EXACT_MATCH"}(He||(He={})),function(e){e.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(je||(je={})),function(e){e.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",e.JOB_STATE_QUEUED="JOB_STATE_QUEUED",e.JOB_STATE_PENDING="JOB_STATE_PENDING",e.JOB_STATE_RUNNING="JOB_STATE_RUNNING",e.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",e.JOB_STATE_FAILED="JOB_STATE_FAILED",e.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",e.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",e.JOB_STATE_PAUSED="JOB_STATE_PAUSED",e.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",e.JOB_STATE_UPDATING="JOB_STATE_UPDATING",e.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"}(Fe||(Fe={})),function(e){e.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",e.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",e.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",e.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",e.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",e.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"}(Xe||(Xe={})),function(e){e.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",e.AVERAGE="AVERAGE",e.MODE="MODE",e.STANDARD_DEVIATION="STANDARD_DEVIATION",e.VARIANCE="VARIANCE",e.MINIMUM="MINIMUM",e.MAXIMUM="MAXIMUM",e.MEDIAN="MEDIAN",e.PERCENTILE_P90="PERCENTILE_P90",e.PERCENTILE_P95="PERCENTILE_P95",e.PERCENTILE_P99="PERCENTILE_P99"}(Be||(Be={})),function(e){e.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",e.BASELINE="BASELINE",e.CANDIDATE="CANDIDATE",e.TIE="TIE"}(Ve||(Ve={})),function(e){e.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",e.LANDSCAPE="LANDSCAPE",e.PORTRAIT="PORTRAIT"}(Je||(Je={})),function(e){e.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",e.REGULAR="REGULAR",e.FAST="FAST"}($e||($e={})),function(e){e.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",e.TUNING_TASK_I2V="TUNING_TASK_I2V",e.TUNING_TASK_T2V="TUNING_TASK_T2V",e.TUNING_TASK_R2V="TUNING_TASK_R2V"}(We||(We={})),function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.STATE_PENDING="STATE_PENDING",e.STATE_ACTIVE="STATE_ACTIVE",e.STATE_FAILED="STATE_FAILED"}(Ye||(Ye={})),function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",e.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"}(Ke||(Ke={})),function(e){e.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",e.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",e.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",e.URL_CONTEXT="URL_CONTEXT",e.GOOGLE_MAPS="GOOGLE_MAPS",e.FILE_SEARCH="FILE_SEARCH",e.MEDIA_PROCESSING="MEDIA_PROCESSING"}(ze||(ze={})),function(e){e.CONTENT_LAYER_UNSPECIFIED="CONTENT_LAYER_UNSPECIFIED",e.PAGE_IMAGE="PAGE_IMAGE",e.PAGE_TEXT="PAGE_TEXT"}(Ze||(Ze={})),function(e){e.CONTENT_LAYER_UNSPECIFIED="CONTENT_LAYER_UNSPECIFIED",e.DATA="DATA",e.FORMULAS="FORMULAS",e.VISUAL="VISUAL"}(Qe||(Qe={})),function(e){e.COLLECTION="COLLECTION"}(et||(et={})),function(e){e.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",e.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",e.BALANCED="BALANCED",e.PRIORITIZE_COST="PRIORITIZE_COST"}(tt||(tt={})),function(e){e.PREDICT="PREDICT",e.EMBED_CONTENT="EMBED_CONTENT",e.BATCH_EMBED_CONTENTS="BATCH_EMBED_CONTENTS"}(nt||(nt={})),function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"}(ot||(ot={})),function(e){e.auto="auto",e.en="en",e.ja="ja",e.ko="ko",e.hi="hi",e.zh="zh",e.pt="pt",e.es="es"}(it||(it={})),function(e){e.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",e.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",e.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",e.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",e.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"}(rt||(rt={})),function(e){e.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",e.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",e.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",e.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"}(st||(st={})),function(e){e.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",e.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",e.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",e.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"}(at||(at={})),function(e){e.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",e.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",e.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",e.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",e.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",e.EDIT_MODE_STYLE="EDIT_MODE_STYLE",e.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",e.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"}(lt||(lt={})),function(e){e.FOREGROUND="FOREGROUND",e.BACKGROUND="BACKGROUND",e.PROMPT="PROMPT",e.SEMANTIC="SEMANTIC",e.INTERACTIVE="INTERACTIVE"}(ut||(ut={})),function(e){e.ASSET="ASSET",e.STYLE="STYLE"}(ct||(ct={})),function(e){e.INSERT="INSERT",e.REMOVE="REMOVE",e.REMOVE_STATIC="REMOVE_STATIC",e.OUTPAINT="OUTPAINT"}(dt||(dt={})),function(e){e.OPTIMIZED="OPTIMIZED",e.LOSSLESS="LOSSLESS"}(pt||(pt={})),function(e){e.CROP="CROP",e.PAD="PAD"}(mt||(mt={})),function(e){e.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",e.PREFERENCE_TUNING="PREFERENCE_TUNING",e.DISTILLATION="DISTILLATION",e.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"}(ht||(ht={})),function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.PROCESSING="PROCESSING",e.ACTIVE="ACTIVE",e.FAILED="FAILED"}(ft||(ft={})),function(e){e.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",e.UPLOADED="UPLOADED",e.GENERATED="GENERATED",e.REGISTERED="REGISTERED"}(vt||(vt={})),function(e){e.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.RESPONSE_REJECTED="RESPONSE_REJECTED",e.NEED_MORE_INPUT="NEED_MORE_INPUT",e.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",e.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",e.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",e.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",e.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",e.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",e.INPUT_OTHER="INPUT_OTHER",e.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",e.BLOCKLIST="BLOCKLIST",e.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",e.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",e.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",e.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",e.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",e.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",e.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",e.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",e.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",e.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",e.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",e.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",e.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",e.GENERATED_OTHER="GENERATED_OTHER",e.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"}(gt||(gt={})),function(e){e.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",e.IN_PROGRESS="IN_PROGRESS",e.REQUIRES_ACTION="REQUIRES_ACTION",e.IDLE="IDLE"}(_t||(_t={})),function(e){e.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",e.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",e.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"}(yt||(yt={})),function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.ACTIVITY_START="ACTIVITY_START",e.ACTIVITY_END="ACTIVITY_END"}(Et||(Et={})),function(e){e.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",e.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",e.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"}(Tt||(Tt={})),function(e){e.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",e.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",e.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"}(At||(At={})),function(e){e.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",e.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",e.NO_INTERRUPTION="NO_INTERRUPTION"}(It||(It={})),function(e){e.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",e.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",e.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",e.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"}(Ct||(Ct={})),function(e){e.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",e.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",e.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",e.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",e.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",e.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",e.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",e.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",e.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",e.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",e.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",e.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",e.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"}(St||(St={})),function(e){e.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",e.QUALITY="QUALITY",e.DIVERSITY="DIVERSITY",e.VOCALIZATION="VOCALIZATION"}(bt||(bt={})),function(e){e.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",e.PLAY="PLAY",e.PAUSE="PAUSE",e.STOP="STOP",e.RESET_CONTEXT="RESET_CONTEXT"}(Ot||(Ot={})),function(e){e.CONTENT_LAYER_UNSPECIFIED="CONTENT_LAYER_UNSPECIFIED",e.FRAMES="FRAMES",e.AUDIO="AUDIO",e.TRANSCRIPT="TRANSCRIPT"}(wt||(wt={}));var Gt,Ut=class{constructor(e){const t={};for(const n of e.headers.entries())t[n[0]]=n[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}},Lt=class{},qt=class{},Ht=class{get text(){var e,t,n,o,i,r,s,a;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;let l="",u=!1;const c=[];for(const d of null!==(a=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)&&void 0!==a?a:[]){for(const[e,t]of Object.entries(d))"text"===e||"thought"===e||"thoughtSignature"===e||null===t&&void 0===t||c.push(e);if("string"==typeof d.text){if("boolean"==typeof d.thought&&d.thought)continue;u=!0,l+=d.text}}return c.length,u?l:void 0}get data(){var e,t,n,o,i,r,s,a;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;let l="";const u=[];for(const c of null!==(a=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)&&void 0!==a?a:[]){for(const[e,t]of Object.entries(c))"inlineData"===e||null===t&&void 0===t||u.push(e);c.inlineData&&"string"==typeof c.inlineData.data&&(l+=atob(c.inlineData.data))}return u.length,l.length>0?btoa(l):void 0}get functionCalls(){var e,t,n,o,i,r,s,a;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;const l=null===(a=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)||void 0===a?void 0:a.filter(e=>e.functionCall).map(e=>e.functionCall).filter(e=>void 0!==e);return 0!==(null==l?void 0:l.length)?l:void 0}get executableCode(){var e,t,n,o,i,r,s,a,l;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;const u=null===(a=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)||void 0===a?void 0:a.filter(e=>e.executableCode).map(e=>e.executableCode).filter(e=>void 0!==e);return 0!==(null==u?void 0:u.length)?null===(l=null==u?void 0:u[0])||void 0===l?void 0:l.code:void 0}get codeExecutionResult(){var e,t,n,o,i,r,s,a,l;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;const u=null===(a=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)||void 0===a?void 0:a.filter(e=>e.codeExecutionResult).map(e=>e.codeExecutionResult).filter(e=>void 0!==e);return 0!==(null==u?void 0:u.length)?null===(l=null==u?void 0:u[0])||void 0===l?void 0:l.output:void 0}get initialPromptTokenCount(){var e;if(this.usageMetadata)return null!==(e=this.usageMetadata._initialPromptTokenCount)&&void 0!==e?e:this.usageMetadata.promptTokenCount}},jt=class{},Ft=class{},Xt=class{},Bt=class{},Vt=class{},Jt=class{},$t=class{},Wt=class{},Yt=class{},Kt=class{},zt=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const o=new e;let i;const r=t;return i=n?function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["videos"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["_self"]);return null!=n&&Nt(t,["video"],function(e){const t={},n=kt(e,["gcsUri"]);null!=n&&Nt(t,["uri"],n);const o=kt(e,["bytesBase64Encoded"]);null!=o&&Nt(t,["videoBytes"],Mt(o));const i=kt(e,["mimeType"]);return null!=i&&Nt(t,["mimeType"],i),t}(n)),t}(e))),Nt(t,["generatedVideos"],e)}const o=kt(e,["raiMediaFilteredCount"]);null!=o&&Nt(t,["raiMediaFilteredCount"],o);const i=kt(e,["raiMediaFilteredReasons"]);return null!=i&&Nt(t,["raiMediaFilteredReasons"],i),t}(s)),t}(r):function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response","generateVideoResponse"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["generatedSamples"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["video"]);return null!=n&&Nt(t,["video"],function(e){const t={},n=kt(e,["uri"]);null!=n&&Nt(t,["uri"],n);const o=kt(e,["encodedVideo"]);null!=o&&Nt(t,["videoBytes"],Mt(o));const i=kt(e,["encoding"]);return null!=i&&Nt(t,["mimeType"],i),t}(n)),t}(e))),Nt(t,["generatedVideos"],e)}const o=kt(e,["raiMediaFilteredCount"]);null!=o&&Nt(t,["raiMediaFilteredCount"],o);const i=kt(e,["raiMediaFilteredReasons"]);return null!=i&&Nt(t,["raiMediaFilteredReasons"],i),t}(s)),t}(r),Object.assign(o,i),o}},Zt=class{},Qt=class{},en=class{},tn=class{},nn=class{},on=class{},rn=class{},sn=class{},an=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const o=new e,i=function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["parent"]);null!=o&&Nt(t,["parent"],o);const i=kt(e,["documentName"]);return null!=i&&Nt(t,["documentName"],i),t}(s)),t}(t);return Object.assign(o,i),o}},ln=class{},un=class{},cn=class{},dn=class{},pn=class{},mn=class{get text(){var e,t,n;let o="",i=!1;const r=[];for(const s of null!==(n=null===(t=null===(e=this.serverContent)||void 0===e?void 0:e.modelTurn)||void 0===t?void 0:t.parts)&&void 0!==n?n:[]){for(const[e,t]of Object.entries(s))"text"!==e&&"thought"!==e&&null!==t&&r.push(e);if("string"==typeof s.text){if("boolean"==typeof s.thought&&s.thought)continue;i=!0,o+=s.text}}return r.length,i?o:void 0}get data(){var e,t,n;let o="";const i=[];for(const r of null!==(n=null===(t=null===(e=this.serverContent)||void 0===e?void 0:e.modelTurn)||void 0===t?void 0:t.parts)&&void 0!==n?n:[]){for(const[e,t]of Object.entries(r))"inlineData"!==e&&null!==t&&i.push(e);r.inlineData&&"string"==typeof r.inlineData.data&&(o+=atob(r.inlineData.data))}return i.length,o.length>0?btoa(o):void 0}},hn=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},fn=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const o=new e,i=xt(t);return Object.assign(o,i),o}};function vn(e,t){if(!t||"string"!=typeof t)throw new Error("model is required and must be a string");if(t.includes("..")||t.includes("?")||t.includes("&"))throw new Error("invalid model parameter");if(e.isVertexAI()){if(t.startsWith("publishers/")||t.startsWith("projects/")||t.startsWith("models/"))return t;if(t.indexOf("/")>=0){const e=t.split("/",2);return`publishers/${e[0]}/models/${e[1]}`}return`publishers/google/models/${t}`}return t.startsWith("models/")||t.startsWith("tunedModels/")?t:`models/${t}`}function gn(e,t){const n=vn(e,t);return n?n.startsWith("publishers/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/${n}`:n.startsWith("models/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${n}`:n:""}function _n(e){return Array.isArray(e)?e.map(e=>yn(e)):[yn(e)]}function yn(e){if("object"==typeof e&&null!==e)return e;throw new Error("Could not parse input as Blob. Unsupported blob type: "+typeof e)}function En(e){const t=yn(e);if(t.mimeType&&t.mimeType.startsWith("image/"))return t;throw new Error(`Unsupported mime type: ${t.mimeType}`)}function Tn(e){const t=yn(e);if(t.mimeType&&t.mimeType.startsWith("audio/"))return t;throw new Error(`Unsupported mime type: ${t.mimeType}`)}function An(e){if(null==e)throw new Error("PartUnion is required");if("object"==typeof e)return e;if("string"==typeof e)return{text:e};throw new Error("Unsupported part type: "+typeof e)}function In(e){if(null==e||Array.isArray(e)&&0===e.length)throw new Error("PartListUnion is required");return Array.isArray(e)?e.map(e=>An(e)):[An(e)]}function Cn(e){return null!=e&&"object"==typeof e&&"parts"in e&&Array.isArray(e.parts)}function Sn(e){return null!=e&&"object"==typeof e&&"functionCall"in e}function bn(e){return null!=e&&"object"==typeof e&&"functionResponse"in e}function On(e){if(null==e)throw new Error("ContentUnion is required");return Cn(e)?e:{role:"user",parts:In(e)}}function wn(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap(e=>{const t=On(e);return t.parts&&t.parts.length>0&&void 0!==t.parts[0].text?[t.parts[0].text]:[]});if(e.isVertexAI()){const e=On(t);return e.parts&&e.parts.length>0&&void 0!==e.parts[0].text?[e.parts[0].text]:[]}return Array.isArray(t)?t.map(e=>On(e)):[On(t)]}function Rn(e){if(null==e||Array.isArray(e)&&0===e.length)throw new Error("contents are required");if(!Array.isArray(e)){if(Sn(e)||bn(e))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[On(e)]}const t=[],n=[],o=Cn(e[0]);for(const i of e){const e=Cn(i);if(e!=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(e)t.push(i);else{if(Sn(i)||bn(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||t.push({role:"user",parts:In(n)}),t}function Pn(e){const t={},n=["items"],o=["anyOf"],i=["properties"];if(e.type&&e.anyOf)throw new Error("type and anyOf cannot be both populated.");const r=e.anyOf;null!=r&&2==r.length&&("null"===r[0].type?(t.nullable=!0,e=r[1]):"null"===r[1].type&&(t.nullable=!0,e=r[0])),e.type instanceof Array&&function(e,t){e.includes("null")&&(t.nullable=!0);const n=e.filter(e=>"null"!==e);if(1===n.length)t.type=Object.values(se).includes(n[0].toUpperCase())?n[0].toUpperCase():se.TYPE_UNSPECIFIED;else{t.anyOf=[];for(const e of n)t.anyOf.push({type:Object.values(se).includes(e.toUpperCase())?e.toUpperCase():se.TYPE_UNSPECIFIED})}}(e.type,t);for(const[s,a]of Object.entries(e))if(null!=a)if("type"==s){if("null"===a)throw new Error("type: null can not be the only possible type for the field.");if(a instanceof Array)continue;t.type=Object.values(se).includes(a.toUpperCase())?a.toUpperCase():se.TYPE_UNSPECIFIED}else if(n.includes(s))t[s]=Pn(a);else if(o.includes(s)){const e=[];for(const n of a)"null"!=n.type?e.push(Pn(n)):t.nullable=!0;t[s]=e}else if(i.includes(s)){const e={};for(const[t,n]of Object.entries(a))e[t]=Pn(n);t[s]=e}else{if("additionalProperties"===s)continue;t[s]=a}return t}function Nn(e){return Pn(e)}function kn(e){if("object"==typeof e)return e;if("string"==typeof e)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};throw new Error("Unsupported speechConfig type: "+typeof e)}function Dn(e){if("multiSpeakerVoiceConfig"in e)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return e}function Mn(e){if(e.functionDeclarations)for(const t of e.functionDeclarations)t.parameters&&(Object.keys(t.parameters).includes("$schema")?t.parametersJsonSchema||(t.parametersJsonSchema=t.parameters,delete t.parameters):t.parameters=Pn(t.parameters)),t.response&&(Object.keys(t.response).includes("$schema")?t.responseJsonSchema||(t.responseJsonSchema=t.response,delete t.response):t.response=Pn(t.response));return e}function xn(e){if(null==e)throw new Error("tools is required");if(!Array.isArray(e))throw new Error("tools is required and must be an array of Tools");const t=[];for(const n of e)t.push(n);return t}function Gn(e,t){if("string"!=typeof t)throw new Error("name must be a string");return function(e,t,n,o=1){const i=!t.startsWith(`${n}/`)&&t.split("/").length===o;return e.isVertexAI()?t.startsWith("projects/")?t:t.startsWith("locations/")?`projects/${e.getProject()}/${t}`:t.startsWith(`${n}/`)?`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`:i?`projects/${e.getProject()}/locations/${e.getLocation()}/${n}/${t}`:t:i?`${n}/${t}`:t}(e,t,"cachedContents")}function Un(e){switch(e){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 e}}function Ln(e){return Mt(e)}function qn(e){var t;let n;var o;if(null!=(o=e)&&"object"==typeof o&&"name"in o&&(n=e.name),!(function(e){return null!=e&&"object"==typeof e&&"uri"in e}(e)&&(n=e.uri,void 0===n)||function(e){return null!=e&&"object"==typeof e&&"video"in e}(e)&&(n=null===(t=e.video)||void 0===t?void 0:t.uri,void 0===n))){if("string"==typeof e&&(n=e),void 0===n)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){const e=n.split("files/")[1].match(/[a-z0-9]+/);if(null===e)throw new Error(`Could not extract file name from URI ${n}`);n=e[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function Hn(e,t){let n;return n=e.isVertexAI()?t?"publishers/google/models":"models":t?"models":"tunedModels",n}function jn(e){for(const t of["models","tunedModels","publisherModels"])if(Fn(e,t))return e[t];return[]}function Fn(e,t){return null!==e&&"object"==typeof e&&t in e}function Xn(e,t={}){const n=e,o={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(o.responseJsonSchema=n.outputSchema),t.behavior&&(o.behavior=t.behavior),{functionDeclarations:[o]}}function Bn(e,t){let n;if("string"==typeof t)if(e.isVertexAI())if(t.startsWith("gs://"))n={format:"jsonl",gcsUri:[t]};else if(t.startsWith("bq://"))n={format:"bigquery",bigqueryUri:t};else{if(!/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(t))throw new Error(`Unsupported string source for Vertex AI: ${t}`);n={format:"vertex-dataset",vertexDatasetName:t}}else{if(!t.startsWith("files/"))throw new Error(`Unsupported string source for Gemini API: ${t}`);n={fileName:t}}else if(Array.isArray(t)){if(e.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:t}}else n=t;const o=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,i=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(e.isVertexAI()){if(i>0||1!==o)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(o>0||1!==i)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function Vn(e){if("object"!=typeof e||null===e)return{};const t=e,n=t.inlinedResponses;if("object"!=typeof n||null===n)return e;const o=n.inlinedResponses;if(!Array.isArray(o)||0===o.length)return e;let i=!1;for(const r of o){if("object"!=typeof r||null===r)continue;const e=r.response;if("object"==typeof e&&null!==e&&void 0!==e.embedding){i=!0;break}}return i&&(t.inlinedEmbedContentResponses=t.inlinedResponses,delete t.inlinedResponses),e}function Jn(e,t){const n=t;if(!e.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 $n(e){return"BATCH_STATE_UNSPECIFIED"===e?"JOB_STATE_UNSPECIFIED":"BATCH_STATE_PENDING"===e?"JOB_STATE_PENDING":"BATCH_STATE_RUNNING"===e?"JOB_STATE_RUNNING":"BATCH_STATE_SUCCEEDED"===e?"JOB_STATE_SUCCEEDED":"BATCH_STATE_FAILED"===e?"JOB_STATE_FAILED":"BATCH_STATE_CANCELLED"===e?"JOB_STATE_CANCELLED":"BATCH_STATE_EXPIRED"===e?"JOB_STATE_EXPIRED":e}function Wn(e){var t;return(null!==(t=e.split("/").pop())&&void 0!==t?t:e).includes("maas")}function Yn(e){var t;const n=null!==(t=e.split("/").pop())&&void 0!==t?t:e;return n.includes("gemini")&&!n.startsWith("gemini-embedding-001")&&!n.startsWith("gemini-embedding-exp")}function Kn(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata","displayName"]);null!=o&&Nt(t,["displayName"],o);const i=kt(e,["metadata","state"]);null!=i&&Nt(t,["state"],$n(i));const r=kt(e,["metadata","createTime"]);null!=r&&Nt(t,["createTime"],r);const s=kt(e,["metadata","endTime"]);null!=s&&Nt(t,["endTime"],s);const a=kt(e,["metadata","updateTime"]);null!=a&&Nt(t,["updateTime"],a);const l=kt(e,["metadata","model"]);null!=l&&Nt(t,["model"],l);const u=kt(e,["metadata","output"]);return null!=u&&Nt(t,["dest"],function(e){const t={},n=kt(e,["responsesFile"]);null!=n&&Nt(t,["fileName"],n);const o=kt(e,["inlinedResponses","inlinedResponses"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["response"]);null!=n&&Nt(t,["response"],function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["candidates"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["content"]);null!=n&&Nt(t,["content"],n);const o=kt(e,["citationMetadata"]);null!=o&&Nt(t,["citationMetadata"],function(e){const t={},n=kt(e,["citationSources"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["citations"],e)}return t}(o));const i=kt(e,["tokenCount"]);null!=i&&Nt(t,["tokenCount"],i);const r=kt(e,["finishReason"]);null!=r&&Nt(t,["finishReason"],r);const s=kt(e,["groundingMetadata"]);null!=s&&Nt(t,["groundingMetadata"],s);const a=kt(e,["avgLogprobs"]);null!=a&&Nt(t,["avgLogprobs"],a);const l=kt(e,["index"]);null!=l&&Nt(t,["index"],l);const u=kt(e,["logprobsResult"]);null!=u&&Nt(t,["logprobsResult"],u);const c=kt(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["safetyRatings"],e)}const d=kt(e,["urlContextMetadata"]);null!=d&&Nt(t,["urlContextMetadata"],d);const p=kt(e,["continuationToken"]);return null!=p&&Nt(t,["continuationToken"],p),t}(e))),Nt(t,["candidates"],e)}const i=kt(e,["modelVersion"]);null!=i&&Nt(t,["modelVersion"],i);const r=kt(e,["promptFeedback"]);null!=r&&Nt(t,["promptFeedback"],r);const s=kt(e,["responseId"]);null!=s&&Nt(t,["responseId"],s);const a=kt(e,["usageMetadata"]);null!=a&&Nt(t,["usageMetadata"],a);const l=kt(e,["modelStatus"]);return null!=l&&Nt(t,["modelStatus"],l),t}(n));const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["error"]);null!=i&&Nt(t,["error"],i);const r=t.response;if(null!=r){const e=new Ht;Object.assign(e,r),t.response=e}return t}(e))),Nt(t,["inlinedResponses"],e)}const i=kt(e,["inlinedEmbedContentResponses","inlinedResponses"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["inlinedEmbedContentResponses"],e)}return t}(Vn(u))),t}function zn(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["displayName"]);null!=o&&Nt(t,["displayName"],o);const i=kt(e,["state"]);null!=i&&Nt(t,["state"],$n(i));const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["createTime"]);null!=s&&Nt(t,["createTime"],s);const a=kt(e,["startTime"]);null!=a&&Nt(t,["startTime"],a);const l=kt(e,["endTime"]);null!=l&&Nt(t,["endTime"],l);const u=kt(e,["updateTime"]);null!=u&&Nt(t,["updateTime"],u);const c=kt(e,["model"]);null!=c&&Nt(t,["model"],c);const d=kt(e,["inputConfig"]);null!=d&&Nt(t,["src"],function(e){const t={},n=kt(e,["instancesFormat"]);null!=n&&Nt(t,["format"],n);const o=kt(e,["gcsSource","uris"]);null!=o&&Nt(t,["gcsUri"],o);const i=kt(e,["bigquerySource","inputUri"]);null!=i&&Nt(t,["bigqueryUri"],i);const r=kt(e,["vertexMultimodalDatasetSource","datasetName"]);return null!=r&&Nt(t,["vertexDatasetName"],r),t}(d));const p=kt(e,["outputConfig"]);null!=p&&Nt(t,["dest"],function(e){const t={},n=kt(e,["predictionsFormat"]);null!=n&&Nt(t,["format"],n);const o=kt(e,["gcsDestination","outputUriPrefix"]);null!=o&&Nt(t,["gcsUri"],o);const i=kt(e,["bigqueryDestination","outputUri"]);null!=i&&Nt(t,["bigqueryUri"],i);const r=kt(e,["vertexMultimodalDatasetDestination"]);return null!=r&&Nt(t,["vertexDataset"],function(e){const t={},n=kt(e,["bigqueryDestination","outputUri"]);null!=n&&Nt(t,["bigqueryDestination"],n);const o=kt(e,["displayName"]);return null!=o&&Nt(t,["displayName"],o),t}(r)),t}(Vn(p)));const m=kt(e,["outputInfo"]);null!=m&&Nt(t,["outputInfo"],m);const h=kt(e,["completionStats"]);return null!=h&&Nt(t,["completionStats"],h),t}function Zn(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);null!=n&&Nt(t,["mediaResolution"],n);const o=kt(e,["toolCall"]);null!=o&&Nt(t,["toolCall"],o);const i=kt(e,["toolResponse"]);null!=i&&Nt(t,["toolResponse"],i);const r=kt(e,["audioTranscription"]);null!=r&&Nt(t,["audioTranscription"],r);const s=kt(e,["codeExecutionResult"]);null!=s&&Nt(t,["codeExecutionResult"],s);const a=kt(e,["executableCode"]);null!=a&&Nt(t,["executableCode"],a);const l=kt(e,["fileData"]);null!=l&&Nt(t,["fileData"],l);const u=kt(e,["functionCall"]);null!=u&&Nt(t,["functionCall"],function(e){const t={},n=kt(e,["args"]);null!=n&&Nt(t,["args"],n);const o=kt(e,["id"]);null!=o&&Nt(t,["id"],o);const i=kt(e,["name"]);if(null!=i&&Nt(t,["name"],i),void 0!==kt(e,["partialArgs"]))throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(u));const c=kt(e,["functionResponse"]);null!=c&&Nt(t,["functionResponse"],c);const d=kt(e,["inlineData"]);null!=d&&Nt(t,["inlineData"],d);const p=kt(e,["text"]);null!=p&&Nt(t,["text"],p);const m=kt(e,["thought"]);null!=m&&Nt(t,["thought"],m);const h=kt(e,["thoughtSignature"]);null!=h&&Nt(t,["thoughtSignature"],h);const f=kt(e,["videoMetadata"]);null!=f&&Nt(t,["videoMetadata"],f);const v=kt(e,["partMetadata"]);null!=v&&Nt(t,["partMetadata"],v);const g=kt(e,["mediaProcessing"]);null!=g&&Nt(t,["mediaProcessing"],g);const _=kt(e,["speechMetadata"]);null!=_&&Nt(t,["speechMetadata"],_);const y=kt(e,["documentMetadata"]);null!=y&&Nt(t,["documentMetadata"],y);const E=kt(e,["spreadsheetMetadata"]);null!=E&&Nt(t,["spreadsheetMetadata"],E);const T=kt(e,["audioMetadata"]);return null!=T&&Nt(t,["audioMetadata"],T),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}function Qn(e,t){const n=kt(e,["displayName"]);void 0!==t&&null!=n&&Nt(t,["displayName"],n);const o=kt(e,["dest"]);if(void 0!==t&&null!=o&&Nt(t,["outputConfig"],function(e){const t={},n=kt(e,["format"]);null!=n&&Nt(t,["predictionsFormat"],n);const o=kt(e,["gcsUri"]);null!=o&&Nt(t,["gcsDestination","outputUriPrefix"],o);const i=kt(e,["bigqueryUri"]);null!=i&&Nt(t,["bigqueryDestination","outputUri"],i);const r=kt(e,["vertexDataset"]);if(null!=r&&Nt(t,["vertexMultimodalDatasetDestination"],function(e){const t={},n=kt(e,["bigqueryDestination"]);null!=n&&Nt(t,["bigqueryDestination","outputUri"],n);const o=kt(e,["displayName"]);return null!=o&&Nt(t,["displayName"],o),t}(r)),void 0!==kt(e,["fileName"]))throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["inlinedResponses"]))throw new Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["inlinedEmbedContentResponses"]))throw new Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(function(e){if("string"!=typeof e)return e;const t=e;if(t.startsWith("gs://"))return{format:"jsonl",gcsUri:t};if(t.startsWith("bq://"))return{format:"bigquery",bigqueryUri:t};throw new Error(`Unsupported destination: ${t}`)}(o))),void 0!==kt(e,["webhookConfig"]))throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}function eo(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["src"]);null!=i&&Nt(n,["batch","inputConfig"],function(e,t){const n={};if(void 0!==kt(t,["format"]))throw new Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(t,["gcsUri"]))throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(t,["bigqueryUri"]))throw new Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(t,["vertexDatasetName"]))throw new Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(t,["fileName"]);null!=o&&Nt(n,["fileName"],o);const i=kt(t,["inlinedRequests"]);if(null!=i){let t=i;Array.isArray(t)&&(t=t.map(t=>function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["request","model"],vn(e,o));const i=kt(t,["contents"]);if(null!=i){let e=Rn(i);Array.isArray(e)&&(e=e.map(e=>Zn(e))),Nt(n,["request","contents"],e)}const r=kt(t,["metadata"]);null!=r&&Nt(n,["metadata"],r);const s=kt(t,["config"]);return null!=s&&Nt(n,["request","generationConfig"],function(e,t,n){const o={},i=kt(t,["serviceTier"]);void 0!==n&&null!=i&&Nt(n,["serviceTier"],i);const r=kt(t,["systemInstruction"]);void 0!==n&&null!=r&&Nt(n,["systemInstruction"],Zn(On(r)));const s=kt(t,["temperature"]);null!=s&&Nt(o,["temperature"],s);const a=kt(t,["topP"]);null!=a&&Nt(o,["topP"],a);const l=kt(t,["topK"]);null!=l&&Nt(o,["topK"],l);const u=kt(t,["candidateCount"]);null!=u&&Nt(o,["candidateCount"],u);const c=kt(t,["maxOutputTokens"]);null!=c&&Nt(o,["maxOutputTokens"],c);const d=kt(t,["stopSequences"]);null!=d&&Nt(o,["stopSequences"],d);const p=kt(t,["responseLogprobs"]);null!=p&&Nt(o,["responseLogprobs"],p);const m=kt(t,["logprobs"]);null!=m&&Nt(o,["logprobs"],m);const h=kt(t,["presencePenalty"]);null!=h&&Nt(o,["presencePenalty"],h);const f=kt(t,["frequencyPenalty"]);null!=f&&Nt(o,["frequencyPenalty"],f);const v=kt(t,["seed"]);null!=v&&Nt(o,["seed"],v);const g=kt(t,["responseMimeType"]);null!=g&&Nt(o,["responseMimeType"],g);const _=kt(t,["responseSchema"]);null!=_&&Nt(o,["responseSchema"],Nn(_));const y=kt(t,["responseJsonSchema"]);if(null!=y&&Nt(o,["responseJsonSchema"],y),void 0!==kt(t,["routingConfig"]))throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(t,["modelSelectionConfig"]))throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const E=kt(t,["safetySettings"]);if(void 0!==n&&null!=E){let e=E;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["category"]);if(null!=n&&Nt(t,["category"],n),void 0!==kt(e,["method"]))throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["threshold"]);return null!=o&&Nt(t,["threshold"],o),t}(e))),Nt(n,["safetySettings"],e)}const T=kt(t,["tools"]);if(void 0!==n&&null!=T){let e=xn(T);Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==kt(e,["retrieval"]))throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["googleMaps"]);null!=n&&Nt(t,["googleMaps"],function(e){const t={},n=kt(e,["authConfig"]);null!=n&&Nt(t,["authConfig"],function(e){const t={},n=kt(e,["apiKey"]);if(null!=n&&Nt(t,["apiKey"],n),void 0!==kt(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["authType"]))throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oauthConfig"]))throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oidcConfig"]))throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["enableWidget"]);if(null!=o&&Nt(t,["enableWidget"],o),void 0!==kt(e,["groundingTypes"]))throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["mcpServers"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mcpServers"],e)}const i=kt(e,["codeExecution"]);null!=i&&Nt(t,["codeExecution"],i);const r=kt(e,["computerUse"]);if(null!=r&&Nt(t,["computerUse"],r),void 0!==kt(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["exaAiSearch"]))throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const a=kt(e,["googleSearch"]);null!=a&&Nt(t,["googleSearch"],function(e){const t={};if(void 0!==kt(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["excludeDomains"]))throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["searchTypes"]);null!=n&&Nt(t,["searchTypes"],n);const o=kt(e,["timeRangeFilter"]);return null!=o&&Nt(t,["timeRangeFilter"],o),t}(a));const l=kt(e,["googleSearchRetrieval"]);if(null!=l&&Nt(t,["googleSearchRetrieval"],l),void 0!==kt(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=kt(e,["urlContext"]);null!=u&&Nt(t,["urlContext"],u);const c=kt(e,["fileSearch"]);return null!=c&&Nt(t,["fileSearch"],c),t}(Mn(e)))),Nt(n,["tools"],e)}const A=kt(t,["toolConfig"]);void 0!==n&&null!=A&&Nt(n,["toolConfig"],function(e){const t={},n=kt(e,["functionCallingConfig"]);null!=n&&Nt(t,["functionCallingConfig"],function(e){const t={},n=kt(e,["allowedFunctionNames"]);null!=n&&Nt(t,["allowedFunctionNames"],n);const o=kt(e,["mode"]);if(null!=o&&Nt(t,["mode"],o),void 0!==kt(e,["streamFunctionCallArguments"]))throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["retrievalConfig"]);null!=o&&Nt(t,["retrievalConfig"],o);const i=kt(e,["includeServerSideToolInvocations"]);return null!=i&&Nt(t,["includeServerSideToolInvocations"],i),t}(A));const I=kt(t,["labels"]);void 0!==n&&null!=I&&Nt(n,["labels"],I);const C=kt(t,["cachedContent"]);void 0!==n&&null!=C&&Nt(n,["cachedContent"],Gn(e,C));const S=kt(t,["responseModalities"]);null!=S&&Nt(o,["responseModalities"],S);const b=kt(t,["mediaResolution"]);null!=b&&Nt(o,["mediaResolution"],b);const O=kt(t,["speechConfig"]);if(null!=O&&Nt(o,["speechConfig"],kn(O)),void 0!==kt(t,["audioTimestamp"]))throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const w=kt(t,["thinkingConfig"]);null!=w&&Nt(o,["thinkingConfig"],w);const R=kt(t,["audioTranscriptionConfig"]);null!=R&&Nt(o,["audioTranscriptionConfig"],R);const P=kt(t,["imageConfig"]);null!=P&&Nt(o,["imageConfig"],function(e){const t={},n=kt(e,["aspectRatio"]);null!=n&&Nt(t,["aspectRatio"],n);const o=kt(e,["imageSize"]);if(null!=o&&Nt(t,["imageSize"],o),void 0!==kt(e,["personGeneration"]))throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["outputMimeType"]))throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["outputCompressionQuality"]))throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["imageOutputOptions"]))throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["prominentPeople"]))throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(P));const N=kt(t,["enableEnhancedCivicAnswers"]);if(null!=N&&Nt(o,["enableEnhancedCivicAnswers"],N),void 0!==kt(t,["modelArmorConfig"]))throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const k=kt(t,["continuationToken"]);if(void 0!==n&&null!=k&&Nt(n,["continuationToken"],k),void 0!==kt(t,["generationOutputConfig"]))throw new Error("generationOutputConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const D=kt(t,["store"]);return void 0!==n&&null!=D&&Nt(n,["store"],D),o}(e,s,kt(n,["request"],{}))),n}(e,t))),Nt(n,["requests","requests"],t)}return n}(e,Bn(e,i)));const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["displayName"]);if(void 0!==t&&null!=n&&Nt(t,["batch","displayName"],n),void 0!==kt(e,["dest"]))throw new Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["webhookConfig"]);void 0!==t&&null!=o&&Nt(t,["batch","webhookConfig"],o)}(r,n),n}!function(e){e.PAGED_ITEM_BATCH_JOBS="batchJobs",e.PAGED_ITEM_MODELS="models",e.PAGED_ITEM_TUNING_JOBS="tuningJobs",e.PAGED_ITEM_FILES="files",e.PAGED_ITEM_CACHED_CONTENTS="cachedContents",e.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",e.PAGED_ITEM_DOCUMENTS="documents",e.PAGED_ITEM_SKILLS="skills"}(Gt||(Gt={}));var to=class{constructor(e,t,n,o){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,n,o)}init(e,t,n){var o,i;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=null==t?void 0:t.sdkHttpResponse,this.idxInternal=0;let r={config:{}};r=n&&0!==Object.keys(n).length?"object"==typeof n?Object.assign({},n):n:{config:{}},r.config&&(r.config.pageToken=t.nextPageToken),this.paramsInternal=r,this.pageInternalSize=null!==(i=null===(o=r.config)||void 0===o?void 0:o.pageSize)&&void 0!==i?i: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())return{value:void 0,done:!0};await this.nextPage()}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 void 0!==(null===(e=this.params.config)||void 0===e?void 0:e.pageToken)}},no=class extends Rt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new to(Gt.PAGED_ITEM_BATCH_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.create=async e=>(this.apiClient.isVertexAI()&&(e.config=this.formatDestination(e.src,e.config)),this.createInternal(e)),this.createEmbeddings=async e=>{if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(e)}}createInlinedGenerateContentRequest(e){const t=eo(this.apiClient,e),n=Pt("{model}:batchGenerateContent",t._url),o=t.batch.inputConfig.requests,i=o.requests,r=[];for(const s of i){const e=Object.assign({},s);if(e.systemInstruction){const t=e.systemInstruction;delete e.systemInstruction;const n=e.request;n.systemInstruction=t,e.request=n}r.push(e)}return o.requests=r,delete t.config,delete t._url,delete t._query,{path:n,body:t}}getGcsUri(e){return"string"==typeof e?e.startsWith("gs://")?e:void 0:!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0?e.gcsUri[0]:void 0}getBigqueryUri(e){return"string"==typeof e?e.startsWith("bq://")?e:void 0:Array.isArray(e)?void 0:e.bigqueryUri}formatDestination(e,t){const n=t?Object.assign({},t):{},o=Date.now().toString();if(n.displayName||(n.displayName=`genaiBatchJob_${o}`),void 0===n.dest){const t=this.getGcsUri(e),i=this.getBigqueryUri(e);if(t)t.endsWith(".jsonl")?n.dest=`${t.slice(0,-6)}/dest`:n.dest=`${t}_dest_${o}`;else{if(!i)throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.");n.dest=`${i}_dest_${o}`}}return n}async createInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["model"],vn(e,o));const i=kt(t,["src"]);null!=i&&Nt(n,["inputConfig"],function(e){const t={},n=kt(e,["format"]);null!=n&&Nt(t,["instancesFormat"],n);const o=kt(e,["gcsUri"]);null!=o&&Nt(t,["gcsSource","uris"],o);const i=kt(e,["bigqueryUri"]);null!=i&&Nt(t,["bigquerySource","inputUri"],i);const r=kt(e,["vertexDatasetName"]);if(null!=r&&Nt(t,["vertexMultimodalDatasetSource","datasetName"],r),void 0!==kt(e,["fileName"]))throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["inlinedRequests"]))throw new Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(Bn(e,i)));const r=kt(t,["config"]);return null!=r&&Qn(r,n),n}(this.apiClient,e);return s=Pt("batchPredictionJobs",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>zn(e))}{const t=eo(this.apiClient,e);return s=Pt("{model}:batchGenerateContent",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Kn(e))}}async createEmbeddingsInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["src"]);null!=i&&Nt(n,["batch","inputConfig"],function(e,t){const n={},o=kt(t,["fileName"]);null!=o&&Nt(n,["file_name"],o);const i=kt(t,["inlinedRequests"]);return null!=i&&Nt(n,["requests"],function(e,t){const n={},o=kt(t,["contents"]);if(null!=o){let t=wn(e,o);Array.isArray(t)&&(t=t.map(e=>e)),Nt(n,["requests[]","request","content"],t)}const i=kt(t,["config"]);return null!=i&&(Nt(n,["_self"],function(e,t){const n=kt(e,["taskType"]);void 0!==t&&null!=n&&Nt(t,["requests[]","taskType"],n);const o=kt(e,["title"]);void 0!==t&&null!=o&&Nt(t,["requests[]","title"],o);const i=kt(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&Nt(t,["requests[]","outputDimensionality"],i),void 0!==kt(e,["mimeType"]))throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["autoTruncate"]))throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["documentOcr"]))throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["audioTrackExtraction"]))throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return{}}(i,n)),function(e){for(const[t,n]of Object.entries({"requests[].*":"requests[].request.*"})){const o=t.split("."),i=n.split("."),r=/* @__PURE__ */new Set;let s=-1;for(let e=0;e<o.length;e++)if("*"===o[e]){s=e;break}if(-1!==s&&i.length>s)for(let e=s;e<i.length;e++){const t=i[e];"*"===t||t.endsWith("[]")||t.endsWith("[0]")||r.add(t)}Dt(e,o,i,0,r)}}(n)),n}(e,i)),n}(e,i));const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["displayName"]);void 0!==t&&null!=n&&Nt(t,["batch","displayName"],n)}(r,n),n}(this.apiClient,e);return i=Pt("{model}:asyncBatchEmbedContent",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>Kn(e))}}async get(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);return s=Pt("batchPredictionJobs/{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>zn(e))}{const t=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);return s=Pt("batches/{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Kn(e))}}async cancel(e){var t,n,o,i;let r="",s={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);r=Pt("batchPredictionJobs/{name}:cancel",o._url),s=o._query,delete o._url,delete o._query,await this.apiClient.request({path:r,queryParams:s,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal})}else{const t=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);r=Pt("batches/{name}:cancel",t._url),s=t._query,delete t._url,delete t._query,await this.apiClient.request({path:r,queryParams:s,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal})}}async listInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o);const i=kt(e,["filter"]);void 0!==t&&null!=i&&Nt(t,["_query","filter"],i)}(n,t),t}(e);return s=Pt("batchPredictionJobs",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["batchPredictionJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>zn(e))),Nt(t,["batchJobs"],e)}return t}(e),n=new pn;return Object.assign(n,t),n})}{const t=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);if(void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o),void 0!==kt(e,["filter"]))throw new Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(n,t),t}(e);return s=Pt("batches",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["operations"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>Kn(e))),Nt(t,["batchJobs"],e)}return t}(e),n=new pn;return Object.assign(n,t),n})}}async delete(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);return s=Pt("batchPredictionJobs/{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);return null!=r&&Nt(t,["error"],r),t}(e))}{const t=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);return s=Pt("batches/{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"DELETE",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);return null!=r&&Nt(t,["error"],r),t}(e))}}};function oo(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);null!=n&&Nt(t,["mediaResolution"],n);const o=kt(e,["toolCall"]);null!=o&&Nt(t,["toolCall"],o);const i=kt(e,["toolResponse"]);null!=i&&Nt(t,["toolResponse"],i);const r=kt(e,["audioTranscription"]);null!=r&&Nt(t,["audioTranscription"],r);const s=kt(e,["codeExecutionResult"]);null!=s&&Nt(t,["codeExecutionResult"],s);const a=kt(e,["executableCode"]);null!=a&&Nt(t,["executableCode"],a);const l=kt(e,["fileData"]);null!=l&&Nt(t,["fileData"],l);const u=kt(e,["functionCall"]);null!=u&&Nt(t,["functionCall"],function(e){const t={},n=kt(e,["args"]);null!=n&&Nt(t,["args"],n);const o=kt(e,["id"]);null!=o&&Nt(t,["id"],o);const i=kt(e,["name"]);if(null!=i&&Nt(t,["name"],i),void 0!==kt(e,["partialArgs"]))throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(u));const c=kt(e,["functionResponse"]);null!=c&&Nt(t,["functionResponse"],c);const d=kt(e,["inlineData"]);null!=d&&Nt(t,["inlineData"],d);const p=kt(e,["text"]);null!=p&&Nt(t,["text"],p);const m=kt(e,["thought"]);null!=m&&Nt(t,["thought"],m);const h=kt(e,["thoughtSignature"]);null!=h&&Nt(t,["thoughtSignature"],h);const f=kt(e,["videoMetadata"]);null!=f&&Nt(t,["videoMetadata"],f);const v=kt(e,["partMetadata"]);null!=v&&Nt(t,["partMetadata"],v);const g=kt(e,["mediaProcessing"]);null!=g&&Nt(t,["mediaProcessing"],g);const _=kt(e,["speechMetadata"]);null!=_&&Nt(t,["speechMetadata"],_);const y=kt(e,["documentMetadata"]);null!=y&&Nt(t,["documentMetadata"],y);const E=kt(e,["spreadsheetMetadata"]);null!=E&&Nt(t,["spreadsheetMetadata"],E);const T=kt(e,["audioMetadata"]);return null!=T&&Nt(t,["audioMetadata"],T),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}function io(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);if(null!=n&&Nt(t,["mediaResolution"],n),void 0!==kt(e,["toolCall"]))throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["toolResponse"]))throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=kt(e,["audioTranscription"]);null!=o&&Nt(t,["audioTranscription"],o);const i=kt(e,["codeExecutionResult"]);null!=i&&Nt(t,["codeExecutionResult"],i);const r=kt(e,["executableCode"]);null!=r&&Nt(t,["executableCode"],r);const s=kt(e,["fileData"]);null!=s&&Nt(t,["fileData"],s);const a=kt(e,["functionCall"]);null!=a&&Nt(t,["functionCall"],a);const l=kt(e,["functionResponse"]);null!=l&&Nt(t,["functionResponse"],function(e){const t={},n=kt(e,["id"]);null!=n&&Nt(t,["id"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["parts"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["fileData"]);null!=n&&Nt(t,["fileData"],n);const o=kt(e,["inlineData"]);if(null!=o&&Nt(t,["inlineData"],o),void 0!==kt(e,["mediaProcessing"]))throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const i=kt(e,["mediaResolution"]);null!=i&&Nt(t,["mediaResolution"],i);const r=kt(e,["videoMetadata"]);null!=r&&Nt(t,["videoMetadata"],r);const s=kt(e,["documentMetadata"]);null!=s&&Nt(t,["documentMetadata"],s);const a=kt(e,["spreadsheetMetadata"]);null!=a&&Nt(t,["spreadsheetMetadata"],a);const l=kt(e,["audioMetadata"]);return null!=l&&Nt(t,["audioMetadata"],l),t}(e))),Nt(t,["parts"],e)}const r=kt(e,["response"]);null!=r&&Nt(t,["response"],r);const s=kt(e,["scheduling"]);if(null!=s&&Nt(t,["scheduling"],s),void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(l));const u=kt(e,["inlineData"]);null!=u&&Nt(t,["inlineData"],u);const c=kt(e,["text"]);null!=c&&Nt(t,["text"],c);const d=kt(e,["thought"]);null!=d&&Nt(t,["thought"],d);const p=kt(e,["thoughtSignature"]);null!=p&&Nt(t,["thoughtSignature"],p);const m=kt(e,["videoMetadata"]);if(null!=m&&Nt(t,["videoMetadata"],m),void 0!==kt(e,["partMetadata"]))throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const h=kt(e,["mediaProcessing"]);null!=h&&Nt(t,["mediaProcessing"],h);const f=kt(e,["speechMetadata"]);null!=f&&Nt(t,["speechMetadata"],f);const v=kt(e,["documentMetadata"]);null!=v&&Nt(t,["documentMetadata"],v);const g=kt(e,["spreadsheetMetadata"]);null!=g&&Nt(t,["spreadsheetMetadata"],g);const _=kt(e,["audioMetadata"]);return null!=_&&Nt(t,["audioMetadata"],_),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}var ro=class extends Rt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new to(Gt.PAGED_ITEM_CACHED_CONTENTS,e=>this.listInternal(e),await this.listInternal(e),e)}async create(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["model"],gn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["ttl"]);void 0!==t&&null!=n&&Nt(t,["ttl"],n);const o=kt(e,["expireTime"]);void 0!==t&&null!=o&&Nt(t,["expireTime"],o);const i=kt(e,["displayName"]);void 0!==t&&null!=i&&Nt(t,["displayName"],i);const r=kt(e,["contents"]);if(void 0!==t&&null!=r){let e=Rn(r);Array.isArray(e)&&(e=e.map(e=>io(e))),Nt(t,["contents"],e)}const s=kt(e,["systemInstruction"]);void 0!==t&&null!=s&&Nt(t,["systemInstruction"],io(On(s)));const a=kt(e,["tools"]);if(void 0!==t&&null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["retrieval"]);null!=n&&Nt(t,["retrieval"],n);const o=kt(e,["googleMaps"]);null!=o&&Nt(t,["googleMaps"],o);const i=kt(e,["mcpServers"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){if(void 0!==kt(e,["name"]))throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["streamableHttpTransport"]))throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}(e))),Nt(t,["mcpServers"],e)}const r=kt(e,["codeExecution"]);null!=r&&Nt(t,["codeExecution"],r);const s=kt(e,["computerUse"]);null!=s&&Nt(t,["computerUse"],s);const a=kt(e,["enterpriseWebSearch"]);null!=a&&Nt(t,["enterpriseWebSearch"],a);const l=kt(e,["exaAiSearch"]);null!=l&&Nt(t,["exaAiSearch"],l);const u=kt(e,["functionDeclarations"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const c=kt(e,["googleSearch"]);null!=c&&Nt(t,["googleSearch"],c);const d=kt(e,["googleSearchRetrieval"]);null!=d&&Nt(t,["googleSearchRetrieval"],d);const p=kt(e,["parallelAiSearch"]);null!=p&&Nt(t,["parallelAiSearch"],p);const m=kt(e,["urlContext"]);if(null!=m&&Nt(t,["urlContext"],m),void 0!==kt(e,["fileSearch"]))throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(e))),Nt(t,["tools"],e)}const l=kt(e,["toolConfig"]);void 0!==t&&null!=l&&Nt(t,["toolConfig"],function(e){const t={},n=kt(e,["functionCallingConfig"]);null!=n&&Nt(t,["functionCallingConfig"],n);const o=kt(e,["retrievalConfig"]);if(null!=o&&Nt(t,["retrievalConfig"],o),void 0!==kt(e,["includeServerSideToolInvocations"]))throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(l));const u=kt(e,["kmsKeyName"]);void 0!==t&&null!=u&&Nt(t,["encryption_spec","kmsKeyName"],u)}(i,n),n}(this.apiClient,e);return s=Pt("cachedContents",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>e)}{const t=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["model"],gn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["ttl"]);void 0!==t&&null!=n&&Nt(t,["ttl"],n);const o=kt(e,["expireTime"]);void 0!==t&&null!=o&&Nt(t,["expireTime"],o);const i=kt(e,["displayName"]);void 0!==t&&null!=i&&Nt(t,["displayName"],i);const r=kt(e,["contents"]);if(void 0!==t&&null!=r){let e=Rn(r);Array.isArray(e)&&(e=e.map(e=>oo(e))),Nt(t,["contents"],e)}const s=kt(e,["systemInstruction"]);void 0!==t&&null!=s&&Nt(t,["systemInstruction"],oo(On(s)));const a=kt(e,["tools"]);if(void 0!==t&&null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==kt(e,["retrieval"]))throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["googleMaps"]);null!=n&&Nt(t,["googleMaps"],function(e){const t={},n=kt(e,["authConfig"]);null!=n&&Nt(t,["authConfig"],function(e){const t={},n=kt(e,["apiKey"]);if(null!=n&&Nt(t,["apiKey"],n),void 0!==kt(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["authType"]))throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oauthConfig"]))throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oidcConfig"]))throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["enableWidget"]);if(null!=o&&Nt(t,["enableWidget"],o),void 0!==kt(e,["groundingTypes"]))throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["mcpServers"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mcpServers"],e)}const i=kt(e,["codeExecution"]);null!=i&&Nt(t,["codeExecution"],i);const r=kt(e,["computerUse"]);if(null!=r&&Nt(t,["computerUse"],r),void 0!==kt(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["exaAiSearch"]))throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const a=kt(e,["googleSearch"]);null!=a&&Nt(t,["googleSearch"],function(e){const t={};if(void 0!==kt(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["excludeDomains"]))throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["searchTypes"]);null!=n&&Nt(t,["searchTypes"],n);const o=kt(e,["timeRangeFilter"]);return null!=o&&Nt(t,["timeRangeFilter"],o),t}(a));const l=kt(e,["googleSearchRetrieval"]);if(null!=l&&Nt(t,["googleSearchRetrieval"],l),void 0!==kt(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=kt(e,["urlContext"]);null!=u&&Nt(t,["urlContext"],u);const c=kt(e,["fileSearch"]);return null!=c&&Nt(t,["fileSearch"],c),t}(e))),Nt(t,["tools"],e)}const l=kt(e,["toolConfig"]);if(void 0!==t&&null!=l&&Nt(t,["toolConfig"],function(e){const t={},n=kt(e,["functionCallingConfig"]);null!=n&&Nt(t,["functionCallingConfig"],function(e){const t={},n=kt(e,["allowedFunctionNames"]);null!=n&&Nt(t,["allowedFunctionNames"],n);const o=kt(e,["mode"]);if(null!=o&&Nt(t,["mode"],o),void 0!==kt(e,["streamFunctionCallArguments"]))throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["retrievalConfig"]);null!=o&&Nt(t,["retrievalConfig"],o);const i=kt(e,["includeServerSideToolInvocations"]);return null!=i&&Nt(t,["includeServerSideToolInvocations"],i),t}(l)),void 0!==kt(e,["kmsKeyName"]))throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(i,n),n}(this.apiClient,e);return s=Pt("cachedContents",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>e)}}async get(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Gn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>e)}{const t=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Gn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>e)}}async delete(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Gn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new tn;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Gn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"DELETE",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new tn;return Object.assign(n,t),n})}}async update(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);null!=o&&Nt(n,["_url","name"],Gn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["ttl"]);void 0!==t&&null!=n&&Nt(t,["ttl"],n);const o=kt(e,["expireTime"]);void 0!==t&&null!=o&&Nt(t,["expireTime"],o)}(i,n),n}(this.apiClient,e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"PATCH",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>e)}{const t=function(e,t){const n={},o=kt(t,["name"]);null!=o&&Nt(n,["_url","name"],Gn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["ttl"]);void 0!==t&&null!=n&&Nt(t,["ttl"],n);const o=kt(e,["expireTime"]);void 0!==t&&null!=o&&Nt(t,["expireTime"],o)}(i,n),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"PATCH",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>e)}}async listInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o)}(n,t),t}(e);return s=Pt("cachedContents",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["cachedContents"],e)}return t}(e),n=new nn;return Object.assign(n,t),n})}{const t=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o)}(n,t),t}(e);return s=Pt("cachedContents",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["cachedContents"],e)}return t}(e),n=new nn;return Object.assign(n,t),n})}}};function so(e){var t;if(null==e.candidates||0===e.candidates.length)return!1;const n=null===(t=e.candidates[0])||void 0===t?void 0:t.content;return void 0!==n&&ao(n)}function ao(e){if(void 0===e.parts||0===e.parts.length)return!1;for(const t of e.parts)if(void 0===t||0===Object.keys(t).length)return!1;return!0}function lo(e){if(void 0===e||0===e.length)return[];const t=[],n=e.length;let o=0;for(;o<n;)if("user"===e[o].role)t.push(e[o]),o++;else{const i=[];let r=!0;for(;o<n&&"model"===e[o].role;)i.push(e[o]),r&&!ao(e[o])&&(r=!1),o++;r?t.push(...i):t.pop()}return t}var uo=class{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new co(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},co=class{constructor(e,t,n,o={},i=[]){this.apiClient=e,this.modelsModule=t,this.model=n,this.config=o,this.history=i,this.sendPromise=Promise.resolve(),function(e){if(0!==e.length)for(const t of e)if("user"!==t.role&&"model"!==t.role)throw new Error(`Role must be user or model, but got ${t.role}.`)}(i)}async sendMessage(e){var t;await this.sendPromise;const n=On(e.message),o=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(n),config:null!==(t=e.config)&&void 0!==t?t:this.config});return this.sendPromise=(async()=>{var e,t,i;const r=await o,s=null===(t=null===(e=r.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content,a=r.automaticFunctionCallingHistory,l=this.getHistory(!0).length;let u=[];null!=a&&(u=null!==(i=a.slice(l))&&void 0!==i?i:[]);const c=s?[s]:[];this.recordHistory(n,c,u)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),o}async sendMessageStream(e){var t;await this.sendPromise;const n=On(e.message),o=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(n),config:null!==(t=e.config)&&void 0!==t?t:this.config});this.sendPromise=o.then(()=>{}).catch(()=>{});const i=await o;return this.processStreamResponse(i,n)}getHistory(e=!1){const t=e?lo(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return D(this,arguments,function*(){var n,o,i,r,s,a,l,u;const c=[];let d=!0,p=!1;try{for(var m,h=!0,f=M(e);!(n=(m=yield k(f.next())).done);h=!0){r=m.value,h=!1;const e=r;if(so(e)){const t=null===(a=null===(s=e.candidates)||void 0===s?void 0:s[0])||void 0===a?void 0:a.content;void 0!==t&&c.push(t)}else d=!1;void 0!==(null===(u=null===(l=e.candidates)||void 0===l?void 0:l[0])||void 0===u?void 0:u.finishReason)&&(p=!0),yield yield k(e)}}catch(v){o={error:v}}finally{try{h||n||!(i=f.return)||(yield k(i.call(f)))}finally{if(o)throw o.error}}this.recordHistory(t,d&&p?c:[])})}recordHistory(e,t,n){let o=[];t.length>0&&t.every(e=>void 0!==e.role)?o=t:o.push({role:"model",parts:[]}),n&&n.length>0?this.history.push(...lo(n)):this.history.push(e),this.history.push(...o)}},po=class e extends Error{constructor(t){super(t.message),this.name="ApiError",this.status=t.status,Object.setPrototypeOf(this,e.prototype)}},mo=class e extends Error{constructor(t){var n;super(t.message,{cause:t.cause}),this.name="ContinuationInterruptedError",void 0===this.cause&&(this.cause=t.cause),this.partialInteraction=t.partialInteraction,this.continuationToken=t.continuationToken,this.interactionId=t.interactionId,this.continuationIds=[...null!==(n=t.continuationIds)&&void 0!==n?n:[]],Object.setPrototypeOf(this,e.prototype)}};var ho=class extends Rt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new to(Gt.PAGED_ITEM_FILES,e=>this.listInternal(e),await this.listInternal(e),e)}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(e=>e)}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 t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o)}(n,t),t}(e);return i=Pt("files",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["files"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["files"],e)}return t}(e),n=new ln;return Object.assign(n,t),n})}}async createInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["file"]);return null!=n&&Nt(t,["file"],n),t}(e);return i=Pt("upload/{api_version}/files",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new un;return Object.assign(n,t),n})}}async get(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","file"],qn(n)),t}(e);return i=Pt("files/{file}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async delete(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","file"],qn(n)),t}(e);return i=Pt("files/{file}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new cn;return Object.assign(n,t),n})}}async registerFilesInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["uris"]);return null!=n&&Nt(t,["uris"],n),t}(e);return i=Pt("files:register",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["files"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["files"],e)}return t}(e),n=new dn;return Object.assign(n,t),n})}}},fo=/* @__PURE__ */new Set([void 0,"in_progress","requires_continuation"]),vo=/* @__PURE__ */new Set(["interaction.created","interaction.status_update"]),go={cached_tokens_by_modality:["modality","tokens"],input_tokens_by_modality:["modality","tokens"],output_tokens_by_modality:["modality","tokens"],tool_use_tokens_by_modality:["modality","tokens"],grounding_tool_count:["type","count"]},_o=!1;function yo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Eo(e,t){return yo(e)?e[t]:void 0}function To(e){return"string"==typeof e&&e?e:void 0}function Ao(e){return"number"==typeof e&&Number.isInteger(e)}function Io(e){return null==e}var Co=class e extends Error{constructor(t){super(t),this.name="ContinuationTimeoutError",Object.setPrototypeOf(this,e.prototype)}},So=class{constructor(e,t={}){var n,o;this.timeoutMs=e,this.now=null!==(n=t.now)&&void 0!==n?n:Date.now,(null===(o=t.enabled)||void 0===o||o)&&"number"==typeof e&&Number.isFinite(e)&&(this.deadlineMs=this.now()+e)}get bounded(){return void 0!==this.deadlineMs}remainingMs(){if(void 0!==this.deadlineMs)return this.deadlineMs-this.now()}expired(){const e=this.remainingMs();return void 0!==e&&e<=0}hopTimeoutMs(){const e=this.remainingMs();return void 0===e?this.timeoutMs:Math.max(1,Math.ceil(e))}check(){if(this.expired())throw new Co(`interactions.create() timed out after ${this.timeoutMs} ms before automatic continuation finished. Increase the timeout (it bounds the whole call, across continuation hops) or resume from the continuation_token.`)}};function bo(e,t,n){return void 0===t?e.body:function(e,t,n){if(!n||!1===e.store)return Object.assign(Object.assign({},e),{continuation_token:t});const{input:o}=e,i=N(e,["input"]);return Object.assign(Object.assign({},i),{continuation_token:t,previous_interaction_id:n})}(e.body,t,n)}function Oo(){_o||(_o=!0)}function wo(e,t,n){const o=Eo(e,"event_type");if("error"===o)return["error",void 0];const i=Eo(e,"interaction");if(null!=i){const e=To(Eo(i,"status"));e&&(t=e);const r=To(Eo(i,"continuation_token"));("interaction.completed"===o||r)&&(n=r)}const r=To(Eo(e,"status"));r&&(t=r);const s=To(Eo(e,"continuation_token"));return s&&(n=s),[t,n]}function Ro(e,t){return!!t&&fo.has(e)}var Po=class{constructor(e){this.options=e,this.hopIds=[],this.noProgressReconnects=0,this.nextToken=e.initialContinuationToken,this.initialToken=e.initialContinuationToken,this.hop={startToken:this.nextToken,startTokenOwnerId:void 0,token:this.nextToken,tokenOwnerId:void 0,interactionId:void 0,status:void 0,streamOpened:!1,contentSinceCheckpoint:!1}}startHop(e=!1){return this.hop={startToken:this.nextToken,startTokenOwnerId:this.nextTokenOwnerId,token:this.nextToken,tokenOwnerId:this.nextTokenOwnerId,interactionId:void 0,status:void 0,streamOpened:e,contentSinceCheckpoint:!1},[this.nextToken,this.nextTokenOwnerId]}markStreamOpened(){this.hop.streamOpened=!0}observe(e){const t=this.hop;t.streamOpened=!0;const n=function(e){var t;return null!==(t=To(Eo(e,"interaction_id")))&&void 0!==t?t:To(Eo(Eo(e,"interaction"),"id"))}(e);n&&(t.interactionId=n,this.hopIds.includes(n)||this.hopIds.push(n));const o=t.token;return[t.status,t.token]=wo(e,t.status,t.token),t.token&&t.token!==o&&(t.tokenOwnerId=t.interactionId),t.contentSinceCheckpoint=function(e,t){const n=Eo(e,"event_type");return"interaction.status_update"===n?!To(Eo(e,"continuation_token"))&&t:"interaction.completed"!==n&&("string"!=typeof n||!vo.has(n)||t)}(e,t.contentSinceCheckpoint),e}canResumeHop(){const e=this.hop;return!e.contentSinceCheckpoint&&Ro(e.status,e.token)}fail(e){const t=this.hop,n=Ro(t.status,t.token)?t.token:void 0;return n&&n!==this.initialToken?new mo({message:`Automatic continuation of the stream was interrupted: ${No(e.error)}. The continuationToken can be used to resume (output yielded after a mid-hop checkpoint is re-generated).`,cause:e.error,partialInteraction:void 0,continuationToken:n,interactionId:!1!==this.options.store?t.tokenOwnerId:void 0,continuationIds:[...this.hopIds]}):e.error}endHop(e){var t,n;const o=this.hop;if(e&&(e.error instanceof Co||(null===(n=(t=this.options).isFatalError)||void 0===n?void 0:n.call(t,e.error))))throw this.fail(e);if(e&&!o.streamOpened&&!this.options.isConnectionError(e.error))throw this.fail(e);if(!this.canResumeHop()){if(e)throw this.fail(e);return!1}if("requires_continuation"===o.status&&o.token===o.startToken){if(e)throw this.fail(e);return!1}var i,r,s,a;if(this.noProgressReconnects=(i=this.noProgressReconnects,r=o.status,s=o.startToken,a=o.token,"requires_continuation"===r||a!==s?0:i+1),0===this.noProgressReconnects&&(this.lastError=void 0),e&&(this.lastError=e),this.noProgressReconnects>3){if(this.lastError)throw this.fail(this.lastError);return!1}return this.nextToken=o.token,this.nextTokenOwnerId=o.tokenOwnerId,!0}};function No(e){return e instanceof Error?e.message||e.name:String(e)}async function ko(e){if(null==e?void 0:e.return)try{await e.return()}catch(Rr){}}function Do(e){if("requires_continuation"===Eo(e,"status"))return To(Eo(e,"continuation_token"))}function Mo(e,t){const n=Do(e);if(n!==t)return n}function xo(e){return yo(e)&&Array.isArray(e.steps)?e:void 0}function Go(e,t,n,o){const i=Lo(t,o),r=!1!==o.store&&!1!==Eo(t[0],"store");return new mo({message:`Automatic continuation was interrupted after ${t.length} completed hop(s): ${No(e)}. The partial interaction (status 'requires_continuation') and its continuationToken can be used to resume.`,cause:e,partialInteraction:i,continuationToken:n,interactionId:r?To(Eo(t[t.length-1],"id")):void 0,continuationIds:Uo(t)})}function Uo(e){const t=[];for(const n of e){const e=Eo(n,"continuation_ids");if(Array.isArray(e))for(const n of e)To(n)&&t.push(n);const o=To(Eo(n,"id"));o&&t.push(o)}return Array.from(new Set(t))}function Lo(e,t={}){var n,o;const i=null!==(n=t.normalizeInteraction)&&void 0!==n?n:xo,r=null!==(o=t.finalizeInteraction)&&void 0!==o?o:e=>e,s=e[e.length-1],a=i(s);if(!a)return s;const l=[];e.forEach((e,t)=>{let n=Eo(e,"steps");Array.isArray(n)&&(t>0&&(n=function(e){let t=0;for(;t<e.length&&"user_input"===Eo(e[t],"type");)t++;return e.slice(t)}(n)),l.push(...n))});const u=Object.assign(Object.assign({},a),{steps:l,continuation_ids:Uo(e)});if(e.length>1)for(const d of["previous_interaction_id","created","input"]){const t=Eo(e[0],d);void 0===t?delete u[d]:u[d]=t}const c=function(e){if(0===e.length)return;const t=e[0],n=e[e.length-1],o=[];for(const a of e)for(const e of Object.keys(a))o.includes(e)||o.push(e);const i={};for(const a of o){if("initial_input_tokens"===a)continue;const t=e.map(e=>e[a]).filter(e=>!Io(e));if(0!==t.length)if(t.every(Ao))i[a]=t.reduce((e,t)=>e+t,0);else if(a in go&&t.every(e=>Array.isArray(e))){const[e,n]=go[a];i[a]=qo(t,e,n)}}const r=Io(t.initial_input_tokens)?t.total_input_tokens:t.initial_input_tokens,s=Object.assign(Object.assign({},n),i);return Io(r)?delete s.initial_input_tokens:s.initial_input_tokens=r,s}(e.map(e=>Eo(e,"usage")).filter(yo));return void 0!==c&&(u.usage=c),r(u)}function qo(e,t,n){const o=/* @__PURE__ */new Map;for(const i of e)for(const e of i){const i=Eo(e,t),r=Eo(e,n),s=o.get(i);if(void 0===s){o.set(i,e);continue}const a=Eo(s,n);Ao(a)&&Ao(r)&&yo(s)&&o.set(i,Object.assign(Object.assign({},s),{[n]:a+r}))}return Array.from(o.values())}var Ho=Object.prototype.hasOwnProperty;function jo(e,t){const n=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(t={}){return e.replace(n,function(e,n){if(!Ho.call(t,n))throw new Error(`Parameter '${n}' is required`);const o=t[n];if("string"!=typeof o&&"number"!=typeof o)throw new Error(`Parameter '${n}' must be a string or number`);return`${o}`}).replace(/^\/+/,"")}}var Fo=["https://generativelanguage.googleapis.com"],Xo="speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai",Bo=void 0;function Vo(){var e,t,n,o,i,r;if(Bo)return Bo;const s=globalThis;let a={};return a="Deno"in globalThis?null!==(o=null===(n=null===(t=null===(e=s.Deno)||void 0===e?void 0:e.env)||void 0===t?void 0:t.toObject)||void 0===n?void 0:n.call(t))&&void 0!==o?o:{}:null!==(r=null===(i=s.process)||void 0===i?void 0:i.env)&&void 0!==r?r:{},Bo=a}var Jo=Symbol.for("undici.globalDispatcher.1"),$o=class{constructor(e){this.options=e}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(e){return function(e){var t,n;const o={};for(const[r,s]of e){const e=r.toLowerCase();"authorization"!==e&&"x-goog-api-key"!==e&&(o[r]=s)}const i={access_token:null!==(t=e.get("authorization"))&&void 0!==t?t:void 0,api_key:null!==(n=e.get("x-goog-api-key"))&&void 0!==n?n:void 0,default_headers:Object.keys(o).length?o:void 0};return ei(i)?i:void 0}(await this.options.getAuthHeaders(e))}},Wo=class{beforeCreateRequest(e,t){var n;const o=Object.assign({},null!==(n=t.options)&&void 0!==n?n:{});return!function(){var e,t;return"string"==typeof(null===(t=null===(e=globalThis.process)||void 0===e?void 0:e.versions)||void 0===t?void 0:t.node)}()||function(e){if(!e||"object"!=typeof e)return!1;if("options"in e){const t=e.options;return Boolean(null==t?void 0:t.fetcher)}return!0}(e.options.http_client)||"dispatcher"in o||(o.dispatcher={dispatch(e,t){const n=globalThis[Jo];if(!n||"function"!=typeof n.dispatch)throw new TypeError("Undici globalDispatcher is not available in this Node.js runtime.");return n.dispatch(Object.assign(Object.assign({},e),{headersTimeout:0,bodyTimeout:0}),t)}}),Object.assign(Object.assign({},t),{url:Yo(t.url),options:o})}async beforeRequest(e,t){if(zo(t.headers,function(e){var t,n;return Qo(e)?null!==(n=null===(t=e.getDefaultHeaders)||void 0===t?void 0:t.call(e))&&void 0!==n?n:e.defaultHeaders:Zo(e)?e.default_headers:void 0}(e.security_source)),function(e,t){void 0!==e.options.user_project&&null===t.get("x-goog-user-project")&&t.set("x-goog-user-project",e.options.user_project)}(e,t.headers),null!==(n=t.headers).get("authorization")||null!==n.get("x-goog-api-key"))return t;var n;const o=await async function(e,t){if(Qo(e))return e.resolveGoogleGenAISecurity(t);const n="function"==typeof e?await e():e;return Zo(n)?Ko(n):Ko(void 0)}(e.security_source,t.url);return zo(t.headers,null==o?void 0:o.default_headers),function(e,t){var n;t&&(t.api_key?e.set("x-goog-api-key",t.api_key):t.access_token&&e.set("Authorization","bearer "===(n=t.access_token).slice(0,7).toLowerCase()?n:`Bearer ${n}`))}(t.headers,o),t}};function Yo(e){const[,t,...n]=e.pathname.split("/");if(!t)return e;const o=decodeURIComponent(t);if(!o.includes("/"))return e;const i=new URL(e);return i.pathname=`/${o}/${n.join("/")}`,i}function Ko(e){var t,n;const o=Vo(),i=Object.assign(Object.assign({},e),{api_key:null!==(t=null==e?void 0:e.api_key)&&void 0!==t?t:o.GOOGLE_GENAI_API_KEY,access_token:null!==(n=null==e?void 0:e.access_token)&&void 0!==n?n:o.GOOGLE_GENAI_ACCESS_TOKEN});return ei(i)?i:void 0}function zo(e,t){if(t)for(const[n,o]of new Headers(t)){const t=e.get(n);(null===t||"user-agent"===n.toLowerCase()&&t===Xo)&&e.set(n,o)}}function Zo(e){return"object"==typeof e&&null!==e}function Qo(e){return"object"==typeof e&&null!==e&&"resolveGoogleGenAISecurity"in e&&"function"==typeof e.resolveGoogleGenAISecurity}function ei(e){return void 0!==e.api_key||void 0!==e.access_token||void 0!==e.default_headers}var ti=class extends Error{constructor(e,t){let n=e;(null==t?void 0:t.cause)&&(n+=`: ${t.cause}`),super(n,t),this.name="HTTPClientError",void 0===this.cause&&(this.cause=null==t?void 0:t.cause)}},ni=class extends ti{constructor(){super(...arguments),this.name="UnexpectedClientError"}},oi=class extends ti{constructor(){super(...arguments),this.name="InvalidRequestError"}},ii=class extends ti{constructor(){super(...arguments),this.name="RequestAbortedError"}},ri=class extends ti{constructor(){super(...arguments),this.name="RequestTimeoutError"}},si=class extends ti{constructor(){super(...arguments),this.name="ConnectionError"}},ai=class extends Error{constructor(e,t){var n,o,i,r;super(e),this.statusCode=null===(n=null==t?void 0:t.response)||void 0===n?void 0:n.status,this.body=null!==(o=null==t?void 0:t.body)&&void 0!==o?o:"",this.headers=null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.headers,this.contentType=(null===(r=null==t?void 0:t.response)||void 0===r?void 0:r.headers.get("content-type"))||"",this.rawResponse=null==t?void 0:t.response,this.name="GoogleGenAiError",Object.setPrototypeOf(this,new.target.prototype)}};function li(e,t,n,o){return e&&o?400===e?new di(e,t,n,o):401===e?new pi(e,t,n,o):403===e?new mi(e,t,n,o):404===e?new hi(e,t,n,o):409===e?new fi(e,t,n,o):422===e?new vi(e,t,n,o):429===e?new gi(e,t,n,o):e>=500?new _i(e,t,n,o):new O(e,t,n,o):new w({message:n,cause:t instanceof Error?t:void 0})}O.generate=li;var ui=class extends O{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ci=class extends w{constructor({message:e}={}){super({message:e||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}},di=class extends O{},pi=class extends O{},mi=class extends O{},hi=class extends O{},fi=class extends O{},vi=class extends O{},gi=class extends O{},_i=class extends O{};function yi(e){return"object"==typeof(t=e)&&null!==t&&O.prototype.isPrototypeOf(t)?e:function(e){return e instanceof ai||e instanceof Error&&"number"==typeof e.statusCode&&"string"==typeof e.body}(e)?function(e){const t=function(e){const t=Ti(e,"data$");if(t&&"object"==typeof t)return t;try{const t=JSON.parse(e.body);if(t&&"object"==typeof t)return t}catch(Rr){}const n=Ti(e,"error");return n&&"object"==typeof n?n:void 0}(e),n=li(e.statusCode,t,e.message,e.headers);return Ai(n,"body",e.body),Ai(n,"contentType",e.contentType),Ai(n,"rawResponse",e.rawResponse),Ai(n,"statusCode",e.statusCode),Ai(n,"cause",e),n}(e):function(e){return e instanceof ti||e instanceof Error&&Ei.has(e.name)}(e)?function(e){return e instanceof ri||"RequestTimeoutError"===e.name?new ci({message:e.message}):e instanceof ii||"RequestAbortedError"===e.name?new ui({message:e.message}):(e instanceof si||e.name,new w({message:e.message,cause:e}))}(e):e;var t}var Ei=/* @__PURE__ */new Set(["HTTPClientError","UnexpectedClientError","InvalidRequestError","RequestAbortedError","RequestTimeoutError","ConnectionError"]);function Ti(e,t){return e&&"object"==typeof e?e[t]:void 0}function Ai(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!1})}function Ii(e){try{return JSON.parse(e)}catch(Rr){return e}}var Ci=function(e,t){const n=new ReadableStream(e,t);return Object.setPrototypeOf(n,Object.getPrototypeOf(this)),n};Ci.prototype=ReadableStream.prototype;var Si=class extends Ci{constructor(e,t,n){var o;const i=e.getReader();let r=/* @__PURE__ */new Uint8Array(4096),s=0,a=0;const l={eventId:void 0},u=null===(o=null==n?void 0:n.dataRequired)||void 0===o||o;super({async pull(e){try{for(;;){const n=Pi(r,s,a);if(!n){a=Math.max(0,s-Ri+1);const t=await i.read();if(t.done)return e.close();if(s+t.value.length>r.length){const e=new Uint8Array(Math.max(2*r.length,s+t.value.length));e.set(r.subarray(0,s)),r=e}r.set(t.value,s),s+=t.value.length;continue}const o=r.slice(0,n.index);if(r.copyWithin(0,n.index+n.length,s),s-=n.index+n.length,r.length>4096&&s<=r.length>>2){const e=new Uint8Array(Math.max(4096,2*s));e.set(r.subarray(0,s)),r=e}a=0;const c=Ni(o,t,l,u);if(c&&!c.done)return e.enqueue(c.value);if(null==c?void 0:c.done)return await i.cancel("done"),e.close()}}catch(n){e.error(n),await i.cancel(n)}},cancel:e=>i.cancel(e)})}[Symbol.asyncIterator](e){const t=ReadableStream.prototype[Symbol.asyncIterator];if("function"==typeof t)return t.call(this,e);const n=this.getReader(),o={next:async()=>{const e=await n.read();return e.done?(n.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}},throw:async e=>(await n.cancel(e),n.releaseLock(),{done:!0,value:void 0}),return:async()=>(await n.cancel("done"),n.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},i=Symbol.asyncDispose;return i&&(o[i]=async()=>{var e;await(null===(e=o.return)||void 0===e?void 0:e.call(o))}),o}values(e){return this[Symbol.asyncIterator](e)}},bi=13,Oi=10,wi=[[bi,Oi,bi,Oi],[bi,Oi,bi],[bi,Oi,Oi],[bi,bi,Oi],[Oi,bi,Oi],[bi,bi],[Oi,bi],[Oi,Oi]],Ri=wi.reduce((e,t)=>Math.max(e,t.length),0);function Pi(e,t,n){for(let o=n;o<t;o++)if(e[o]===bi||e[o]===Oi)for(const n of wi){if(o+n.length>t)continue;let i=!0;for(let t=0;t<n.length;t++)if(e[o+t]!==n[t]){i=!1;break}if(i)return{index:o,length:n.length}}return null}function Ni(e,t,n,o){const i=(new TextDecoder).decode(e).split(/\r\n|\r|\n/),r=[],s={};let a=!0;for(const l of i){if(!l||l.startsWith(":"))continue;a=!1;const e=l.indexOf(":");let t=l,o="";e>0&&(t=l.slice(0,e),o=" "===l[e+1]?l.slice(e+2):l.slice(e+1)),"data"===t?r.push(o):"event"===t?s.event=o:"id"!==t||o.includes("\0")?"retry"===t&&/^\d+$/.test(o)&&(s.retry=Number(o)):n.eventId=o}if(!a){if(s.id=n.eventId,r.length)s.data=r.join("\n");else if(o)return;return t(s)}}var ki=(e,t)=>null==t?fetch(e):fetch(e,t),Di=class e{constructor(e={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=e,this.fetcher=e.fetcher||ki}async request(e){let t=e;for(const o of this.requestHooks){const e=await o(t);e&&(t=e)}try{const e=await this.fetcher(t);for(const n of this.responseHooks)await n(e,t);return e}catch(n){for(const e of this.requestErrorHooks)await e(n,t);throw n}}addHook(...e){if("beforeRequest"===e[0])this.requestHooks.push(e[1]);else if("requestError"===e[0])this.requestErrorHooks.push(e[1]);else{if("response"!==e[0])throw new Error(`Invalid hook type: ${e[0]}`);this.responseHooks.push(e[1])}return this}removeHook(...e){let t;if("beforeRequest"===e[0])t=this.requestHooks;else if("requestError"===e[0])t=this.requestErrorHooks;else{if("response"!==e[0])throw new Error(`Invalid hook type: ${e[0]}`);t=this.responseHooks}const n=t.findIndex(t=>t===e[1]);return n>=0&&t.splice(n,1),this}clone(){const t=new e(this.options);return t.requestHooks=this.requestHooks.slice(),t.requestErrorHooks=this.requestErrorHooks.slice(),t.responseHooks=this.responseHooks.slice(),t}},Mi=/\s*;\s*/g;function xi(e,t){var n;if("*"===t)return!0;let o=(null===(n=e.headers.get("content-type"))||void 0===n?void 0:n.trim())||"application/octet-stream";o=o.toLowerCase();const[i="",...r]=t.toLowerCase().trim().split(Mi);if(2!==i.split("/").length)return!1;const[s="",...a]=o.split(Mi),[l="",u=""]=s.split("/");if(!l||!u)return!1;if("*/*"!==i&&s!==i&&`${l}/*`!==i&&`*/${u}`!==i)return!1;if(a.length<r.length)return!1;const c=new Set(a);for(const d of r)if(!c.has(d))return!1;return!0}var Gi=/* @__PURE__ */new RegExp("^[0-9]xx$","i");function Ui(e,t){const n=`${e.status}`,o=Array.isArray(t)?t:[t];return!!o.length&&o.some(e=>{const t=`${e}`;if("default"===t)return!0;if(!Gi.test(`${t}`))return t===n;const o=t.charAt(0);if(!o)throw new Error("Invalid status code range");const i=n.charAt(0);if(!i)throw new Error(`Invalid response status code: ${n}`);return i===o})}function Li(e,t,n){return Ui(e,t)&&xi(e,n)}function qi(e){if("object"!=typeof e||null==e)return!1;const t=e instanceof TypeError&&e.message.toLowerCase().startsWith("failed to fetch"),n=e instanceof TypeError&&e.message.toLowerCase().startsWith("fetch failed"),o="name"in e&&"ConnectionError"===e.name,i="code"in e&&"string"==typeof e.code&&"econnreset"===e.code.toLowerCase();return t||n||i||o}function Hi(e){if("object"!=typeof e||null==e)return!1;const t="name"in e&&"TimeoutError"===e.name,n="code"in e&&23===e.code,o="code"in e&&"string"==typeof e.code&&"econnaborted"===e.code.toLowerCase();return t||n||o}var ji=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];for(const e of[])"sdkInit"in e&&this.registerSDKInitHook(e),"beforeCreateRequest"in e&&this.registerBeforeCreateRequestHook(e),"beforeRequest"in e&&this.registerBeforeRequestHook(e),"afterSuccess"in e&&this.registerAfterSuccessHook(e),"afterError"in e&&this.registerAfterErrorHook(e);!function(e){const t=new Wo;e.registerBeforeCreateRequestHook(t),e.registerBeforeRequestHook(t)}(this)}registerSDKInitHook(e){this.sdkInitHooks.push(e)}registerBeforeCreateRequestHook(e){this.beforeCreateRequestHooks.push(e)}registerBeforeRequestHook(e){this.beforeRequestHooks.push(e)}registerAfterSuccessHook(e){this.afterSuccessHooks.push(e)}registerAfterErrorHook(e){this.afterErrorHooks.push(e)}sdkInit(e){return this.sdkInitHooks.reduce((e,t)=>t.sdkInit(e),e)}beforeCreateRequest(e,t){let n=t;for(const o of this.beforeCreateRequestHooks)n=o.beforeCreateRequest(e,n);return n}async beforeRequest(e,t){let n=t;for(const o of this.beforeRequestHooks)n=await o.beforeRequest(e,n);return n}async afterSuccess(e,t){let n=t;for(const o of this.afterSuccessHooks)n=await o.afterSuccess(e,n);return n}async afterError(e,t,n){let o=t,i=n;for(const r of this.afterErrorHooks){const t=await r.afterError(e,o,i);o=t.response,i=t.error}return{response:o,error:i}}};function Fi(e){return{ok:!0,value:e}}function Xi(e){return{ok:!1,error:e}}function Bi(e){return btoa(String.fromCodePoint(...e))}function Vi(...e){const t=[];for(const n of e)n&&t.push(n);switch(t.length){case 0:case 1:return t[0]||null;default:return"any"in AbortSignal&&"function"==typeof AbortSignal.any?AbortSignal.any(t):function(e){const t=new AbortController,n=t.signal;if(!e.length)return t.signal;if(1===e.length)return e[0]||t.signal;for(const r of e)if(r.aborted)return r;function o(){t.abort(this.reason),function(){for(const e of i){const t=e.deref();t&&t.removeEventListener("abort",o)}}()}const i=[];for(const r of e)i.push(new WeakRef(r)),r.addEventListener("abort",o);return n}(t)}}function Ji(e){const t={};for(const[n,o]of Object.entries(e))void 0!==o&&(t[n]=o);return t}function $i(e){if(null===e||"object"!=typeof e)return!1;if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);if(null===t||t===Object.prototype)return!0;try{return null===Object.getPrototypeOf(t)}catch(Rr){return!1}}var Wi=/%(2[346bcf]|3[abdf]|40|5[bd])/gi;function Yi(e,t){return Ki(e,"percentExceptReserved"===t?"percent":t)}function Ki(e,t){switch(t){case"percent":return encodeURIComponent(e);case"percentExceptReserved":return encodeURIComponent(e).replace(Wi,e=>decodeURIComponent(e));default:return e}}var zi=(e,t,n)=>{let o="";const i=(null==n?void 0:n.explode)?er(e,t):[[e,t]];if(i.every(([e,t])=>null==t))return;const r=e=>Ki(e,null==n?void 0:n.charEncoding),s=e=>r(tr(e)),a=r(",");return i.forEach(([e,t])=>{var i,l;let u="",c=null;null!=t&&(c=Array.isArray(t)?null===(i=or(t,e=>`${s(e)}`))||void 0===i?void 0:i.join(a):$i(t)?null===(l=ir(Object.entries(t),([e,t])=>`${r(e)}${a}${s(t)}`))||void 0===l?void 0:l.join(a):`${s(t)}`,null!=c&&(u=`${Yi(e,null==n?void 0:n.charEncoding)}=${c}`,u&&"="!==u&&(o+=`&${u}`)))}),o.slice(1)};function Zi(e,t,n){if(void 0===t)return;const o=Ki(JSON.stringify(t,nr),null==n?void 0:n.charEncoding);return(null==n?void 0:n.explode)?o:`${Yi(e,null==n?void 0:n.charEncoding)}=${o}`}var Qi=(e,t,n)=>{let o="";const i=(null==n?void 0:n.explode)?er(e,t):[[e,t]];if(i.every(([e,t])=>null==t))return;const r=e=>Ki(e,null==n?void 0:n.charEncoding),s=e=>r(tr(e));return i.forEach(([e,i])=>{var a;let l="";if(null!=i){if(Array.isArray(i))l=null===(a=or(i,e=>`${s(e)}`))||void 0===a?void 0:a.join(",");else if($i(i)){const e=ir(Object.entries(i),([e,t])=>`,${r(e)},${s(t)}`);l=null==e?void 0:e.join("").slice(1)}else l=`${(null==n?void 0:n.explode)&&$i(t)?`${e}=`:""}${s(i)}`;o+=l?`,${l}`:""}}),o.slice(1)};function er(e,t){return Array.isArray(t)?t.map(t=>[e,t]):$i(t)?Object.entries(null!=t?t:{}).map(([e,t])=>[e,t]):[[e,t]]}function tr(e){return null==e?"":e instanceof Date?e.toISOString():e instanceof Uint8Array?Bi(e):"object"==typeof e?JSON.stringify(e,nr):`${e}`}function nr(e,t){return t instanceof Uint8Array?Bi(t):t}function or(e,t){const n=e.reduce((e,n)=>{if(null==n)return e;const o=t(n);return null==o||e.push(o),e},[]);return n.length?n:null}function ir(e,t){const n=[];for(const[o,i]of e){if(null==i)continue;const e=t([o,i]);null!=e&&n.push(e)}return n.length?n:null}var rr,sr=(rr=zi,function(e,t){var n,o,i;const r=Object.assign(Object.assign({},t),{explode:null===(n=null==t?void 0:t.explode)||void 0===n||n,charEncoding:null!==(o=null==t?void 0:t.charEncoding)&&void 0!==o?o:"percent"}),s=new Set(null!==(i=null==t?void 0:t.allowEmptyValue)&&void 0!==i?i:[]);return function(...e){return e.filter(Boolean).join("&")}(...Object.entries(e).map(([e,t])=>s.has(e)&&(null==t||""===t||Array.isArray(t)&&0===t.length)?`${encodeURIComponent(e)}=`:rr(e,t,r)))}),ar={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},lr=class e extends Error{constructor(t,n){let o=t;(null==n?void 0:n.cause)&&(o+=`: ${n.cause}`),super(o,n),this.name="PermanentError",void 0===this.cause&&(this.cause=null==n?void 0:n.cause),Object.setPrototypeOf(this,e.prototype)}},ur=class e extends Error{constructor(t,n){super(t),this.response=n,this.name="TemporaryError",Object.setPrototypeOf(this,e.prototype)}};function cr(e,t){return async n=>{try{const o=await e(n);if(function(e,t){const n=`${e.status}`;return t.some(e=>{if(!dr.test(e))return e===n;const t=e.charAt(0);if(!t)throw new Error("Invalid status code range");const o=n.charAt(0);if(!o)throw new Error(`Invalid response status code: ${n}`);return o===t})}(o,t.statusCodes))throw new ur("Response failed with retryable status code",o);return o}catch(o){if(o instanceof ur)throw o;if(t.retryConnectionErrors&&(Hi(o)||qi(o)))throw o;throw new lr("Permanent error",{cause:o})}}}var dr=/* @__PURE__ */new RegExp("^[0-9]xx$","i");function pr(e){const t=e.headers.get("retry-after-ms");if(t){const e=Number(t);if(Number.isFinite(e)&&e>=0)return e}const n=e.headers.get("retry-after")||"";if(!n)return 0;const o=Number(n);if(Number.isInteger(o))return 1e3*o;const i=Date.parse(n);if(Number.isInteger(i)){const e=i-Date.now();return e>0?Math.ceil(e):0}return 0}async function mr(e){return new Promise(t=>setTimeout(t,e))}var hr="undefined"==typeof globalThis?null:globalThis,fr="object"==typeof hr&&null!=hr&&"importScripts"in hr&&"function"==typeof hr.importScripts||"undefined"!=typeof navigator&&"serviceWorker"in navigator||"object"==typeof window&&void 0!==window.document,vr=class{constructor(e={}){const t=e;"object"==typeof t&&null!=t&&"hooks"in t&&t.hooks instanceof ji?this._hooks=t.hooks:this._hooks=new ji;const n=new Di;e.http_client=e.http_client||n;const o=function(e){var t;let n=e.server_url;if(!n){const o=null!==(t=e.server_idx)&&void 0!==t?t:0;if(o<0||o>=Fo.length)throw new Error(`Invalid server index ${o}`);n=Fo[o]||""}const o=jo(n)({});return new URL(o)}(e=this._hooks.sdkInit(e));o&&(o.pathname=o.pathname.replace(/\/+$/,"")+"/"),this._baseURL=o,this._httpClient=e.http_client||n,this._options=Object.assign(Object.assign({},function(e){var t,n;const o=Object.assign({},e),i=Vo();return void 0!==i.GOOGLE_GENAI_API_VERSION&&(null!==(t=o.api_version)&&void 0!==t||(o.api_version=i.GOOGLE_GENAI_API_VERSION)),void 0!==i.GOOGLE_GENAI_USER_PROJECT&&(null!==(n=o.user_project)&&void 0!==n||(o.user_project=i.GOOGLE_GENAI_USER_PROJECT)),o}(e)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&Vo().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(e,t,n){var o,i,r,s,a;const{method:l,path:u,query:c,headers:d,security:p}=t,m=null!==(o=t.baseURL)&&void 0!==o?o:this._baseURL;if(!m)return Xi(new oi("No base URL provided for operation"));const h=new URL(m);let f;u?(h.pathname=h.pathname.replace(/\/+$/,"")+"/",f=new URL(u,h),!f.search&&h.search&&(f.search=h.search)):f=h,f.hash="";const v=e=>Object.entries(e).map(([e,t])=>{if(null==t)return;const n=$i(t)?JSON.stringify(t):t;return zi(e,n,{explode:Array.isArray(n),charEncoding:"percent"})}).filter(e=>void 0!==e).join("&"),g=[c||"",v((null==n?void 0:n.extra_query)||{}),v((null==p?void 0:p.queryParams)||{})].reduce((e,t)=>{if(!t)return e;const n=new Set(t.split("&").filter(e=>""!==e).map(e=>{var t;return null!==(t=e.split("=")[0])&&void 0!==t?t:""}));return[...e.split("&").filter(e=>{var t;return""!==e&&!n.has(null!==(t=e.split("=")[0])&&void 0!==t?t:"")}),t].join("&")},f.search.slice(1));g&&(f.search=`?${g}`);const _=new Headers(d),y=null==p?void 0:p.basic.username,E=null==p?void 0:p.basic.password;if(null!=y||null!=E){const e=Bi(function(e){return(new TextEncoder).encode(e)}([y||"",E||""].join(":")));_.set("Authorization",`Basic ${e}`)}const T=new Headers((null==p?void 0:p.headers)||{});for(const[R,P]of T)_.set(R,P);let A=_.get("cookie")||"";for(const[R,P]of Object.entries((null==p?void 0:p.cookies)||{}))A+=`; ${R}=${P}`;A=A.startsWith("; ")?A.slice(2):A,_.set("cookie",A);const I=new Headers(null!==(i=null==n?void 0:n.headers)&&void 0!==i?i:null===(r=null==n?void 0:n.fetch_options)||void 0===r?void 0:r.headers);for(const[R,P]of I)_.set(R,P);fr||_.set(null!==(s=t.uaHeader)&&void 0!==s?s:"user-agent",null!==(a=t.userAgent)&&void 0!==a?a:Xo);let C=t.body;const S=Object.fromEntries(Object.entries((null==n?void 0:n.extra_body)||{}).filter(([,e])=>void 0!==e));if(Object.keys(S).length>0){const e=new Headers(d).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(e)||"string"!=typeof C&&null!=C)return Xi(new oi("extra_body can only be merged into JSON object request bodies"));let t;try{t=C?JSON.parse(C):{}}catch(w){return Xi(new oi("extra_body can only be merged into JSON object request bodies",{cause:w}))}if(!$i(t))return Xi(new oi("extra_body can only be merged into JSON object request bodies"));C=JSON.stringify(Object.assign(Object.assign({},t),S)),_.delete("content-length")}const b=Object.assign(Object.assign({},null==n?void 0:n.fetch_options),n);let O;!(null==b?void 0:b.signal)&&null!=t.timeout_ms&&t.timeout_ms>0&&(e.timeout_ms=t.timeout_ms),t.body instanceof ReadableStream&&Object.assign(b,{duplex:"half"});try{O=this._hooks.beforeCreateRequest(e,{url:f,options:Object.assign(Object.assign({},b),{body:null!=C?C:null,headers:_,method:l})})}catch(w){return Xi(new ni("Create request hook failed to execute",{cause:w}))}return Fi(new Request(O.url,O.options))}async _do(e,t){const{context:n,isErrorStatusCode:o}=t,i=n.timeout_ms;return async function(e,t){var n;switch(t.config.strategy){case"backoff":return async function(e,t){const{maxElapsedTime:n,initialInterval:o,exponent:i,maxInterval:r}=t,s=Date.now();let a=0;for(;;)try{return await e(a)}catch(l){if(l instanceof lr)throw l.cause;if(Date.now()-s>n){if(l instanceof ur)return l.response;throw l}let e=0;l instanceof ur&&(e=pr(l.response)),e<=0&&(e=o*Math.pow(a,i)+1e3*Math.random()),await mr(Math.min(e,r)),a++}}(cr(e,{statusCodes:t.statusCodes,retryConnectionErrors:!!t.config.retryConnectionErrors}),null!==(n=t.config.backoff)&&void 0!==n?n:ar);case"attempt-count-backoff":return async function(e,t,n){let o=0;for(;;)try{return await e(o)}catch(i){if(i instanceof lr)throw i.cause;if(o>=n.maxRetries){if(i instanceof ur)return i.response;throw i}let e=0;i instanceof ur&&(e=pr(i.response)),e<=0&&(e=t.initialInterval*Math.pow(t.exponent,o)*(1-.25*Math.random())),await mr(Math.min(e,t.maxInterval)),o++}}(cr(e,{statusCodes:t.statusCodes,retryConnectionErrors:!!t.config.retryConnectionErrors}),Object.assign(Object.assign({},ar),t.config.backoff),t.config);default:return await e(0)}}(async()=>{var t;const r=e.clone();let s=r;if(null!=i&&i>0){const e=AbortSignal.timeout(i),n=null!==(t=Vi(r.signal,e))&&void 0!==t?t:e;s=new Request(r,{signal:n})}const a=await this._hooks.beforeRequest(n,s);await async function(e,t){if(!e)return;const n=t.headers.get("content-type"),o=(null==n?void 0:n.split(";")[0])||"";e.group(`> Request: ${t.method} ${t.url}`),e.group("Headers:");for(const[i,r]of t.headers.entries())e.log(`${i}: ${r}`);switch(e.groupEnd(),e.group("Body:"),!0){case gr.test(o):e.log(await t.clone().json());break;case o.startsWith("text/"):e.log(await t.clone().text());break;case"multipart/form-data"===o:{const n=await t.clone().formData();for(const[t,o]of n){const n=o instanceof Blob?"<Blob>":o;e.log(`${t}: ${n}`)}break}default:e.log(`<${n}>`)}e.groupEnd(),e.groupEnd()}(this._logger,a).catch(e=>{var t;return null===(t=this._logger)||void 0===t?void 0:t.log("Failed to log request:",e)});let l=await this._httpClient.request(a);try{if(o(l.status)){const e=await this._hooks.afterError(n,l,null);if(e.error)throw e.error;l=e.response||l}else l=await this._hooks.afterSuccess(n,l)}finally{await async function(e,t,n){if(!e)return;const o=t.headers.get("content-type"),i=(null==o?void 0:o.split(";")[0])||"";e.group(`< Response: ${n.method} ${n.url}`),e.log("Status Code:",t.status,t.statusText),e.group("Headers:");for(const[r,s]of t.headers.entries())e.log(`${r}: ${s}`);switch(e.groupEnd(),e.group("Body:"),!0){case xi(t,"application/json")||gr.test(i)&&!_r.test(i):e.log(await t.clone().json());break;case xi(t,"application/jsonl")||_r.test(i):case xi(t,"text/event-stream"):e.log(`<${o}>`);break;case xi(t,"text/*"):e.log(await t.clone().text());break;case xi(t,"multipart/form-data"):{const n=await t.clone().formData();for(const[t,o]of n){const n=o instanceof Blob?"<Blob>":o;e.log(`${t}: ${n}`)}break}default:e.log(`<${o}>`)}e.groupEnd(),e.groupEnd()}(this._logger,l,a).catch(e=>{var t;return null===(t=this._logger)||void 0===t?void 0:t.log("Failed to log response:",e)})}return l},{config:t.retryConfig,statusCodes:t.retryCodes}).then(e=>Fi(e),e=>{switch(!0){case function(e){if("object"!=typeof e||null==e)return!1;const t="name"in e&&"AbortError"===e.name,n="code"in e&&20===e.code,o="code"in e&&"string"==typeof e.code&&"econnaborted"===e.code.toLowerCase();return t||n||o}(e):return Xi(new ii("Request aborted by client",{cause:e}));case Hi(e):return Xi(new ri("Request timed out",{cause:e}));case qi(e):return Xi(new si("Unable to make request",{cause:e}));default:return Xi(new ni("Unexpected HTTP client error",{cause:e}))}})}},gr=/^(application|text)\/([^+]+\+)*json.*/,_r=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/,yr=class extends ai{constructor(e,t){e&&(e+=": "),e+=`Status ${t.response.status}`;const n=t.response.headers.get("content-type")||'""';"application/json"!==n&&(e+=` Content-Type ${n.includes(" ")?`"${n}"`:n}`);const o=t.body||'""';e+=o.length>100?"\n":". ";let i=o;o.length>1e4&&(i=`${o.substring(0,1e4)}...and ${o.length-1e4} more chars`),super(e=(e+=`Body: ${i}`).trim(),t),this.name="GoogleGenAiDefaultError",Object.setPrototypeOf(this,new.target.prototype)}},Er={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function Tr(e,t,n){return Object.assign(Object.assign({},n),{err:!0,enc:"json",codes:e,errorClass:t})}function Ar(e,t){return Object.assign(Object.assign({},t),{enc:"json",codes:e})}function Ir(e,t,n){return Object.assign(Object.assign(Object.assign({},n),{enc:"sse",codes:e}),t?{sse:t}:{})}function Cr(e,t){return Object.assign(Object.assign({},t),{enc:"nil",codes:e})}function Sr(e){return{enc:"fail",codes:e}}function br(...e){return async function(t,n,o){let i,r;for(const p of e){const{codes:e}=p,n="ctype"in p?p.ctype:Er[p.enc];if(n&&Li(t,e,n)){r=p;break}if(!n&&Ui(t,e)){r=p;break}}if(!r)return[{ok:!1,error:new yr("Unexpected Status or Content-Type",{response:t,request:n,body:await t.text().catch(()=>"")})},i];const s=r.enc;let a="";switch(s){case"json":a=await t.text();try{i=JSON.parse(a)}catch(d){if(!("err"in r))throw d;i=a}break;case"jsonl":case"stream":i=t.body;break;case"bytes":i=new Uint8Array(await t.arrayBuffer());break;case"text":case"fail":a=await t.text(),i=a;break;case"sse":if(t.body){const e="sse"in r&&r.sse||{};i=function(e,t={}){var n,o;const i=!0===t.flattened,r=null!==(n=t.sentinel)&&void 0!==n?n:"";return new Si(e,e=>""!==r&&e.data===r?{done:!0,value:void 0}:i?{done:!1,value:null==e.data?void 0:Ii(e.data)}:{done:!1,value:Object.assign(Object.assign({},e),{data:null==e.data?e.data:Ii(e.data)})},{dataRequired:null===(o=t.dataRequired)||void 0===o||o})}(t.body,e)}else i=null;break;case"nil":a=await t.text(),i=void 0;break;default:throw new Error(`Unsupported response type: ${s}`)}if("fail"===r.enc)return[{ok:!1,error:new yr("API error occurred",{request:n,response:t,body:a})},i];const l=r.key||(null==o?void 0:o.resultKey);let u;const c=r.hdrs?{headers:wr(t.headers)}:null;return u="err"in r?Object.assign(Object.assign(Object.assign({},null==o?void 0:o.extraFields),c),$i(i)?i:null):l?Object.assign(Object.assign(Object.assign({},null==o?void 0:o.extraFields),c),{[l]:i}):r.hdrs?Object.assign(Object.assign(Object.assign({},null==o?void 0:o.extraFields),c),$i(i)?i:null):i,"err"in r?[{ok:!1,error:r.errorClass?new r.errorClass(u,{request:n,response:t,body:a}):u},i]:[{ok:!0,value:u},i]}}var Or=/, */;function wr(e){const t={};for(const[n,o]of e.entries())t[n]=o.split(Or);return t}var Rr,Pr=class e extends Error{constructor(e,t){super(t),this.code=e,this.name="SecurityError"}static incomplete(){return new e("incomplete","Security requirements not met in order to perform the operation")}static unrecognizedType(t){return new e("unrecognized_security_type",`Unrecognised security type: ${t}`)}};function Nr(e,t){var n,o;return function(...e){const t={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},n=e.find(e=>e.every(e=>{if(null==e.value)return!1;if("http:basic"===e.type)return null!=e.value.username||null!=e.value.password;if("http:custom"===e.type)return null;if("oauth2:password"===e.type)return"string"==typeof e.value&&!!e.value;if("oauth2:client_credentials"===e.type)return"string"==typeof e.value?!!e.value:null!=e.value.client_id||null!=e.value.client_secret;if("string"==typeof e.value)return!!e.value;throw new Error(`Unrecognized security type: ${e.type} (value type: ${typeof e.value})`)}));return null==n?null:(n.forEach(e=>{if(null==e.value)return;const{type:n}=e;switch(n){case"apiKey:header":t.headers[e.fieldName]=e.value;break;case"apiKey:query":t.queryParams[e.fieldName]=e.value;break;case"apiKey:cookie":t.cookies[e.fieldName]=e.value;break;case"http:basic":!function(e,t){null!=t.value&&(e.basic=t.value)}(t,e);break;case"http:custom":case"oauth2:client_credentials":break;case"http:bearer":case"oauth2":case"oauth2:password":case"openIdConnect":!function(e,t){if("string"!=typeof t.value||!t.value)return;let n=t.value;"bearer "!==n.slice(0,7).toLowerCase()&&(n=`Bearer ${n}`),void 0!==t.fieldName&&(e.headers[t.fieldName]=n)}(t,e);break;default:throw Pr.unrecognizedType(n)}}),t)}([{fieldName:"accessToken",type:"http:custom",value:null!==(n=null==e?void 0:e.access_token)&&void 0!==n?n:Vo().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:null!==(o=null==e?void 0:e.api_key)&&void 0!==o?o:Vo().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:null==e?void 0:e.default_headers}])}async function kr(e){if(null!=e)return"function"==typeof e?e():e}var Dr=class e{constructor(e,t){this[Rr]="APIPromise",this._promise=e instanceof Promise?e:Promise.resolve(e),this._unwrapped=e instanceof Promise?null:Promise.resolve(e[0]),this._callSource=null!=t?t:null}_getUnwrapped(){var e;return null!==(e=this._unwrapped)&&void 0!==e?e:this._unwrapped=this._promise.then(([e])=>e)}then(e,t){return this._promise.then(e?([t])=>e(t):void 0,t)}catch(e){return this._getUnwrapped().catch(e)}finally(e){return this._getUnwrapped().finally(e)}$inspect(){return this._promise}asResponse(){var e;return(null!==(e=this._callSource)&&void 0!==e?e:this._callSource=this._promise.then(([,e])=>e)).then(e=>{if(!e.response)throw new Error("APIPromise.asResponse: response unavailable");return e.response})}async withResponse(){const[[e],t]=await Promise.all([this._promise,this.asResponse()]);return{data:e,response:t}}_thenUnwrap(t){var n;const o=this._promise.then(([e,n])=>[t(e),n]);return o.catch(()=>{}),new e(o,null!==(n=this._callSource)&&void 0!==n?n:void 0)}};function Mr(e){const t=e.$inspect(),n=t.then(([e,t])=>{if(!e.ok)throw e.error;return[e.value,t]}),o=t.then(([e,t])=>{var n;if(!e.ok&&!(null===(n=t.response)||void 0===n?void 0:n.ok))throw e.error;return t});return n.catch(()=>{}),o.catch(()=>{}),new Dr(n,o)}function xr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/agents")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function Gr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:Qi("agentsId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/agents/{agentsId}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Ur(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:Qi("agentsId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/agents/{agentsId}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Lr(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={api_version:t,page_size:n,page_token:o,parent:i},c={api_version:Qi("api_version",null!==(s=null==u?void 0:u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/agents")(c),p=sr({page_size:null==u?void 0:u.page_size,page_token:null==u?void 0:u.page_token,parent:null==u?void 0:u.parent}),m=new Headers(Ji({Accept:"application/json"})),h=Nr(await kr(e._options.security)),f={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},v=e._createRequest(f,{security:h,method:"GET",baseURL:null==r?void 0:r.server_url,path:d,headers:m,query:p,body:null,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];const g=v.value,_=await e._do(g,{context:f,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:f.retry_config,retryCodes:f.retry_codes});if(!_.ok)return[_,{status:"request-error",request:g}];const y=_.value,[E]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(y,g);return E.ok,[E,{status:"complete",request:g,response:y}]}(e,t,n,o,i,r))}Rr=Symbol.toStringTag;var qr=class extends vr{list(e,t){return Mr(Lr(this,null==e?void 0:e.api_version,null==e?void 0:e.page_size,null==e?void 0:e.page_token,null==e?void 0:e.parent,t))}create(e,t){const{api_version:n}=e;return Mr(xr(this,N(e,["api_version"]),n,t))}delete(e,t,n){return Mr(Gr(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(Ur(this,e,null==t?void 0:t.api_version,n))}};function Hr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/credentials")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateCredential",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function jr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/credentials/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteCredential",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Fr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/credentials/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetCredential",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Xr(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={api_version:t,page_size:n,page_token:o},u={api_version:Qi("api_version",null!==(r=null==l?void 0:l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/credentials")(u),d=sr({page_size:null==l?void 0:l.page_size,page_token:null==l?void 0:l.page_token}),p=new Headers(Ji({Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"ListCredentials",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"GET",baseURL:null==i?void 0:i.server_url,path:c,headers:p,query:d,body:null,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}function Br(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={id:t,body:n,api_version:o,update_mask:i},c=Zi("body",u.body,{explode:!0}),d={api_version:Qi("api_version",null!==(s=u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",u.id,{explode:!1,charEncoding:"percent"})},p=jo("/{api_version}/credentials/{id}")(d),m=sr({update_mask:u.update_mask}),h=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),f=Nr(await kr(e._options.security)),v={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"UpdateCredential",o_auth2_scopes:null,resolved_security:f,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},g=e._createRequest(v,{security:f,method:"PATCH",baseURL:null==r?void 0:r.server_url,path:p,headers:h,query:m,body:c,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!g.ok)return[g,{status:"invalid"}];const _=g.value,y=await e._do(_,{context:v,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!y.ok)return[y,{status:"request-error",request:_}];const E=y.value,[T]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(E,_);return T.ok,[T,{status:"complete",request:_,response:E}]}(e,t,n,o,i,r))}var Vr=class extends vr{list(e,t){return Mr(Xr(this,null==e?void 0:e.api_version,null==e?void 0:e.page_size,null==e?void 0:e.page_token,t))}create(e,t){const{api_version:n}=e;return Mr(Hr(this,N(e,["api_version"]),n,t))}delete(e,t,n){return Mr(jr(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(Fr(this,e,null==t?void 0:t.api_version,n))}update(e,t,n){const{api_version:o,update_mask:i}=t;return Mr(Br(this,e,N(t,["api_version","update_mask"]),o,i,n))}};function Jr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/decisions")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateDecision",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}var $r=class extends vr{create(e,t,n){return Mr(Jr(this,e,t,n))}};function Wr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/environments")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function Yr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/environments/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Kr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/environments/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function zr(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={api_version:t,mode:n,page_size:o,page_token:i},c={api_version:Qi("api_version",null!==(s=null==u?void 0:u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/environments")(c),p=sr({mode:null==u?void 0:u.mode,page_size:null==u?void 0:u.page_size,page_token:null==u?void 0:u.page_token}),m=new Headers(Ji({Accept:"application/json"})),h=Nr(await kr(e._options.security)),f={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},v=e._createRequest(f,{security:h,method:"GET",baseURL:null==r?void 0:r.server_url,path:d,headers:m,query:p,body:null,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];const g=v.value,_=await e._do(g,{context:f,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:f.retry_config,retryCodes:f.retry_codes});if(!_.ok)return[_,{status:"request-error",request:g}];const y=_.value,[E]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(y,g);return E.ok,[E,{status:"complete",request:g,response:y}]}(e,t,n,o,i,r))}function Zr(e,t,n,o,i,r,s,a){return new Dr(async function(e,t,n,o,i,r,s,a){var l,u,c;const d={environment:t,path:n,api_version:o,page_size:i,page_token:r,recursive:s},p={api_version:Qi("api_version",null!==(l=d.api_version)&&void 0!==l?l:e._options.api_version,{explode:!1,charEncoding:"percent"}),environment:Qi("environment",d.environment,{explode:!1,charEncoding:"percent"}),path:Qi("path",d.path,{explode:!1,charEncoding:"percentExceptReserved"})},m=jo("/{api_version}/environments/{environment}/files/{path}")(p),h=sr({page_size:d.page_size,page_token:d.page_token,recursive:d.recursive}),f=new Headers(Ji({Accept:"application/json"})),v=Nr(await kr(e._options.security)),g={options:e._options,base_url:null!==(c=null!==(u=null==a?void 0:a.server_url)&&void 0!==u?u:e._baseURL)&&void 0!==c?c:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:(null==a?void 0:a.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==a?void 0:a.retry_codes)||["408","409","429","5XX"]},_=e._createRequest(g,{security:v,method:"GET",baseURL:null==a?void 0:a.server_url,path:m,headers:f,query:h,body:null,userAgent:e._options.user_agent,timeout_ms:(null==a?void 0:a.timeout_ms)||e._options.timeout_ms||-1},a);if(!_.ok)return[_,{status:"invalid"}];const y=_.value,E=await e._do(y,{context:g,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];const T=E.value,[A]=await br(Ar(200),Sr("4XX"),Sr("5XX"))(T,y);return A.ok,[A,{status:"complete",request:y,response:T}]}(e,t,n,o,i,r,s,a))}var Qr=class extends vr{list(e,t,n,o){return Mr(Zr(this,e,t,null==n?void 0:n.api_version,null==n?void 0:n.page_size,null==n?void 0:n.page_token,null==n?void 0:n.recursive,o))}};function es(e,t,n,o,i,r,s,a,l,u,c){return new Dr(async function(e,t,n,o,i,r,s,a,l,u,c){var d,p,m;const h={environment:t,path:n,"X-Goog-Upload-Command":o,"X-Goog-Upload-Header-Content-Length":i,"X-Goog-Upload-Header-Content-Type":r,"X-Goog-Upload-Protocol":s,api_version:a,extract:l,overwrite:u},f={api_version:Qi("api_version",null!==(d=h.api_version)&&void 0!==d?d:e._options.api_version,{explode:!1,charEncoding:"percent"}),environment:Qi("environment",h.environment,{explode:!1,charEncoding:"percent"}),path:Qi("path",h.path,{explode:!1,charEncoding:"percentExceptReserved"})},v=jo("/upload/{api_version}/environments/{environment}/files/{path}")(f),g=sr({extract:h.extract,overwrite:h.overwrite}),_=new Headers(Ji({Accept:"*/*","X-Goog-Upload-Command":Qi("X-Goog-Upload-Command",h["X-Goog-Upload-Command"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Length":Qi("X-Goog-Upload-Header-Content-Length",h["X-Goog-Upload-Header-Content-Length"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Type":Qi("X-Goog-Upload-Header-Content-Type",h["X-Goog-Upload-Header-Content-Type"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Protocol":Qi("X-Goog-Upload-Protocol",h["X-Goog-Upload-Protocol"],{explode:!1,charEncoding:"none"})})),y=Nr(await kr(e._options.security)),E={options:e._options,base_url:null!==(m=null!==(p=null==c?void 0:c.server_url)&&void 0!==p?p:e._baseURL)&&void 0!==m?m:"",operation_id:"StartEnvironmentFileUpload",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(null==c?void 0:c.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==c?void 0:c.retry_codes)||["408","409","429","5XX"]},T=e._createRequest(E,{security:y,method:"PUT",baseURL:null==c?void 0:c.server_url,path:v,headers:_,query:g,body:null,userAgent:e._options.user_agent,timeout_ms:(null==c?void 0:c.timeout_ms)||e._options.timeout_ms||-1},c);if(!T.ok)return[T,{status:"invalid"}];const A=T.value,I=await e._do(A,{context:E,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!I.ok)return[I,{status:"request-error",request:A}];const C=I.value,S={httpMeta:{response:C,request:A}},[b]=await br(Cr(200,{hdrs:!0}),Sr("4XX"),Sr("5XX"))(C,A,{extraFields:S});return b.ok,[b,{status:"complete",request:A,response:C}]}(e,t,n,o,i,r,s,a,l,u,c))}var ts=class extends vr{startUpload(e,t,n,o){return Mr(es(this,e,t,n["X-Goog-Upload-Command"],n["X-Goog-Upload-Header-Content-Length"],n["X-Goog-Upload-Header-Content-Type"],n["X-Goog-Upload-Protocol"],n.api_version,n.extract,n.overwrite,o))}},ns=class extends vr{get internal(){var e;return null!==(e=this._internal)&&void 0!==e?e:this._internal=new ts(this._options)}get files(){var e;return null!==(e=this._files)&&void 0!==e?e:this._files=new Qr(this._options)}listEnvironments(e,t){return Mr(zr(this,null==e?void 0:e.api_version,null==e?void 0:e.mode,null==e?void 0:e.page_size,null==e?void 0:e.page_token,t))}createEnvironment(e,t,n){return Mr(Wr(this,e,t,n))}deleteEnvironment(e,t,n){return Mr(Yr(this,e,null==t?void 0:t.api_version,n))}getEnvironment(e,t,n){return Mr(Kr(this,e,null==t?void 0:t.api_version,n))}},os=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdServerError"}},is=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdClientError"}},rs=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="CreateInteractionServerError"}},ss=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="CreateInteractionClientError"}},as=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="DeleteInteractionServerError"}},ls=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="DeleteInteractionClientError"}},us=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="GetInteractionByIdServerError"}},cs=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="GetInteractionByIdClientError"}};function ds(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:Qi("interactionsId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/interactions/{interactionsId}/cancel")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"POST",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,g={httpMeta:{response:v,request:h}},[_]=await br(Ar(200),Tr("4XX",is),Tr("5XX",os))(v,h,{extraFields:g});return _.ok,[_,{status:"complete",request:h,response:v}]}(e,t,n,o))}function ps(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s,a;const l={body:t,api_version:n},u=l,c=Zi("body",u.body,{explode:!0}),d={api_version:Qi("api_version",null!==(i=u.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},p=jo("/{api_version}/interactions")(d),m=new Headers(Ji({"Content-Type":"application/json",Accept:(null===(r=null==l?void 0:l.body)||void 0===r?void 0:r.stream)?"text/event-stream":"application/json"})),h=Nr(await kr(e._options.security)),f={options:e._options,base_url:null!==(a=null!==(s=null==o?void 0:o.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},v=e._createRequest(f,{security:h,method:"POST",baseURL:null==o?void 0:o.server_url,path:p,headers:m,body:c,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];const g=v.value,_=await e._do(g,{context:f,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:f.retry_config,retryCodes:f.retry_codes});if(!_.ok)return[_,{status:"request-error",request:g}];const y=_.value,E={httpMeta:{response:y,request:g}},[T]=await br(Ar(200),Ir(200,{sentinel:"[DONE]",flattened:!0}),Tr("4XX",ss),Tr("5XX",rs))(y,g,{extraFields:E});return T.ok,[T,{status:"complete",request:g,response:y}]}(e,t,n,o))}function ms(e,t,n,o,i,r,s){return new Dr(async function(e,t,n,o,i,r,s){var a,l,u;const c={id:t,api_version:n,include_input:o,last_event_id:i,stream:r},d=c,p={api_version:Qi("api_version",null!==(a=d.api_version)&&void 0!==a?a:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:Qi("interactionsId",d.id,{explode:!1,charEncoding:"percent"})},m=jo("/{api_version}/interactions/{interactionsId}")(p),h=sr({include_input:d.include_input,last_event_id:d.last_event_id,stream:d.stream}),f=new Headers(Ji({Accept:(null==c?void 0:c.stream)?"text/event-stream":"application/json"})),v=Nr(await kr(e._options.security)),g={options:e._options,base_url:null!==(u=null!==(l=null==s?void 0:s.server_url)&&void 0!==l?l:e._baseURL)&&void 0!==u?u:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:(null==s?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==s?void 0:s.retry_codes)||["408","409","429","5XX"]},_=e._createRequest(g,{security:v,method:"GET",baseURL:null==s?void 0:s.server_url,path:m,headers:f,query:h,body:null,userAgent:e._options.user_agent,timeout_ms:(null==s?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!_.ok)return[_,{status:"invalid"}];const y=_.value,E=await e._do(y,{context:g,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];const T=E.value,A={httpMeta:{response:T,request:y}},[I]=await br(Ar(200),Ir(200,{sentinel:"[DONE]",flattened:!0}),Tr("4XX",cs),Tr("5XX",us))(T,y,{extraFields:A});return I.ok,[I,{status:"complete",request:y,response:T}]}(e,t,n,o,i,r,s))}function hs(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={interaction_id:t,body:n,api_version:o},u=Zi("body",l.body,{explode:!0}),c={api_version:Qi("api_version",null!==(r=l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:Qi("interactionsId",l.interaction_id,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/interactions/{interactionsId}/auth_tokens")(c),p=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"CreateInteractionAuthToken",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"POST",baseURL:null==i?void 0:i.server_url,path:d,headers:p,body:u,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}function fs(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={interaction_id:t,auth_token:n,api_version:o},u={api_version:Qi("api_version",null!==(r=l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"}),auth_tokensId:Qi("auth_tokensId",l.auth_token,{explode:!1,charEncoding:"percent"}),interactionsId:Qi("interactionsId",l.interaction_id,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/interactions/{interactionsId}/auth_tokens/{auth_tokensId}")(u),d=new Headers(Ji({Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"DeleteInteractionAuthToken",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"DELETE",baseURL:null==i?void 0:i.server_url,path:c,headers:d,body:null,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o,i))}var vs=class extends vr{create(e,t,n){const{api_version:o}=t;return Mr(hs(this,e,N(t,["api_version"]),o,n))}delete(e,t,n,o){return Mr(fs(this,e,t,null==n?void 0:n.api_version,o))}},gs=class extends vr{get auth_tokens(){var e;return null!==(e=this._auth_tokens)&&void 0!==e?e:this._auth_tokens=new vs(this._options)}create(e,t){const{api_version:n}=e;return Mr(ps(this,N(e,["api_version"]),n,t))}delete(e,t,n){return Mr(function(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:Qi("interactionsId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/interactions/{interactionsId}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,g={httpMeta:{response:v,request:h}},[_]=await br(Cr(200),Tr("4XX",ls),Tr("5XX",as))(v,h,{extraFields:g});return _.ok,[_,{status:"complete",request:h,response:v}]}(e,t,n,o))}(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(ms(this,e,null==t?void 0:t.api_version,null==t?void 0:t.include_input,null==t?void 0:t.last_event_id,null==t?void 0:t.stream,n))}cancel(e,t,n){return Mr(ds(this,e,null==t?void 0:t.api_version,n))}};function _s(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/triggers")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function ys(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/triggers/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Es(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/triggers/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Ts(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={trigger_id:t,api_version:n,page_size:o,page_token:i},c={api_version:Qi("api_version",null!==(s=u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:Qi("triggerId",u.trigger_id,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/triggers/{triggerId}/executions")(c),p=sr({page_size:u.page_size,page_token:u.page_token}),m=new Headers(Ji({Accept:"application/json"})),h=Nr(await kr(e._options.security)),f={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},v=e._createRequest(f,{security:h,method:"GET",baseURL:null==r?void 0:r.server_url,path:d,headers:m,query:p,body:null,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];const g=v.value,_=await e._do(g,{context:f,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:f.retry_config,retryCodes:f.retry_codes});if(!_.ok)return[_,{status:"request-error",request:g}];const y=_.value,[E]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(y,g);return E.ok,[E,{status:"complete",request:g,response:y}]}(e,t,n,o,i,r))}function As(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={api_version:t,filter:n,page_size:o,page_token:i},c={api_version:Qi("api_version",null!==(s=null==u?void 0:u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/triggers")(c),p=sr({filter:null==u?void 0:u.filter,page_size:null==u?void 0:u.page_size,page_token:null==u?void 0:u.page_token}),m=new Headers(Ji({Accept:"application/json"})),h=Nr(await kr(e._options.security)),f={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},v=e._createRequest(f,{security:h,method:"GET",baseURL:null==r?void 0:r.server_url,path:d,headers:m,query:p,body:null,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];const g=v.value,_=await e._do(g,{context:f,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:f.retry_config,retryCodes:f.retry_codes});if(!_.ok)return[_,{status:"request-error",request:g}];const y=_.value,[E]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(y,g);return E.ok,[E,{status:"complete",request:g,response:y}]}(e,t,n,o,i,r))}function Is(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={trigger_id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:Qi("triggerId",a.trigger_id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/triggers/{triggerId}/executions")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"POST",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Cs(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={id:t,body:n,api_version:o},u=Zi("body",l.body,{explode:!0}),c={api_version:Qi("api_version",null!==(r=l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",l.id,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/triggers/{id}")(c),p=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"PATCH",baseURL:null==i?void 0:i.server_url,path:d,headers:p,body:u,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}var Ss=class extends vr{list(e,t){return Mr(As(this,null==e?void 0:e.api_version,null==e?void 0:e.filter,null==e?void 0:e.page_size,null==e?void 0:e.page_token,t))}create(e,t){const{api_version:n}=e;return Mr(_s(this,N(e,["api_version"]),n,t))}delete(e,t,n){return Mr(ys(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(Es(this,e,null==t?void 0:t.api_version,n))}update(e,t,n){const{api_version:o}=t;return Mr(Cs(this,e,N(t,["api_version"]),o,n))}listExecutions(e,t,n){return Mr(Ts(this,e,null==t?void 0:t.api_version,null==t?void 0:t.page_size,null==t?void 0:t.page_token,n))}run(e,t,n){return Mr(Is(this,e,null==t?void 0:t.api_version,n))}};function bs(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/voices")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateVoice",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function Os(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:Qi("voicesId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/voices/{voicesId}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteVoice",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function ws(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:Qi("voicesId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/voices/{voicesId}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetVoice",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Rs(e,t,n,o,i,r,s,a,l,u,c,d,p,m){return new Dr(async function(e,t,n,o,i,r,s,a,l,u,c,d,p,m){var h,f,v;const g={api_version:t,accent:n,contexts:o,gender:i,language_code:r,page_size:s,page_token:a,persona:l,pitch:u,region_code:c,search:d,type:p},_={api_version:Qi("api_version",null!==(h=null==g?void 0:g.api_version)&&void 0!==h?h:e._options.api_version,{explode:!1,charEncoding:"percent"})},y=jo("/{api_version}/voices")(_),E=sr({accent:null==g?void 0:g.accent,context:null==g?void 0:g.contexts,gender:null==g?void 0:g.gender,language_code:null==g?void 0:g.language_code,page_size:null==g?void 0:g.page_size,page_token:null==g?void 0:g.page_token,persona:null==g?void 0:g.persona,pitch:null==g?void 0:g.pitch,region_code:null==g?void 0:g.region_code,search:null==g?void 0:g.search,type:null==g?void 0:g.type}),T=new Headers(Ji({Accept:"application/json"})),A=Nr(await kr(e._options.security)),I={options:e._options,base_url:null!==(v=null!==(f=null==m?void 0:m.server_url)&&void 0!==f?f:e._baseURL)&&void 0!==v?v:"",operation_id:"ListVoices",o_auth2_scopes:null,resolved_security:A,security_source:e._options.security,retry_config:(null==m?void 0:m.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==m?void 0:m.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(I,{security:A,method:"GET",baseURL:null==m?void 0:m.server_url,path:y,headers:T,query:E,body:null,userAgent:e._options.user_agent,timeout_ms:(null==m?void 0:m.timeout_ms)||e._options.timeout_ms||-1},m);if(!C.ok)return[C,{status:"invalid"}];const S=C.value,b=await e._do(S,{context:I,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:I.retry_config,retryCodes:I.retry_codes});if(!b.ok)return[b,{status:"request-error",request:S}];const O=b.value,[w]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(O,S);return w.ok,[w,{status:"complete",request:S,response:O}]}(e,t,n,o,i,r,s,a,l,u,c,d,p,m))}var Ps=class extends vr{list(e,t){return Mr(Rs(this,null==e?void 0:e.api_version,null==e?void 0:e.accent,null==e?void 0:e.contexts,null==e?void 0:e.gender,null==e?void 0:e.language_code,null==e?void 0:e.page_size,null==e?void 0:e.page_token,null==e?void 0:e.persona,null==e?void 0:e.pitch,null==e?void 0:e.region_code,null==e?void 0:e.search,null==e?void 0:e.type,t))}create(e,t,n){return Mr(bs(this,e,t,n))}delete(e,t,n){return Mr(Os(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(ws(this,e,null==t?void 0:t.api_version,n))}};function Ns(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/webhooks")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function ks(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/webhooks/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Ds(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/webhooks/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Ms(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={api_version:t,page_size:n,page_token:o},u={api_version:Qi("api_version",null!==(r=null==l?void 0:l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/webhooks")(u),d=sr({page_size:null==l?void 0:l.page_size,page_token:null==l?void 0:l.page_token}),p=new Headers(Ji({Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"GET",baseURL:null==i?void 0:i.server_url,path:c,headers:p,query:d,body:null,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}function xs(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={id:t,api_version:n,body:o},u=Zi("body",l.body,{explode:!0}),c={api_version:Qi("api_version",null!==(r=l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",l.id,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/webhooks/{id}:ping")(c),p=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"POST",baseURL:null==i?void 0:i.server_url,path:d,headers:p,body:u,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}function Gs(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={id:t,body:n,api_version:o},u=Zi("body",l.body,{explode:!0}),c={api_version:Qi("api_version",null!==(r=l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",l.id,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/webhooks/{id}:rotateSigningSecret")(c),p=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"POST",baseURL:null==i?void 0:i.server_url,path:d,headers:p,body:u,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}function Us(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={id:t,body:n,api_version:o,update_mask:i},c=Zi("body",u.body,{explode:!0}),d={api_version:Qi("api_version",null!==(s=u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",u.id,{explode:!1,charEncoding:"percent"})},p=jo("/{api_version}/webhooks/{id}")(d),m=sr({update_mask:u.update_mask}),h=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),f=Nr(await kr(e._options.security)),v={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:f,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},g=e._createRequest(v,{security:f,method:"PATCH",baseURL:null==r?void 0:r.server_url,path:p,headers:h,query:m,body:c,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!g.ok)return[g,{status:"invalid"}];const _=g.value,y=await e._do(_,{context:v,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!y.ok)return[y,{status:"request-error",request:_}];const E=y.value,[T]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(E,_);return T.ok,[T,{status:"complete",request:_,response:E}]}(e,t,n,o,i,r))}var Ls=class extends vr{list(e,t){return Mr(Ms(this,null==e?void 0:e.api_version,null==e?void 0:e.page_size,null==e?void 0:e.page_token,t))}create(e,t){const{api_version:n}=e;return Mr(Ns(this,N(e,["api_version"]),n,t))}delete(e,t,n){return Mr(ks(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(Ds(this,e,null==t?void 0:t.api_version,n))}update(e,t,n){const{api_version:o,update_mask:i}=t;return Mr(Us(this,e,N(t,["api_version","update_mask"]),o,i,n))}ping(e,t,n,o){return Mr(xs(this,e,t,n,o))}rotateSigningSecret(e,t,n,o){return Mr(Gs(this,e,t,n,o))}},qs=class extends vr{get environments(){var e;return null!==(e=this._environments)&&void 0!==e?e:this._environments=new ns(this._options)}get agents(){var e;return null!==(e=this._agents)&&void 0!==e?e:this._agents=new qr(this._options)}get credentials(){var e;return null!==(e=this._credentials)&&void 0!==e?e:this._credentials=new Vr(this._options)}get decisions(){var e;return null!==(e=this._decisions)&&void 0!==e?e:this._decisions=new $r(this._options)}get interactions(){var e;return null!==(e=this._interactions)&&void 0!==e?e:this._interactions=new gs(this._options)}get triggers(){var e;return null!==(e=this._triggers)&&void 0!==e?e:this._triggers=new Ss(this._options)}get voices(){var e;return null!==(e=this._voices)&&void 0!==e?e:this._voices=new Ps(this._options)}get webhooks(){var e;return null!==(e=this._webhooks)&&void 0!==e?e:this._webhooks=new Ls(this._options)}},Hs=/* @__PURE__ */new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function js(e){const t=e.getBaseUrl();if(!t)throw new Error("Base URL must be set.");return t.replace(/\/+$/,"")}function Fs(e){const t=e.getApiVersion().replace(/^\/+|\/+$/g,""),n=e.getProject(),o=e.getLocation();return e.isVertexAI()&&t&&n&&o?`${t}/projects/${encodeURIComponent(n)}/locations/${encodeURIComponent(o)}`:t}function Xs(e,t={}){var n,o,i,r,s,a,l,u,c,d;const{timeout:p}=t,m=N(t,["timeout"]),h=m.http_client||null===(n=e.getFetch)||void 0===n?void 0:n.call(e),f=null!==(o=m.http_client)&&void 0!==o?o:h?new Di({fetcher:h}):void 0,v=null!==(r=null!==(i=m.timeout_ms)&&void 0!==i?i:p)&&void 0!==r?r:null===(s=e.getTimeout)||void 0===s?void 0:s.call(e);return new qs(Object.assign(Object.assign({},m),{http_client:f,api_version:null!==(a=m.api_version)&&void 0!==a?a:Fs(e),security:null!==(l=m.security)&&void 0!==l?l:new $o({defaultHeaders:Object.assign(Object.assign({},null===(u=e.getDefaultHeaders)||void 0===u?void 0:u.call(e)),null===(c=e.getHeaders)||void 0===c?void 0:c.call(e)),getAuthHeaders:t=>e.getAuthHeaders(t)}),server_url:null!==(d=m.server_url)&&void 0!==d?d:js(e),timeout_ms:v}))}var Bs=class{constructor(e,t=()=>!1){this.resolveClient=e,this.isVertexAI=t}async create(e,t={},n){if(G(),this.isVertexAI())throw new U("Live Interactions is currently Gemini API only.");const o=null!=t?t:{},{api_version:i}=o,r=N(o,["api_version"]);return Ks(hs(this.resolveClient(i),e,r,i,Ys(n)))}async delete(e,t,n={},o){if(G(),this.isVertexAI())throw new U("Live Interactions is currently Gemini API only.");const i=t.startsWith("auth_tokens/")?t.slice(12):t;return Ks(fs(this.resolveClient(null==n?void 0:n.api_version),e,i,null==n?void 0:n.api_version,Ys(o)))}},Vs=class{constructor(e,t){this.parentClient=e,this.webSocketFactory=t,this.authTokens=new Bs(e=>this.getClient(e),()=>this.parentClient.isVertexAI())}async create(e,t){var n;const{api_version:o,automatic_continuation:i}=e,r=function(e,t){const n=!0===e.background,o=!0===e.stream;if(n&&!1===t)throw new Error("automatic_continuation: false cannot be used with background: true.");const i=!1!==(null==t||t)&&!n&&!function(e){return!Io(Eo(e,"agent"))||!Io(Eo(e,"agent_config"))}(e);return{body:e,stream:o,callerToken:To(e.continuation_token),enableContinuation:i}}(N(e,["api_version","automatic_continuation"]),i),s=new So(null!==(n=null==t?void 0:t.timeout_ms)&&void 0!==n?n:null==t?void 0:t.timeout,{enabled:r.enableContinuation}),a=()=>{if(!s.bounded)return t;const e=null!=t?t:{},{timeout:n}=e,o=N(e,["timeout"]);return Object.assign(Object.assign({},o),{timeout_ms:s.hopTimeoutMs()})},l=this.getClient(o);if(r.stream){const e=async(e,t)=>Zs(await zs(()=>l.interactions.create(Object.assign(Object.assign({},bo(r,e,t)),{stream:!0,api_version:o}),Ys(a(),!0)))),t=await e();return r.enableContinuation?ea(function(e,t,n){return D(this,arguments,function*(){var o,i;const r=null!==(o=n.deadline)&&void 0!==o?o:new So(void 0),s=null!==(i=n.wrapIterationError)&&void 0!==i?i:e=>e,a=new Po({initialContinuationToken:n.initialContinuationToken,isConnectionError:n.isConnectionError,isFatalError:n.isFatalError,store:n.store});let l,u=!0;try{for(;;){const[n,o]=a.startHop(u);let i;if(u)u=!1,l=e[Symbol.asyncIterator]();else{yield k(ko(l)),l=void 0;try{r.check();const e=yield k(t(n,o));a.markStreamOpened(),l=e[Symbol.asyncIterator]()}catch(c){i={error:c}}}if(!i&&l)for(;;){let e;try{r.check(),e=yield k(l.next())}catch(c){i={error:c instanceof Co?c:s(c)};break}if(e.done)break;yield yield k(a.observe(e.value))}if(!a.endHop(i))break}}finally{yield k(ko(l))}})}(t,e,{initialContinuationToken:r.callerToken,isConnectionError:e=>e instanceof w&&!(e instanceof ui),isFatalError:e=>e instanceof ui,wrapIterationError:Qs,deadline:s,store:!1!==r.body.store})):r.callerToken?t:ea(function(e){return D(this,arguments,function*(){var t,n,o,i;let r,s;try{for(var a,l=!0,u=M(e);!(t=(a=yield k(u.next())).done);l=!0){i=a.value,l=!1;const e=i;[r,s]=wo(e,r,s),yield yield k(e)}}catch(c){n={error:c}}finally{try{l||t||!(o=u.return)||(yield k(o.call(u)))}finally{if(n)throw n.error}}"requires_continuation"===r&&s&&Oo()})}(t))}const u=async(e,t)=>Ks(ps(l,bo(r,e,t),o,Ys(a()))),c=await u();if(r.enableContinuation)return await async function(e,t,n={}){var o;const i=null!==(o=n.deadline)&&void 0!==o?o:new So(void 0),r=[e];let s=n.initialContinuationToken;for(;;){const e=Mo(r[r.length-1],s);if(!e)return Lo(r,n);let o;try{i.check(),o=await t(e,To(Eo(r[r.length-1],"id")))}catch(a){throw Go(a,r,e,n)}r.push(o),s=e}}(c,u,{initialContinuationToken:r.callerToken,normalizeInteraction:oa,finalizeInteraction:ra,deadline:s,store:!1!==r.body.store});const d=na(c);return r.callerToken||Do(d)&&Oo(),d}connect(e,t={},n){return G(),"webrtc"===t.transport||t.transport instanceof te?function(e,t,n={},o){return async function(e,t,n={},o){G();const{timeout:i,extraHeaders:r}=J(e,t,o);return async function(e,t,n,o){const i=new ee(t,n);try{const r=await n.connect(e,t,{onopen:()=>{},onerror:()=>i.handleTransportError(),onmessage:e=>i.handleMessage(null==e?void 0:e.data),onclose:e=>{var t;return i.handleClose(null!==(t=null==e?void 0:e.code)&&void 0!==t?t:1e3)}},{apiVersion:o.apiVersion,extraHeaders:o.extraHeaders,timeoutMs:o.timeoutMs});return i.attach(r),i}catch(r){if(i.detach(),r instanceof w||r instanceof U)throw r;throw new P({message:"Failed to complete WebRTC live setup."})}}(e,t,n.transport instanceof te?n.transport:new te,{apiVersion:n.api_version,extraHeaders:r,timeoutMs:i})}(e,t,n,o)}(this.parentClient,e,t,n):function(e,t,n,o={},i){return async function(e,t,n,o={},i,r){var s;G();const{timeout:a,extraHeaders:l}=J(e,n,i);if(!t)throw new U("Live Interactions WebSocket support requires a platform WebSocket factory.");const u=null===(s=e.getApiKey)||void 0===s?void 0:s.call(e),c=(null==u?void 0:u.startsWith("auth_tokens/"))?u:void 0,d=!1===t.supportsHeaders;if(d){if(void 0===c)throw new U("Browser WebSocket connections cannot send authentication headers; pass an auth token as apiKey to the GoogleGenAI client.");if(l&&Object.keys(l).length>0)throw new U("Browser WebSocket connections cannot send extra_headers.")}const p=d?c:void 0,m=function(e,t,n){var o;if(e.isVertexAI())throw new U("Live Interactions is currently Gemini API only.");const i=null===(o=e.getWebsocketBaseUrl)||void 0===o?void 0:o.call(e);if(!i)throw new U("WebSocket base URL is required.");const r=new URL(i),s=null!=t?t:e.getApiVersion();return r.pathname=`${r.pathname.replace(/\/+$/g,"")}/${s}/interactions/live`,void 0!==n&&r.searchParams.set("auth_token",n),r.toString()}(e,o.api_version,p);let h;try{h=await async function(e,t,n,o,i){const r=await $(e,t,n,{"api-revision":i});return void 0!==o&&(V(r,"authorization"),V(r,"x-goog-api-key")),r}(e,m,l,p,r)}catch(v){throw new R({message:"Live authentication setup failed.",httpStatus:H(v)})}const f=new K(n);await new Promise((e,n)=>{let o,i=!1,r=!1;const l=()=>{void 0!==o&&clearTimeout(o)},u=(e={closeCode:1006})=>{i||r||(r=!0,l(),n(new R({message:"WebSocket upgrade failed.",closeCode:e.closeCode,httpStatus:e.httpStatus})),f.detach())},c=t.create(m,h,{onopen:()=>{r||(i=!0,r=!0,l(),e())},onerror:e=>{if(i)f.handleTransportError();else{const t=H(e);u(void 0!==t?{httpStatus:t}:{closeCode:1006})}},onmessage:e=>f.handleMessage(null==e?void 0:e.data),onclose:e=>{const t="number"==typeof(null==e?void 0:e.code)?e.code:1006;i||u({closeCode:t}),f.handleClose(t)}});f.attach(c);try{o=setTimeout(()=>{u({closeCode:1006});try{c.close()}catch(s){}},a),c.connect();const e=c.ws;"blob"===(null==e?void 0:e.binaryType)&&(e.binaryType="arraybuffer")}catch(v){const t=H(v);u(void 0!==t?{httpStatus:t}:{closeCode:1006})}});try{return f.sendInitial({event_type:"interaction.connect",id:n}),f}catch(v){if(f.detach(),v instanceof w)throw v;throw new R({message:"Failed to send live setup."})}}(e,t,n,o,i,"2026-05-20")}(this.parentClient,this.webSocketFactory,e,t,n)}async get(e,t={},n){const{api_version:o,stream:i=!1,last_event_id:r,include_input:s}=null!=t?t:{};return!0===i?Zs(await zs(()=>this.getClient(o).interactions.get(e,{stream:i,last_event_id:r,include_input:s,api_version:o},Ys(n,!0)))):na(await Ks(ms(this.getClient(o),e,o,s,r,i,Ys(n))))}async delete(e,t={},n){return zs(()=>this.getClient(null==t?void 0:t.api_version).interactions.delete(e,{api_version:null==t?void 0:t.api_version},Ys(n)))}async cancel(e,t={},n){return na(await Ks(ds(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n))))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}},Js=class{constructor(e){this.parentClient=e}async create(e={},t){const n=null!=e?e:{},{api_version:o}=n,i=N(n,["api_version"]);return Ks(xr(this.getClient(o),i,o,Ys(t)))}async list(e={},t){const{api_version:n,page_size:o,page_token:i,parent:r}=null!=e?e:{};return Ks(Lr(this.getClient(n),n,o,i,r,Ys(t)))}async get(e,t={},n){return Ks(Ur(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async delete(e,t={},n){return Ks(Gr(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}},$s=class{constructor(e){this.parentClient=e}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(Ns(this.getClient(),o,n,Ys(t)))}async list(e={},t){const{api_version:n,page_size:o,page_token:i}=null!=e?e:{};return Ks(Ms(this.getClient(),n,o,i,Ys(t)))}async get(e,t={},n){return Ks(Ds(this.getClient(),e,null==t?void 0:t.api_version,Ys(n)))}async update(e,t={},n){const o=null!=t?t:{},{api_version:i,update_mask:r}=o,s=N(o,["api_version","update_mask"]);return Ks(Us(this.getClient(),e,s,i,r,Ys(n)))}async delete(e,t={},n){return Ks(ks(this.getClient(),e,null==t?void 0:t.api_version,Ys(n)))}async rotateSigningSecret(e,t={},n){const o=null!=t?t:{},{api_version:i}=o,r=N(o,["api_version"]);return Ks(Gs(this.getClient(),e,r,i,Ys(n)))}async ping(e,t=void 0,n){const{api_version:o,body:i}=null!=t?t:{};return Ks(xs(this.getClient(),e,o,i,Ys(n)))}getClient(){var e;return null!==(e=this.sdk)&&void 0!==e||(this.sdk=Xs(this.parentClient)),this.sdk}},Ws=class{constructor(e){this.parentClient=e}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(_s(this.getClient(n),o,n,Ys(t)))}async list(e={},t){const{api_version:n,filter:o,page_size:i,page_token:r}=null!=e?e:{};return Ks(As(this.getClient(n),n,o,i,r,Ys(t)))}async get(e,t={},n){return Ks(Es(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async update(e,t,n){const{api_version:o}=t,i=N(t,["api_version"]);return Ks(Cs(this.getClient(o),e,i,o,Ys(n)))}async delete(e,t={},n){return Ks(ys(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async run(e,t={},n){return Ks(Is(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async listExecutions(e,t={},n){const{api_version:o,page_size:i,page_token:r}=null!=t?t:{};return Ks(Ts(this.getClient(o),e,o,i,r,Ys(n)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}};function Ys(e,t=!1){var n,o,i,r;if(!e&&!t)return;const s=null!=e?e:{},{timeout:a,maxRetries:l,defaultBaseURL:u,query:c,body:d,fetchOptions:p}=s,m=N(s,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),h=Object.assign({},m);ia(c)&&(h.extra_query=c),ia(d)&&(h.extra_body=d);const f=null!==(n=m.fetch_options)&&void 0!==n?n:p;f&&(h.fetch_options=f);const v=null!==(o=m.server_url)&&void 0!==o?o:u;v&&(h.server_url=v);const g=null!==(i=m.timeout_ms)&&void 0!==i?i:a;if(void 0!==g&&(h.timeout_ms=g),void 0!==l&&(h.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:l}),t){const e=new Headers(null!==(r=h.headers)&&void 0!==r?r:null==f?void 0:f.headers);e.set("Accept","text/event-stream"),h.headers=e}return h}async function Ks(e){const[t,n]=await e.$inspect();if(!t.ok)throw yi(t.error);return function(e,t){return ia(e)&&"complete"===t.status?Object.assign(Object.assign({},e),{sdkHttpResponse:ta(t.response,e)}):e}(t.value,n)}async function zs(e){try{return await e()}catch(t){throw yi(t)}}function Zs(e){const t=e;return new Proxy(e,{get(e,n){if(n!==Symbol.asyncIterator){const t=Reflect.get(e,n,e);return"function"==typeof t?t.bind(e):t}return function(){const e=t[Symbol.asyncIterator]();return{async next(...t){try{return await e.next(...t)}catch(n){throw yi(n)}},async return(t){if(!e.return)return{done:!0,value:t};try{return await e.return(t)}catch(n){throw yi(n)}},async throw(t){if(!e.throw)throw yi(t);try{return await e.throw(t)}catch(n){throw yi(n)}},[Symbol.asyncIterator](){return this}}}}})}function Qs(e){const t=yi(e);if(t instanceof O||t instanceof Co)return t;if(t instanceof Error&&"AbortError"===t.name)return new ui({message:t.message});const n=t instanceof Error?t.message:String(t);return new w({message:n,cause:t})}function ea(e){const t=e[Symbol.asyncIterator](),n=new ReadableStream({async pull(e){const n=await t.next();n.done?e.close():e.enqueue(n.value)},async cancel(){var e;await(null===(e=t.return)||void 0===e?void 0:e.call(t))}},{highWaterMark:0});return Object.setPrototypeOf(n,Si.prototype),n}function ta(e,t){const n={};for(const[o,i]of e.headers.entries())n[o]=i;return{headers:n,responseInternal:e,json:async()=>t}}function na(e){const t=oa(e);return t?ra(t):e}function oa(e){if(ia(e)){if(Array.isArray(e.steps))return e;if(function(e){const t=e.model;return"string"==typeof t&&Hs.has(t)}(e)){const t=e.outputs;if(Array.isArray(t)){const{outputs:n}=e,o=N(e,["outputs"]);return Object.assign(Object.assign({},o),{steps:[{type:"model_output",content:t}]})}}return Object.assign(Object.assign({},e),{steps:[]})}}function ia(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ra(e){var t,n;const o=function(e){return Object.assign(Object.assign({},e),{created:sa(e.created),updated:sa(e.updated)})}(e),i=null!==(t=o.steps)&&void 0!==t?t:[],r=[];let s,a,l,u=!1;e:for(let d=i.length-1;d>=0;d--){const e=i[d];if("user_input"===e.type)break;if("thought"===e.type)continue;if("model_output"!==e.type){if(u)break;continue}if(!e.content)continue;const t=e.content;for(let o=t.length-1;o>=0;o--){const e=t[o];if("text"===e.type)u=!0,r.push(null!==(n=e.text)&&void 0!==n?n:"");else if(u)break e}}for(let d=i.length-1;d>=0;d--){const e=i[d];if("user_input"===e.type)break;if("model_output"===e.type&&e.content)for(let t=e.content.length-1;t>=0;t--){const n=e.content[t];"image"!==n.type||s||(s=n),"audio"!==n.type||a||(a=n),"video"!==n.type||l||(l=n)}}const c=r.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},o),c&&{output_text:c}),s?{output_image:s}:{}),a?{output_audio:a}:{}),l?{output_video:l}:{})}function sa(e){return e instanceof Date?e.toISOString():e}var aa=class{constructor(e,t){this.resolveClient=e,this.parentClient=t}async list(e,t){return Ks(Zr(this.resolveClient(e.api_version),e.environment,e.path,e.api_version,e.page_size,e.page_token,e.recursive,Ys(t)))}async download(e,t){var n,o;const i=e.environment;if(!i)throw new Error("environment is required.");const r=`${i.startsWith("environments/")?i:`environments/${i}`}/files/${e.path.replace(/^\/+/,"")}`,s=this.parentClient;if(!s||"function"!=typeof s.request)throw new Error("apiClient is required to download files.");const a=await s.request({path:r,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:Object.assign(Object.assign({},null==t?void 0:t.httpOptions),{apiVersion:null!==(n=e.api_version)&&void 0!==n?n:null===(o=null==t?void 0:t.httpOptions)||void 0===o?void 0:o.apiVersion})});if(a&&a.responseInternal&&"function"==typeof a.responseInternal.arrayBuffer){const e=await a.responseInternal.arrayBuffer();return new Uint8Array(e)}throw new Error("Unexpected response type from download")}async upload(e,t){var n,o,i,r,s,a,l,u;const c=e.environment;if(!c)throw new Error("environment is required.");c.startsWith("environments/");const d=e.path.replace(/^\/+/,""),p=this.parentClient;if(!p||"function"!=typeof p.request)throw new Error("apiClient is required to upload files.");let m,h=0,f=e.mime_type;if("string"==typeof e.file){let t;try{const n=globalThis.require;n&&(t=n("fs").readFileSync(e.file))}catch(S){}if(!t&&void 0!==globalThis.process)try{const i=null!==(o=null===(n=globalThis.process.mainModule)||void 0===n?void 0:n.require)&&void 0!==o?o:globalThis.require;i&&(t=i("fs").readFileSync(e.file))}catch(b){}if(!t)throw new Error(`Unable to read file from path "${e.file}". File path string inputs are only supported in Node.js environments.`);m=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),h=m.byteLength,f||(f={txt:"text/plain",json:"application/json",js:"text/javascript",mjs:"text/javascript",ts:"text/plain",py:"text/x-python",html:"text/html",htm:"text/html",css:"text/css",csv:"text/csv",xml:"application/xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[(v=e.file).slice(v.lastIndexOf(".")+1).toLowerCase()])}else if("undefined"!=typeof Blob&&e.file instanceof Blob)m=e.file,h=e.file.size,!f&&e.file.type&&(f=e.file.type);else if(e.file instanceof Uint8Array||e.file instanceof ArrayBuffer)m=e.file instanceof ArrayBuffer?new Uint8Array(e.file):e.file,h=m.byteLength;else{if(void 0===globalThis.Buffer||"function"!=typeof globalThis.Buffer.isBuffer||!globalThis.Buffer.isBuffer(e.file))throw new Error("Unsupported file type for upload.");{const t=e.file;m=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),h=m.byteLength}}var v;f||(f="application/octet-stream");const g=c.startsWith("environments/")?c.replace(/^environments\//,""):c,[_,y]=await es(this.resolveClient(e.api_version),g,d,"start",h,f,"resumable",e.api_version,e.extract,e.overwrite,Ys(t)).$inspect();if(!_.ok)throw yi(_.error);const E="complete"===y.status?null!==(s=null===(r=null===(i=y.response)||void 0===i?void 0:i.headers)||void 0===r?void 0:r.get("x-goog-upload-url"))&&void 0!==s?s:null===(l=null===(a=y.response)||void 0===a?void 0:a.headers)||void 0===l?void 0:l.get("X-Goog-Upload-URL"):void 0;if(!E)throw new Error("Failed to get upload URL from upload handshake response.");let T,A=0;const I=m instanceof Blob?m:new Blob([m]);for(;A<h||0===h&&0===A;){const e=Math.min(A+8388608,h),n=I.slice(A,e),o=e>=h,i=o?"upload, finalize":"upload";if(T=await p.request({path:"",body:n,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},null==t?void 0:t.httpOptions),{apiVersion:"",baseUrl:E,headers:Object.assign(Object.assign({},(null===(u=null==t?void 0:t.httpOptions)||void 0===u?void 0:u.headers)||{}),{"X-Goog-Upload-Command":i,"X-Goog-Upload-Offset":`${A}`})})}),A=e,o)break}let C;if(T&&"function"==typeof T.json?C=await T.json():T&&T.responseInternal&&"function"==typeof T.responseInternal.json&&(C=await T.responseInternal.json()),C&&"object"==typeof C){if(Array.isArray(C.files))return C;if(C.name||C.path)return{files:[C]};if(C.file&&"object"==typeof C.file)return{files:[C.file]}}return C}},la=class{constructor(e){this.parentClient=e,this.files=new aa(e=>this.getClient(e),this.parentClient)}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(Wr(this.getClient(n),o,n,Ys(t)))}async list(e={},t){const{api_version:n,mode:o,page_size:i,page_token:r}=null!=e?e:{};return Ks(zr(this.getClient(n),n,o,i,r,Ys(t)))}async get(e,t={},n){return Ks(Kr(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async delete(e,t={},n){return Ks(Yr(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}},ua=class{constructor(e){this.parentClient=e}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(Hr(this.getClient(n),o,n,Ys(t)))}async list(e={},t){const{api_version:n,page_size:o,page_token:i}=null!=e?e:{};return Ks(Xr(this.getClient(n),n,o,i,Ys(t)))}async get(e,t={},n){return Ks(Fr(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async update(e,t,n){const{api_version:o,update_mask:i}=t,r=N(t,["api_version","update_mask"]);return Ks(Br(this.getClient(o),e,r,o,i,Ys(n)))}async delete(e,t={},n){return Ks(jr(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}},ca=class{constructor(e){this.parentClient=e}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(bs(this.getClient(n),o,n,Ys(t)))}async list(e={},t){const{api_version:n,accent:o,contexts:i,gender:r,language_code:s,page_size:a,page_token:l,persona:u,pitch:c,region_code:d,search:p,type:m}=null!=e?e:{};return Ks(Rs(this.getClient(n),n,o,i,r,s,a,l,u,c,d,p,m,Ys(t)))}async get(e,t={},n){return Ks(ws(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async delete(e,t={},n){return Ks(Os(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}},da=class{constructor(e){this.parentClient=e}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(Jr(this.getClient(n),o,n,Ys(t)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}};function pa(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);null!=n&&Nt(t,["mediaResolution"],n);const o=kt(e,["toolCall"]);null!=o&&Nt(t,["toolCall"],o);const i=kt(e,["toolResponse"]);null!=i&&Nt(t,["toolResponse"],i);const r=kt(e,["audioTranscription"]);null!=r&&Nt(t,["audioTranscription"],r);const s=kt(e,["codeExecutionResult"]);null!=s&&Nt(t,["codeExecutionResult"],s);const a=kt(e,["executableCode"]);null!=a&&Nt(t,["executableCode"],a);const l=kt(e,["fileData"]);null!=l&&Nt(t,["fileData"],l);const u=kt(e,["functionCall"]);null!=u&&Nt(t,["functionCall"],function(e){const t={},n=kt(e,["args"]);null!=n&&Nt(t,["args"],n);const o=kt(e,["id"]);null!=o&&Nt(t,["id"],o);const i=kt(e,["name"]);if(null!=i&&Nt(t,["name"],i),void 0!==kt(e,["partialArgs"]))throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(u));const c=kt(e,["functionResponse"]);null!=c&&Nt(t,["functionResponse"],c);const d=kt(e,["inlineData"]);null!=d&&Nt(t,["inlineData"],d);const p=kt(e,["text"]);null!=p&&Nt(t,["text"],p);const m=kt(e,["thought"]);null!=m&&Nt(t,["thought"],m);const h=kt(e,["thoughtSignature"]);null!=h&&Nt(t,["thoughtSignature"],h);const f=kt(e,["videoMetadata"]);null!=f&&Nt(t,["videoMetadata"],f);const v=kt(e,["partMetadata"]);null!=v&&Nt(t,["partMetadata"],v);const g=kt(e,["mediaProcessing"]);null!=g&&Nt(t,["mediaProcessing"],g);const _=kt(e,["speechMetadata"]);null!=_&&Nt(t,["speechMetadata"],_);const y=kt(e,["documentMetadata"]);null!=y&&Nt(t,["documentMetadata"],y);const E=kt(e,["spreadsheetMetadata"]);null!=E&&Nt(t,["spreadsheetMetadata"],E);const T=kt(e,["audioMetadata"]);return null!=T&&Nt(t,["audioMetadata"],T),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}function ma(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);if(null!=n&&Nt(t,["mediaResolution"],n),void 0!==kt(e,["toolCall"]))throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["toolResponse"]))throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=kt(e,["audioTranscription"]);null!=o&&Nt(t,["audioTranscription"],o);const i=kt(e,["codeExecutionResult"]);null!=i&&Nt(t,["codeExecutionResult"],i);const r=kt(e,["executableCode"]);null!=r&&Nt(t,["executableCode"],r);const s=kt(e,["fileData"]);null!=s&&Nt(t,["fileData"],s);const a=kt(e,["functionCall"]);null!=a&&Nt(t,["functionCall"],a);const l=kt(e,["functionResponse"]);null!=l&&Nt(t,["functionResponse"],function(e){const t={},n=kt(e,["id"]);null!=n&&Nt(t,["id"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["parts"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["fileData"]);null!=n&&Nt(t,["fileData"],n);const o=kt(e,["inlineData"]);if(null!=o&&Nt(t,["inlineData"],o),void 0!==kt(e,["mediaProcessing"]))throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const i=kt(e,["mediaResolution"]);null!=i&&Nt(t,["mediaResolution"],i);const r=kt(e,["videoMetadata"]);null!=r&&Nt(t,["videoMetadata"],r);const s=kt(e,["documentMetadata"]);null!=s&&Nt(t,["documentMetadata"],s);const a=kt(e,["spreadsheetMetadata"]);null!=a&&Nt(t,["spreadsheetMetadata"],a);const l=kt(e,["audioMetadata"]);return null!=l&&Nt(t,["audioMetadata"],l),t}(e))),Nt(t,["parts"],e)}const r=kt(e,["response"]);null!=r&&Nt(t,["response"],r);const s=kt(e,["scheduling"]);if(null!=s&&Nt(t,["scheduling"],s),void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(l));const u=kt(e,["inlineData"]);null!=u&&Nt(t,["inlineData"],u);const c=kt(e,["text"]);null!=c&&Nt(t,["text"],c);const d=kt(e,["thought"]);null!=d&&Nt(t,["thought"],d);const p=kt(e,["thoughtSignature"]);null!=p&&Nt(t,["thoughtSignature"],p);const m=kt(e,["videoMetadata"]);if(null!=m&&Nt(t,["videoMetadata"],m),void 0!==kt(e,["partMetadata"]))throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const h=kt(e,["mediaProcessing"]);null!=h&&Nt(t,["mediaProcessing"],h);const f=kt(e,["speechMetadata"]);null!=f&&Nt(t,["speechMetadata"],f);const v=kt(e,["documentMetadata"]);null!=v&&Nt(t,["documentMetadata"],v);const g=kt(e,["spreadsheetMetadata"]);null!=g&&Nt(t,["spreadsheetMetadata"],g);const _=kt(e,["audioMetadata"]);return null!=_&&Nt(t,["audioMetadata"],_),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}function ha(e){const t={},n=kt(e,["systemInstruction"]);null!=n&&Nt(t,["systemInstruction"],pa(On(n)));const o=kt(e,["tools"]);return null!=o&&Nt(t,["tools"],function(e){const t={},n=kt(e,["tools"]);if(null!=n){let e=xn(n);Array.isArray(e)&&(e=e.map(e=>ya(Mn(e)))),Nt(t,["tools"],e)}return t}(o)),t}function fa(e){const t={},n=kt(e,["systemInstruction"]);null!=n&&Nt(t,["systemInstruction"],ma(On(n)));const o=kt(e,["tools"]);return null!=o&&Nt(t,["tools"],function(e){const t={},n=kt(e,["tools"]);if(null!=n){let e=xn(n);Array.isArray(e)&&(e=e.map(e=>Ea(Mn(e)))),Nt(t,["tools"],e)}return t}(o)),t}function va(e){const t={},n=kt(e,["media"]);if(null!=n){let e=_n(n);Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mediaChunks"],e)}const o=kt(e,["audio"]);null!=o&&Nt(t,["audio"],Tn(o));const i=kt(e,["audioStreamEnd"]);null!=i&&Nt(t,["audioStreamEnd"],i);const r=kt(e,["video"]);null!=r&&Nt(t,["video"],En(r));const s=kt(e,["text"]);null!=s&&Nt(t,["text"],s);const a=kt(e,["activityStart"]);null!=a&&Nt(t,["activityStart"],a);const l=kt(e,["activityEnd"]);return null!=l&&Nt(t,["activityEnd"],l),t}function ga(e){const t={},n=kt(e,["media"]);if(null!=n){let e=_n(n);Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mediaChunks"],e)}const o=kt(e,["audio"]);null!=o&&Nt(t,["audio"],Tn(o));const i=kt(e,["audioStreamEnd"]);null!=i&&Nt(t,["audioStreamEnd"],i);const r=kt(e,["video"]);null!=r&&Nt(t,["video"],En(r));const s=kt(e,["text"]);null!=s&&Nt(t,["text"],s);const a=kt(e,["activityStart"]);null!=a&&Nt(t,["activityStart"],a);const l=kt(e,["activityEnd"]);return null!=l&&Nt(t,["activityEnd"],l),t}function _a(e){const t={},n=kt(e,["voiceConfig"]);null!=n&&Nt(t,["voiceConfig"],Ta(n));const o=kt(e,["languageCode"]);null!=o&&Nt(t,["languageCode"],o);const i=kt(e,["multiSpeakerVoiceConfig"]);return null!=i&&Nt(t,["multiSpeakerVoiceConfig"],function(e){const t={},n=kt(e,["speakerVoiceConfigs"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["speaker"]);null!=n&&Nt(t,["speaker"],n);const o=kt(e,["voiceConfig"]);return null!=o&&Nt(t,["voiceConfig"],Ta(o)),t}(e))),Nt(t,["speakerVoiceConfigs"],e)}return t}(i)),t}function ya(e){const t={};if(void 0!==kt(e,["retrieval"]))throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["googleMaps"]);null!=n&&Nt(t,["googleMaps"],function(e){const t={},n=kt(e,["authConfig"]);null!=n&&Nt(t,["authConfig"],function(e){const t={},n=kt(e,["apiKey"]);if(null!=n&&Nt(t,["apiKey"],n),void 0!==kt(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["authType"]))throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oauthConfig"]))throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oidcConfig"]))throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["enableWidget"]);if(null!=o&&Nt(t,["enableWidget"],o),void 0!==kt(e,["groundingTypes"]))throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["mcpServers"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mcpServers"],e)}const i=kt(e,["codeExecution"]);null!=i&&Nt(t,["codeExecution"],i);const r=kt(e,["computerUse"]);if(null!=r&&Nt(t,["computerUse"],r),void 0!==kt(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["exaAiSearch"]))throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const a=kt(e,["googleSearch"]);null!=a&&Nt(t,["googleSearch"],function(e){const t={};if(void 0!==kt(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["excludeDomains"]))throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["searchTypes"]);null!=n&&Nt(t,["searchTypes"],n);const o=kt(e,["timeRangeFilter"]);return null!=o&&Nt(t,["timeRangeFilter"],o),t}(a));const l=kt(e,["googleSearchRetrieval"]);if(null!=l&&Nt(t,["googleSearchRetrieval"],l),void 0!==kt(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=kt(e,["urlContext"]);null!=u&&Nt(t,["urlContext"],u);const c=kt(e,["fileSearch"]);return null!=c&&Nt(t,["fileSearch"],c),t}function Ea(e){const t={},n=kt(e,["retrieval"]);null!=n&&Nt(t,["retrieval"],n);const o=kt(e,["googleMaps"]);null!=o&&Nt(t,["googleMaps"],o);const i=kt(e,["mcpServers"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){if(void 0!==kt(e,["name"]))throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["streamableHttpTransport"]))throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}(e))),Nt(t,["mcpServers"],e)}const r=kt(e,["codeExecution"]);null!=r&&Nt(t,["codeExecution"],r);const s=kt(e,["computerUse"]);null!=s&&Nt(t,["computerUse"],s);const a=kt(e,["enterpriseWebSearch"]);null!=a&&Nt(t,["enterpriseWebSearch"],a);const l=kt(e,["exaAiSearch"]);null!=l&&Nt(t,["exaAiSearch"],l);const u=kt(e,["functionDeclarations"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const c=kt(e,["googleSearch"]);null!=c&&Nt(t,["googleSearch"],c);const d=kt(e,["googleSearchRetrieval"]);null!=d&&Nt(t,["googleSearchRetrieval"],d);const p=kt(e,["parallelAiSearch"]);null!=p&&Nt(t,["parallelAiSearch"],p);const m=kt(e,["urlContext"]);if(null!=m&&Nt(t,["urlContext"],m),void 0!==kt(e,["fileSearch"]))throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function Ta(e){const t={},n=kt(e,["replicatedVoiceConfig"]);null!=n&&Nt(t,["replicatedVoiceConfig"],function(e){const t={},n=kt(e,["mimeType"]);null!=n&&Nt(t,["mimeType"],n);const o=kt(e,["voiceSampleAudio"]);if(null!=o&&Nt(t,["voiceSampleAudio"],o),void 0!==kt(e,["consentAudio"]))throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["voiceConsentSignature"]))throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(n));const o=kt(e,["prebuiltVoiceConfig"]);null!=o&&Nt(t,["prebuiltVoiceConfig"],o);const i=kt(e,["voice"]);return null!=i&&Nt(t,["voice"],i),t}function Aa(e,t){const n={},o=kt(e,["values"]);null!=o&&Nt(n,["values"],o);const i=kt(e,["statistics"]);return null!=i&&Nt(n,["statistics"],function(e){const t={},n=kt(e,["truncated"]);null!=n&&Nt(t,["truncated"],n);const o=kt(e,["token_count"]);null!=o&&Nt(t,["tokenCount"],o);const i=kt(e,["tokensDetails"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["tokensDetails"],e)}return t}(i)),n}function Ia(e,t){const n={},o=kt(e,["parts"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);null!=n&&Nt(t,["mediaResolution"],n);const o=kt(e,["toolCall"]);null!=o&&Nt(t,["toolCall"],o);const i=kt(e,["toolResponse"]);null!=i&&Nt(t,["toolResponse"],i);const r=kt(e,["audioTranscription"]);null!=r&&Nt(t,["audioTranscription"],r);const s=kt(e,["codeExecutionResult"]);null!=s&&Nt(t,["codeExecutionResult"],s);const a=kt(e,["executableCode"]);null!=a&&Nt(t,["executableCode"],a);const l=kt(e,["fileData"]);null!=l&&Nt(t,["fileData"],l);const u=kt(e,["functionCall"]);null!=u&&Nt(t,["functionCall"],function(e){const t={},n=kt(e,["args"]);null!=n&&Nt(t,["args"],n);const o=kt(e,["id"]);null!=o&&Nt(t,["id"],o);const i=kt(e,["name"]);if(null!=i&&Nt(t,["name"],i),void 0!==kt(e,["partialArgs"]))throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(u));const c=kt(e,["functionResponse"]);null!=c&&Nt(t,["functionResponse"],c);const d=kt(e,["inlineData"]);null!=d&&Nt(t,["inlineData"],d);const p=kt(e,["text"]);null!=p&&Nt(t,["text"],p);const m=kt(e,["thought"]);null!=m&&Nt(t,["thought"],m);const h=kt(e,["thoughtSignature"]);null!=h&&Nt(t,["thoughtSignature"],h);const f=kt(e,["videoMetadata"]);null!=f&&Nt(t,["videoMetadata"],f);const v=kt(e,["partMetadata"]);null!=v&&Nt(t,["partMetadata"],v);const g=kt(e,["mediaProcessing"]);null!=g&&Nt(t,["mediaProcessing"],g);const _=kt(e,["speechMetadata"]);null!=_&&Nt(t,["speechMetadata"],_);const y=kt(e,["documentMetadata"]);null!=y&&Nt(t,["documentMetadata"],y);const E=kt(e,["spreadsheetMetadata"]);null!=E&&Nt(t,["spreadsheetMetadata"],E);const T=kt(e,["audioMetadata"]);return null!=T&&Nt(t,["audioMetadata"],T),t}(e))),Nt(n,["parts"],e)}const i=kt(e,["role"]);return null!=i&&Nt(n,["role"],i),n}function Ca(e,t){const n={},o=kt(e,["parts"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);if(null!=n&&Nt(t,["mediaResolution"],n),void 0!==kt(e,["toolCall"]))throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["toolResponse"]))throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=kt(e,["audioTranscription"]);null!=o&&Nt(t,["audioTranscription"],o);const i=kt(e,["codeExecutionResult"]);null!=i&&Nt(t,["codeExecutionResult"],i);const r=kt(e,["executableCode"]);null!=r&&Nt(t,["executableCode"],r);const s=kt(e,["fileData"]);null!=s&&Nt(t,["fileData"],s);const a=kt(e,["functionCall"]);null!=a&&Nt(t,["functionCall"],a);const l=kt(e,["functionResponse"]);null!=l&&Nt(t,["functionResponse"],function(e){const t={},n=kt(e,["id"]);null!=n&&Nt(t,["id"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["parts"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["fileData"]);null!=n&&Nt(t,["fileData"],n);const o=kt(e,["inlineData"]);if(null!=o&&Nt(t,["inlineData"],o),void 0!==kt(e,["mediaProcessing"]))throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const i=kt(e,["mediaResolution"]);null!=i&&Nt(t,["mediaResolution"],i);const r=kt(e,["videoMetadata"]);null!=r&&Nt(t,["videoMetadata"],r);const s=kt(e,["documentMetadata"]);null!=s&&Nt(t,["documentMetadata"],s);const a=kt(e,["spreadsheetMetadata"]);null!=a&&Nt(t,["spreadsheetMetadata"],a);const l=kt(e,["audioMetadata"]);return null!=l&&Nt(t,["audioMetadata"],l),t}(e))),Nt(t,["parts"],e)}const r=kt(e,["response"]);null!=r&&Nt(t,["response"],r);const s=kt(e,["scheduling"]);if(null!=s&&Nt(t,["scheduling"],s),void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(l));const u=kt(e,["inlineData"]);null!=u&&Nt(t,["inlineData"],u);const c=kt(e,["text"]);null!=c&&Nt(t,["text"],c);const d=kt(e,["thought"]);null!=d&&Nt(t,["thought"],d);const p=kt(e,["thoughtSignature"]);null!=p&&Nt(t,["thoughtSignature"],p);const m=kt(e,["videoMetadata"]);if(null!=m&&Nt(t,["videoMetadata"],m),void 0!==kt(e,["partMetadata"]))throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const h=kt(e,["mediaProcessing"]);null!=h&&Nt(t,["mediaProcessing"],h);const f=kt(e,["speechMetadata"]);null!=f&&Nt(t,["speechMetadata"],f);const v=kt(e,["documentMetadata"]);null!=v&&Nt(t,["documentMetadata"],v);const g=kt(e,["spreadsheetMetadata"]);null!=g&&Nt(t,["spreadsheetMetadata"],g);const _=kt(e,["audioMetadata"]);return null!=_&&Nt(t,["audioMetadata"],_),t}(e))),Nt(n,["parts"],e)}const i=kt(e,["role"]);return null!=i&&Nt(n,["role"],i),n}function Sa(e,t,n){const o={},i=kt(t,["model"]);null!=i&&Nt(o,["_url","model"],vn(e,i));const r=kt(t,["contents"]);if(null!=r){let e=Rn(r);Array.isArray(e)&&(e=e.map(e=>Ia(e))),Nt(o,["contents"],e)}const s=kt(t,["config"]);return null!=s&&Nt(o,["generationConfig"],function(e,t,n){const o={},i=kt(t,["serviceTier"]);void 0!==n&&null!=i&&Nt(n,["serviceTier"],i);const r=kt(t,["systemInstruction"]);void 0!==n&&null!=r&&Nt(n,["systemInstruction"],Ia(On(r)));const s=kt(t,["temperature"]);null!=s&&Nt(o,["temperature"],s);const a=kt(t,["topP"]);null!=a&&Nt(o,["topP"],a);const l=kt(t,["topK"]);null!=l&&Nt(o,["topK"],l);const u=kt(t,["candidateCount"]);null!=u&&Nt(o,["candidateCount"],u);const c=kt(t,["maxOutputTokens"]);null!=c&&Nt(o,["maxOutputTokens"],c);const d=kt(t,["stopSequences"]);null!=d&&Nt(o,["stopSequences"],d);const p=kt(t,["responseLogprobs"]);null!=p&&Nt(o,["responseLogprobs"],p);const m=kt(t,["logprobs"]);null!=m&&Nt(o,["logprobs"],m);const h=kt(t,["presencePenalty"]);null!=h&&Nt(o,["presencePenalty"],h);const f=kt(t,["frequencyPenalty"]);null!=f&&Nt(o,["frequencyPenalty"],f);const v=kt(t,["seed"]);null!=v&&Nt(o,["seed"],v);const g=kt(t,["responseMimeType"]);null!=g&&Nt(o,["responseMimeType"],g);const _=kt(t,["responseSchema"]);null!=_&&Nt(o,["responseSchema"],Nn(_));const y=kt(t,["responseJsonSchema"]);if(null!=y&&Nt(o,["responseJsonSchema"],y),void 0!==kt(t,["routingConfig"]))throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(t,["modelSelectionConfig"]))throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const E=kt(t,["safetySettings"]);if(void 0!==n&&null!=E){let e=E;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["category"]);if(null!=n&&Nt(t,["category"],n),void 0!==kt(e,["method"]))throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["threshold"]);return null!=o&&Nt(t,["threshold"],o),t}(e))),Nt(n,["safetySettings"],e)}const T=kt(t,["tools"]);if(void 0!==n&&null!=T){let e=xn(T);Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==kt(e,["retrieval"]))throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["googleMaps"]);null!=n&&Nt(t,["googleMaps"],function(e){const t={},n=kt(e,["authConfig"]);null!=n&&Nt(t,["authConfig"],function(e){const t={},n=kt(e,["apiKey"]);if(null!=n&&Nt(t,["apiKey"],n),void 0!==kt(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["authType"]))throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oauthConfig"]))throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oidcConfig"]))throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["enableWidget"]);if(null!=o&&Nt(t,["enableWidget"],o),void 0!==kt(e,["groundingTypes"]))throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["mcpServers"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mcpServers"],e)}const i=kt(e,["codeExecution"]);null!=i&&Nt(t,["codeExecution"],i);const r=kt(e,["computerUse"]);if(null!=r&&Nt(t,["computerUse"],r),void 0!==kt(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["exaAiSearch"]))throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const a=kt(e,["googleSearch"]);null!=a&&Nt(t,["googleSearch"],function(e){const t={};if(void 0!==kt(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["excludeDomains"]))throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["searchTypes"]);null!=n&&Nt(t,["searchTypes"],n);const o=kt(e,["timeRangeFilter"]);return null!=o&&Nt(t,["timeRangeFilter"],o),t}(a));const l=kt(e,["googleSearchRetrieval"]);if(null!=l&&Nt(t,["googleSearchRetrieval"],l),void 0!==kt(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=kt(e,["urlContext"]);null!=u&&Nt(t,["urlContext"],u);const c=kt(e,["fileSearch"]);return null!=c&&Nt(t,["fileSearch"],c),t}(Mn(e)))),Nt(n,["tools"],e)}const A=kt(t,["toolConfig"]);void 0!==n&&null!=A&&Nt(n,["toolConfig"],function(e){const t={},n=kt(e,["functionCallingConfig"]);null!=n&&Nt(t,["functionCallingConfig"],function(e){const t={},n=kt(e,["allowedFunctionNames"]);null!=n&&Nt(t,["allowedFunctionNames"],n);const o=kt(e,["mode"]);if(null!=o&&Nt(t,["mode"],o),void 0!==kt(e,["streamFunctionCallArguments"]))throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["retrievalConfig"]);null!=o&&Nt(t,["retrievalConfig"],o);const i=kt(e,["includeServerSideToolInvocations"]);return null!=i&&Nt(t,["includeServerSideToolInvocations"],i),t}(A));const I=kt(t,["labels"]);void 0!==n&&null!=I&&Nt(n,["labels"],I);const C=kt(t,["cachedContent"]);void 0!==n&&null!=C&&Nt(n,["cachedContent"],Gn(e,C));const S=kt(t,["responseModalities"]);null!=S&&Nt(o,["responseModalities"],S);const b=kt(t,["mediaResolution"]);null!=b&&Nt(o,["mediaResolution"],b);const O=kt(t,["speechConfig"]);if(null!=O&&Nt(o,["speechConfig"],kn(O)),void 0!==kt(t,["audioTimestamp"]))throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const w=kt(t,["thinkingConfig"]);null!=w&&Nt(o,["thinkingConfig"],w);const R=kt(t,["audioTranscriptionConfig"]);null!=R&&Nt(o,["audioTranscriptionConfig"],R);const P=kt(t,["imageConfig"]);null!=P&&Nt(o,["imageConfig"],function(e){const t={},n=kt(e,["aspectRatio"]);null!=n&&Nt(t,["aspectRatio"],n);const o=kt(e,["imageSize"]);if(null!=o&&Nt(t,["imageSize"],o),void 0!==kt(e,["personGeneration"]))throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["outputMimeType"]))throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["outputCompressionQuality"]))throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["imageOutputOptions"]))throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["prominentPeople"]))throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(P));const N=kt(t,["enableEnhancedCivicAnswers"]);if(null!=N&&Nt(o,["enableEnhancedCivicAnswers"],N),void 0!==kt(t,["modelArmorConfig"]))throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const k=kt(t,["continuationToken"]);if(void 0!==n&&null!=k&&Nt(n,["continuationToken"],k),void 0!==kt(t,["generationOutputConfig"]))throw new Error("generationOutputConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const D=kt(t,["store"]);return void 0!==n&&null!=D&&Nt(n,["store"],D),o}(e,s,o)),o}function ba(e,t,n){const o={},i=kt(t,["model"]);null!=i&&Nt(o,["_url","model"],vn(e,i));const r=kt(t,["contents"]);if(null!=r){let e=Rn(r);Array.isArray(e)&&(e=e.map(e=>Ca(e))),Nt(o,["contents"],e)}const s=kt(t,["config"]);return null!=s&&Nt(o,["generationConfig"],function(e,t,n){const o={},i=kt(t,["serviceTier"]);void 0!==n&&null!=i&&Nt(n,["serviceTier"],i);const r=kt(t,["systemInstruction"]);void 0!==n&&null!=r&&Nt(n,["systemInstruction"],Ca(On(r)));const s=kt(t,["temperature"]);null!=s&&Nt(o,["temperature"],s);const a=kt(t,["topP"]);null!=a&&Nt(o,["topP"],a);const l=kt(t,["topK"]);null!=l&&Nt(o,["topK"],l);const u=kt(t,["candidateCount"]);null!=u&&Nt(o,["candidateCount"],u);const c=kt(t,["maxOutputTokens"]);null!=c&&Nt(o,["maxOutputTokens"],c);const d=kt(t,["stopSequences"]);null!=d&&Nt(o,["stopSequences"],d);const p=kt(t,["responseLogprobs"]);null!=p&&Nt(o,["responseLogprobs"],p);const m=kt(t,["logprobs"]);null!=m&&Nt(o,["logprobs"],m);const h=kt(t,["presencePenalty"]);null!=h&&Nt(o,["presencePenalty"],h);const f=kt(t,["frequencyPenalty"]);null!=f&&Nt(o,["frequencyPenalty"],f);const v=kt(t,["seed"]);null!=v&&Nt(o,["seed"],v);const g=kt(t,["responseMimeType"]);null!=g&&Nt(o,["responseMimeType"],g);const _=kt(t,["responseSchema"]);null!=_&&Nt(o,["responseSchema"],Nn(_));const y=kt(t,["responseJsonSchema"]);null!=y&&Nt(o,["responseJsonSchema"],y);const E=kt(t,["routingConfig"]);null!=E&&Nt(o,["routingConfig"],E);const T=kt(t,["modelSelectionConfig"]);null!=T&&Nt(o,["modelConfig"],T);const A=kt(t,["safetySettings"]);if(void 0!==n&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>e)),Nt(n,["safetySettings"],e)}const I=kt(t,["tools"]);if(void 0!==n&&null!=I){let e=xn(I);Array.isArray(e)&&(e=e.map(e=>Ua(Mn(e)))),Nt(n,["tools"],e)}const C=kt(t,["toolConfig"]);void 0!==n&&null!=C&&Nt(n,["toolConfig"],function(e){const t={},n=kt(e,["functionCallingConfig"]);null!=n&&Nt(t,["functionCallingConfig"],n);const o=kt(e,["retrievalConfig"]);if(null!=o&&Nt(t,["retrievalConfig"],o),void 0!==kt(e,["includeServerSideToolInvocations"]))throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(C));const S=kt(t,["labels"]);void 0!==n&&null!=S&&Nt(n,["labels"],S);const b=kt(t,["cachedContent"]);void 0!==n&&null!=b&&Nt(n,["cachedContent"],Gn(e,b));const O=kt(t,["responseModalities"]);null!=O&&Nt(o,["responseModalities"],O);const w=kt(t,["mediaResolution"]);null!=w&&Nt(o,["mediaResolution"],w);const R=kt(t,["speechConfig"]);null!=R&&Nt(o,["speechConfig"],Ga(kn(R)));const P=kt(t,["audioTimestamp"]);null!=P&&Nt(o,["audioTimestamp"],P);const N=kt(t,["thinkingConfig"]);null!=N&&Nt(o,["thinkingConfig"],N);const k=kt(t,["audioTranscriptionConfig"]);null!=k&&Nt(o,["audioTranscriptionConfig"],k);const D=kt(t,["imageConfig"]);if(null!=D&&Nt(o,["imageConfig"],function(e){const t={},n=kt(e,["aspectRatio"]);null!=n&&Nt(t,["aspectRatio"],n);const o=kt(e,["imageSize"]);null!=o&&Nt(t,["imageSize"],o);const i=kt(e,["personGeneration"]);null!=i&&Nt(t,["personGeneration"],i);const r=kt(e,["outputMimeType"]);null!=r&&Nt(t,["imageOutputOptions","mimeType"],r);const s=kt(e,["outputCompressionQuality"]);null!=s&&Nt(t,["imageOutputOptions","compressionQuality"],s);const a=kt(e,["imageOutputOptions"]);null!=a&&Nt(t,["imageOutputOptions"],a);const l=kt(e,["prominentPeople"]);return null!=l&&Nt(t,["prominentPeople"],l),t}(D)),void 0!==kt(t,["enableEnhancedCivicAnswers"]))throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const M=kt(t,["modelArmorConfig"]);void 0!==n&&null!=M&&Nt(n,["modelArmorConfig"],M);const x=kt(t,["continuationToken"]);void 0!==n&&null!=x&&Nt(n,["continuationToken"],x);const G=kt(t,["generationOutputConfig"]);if(void 0!==n&&null!=G&&Nt(n,["outputConfig"],G),void 0!==kt(t,["store"]))throw new Error("store parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return o}(e,s,o)),o}function Oa(e,t){const n={},o=kt(e,["sdkHttpResponse"]);null!=o&&Nt(n,["sdkHttpResponse"],o);const i=kt(e,["candidates"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["content"]);null!=n&&Nt(t,["content"],n);const o=kt(e,["citationMetadata"]);null!=o&&Nt(t,["citationMetadata"],function(e){const t={},n=kt(e,["citationSources"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["citations"],e)}return t}(o));const i=kt(e,["tokenCount"]);null!=i&&Nt(t,["tokenCount"],i);const r=kt(e,["finishReason"]);null!=r&&Nt(t,["finishReason"],r);const s=kt(e,["groundingMetadata"]);null!=s&&Nt(t,["groundingMetadata"],s);const a=kt(e,["avgLogprobs"]);null!=a&&Nt(t,["avgLogprobs"],a);const l=kt(e,["index"]);null!=l&&Nt(t,["index"],l);const u=kt(e,["logprobsResult"]);null!=u&&Nt(t,["logprobsResult"],u);const c=kt(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["safetyRatings"],e)}const d=kt(e,["urlContextMetadata"]);null!=d&&Nt(t,["urlContextMetadata"],d);const p=kt(e,["continuationToken"]);return null!=p&&Nt(t,["continuationToken"],p),t}(e))),Nt(n,["candidates"],e)}const r=kt(e,["modelVersion"]);null!=r&&Nt(n,["modelVersion"],r);const s=kt(e,["promptFeedback"]);null!=s&&Nt(n,["promptFeedback"],s);const a=kt(e,["responseId"]);null!=a&&Nt(n,["responseId"],a);const l=kt(e,["usageMetadata"]);null!=l&&Nt(n,["usageMetadata"],l);const u=kt(e,["modelStatus"]);return null!=u&&Nt(n,["modelStatus"],u),n}function wa(e,t){const n={},o=kt(e,["sdkHttpResponse"]);null!=o&&Nt(n,["sdkHttpResponse"],o);const i=kt(e,["candidates"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(n,["candidates"],e)}const r=kt(e,["createTime"]);null!=r&&Nt(n,["createTime"],r);const s=kt(e,["modelVersion"]);null!=s&&Nt(n,["modelVersion"],s);const a=kt(e,["promptFeedback"]);null!=a&&Nt(n,["promptFeedback"],a);const l=kt(e,["responseId"]);null!=l&&Nt(n,["responseId"],l);const u=kt(e,["usageMetadata"]);return null!=u&&Nt(n,["usageMetadata"],u),n}function Ra(e,t,n){const o={},i=kt(t,["model"]);null!=i&&Nt(o,["_url","model"],vn(e,i));const r=kt(t,["prompt"]);null!=r&&Nt(o,["instances[0]","prompt"],r);const s=kt(t,["image"]);null!=s&&Nt(o,["instances[0]","image"],ka(s));const a=kt(t,["video"]);null!=a&&Nt(o,["instances[0]","video"],La(a));const l=kt(t,["source"]);null!=l&&function(e,t){const n=kt(e,["prompt"]);void 0!==t&&null!=n&&Nt(t,["instances[0]","prompt"],n);const o=kt(e,["image"]);void 0!==t&&null!=o&&Nt(t,["instances[0]","image"],ka(o));const i=kt(e,["video"]);void 0!==t&&null!=i&&Nt(t,["instances[0]","video"],La(i))}(l,o);const u=kt(t,["config"]);return null!=u&&function(e,t){const n=kt(e,["numberOfVideos"]);void 0!==t&&null!=n&&Nt(t,["parameters","sampleCount"],n);const o=kt(e,["outputGcsUri"]);void 0!==t&&null!=o&&Nt(t,["parameters","storageUri"],o);const i=kt(e,["fps"]);void 0!==t&&null!=i&&Nt(t,["parameters","fps"],i);const r=kt(e,["durationSeconds"]);void 0!==t&&null!=r&&Nt(t,["parameters","durationSeconds"],r);const s=kt(e,["seed"]);void 0!==t&&null!=s&&Nt(t,["parameters","seed"],s);const a=kt(e,["aspectRatio"]);void 0!==t&&null!=a&&Nt(t,["parameters","aspectRatio"],a);const l=kt(e,["resolution"]);void 0!==t&&null!=l&&Nt(t,["parameters","resolution"],l);const u=kt(e,["personGeneration"]);void 0!==t&&null!=u&&Nt(t,["parameters","personGeneration"],u);const c=kt(e,["pubsubTopic"]);void 0!==t&&null!=c&&Nt(t,["parameters","pubsubTopic"],c);const d=kt(e,["negativePrompt"]);void 0!==t&&null!=d&&Nt(t,["parameters","negativePrompt"],d);const p=kt(e,["enhancePrompt"]);void 0!==t&&null!=p&&Nt(t,["parameters","enhancePrompt"],p);const m=kt(e,["generateAudio"]);void 0!==t&&null!=m&&Nt(t,["parameters","generateAudio"],m);const h=kt(e,["lastFrame"]);void 0!==t&&null!=h&&Nt(t,["instances[0]","lastFrame"],ka(h));const f=kt(e,["referenceImages"]);if(void 0!==t&&null!=f){let e=f;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["image"]);null!=n&&Nt(t,["image"],ka(n));const o=kt(e,["referenceType"]);return null!=o&&Nt(t,["referenceType"],o),t}(e))),Nt(t,["instances[0]","referenceImages"],e)}const v=kt(e,["mask"]);void 0!==t&&null!=v&&Nt(t,["instances[0]","mask"],function(e){const t={},n=kt(e,["image"]);null!=n&&Nt(t,["_self"],ka(n));const o=kt(e,["maskMode"]);return null!=o&&Nt(t,["maskMode"],o),t}(v));const g=kt(e,["compressionQuality"]);void 0!==t&&null!=g&&Nt(t,["parameters","compressionQuality"],g);const _=kt(e,["labels"]);if(void 0!==t&&null!=_&&Nt(t,["labels"],_),void 0!==kt(e,["webhookConfig"]))throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const y=kt(e,["resizeMode"]);void 0!==t&&null!=y&&Nt(t,["parameters","resizeMode"],y)}(u,o),o}function Pa(e,t){const n={},o=kt(e,["_self"]);null!=o&&Nt(n,["image"],Na(o));const i=kt(e,["raiFilteredReason"]);null!=i&&Nt(n,["raiFilteredReason"],i);const r=kt(e,["_self"]);null!=r&&Nt(n,["safetyAttributes"],xa(r));const s=kt(e,["prompt"]);return null!=s&&Nt(n,["enhancedPrompt"],s),n}function Na(e,t){const n={},o=kt(e,["gcsUri"]);null!=o&&Nt(n,["gcsUri"],o);const i=kt(e,["bytesBase64Encoded"]);null!=i&&Nt(n,["imageBytes"],Ln(i));const r=kt(e,["mimeType"]);return null!=r&&Nt(n,["mimeType"],r),n}function ka(e,t){const n={},o=kt(e,["gcsUri"]);null!=o&&Nt(n,["gcsUri"],o);const i=kt(e,["imageBytes"]);null!=i&&Nt(n,["bytesBase64Encoded"],Ln(i));const r=kt(e,["mimeType"]);return null!=r&&Nt(n,["mimeType"],r),n}function Da(e,t){const n={},o=kt(e,["name"]);null!=o&&Nt(n,["name"],o);const i=kt(e,["displayName"]);null!=i&&Nt(n,["displayName"],i);const r=kt(e,["description"]);null!=r&&Nt(n,["description"],r);const s=kt(e,["version"]);null!=s&&Nt(n,["version"],s);const a=kt(e,["_self"]);null!=a&&Nt(n,["tunedModelInfo"],function(e){const t={},n=kt(e,["baseModel"]);null!=n&&Nt(t,["baseModel"],n);const o=kt(e,["createTime"]);null!=o&&Nt(t,["createTime"],o);const i=kt(e,["updateTime"]);return null!=i&&Nt(t,["updateTime"],i),t}(a));const l=kt(e,["inputTokenLimit"]);null!=l&&Nt(n,["inputTokenLimit"],l);const u=kt(e,["outputTokenLimit"]);null!=u&&Nt(n,["outputTokenLimit"],u);const c=kt(e,["supportedGenerationMethods"]);null!=c&&Nt(n,["supportedActions"],c);const d=kt(e,["temperature"]);null!=d&&Nt(n,["temperature"],d);const p=kt(e,["maxTemperature"]);null!=p&&Nt(n,["maxTemperature"],p);const m=kt(e,["topP"]);null!=m&&Nt(n,["topP"],m);const h=kt(e,["topK"]);null!=h&&Nt(n,["topK"],h);const f=kt(e,["thinking"]);return null!=f&&Nt(n,["thinking"],f),n}function Ma(e,t){const n={},o=kt(e,["name"]);null!=o&&Nt(n,["name"],o);const i=kt(e,["displayName"]);null!=i&&Nt(n,["displayName"],i);const r=kt(e,["description"]);null!=r&&Nt(n,["description"],r);const s=kt(e,["versionId"]);null!=s&&Nt(n,["version"],s);const a=kt(e,["deployedModels"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["endpoint"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["deployedModelId"]);return null!=o&&Nt(t,["deployedModelId"],o),t}(e))),Nt(n,["endpoints"],e)}const l=kt(e,["labels"]);null!=l&&Nt(n,["labels"],l);const u=kt(e,["_self"]);null!=u&&Nt(n,["tunedModelInfo"],function(e){const t={},n=kt(e,["labels","google-vertex-llm-tuning-base-model-id"]);null!=n&&Nt(t,["baseModel"],n);const o=kt(e,["createTime"]);null!=o&&Nt(t,["createTime"],o);const i=kt(e,["updateTime"]);return null!=i&&Nt(t,["updateTime"],i),t}(u));const c=kt(e,["defaultCheckpointId"]);null!=c&&Nt(n,["defaultCheckpointId"],c);const d=kt(e,["checkpoints"]);if(null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),Nt(n,["checkpoints"],e)}return n}function xa(e,t){const n={},o=kt(e,["safetyAttributes","categories"]);null!=o&&Nt(n,["categories"],o);const i=kt(e,["safetyAttributes","scores"]);null!=i&&Nt(n,["scores"],i);const r=kt(e,["contentType"]);return null!=r&&Nt(n,["contentType"],r),n}function Ga(e,t){const n={},o=kt(e,["voiceConfig"]);null!=o&&Nt(n,["voiceConfig"],qa(o));const i=kt(e,["languageCode"]);null!=i&&Nt(n,["languageCode"],i);const r=kt(e,["multiSpeakerVoiceConfig"]);return null!=r&&Nt(n,["multiSpeakerVoiceConfig"],function(e){const t={},n=kt(e,["speakerVoiceConfigs"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["speaker"]);null!=n&&Nt(t,["speaker"],n);const o=kt(e,["voiceConfig"]);return null!=o&&Nt(t,["voiceConfig"],qa(o)),t}(e))),Nt(t,["speakerVoiceConfigs"],e)}return t}(r)),n}function Ua(e,t){const n={},o=kt(e,["retrieval"]);null!=o&&Nt(n,["retrieval"],o);const i=kt(e,["googleMaps"]);null!=i&&Nt(n,["googleMaps"],i);const r=kt(e,["mcpServers"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>function(e){if(void 0!==kt(e,["name"]))throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["streamableHttpTransport"]))throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}(e))),Nt(n,["mcpServers"],e)}const s=kt(e,["codeExecution"]);null!=s&&Nt(n,["codeExecution"],s);const a=kt(e,["computerUse"]);null!=a&&Nt(n,["computerUse"],a);const l=kt(e,["enterpriseWebSearch"]);null!=l&&Nt(n,["enterpriseWebSearch"],l);const u=kt(e,["exaAiSearch"]);null!=u&&Nt(n,["exaAiSearch"],u);const c=kt(e,["functionDeclarations"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),Nt(n,["functionDeclarations"],e)}const d=kt(e,["googleSearch"]);null!=d&&Nt(n,["googleSearch"],d);const p=kt(e,["googleSearchRetrieval"]);null!=p&&Nt(n,["googleSearchRetrieval"],p);const m=kt(e,["parallelAiSearch"]);null!=m&&Nt(n,["parallelAiSearch"],m);const h=kt(e,["urlContext"]);if(null!=h&&Nt(n,["urlContext"],h),void 0!==kt(e,["fileSearch"]))throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function La(e,t){const n={},o=kt(e,["uri"]);null!=o&&Nt(n,["gcsUri"],o);const i=kt(e,["videoBytes"]);null!=i&&Nt(n,["bytesBase64Encoded"],Ln(i));const r=kt(e,["mimeType"]);return null!=r&&Nt(n,["mimeType"],r),n}function qa(e,t){const n={},o=kt(e,["replicatedVoiceConfig"]);null!=o&&Nt(n,["replicatedVoiceConfig"],function(e){const t={},n=kt(e,["mimeType"]);null!=n&&Nt(t,["mimeType"],n);const o=kt(e,["voiceSampleAudio"]);if(null!=o&&Nt(t,["voiceSampleAudio"],o),void 0!==kt(e,["consentAudio"]))throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["voiceConsentSignature"]))throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(o));const i=kt(e,["prebuiltVoiceConfig"]);null!=i&&Nt(n,["prebuiltVoiceConfig"],i);const r=kt(e,["voice"]);return null!=r&&Nt(n,["voice"],r),n}function Ha(e,t){const n=kt(e,["mimeType"]);void 0!==t&&null!=n&&Nt(t,["mimeType"],n);const o=kt(e,["displayName"]);void 0!==t&&null!=o&&Nt(t,["displayName"],o);const i=kt(e,["customMetadata"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["customMetadata"],e)}const r=kt(e,["chunkingConfig"]);return void 0!==t&&null!=r&&Nt(t,["chunkingConfig"],r),{}}var ja="x-goog-api-client",Fa=/* @__PURE__ */new Set(["us","eu"]),Xa=Symbol.for("undici.globalDispatcher.1"),Ba=[408,429,500,502,503,504],Va=class{constructor(e){var t,n,o,i;this.clientOptions=Object.assign({},e),this.customBaseUrl=null===(t=e.httpOptions)||void 0===t?void 0:t.baseUrl;const r={};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 t=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!t?(r.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||"global"===this.clientOptions.location?r.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&Fa.has(this.clientOptions.location)?r.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(r.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),r.apiVersion=null!==(n=this.clientOptions.apiVersion)&&void 0!==n?n:"v1beta1"}else this.clientOptions.apiKey,r.apiVersion=null!==(i=null!==(o=this.clientOptions.apiVersion)&&void 0!==o?o:void 0)&&void 0!==i?i:"v1",r.baseUrl="https://generativelanguage.googleapis.com/";r.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=r,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(r,e.httpOptions))}isVertexAI(){var e;return null!==(e=this.clientOptions.vertexai)&&void 0!==e&&e}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&&void 0!==this.clientOptions.httpOptions.apiVersion)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.baseUrl)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&&void 0!==this.clientOptions.httpOptions.headers)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getFetch(){var e;return null===(e=this.clientOptions.httpOptions)||void 0===e?void 0:e.fetch}getTimeout(){var e;return null===(e=this.clientOptions.httpOptions)||void 0===e?void 0:e.timeout}getRequestUrlInternal(e){if(!e||void 0===e.baseUrl||void 0===e.apiVersion)throw new Error("HTTP options are not correctly set.");const t=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&""!==e.apiVersion&&t.push(e.apiVersion),t.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const e=this.getBaseUrl(),t=new URL(e);return t.protocol="http:"==t.protocol?"ws":"wss",t.toString()}setBaseUrl(e){if(!this.clientOptions.httpOptions)throw new Error("HTTP options are not correctly set.");this.clientOptions.httpOptions.baseUrl=e}resolveApiVersionInPath(e,t){const n="{api_version}";return""!==t?e.replaceAll(n,t):e.replaceAll(`${n}/`,"").replaceAll(`/${n}`,"").replaceAll(n,"")}constructUrl(e,t,n){if(e.includes("{api_version}")){if(!t||void 0===t.baseUrl||void 0===t.apiVersion)throw new Error("HTTP options are not correctly set.");const o=[t.baseUrl.endsWith("/")?t.baseUrl.slice(0,-1):t.baseUrl];n&&o.push(this.getBaseResourcePath());const i=this.resolveApiVersionInPath(e,t.apiVersion);return""!==i&&o.push(i),new URL(`${o.join("/")}`)}const o=[this.getRequestUrlInternal(t)];return n&&o.push(this.getBaseResourcePath()),""!==e&&o.push(e),new URL(`${o.join("/")}`)}shouldPrependVertexProjectPath(e,t){return!(t.baseUrl&&t.baseUrlResourceScope===et.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||e.path.startsWith("projects/")||"GET"===e.httpMethod&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const n=this.shouldPrependVertexProjectPath(e,t),o=this.constructUrl(e.path,t,n);if(e.queryParams)for(const[r,s]of Object.entries(e.queryParams))o.searchParams.append(r,String(s));let i={};if("GET"===e.httpMethod){if(e.body&&"{}"!==e.body)throw new Error("Request body should be empty for GET request, but got non empty request body")}else i.body=e.body;return i=await this.includeExtraHttpOptionsToRequestInit(i,t,o.toString()),this.unaryApiCall(o,i,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal,t.fetch)}patchHttpOptions(e,t){const n=JSON.parse(JSON.stringify(e));e.fetch&&(n.fetch=e.fetch);for(const[o,i]of Object.entries(t))"object"==typeof i?n[o]=Object.assign(Object.assign({},n[o]),i):void 0!==i&&(n[o]=i);return n}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const n=this.shouldPrependVertexProjectPath(e,t),o=this.constructUrl(e.path,t,n);o.searchParams.has("alt")&&"sse"===o.searchParams.get("alt")||o.searchParams.set("alt","sse");let i={};return i.body=e.body,i=await this.includeExtraHttpOptionsToRequestInit(i,t,o.toString()),this.streamApiCall(o,i,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal,t.fetch)}async includeExtraHttpOptionsToRequestInit(e,t,n){return!function(){var e,t;return"string"==typeof(null===(t=null===(e=globalThis.process)||void 0===e?void 0:e.versions)||void 0===t?void 0:t.node)}()||(null==t?void 0:t.fetch)||"dispatcher"in e||(e.dispatcher={dispatch(e,t){let n=globalThis[Xa];if(n||"undefined"==typeof Headers||(new Headers,n=globalThis[Xa]),!n||"function"!=typeof n.dispatch)throw new Error("Undici globalDispatcher is not available.");return n.dispatch(Object.assign(Object.assign({},e),{headersTimeout:0,bodyTimeout:0}),t)}}),t&&null!==t.extraBody&&function(e,t){if(!t||0===Object.keys(t).length)return;if(e.body instanceof Blob)return;let n={};if("string"==typeof e.body&&e.body.length>0)try{const t=JSON.parse(e.body);if("object"!=typeof t||null===t||Array.isArray(t))return;n=t}catch(i){return}const o=function e(t,n){const o=Object.assign({},t);for(const i in n)if(Object.prototype.hasOwnProperty.call(n,i)){const t=n[i],r=o[i];t&&"object"==typeof t&&!Array.isArray(t)&&r&&"object"==typeof r&&!Array.isArray(r)?o[i]=e(r,t):o[i]=t}return o}(n,t);e.body=JSON.stringify(o)}(e,t.extraBody),e.headers=await this.getHeadersInternal(t,n),e}async unaryApiCall(e,t,n,o,i,r,s){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n}),o,i,r,s).then(async e=>(await $a(e),new Ut(e))).catch(e=>{throw e instanceof Error?e:new Error(`exception ${e} sending request`,{cause:e})})}async streamApiCall(e,t,n,o,i,r,s){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n}),o,i,r,s).then(async e=>(await $a(e),this.processStreamResponse(e))).catch(e=>{throw e instanceof Error?e:new Error(`exception ${e} sending request`,{cause:e})})}processStreamResponse(e){return D(this,arguments,function*(){var t;const n=null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.getReader(),o=new TextDecoder("utf-8");if(!n)throw new Error("Response body is empty");try{let t="";const r="data:",s=["\n\n","\r\r","\r\n\r\n"];for(;;){const{done:a,value:l}=yield k(n.read());if(a){if(t.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}const u=o.decode(l,{stream:!0});Ja(u),t+=u;let c=-1,d=0;for(;;){c=-1,d=0;for(const e of s){const n=t.indexOf(e);-1!==n&&(-1===c||n<c)&&(c=n,d=e.length)}if(-1===c)break;const n=t.substring(0,c);t=t.substring(c+d);const o=n.trim();if(o.startsWith(r)){const t=o.substring(5).trim();Ja(t);try{const n=new Response(t,{headers:null==e?void 0:e.headers,status:null==e?void 0:e.status,statusText:null==e?void 0:e.statusText});yield yield k(new Ut(n))}catch(i){throw new Error(`exception parsing stream chunk ${t}. ${i}`)}}}}}finally{n.releaseLock()}})}async apiCall(e,t,n,o,i,r){var s,a,l,u,c,d;const p=null!=r?r:fetch,m=null!==(s=null==n?void 0:n.httpStatusCodes)&&void 0!==s?s:Ba,h=async()=>{const r=function(e,t){if(!(e&&e>0||t))return{signal:void 0,dispose:()=>{}};const n=new AbortController;let o;e&&e>0&&(o=setTimeout(()=>n.abort(),e),o&&"function"==typeof o.unref&&o.unref());const i=()=>n.abort();return t&&(t.aborted?n.abort():t.addEventListener("abort",i)),{signal:n.signal,dispose:()=>{void 0!==o&&clearTimeout(o),null==t||t.removeEventListener("abort",i)}}}(o,i);let s;try{s=await p(e,Object.assign(Object.assign({},t),{signal:r.signal}))}catch(a){throw r.dispose(),a}if(!n||s.ok||!m.includes(s.status))return s;try{await $a(s)}finally{r.dispose()}return s};if(!n)return h();const f=Math.max(1,null!==(a=n.attempts)&&void 0!==a?a:5),v=Math.round(1e3*(null!==(l=n.initialDelay)&&void 0!==l?l:1)),g=Math.max(v,Math.round(1e3*(null!==(u=n.maxDelay)&&void 0!==u?u:60)));return(0,C.default)(h,{retries:f-1,factor:null!==(c=n.expBase)&&void 0!==c?c:2,minTimeout:v,maxTimeout:g,randomize:(null!==(d=n.jitter)&&void 0!==d?d:1)>0,onFailedAttempt:e=>{var t;if(null==i?void 0:i.aborted)throw null!==(t=e.error)&&void 0!==t?t:e}})}getDefaultHeaders(){const e={},t="google-genai-sdk/3.6.1 "+this.clientOptions.userAgentExtra;return e["User-Agent"]=t,e[ja]=t,e["Content-Type"]="application/json",e}async getHeadersInternal(e,t){const n=new Headers;if(e&&e.headers)for(const[o,i]of Object.entries(e.headers))n.append(o,i);return(null==e?void 0:e.timeout)&&e.timeout>0&&n.append("X-Server-Timeout",String(Math.ceil(e.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(n,t),n}getFileName(e){var t;let n="";return"string"==typeof e&&(n=e.replace(/[/\\]+$/,""),n=null!==(t=n.split(/[/\\]/).pop())&&void 0!==t?t:""),n}async uploadFile(e,t){var n;const o={};null!=t&&(o.mimeType=t.mimeType,o.name=t.name,o.displayName=t.displayName),o.name&&!o.name.startsWith("files/")&&(o.name=`files/${o.name}`);const i=this.clientOptions.uploader,r=await i.stat(e);o.sizeBytes=String(r.size);const s=null!==(n=null==t?void 0:t.mimeType)&&void 0!==n?n:r.type;if(void 0===s||""===s)throw new Error("Can not determine mimeType. Please provide mimeType in the config.");o.mimeType=s;const a={file:o},l=this.getFileName(e),u=await this.fetchUploadUrl("upload/{api_version}/files",o.sizeBytes,o.mimeType,l,a,null==t?void 0:t.httpOptions);return i.upload(e,u,this)}async uploadFileToFileSearchStore(e,t,n){var o;const i=this.clientOptions.uploader,r=await i.stat(t),s=String(r.size),a=null!==(o=null==n?void 0:n.mimeType)&&void 0!==o?o:r.type;if(void 0===a||""===a)throw new Error("Can not determine mimeType. Please provide mimeType in the config.");const l=`upload/{api_version}/${e}:uploadToFileSearchStore`,u=this.getFileName(t),c={};null!=n&&Ha(n,c);const d=await this.fetchUploadUrl(l,s,a,u,c,null==n?void 0:n.httpOptions);return i.uploadToFileSearchStore(t,d,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,t,n,o,i,r){var s;const a=Object.assign(Object.assign({},r),{headers:Object.assign(Object.assign(Object.assign({},null==r?void 0:r.headers),{"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${n}`}),o?{"X-Goog-Upload-File-Name":o}:{})}),l=await this.request({path:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:a});if(!l||!(null==l?void 0:l.headers))throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");const u=null===(s=null==l?void 0:l.headers)||void 0===s?void 0:s["x-goog-upload-url"];if(void 0===u)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return u}};function Ja(e){try{const t=JSON.parse(e);if(null!==t&&"object"==typeof t&&"error"in t&&null!==t.error&&"object"==typeof t.error){const e=t.error,n=e.status,o=e.code,i=`got status: ${n}. ${JSON.stringify(t)}`;if("number"==typeof o&&o>=400&&o<600)throw new po({message:i,status:o})}}catch(t){if("ApiError"===(null==t?void 0:t.name))throw t}}async function $a(e){var t;if(void 0===e)throw new Error("response is undefined");if(!e.ok){const n=e.status;let o;o=(null===(t=e.headers.get("content-type"))||void 0===t?void 0:t.includes("application/json"))?await e.json():{error:{message:await e.text(),code:e.status,status:e.statusText}};const i=JSON.stringify(o);if(n>=400&&n<600)throw new po({message:i,status:n});throw new Error(i)}}function Wa(e){for(const t of e){if(Ka(t))return!0;if("object"==typeof t&&"inputSchema"in t)return!0}return!1}function Ya(e){var t;const n=null!==(t=e[ja])&&void 0!==t?t:"";e[ja]=(n+" mcp_used/unknown").trimStart()}function Ka(e){return null!==e&&"object"==typeof e&&e instanceof Za}function za(e){return D(this,arguments,function*(e,t=100){let n,o=0;for(;o<t;){const t=yield k(e.listTools({cursor:n}));for(const e of t.tools)yield yield k(e),o++;if(!t.nextCursor)break;n=t.nextCursor}})}var Za=class e{constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(t,n){return new e(t,n)}async initialize(){var e,t,n,o;if(this.mcpTools.length>0)return;const i={},r=[];for(const c of this.mcpClients)try{for(var s,a=!0,l=(t=void 0,M(za(c)));!(e=(s=await l.next()).done);a=!0){o=s.value,a=!1;const e=o;r.push(e);const t=e.name;if(i[t])throw new Error(`Duplicate function name ${t} found in MCP tools. Please ensure function names are unique.`);i[t]=c}}catch(u){t={error:u}}finally{try{a||e||!(n=l.return)||await n.call(l)}finally{if(t)throw t.error}}this.mcpTools=r,this.functionNameToMcpClient=i}async tool(){return await this.initialize(),function(e,t={}){const n=[],o=/* @__PURE__ */new Set;for(const i of e){const e=i.name;if(o.has(e))throw new Error(`Duplicate function name ${e} found in MCP tools. Please ensure function names are unique.`);o.add(e);const r=Xn(i,t);r.functionDeclarations&&n.push(...r.functionDeclarations)}return{functionDeclarations:n}}(this.mcpTools,this.config)}async callTool(e){await this.initialize();const t=[];for(const n of e)if(n.name in this.functionNameToMcpClient){const e=this.functionNameToMcpClient[n.name];let o;this.config.timeout&&(o={timeout:this.config.timeout});const i=await e.callTool({name:n.name,arguments:n.args},void 0,o);t.push({functionResponse:{name:n.name,response:i.isError?{error:i}:i}})}return t}},Qa=class{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n}async connect(e){var t,n;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");const o=this.apiClient.getWebsocketBaseUrl(),i=this.apiClient.getApiVersion(),r=function(e){const t=new Headers;for(const[n,o]of Object.entries(e))t.append(n,o);return t}(this.apiClient.getDefaultHeaders()),s=`${o}/ws/google.ai.generativelanguage.${i}.GenerativeService.BidiGenerateMusic?key=${this.apiClient.getApiKey()}`;let a=()=>{};const l=new Promise(e=>{a=e}),u=e.callbacks,c=(this.apiClient,{onopen:function(){a({})},onmessage:e=>{!async function(e,t,n){const o=new hn;let i;i=n.data instanceof Blob?JSON.parse(await n.data.text()):JSON.parse(n.data),Object.assign(o,i),t(o)}(0,u.onmessage,e)},onerror:null!==(t=null==u?void 0:u.onerror)&&void 0!==t?t:function(e){},onclose:null!==(n=null==u?void 0:u.onclose)&&void 0!==n?n:function(e){}}),d=this.webSocketFactory.create(s,function(e){const t={};return e.forEach((e,n)=>{t[n]=e}),t}(r),c);d.connect(),await l;const p={setup:{model:vn(this.apiClient,e.model)}};return d.send(JSON.stringify(p)),new el(d,this.apiClient)}},el=class{constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||0===Object.keys(e.weightedPrompts).length)throw new Error("Weighted prompts must be set and contain at least one entry.");const t=function(e){const t={},n=kt(e,["weightedPrompts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["weightedPrompts"],e)}return t}(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});const t=function(e){const t={},n=kt(e,["musicGenerationConfig"]);return null!=n&&Nt(t,["musicGenerationConfig"],n),t}(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){const t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(Ot.PLAY)}pause(){this.sendPlaybackControl(Ot.PAUSE)}stop(){this.sendPlaybackControl(Ot.STOP)}resetContext(){this.sendPlaybackControl(Ot.RESET_CONTEXT)}close(){this.conn.close()}},tl=class{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n,this.music=new Qa(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,n,o,i;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 r=this.apiClient.getWebsocketBaseUrl(),s=this.apiClient.getApiVersion();let a;const l=this.apiClient.getHeaders();e.config&&e.config.tools&&Wa(e.config.tools)&&Ya(l);const u=function(e){const t=new Headers;for(const[n,o]of Object.entries(e))t.append(n,o);return t}(l);if(this.apiClient.isVertexAI()){const e=this.apiClient.getProject(),t=this.apiClient.getLocation(),n=this.apiClient.getApiKey(),o=!!e&&!!t||!!n;this.apiClient.getCustomBaseUrl()&&!o?a=r:(a=`${r}/ws/google.cloud.aiplatform.${s}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(u,a))}else{const e=this.apiClient.getApiKey();let t="BidiGenerateContent",n="key";(null==e?void 0:e.startsWith("auth_tokens/"))&&(t="BidiGenerateContentConstrained",n="access_token"),a=`${r}/ws/google.ai.generativelanguage.${s}.GenerativeService.${t}?${n}=${e}`}let c=()=>{},d=()=>{};const p=new Promise((e,t)=>{c=e,d=t});p.catch(()=>{});const m=e.callbacks,h=this.apiClient;let f=!1;const v=[];let g=()=>{},_=()=>{};const y=new Promise((e,t)=>{g=e,_=t});y.catch(()=>{});const E=e=>{d(e),_(e)},T={onopen:function(){var e;null===(e=null==m?void 0:m.onopen)||void 0===e||e.call(m),c({})},onmessage:e=>{!async function(e,t,n){const o=new mn;let i;i=n.data instanceof Blob?await n.data.text():n.data instanceof ArrayBuffer?(new TextDecoder).decode(n.data):n.data;const r=JSON.parse(i);if(e.isVertexAI()){const e=function(e){const t={},n=kt(e,["setupComplete"]);null!=n&&Nt(t,["setupComplete"],n);const o=kt(e,["serverContent"]);null!=o&&Nt(t,["serverContent"],o);const i=kt(e,["toolCall"]);null!=i&&Nt(t,["toolCall"],i);const r=kt(e,["toolCallCancellation"]);null!=r&&Nt(t,["toolCallCancellation"],r);const s=kt(e,["usageMetadata"]);null!=s&&Nt(t,["usageMetadata"],function(e){const t={},n=kt(e,["candidatesTokenCount"]);null!=n&&Nt(t,["responseTokenCount"],n);const o=kt(e,["candidatesTokensDetails"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["responseTokensDetails"],e)}const i=kt(e,["cacheTokensDetails"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["cacheTokensDetails"],e)}const r=kt(e,["cachedContentTokenCount"]);null!=r&&Nt(t,["cachedContentTokenCount"],r);const s=kt(e,["promptTokenCount"]);null!=s&&Nt(t,["promptTokenCount"],s);const a=kt(e,["promptTokensDetails"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["promptTokensDetails"],e)}const l=kt(e,["thoughtsTokenCount"]);null!=l&&Nt(t,["thoughtsTokenCount"],l);const u=kt(e,["toolUsePromptTokenCount"]);null!=u&&Nt(t,["toolUsePromptTokenCount"],u);const c=kt(e,["toolUsePromptTokensDetails"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["toolUsePromptTokensDetails"],e)}const d=kt(e,["totalTokenCount"]);null!=d&&Nt(t,["totalTokenCount"],d);const p=kt(e,["trafficType"]);return null!=p&&Nt(t,["trafficType"],p),t}(s));const a=kt(e,["goAway"]);null!=a&&Nt(t,["goAway"],a);const l=kt(e,["sessionResumptionUpdate"]);null!=l&&Nt(t,["sessionResumptionUpdate"],l);const u=kt(e,["voiceActivityDetectionSignal"]);null!=u&&Nt(t,["voiceActivityDetectionSignal"],u);const c=kt(e,["voiceActivity"]);return null!=c&&Nt(t,["voiceActivity"],function(e){const t={},n=kt(e,["type"]);null!=n&&Nt(t,["voiceActivityType"],n);const o=kt(e,["audioOffset"]);return null!=o&&Nt(t,["audioOffset"],o),t}(c)),t}(r);Object.assign(o,e)}else Object.assign(o,r);var s;(s=o).setupComplete&&!w.setupComplete&&(w.setupComplete=s.setupComplete,g({})),f?m.onmessage(s):v.push(s)}(h,0,e)},onerror:e=>{var t;try{null===(t=null==m?void 0:m.onerror)||void 0===t||t.call(m,e)}finally{E(/* @__PURE__ */new Error(`Live connection failed before setup completed: ${(null==e?void 0:e.message)||"WebSocket error"}`))}},onclose:e=>{var t,n;try{null===(t=null==m?void 0:m.onclose)||void 0===t||t.call(m,e)}finally{E(/* @__PURE__ */new Error(`Live connection closed before setup completed (code ${null!==(n=null==e?void 0:e.code)&&void 0!==n?n:1006}): ${(null==e?void 0:e.reason)||"Abnormal closure."}`))}}},A=this.webSocketFactory.create(a,function(e){const t={};return e.forEach((e,n)=>{t[n]=e}),t}(u),T);A.connect(),await p;let I=vn(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&I.startsWith("publishers/")){const e=this.apiClient.getProject(),t=this.apiClient.getLocation();e&&t&&(I=`projects/${e}/locations/${t}/`+I)}let C={};this.apiClient.isVertexAI()&&void 0===(null===(t=e.config)||void 0===t?void 0:t.responseModalities)&&(void 0===e.config?e.config={responseModalities:[De.AUDIO]}:e.config.responseModalities=[De.AUDIO]),null===(n=e.config)||void 0===n||n.generationConfig;const S=null!==(i=null===(o=e.config)||void 0===o?void 0:o.tools)&&void 0!==i?i:[],b=[];for(const P of S)if(this.isCallableTool(P)){const e=P;b.push(await e.tool())}else b.push(P);b.length>0&&(e.config.tools=b);const O={model:I,config:e.config,callbacks:e.callbacks};C=this.apiClient.isVertexAI()?function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["setup","model"],vn(e,o));const i=kt(t,["config"]);return null!=i&&Nt(n,["config"],function(e,t){const n=kt(e,["generationConfig"]);void 0!==t&&null!=n&&Nt(t,["setup","generationConfig"],function(e){const t={},n=kt(e,["modelSelectionConfig"]);null!=n&&Nt(t,["modelConfig"],n);const o=kt(e,["responseJsonSchema"]);null!=o&&Nt(t,["responseJsonSchema"],o);const i=kt(e,["audioTranscriptionConfig"]);null!=i&&Nt(t,["audioTranscriptionConfig"],i);const r=kt(e,["audioTimestamp"]);null!=r&&Nt(t,["audioTimestamp"],r);const s=kt(e,["candidateCount"]);null!=s&&Nt(t,["candidateCount"],s);const a=kt(e,["enableAffectiveDialog"]);null!=a&&Nt(t,["enableAffectiveDialog"],a);const l=kt(e,["frequencyPenalty"]);null!=l&&Nt(t,["frequencyPenalty"],l);const u=kt(e,["logprobs"]);null!=u&&Nt(t,["logprobs"],u);const c=kt(e,["maxOutputTokens"]);null!=c&&Nt(t,["maxOutputTokens"],c);const d=kt(e,["mediaResolution"]);null!=d&&Nt(t,["mediaResolution"],d);const p=kt(e,["presencePenalty"]);null!=p&&Nt(t,["presencePenalty"],p);const m=kt(e,["responseFormat"]);if(null!=m){let e=m;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["responseFormat"],e)}const h=kt(e,["responseLogprobs"]);null!=h&&Nt(t,["responseLogprobs"],h);const f=kt(e,["responseMimeType"]);null!=f&&Nt(t,["responseMimeType"],f);const v=kt(e,["responseModalities"]);null!=v&&Nt(t,["responseModalities"],v);const g=kt(e,["responseSchema"]);null!=g&&Nt(t,["responseSchema"],g);const _=kt(e,["routingConfig"]);null!=_&&Nt(t,["routingConfig"],_);const y=kt(e,["seed"]);null!=y&&Nt(t,["seed"],y);const E=kt(e,["speechConfig"]);null!=E&&Nt(t,["speechConfig"],_a(E));const T=kt(e,["stopSequences"]);null!=T&&Nt(t,["stopSequences"],T);const A=kt(e,["temperature"]);null!=A&&Nt(t,["temperature"],A);const I=kt(e,["thinkingConfig"]);null!=I&&Nt(t,["thinkingConfig"],I);const C=kt(e,["topK"]);null!=C&&Nt(t,["topK"],C);const S=kt(e,["topP"]);if(null!=S&&Nt(t,["topP"],S),void 0!==kt(e,["enableEnhancedCivicAnswers"]))throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const b=kt(e,["translationConfig"]);return null!=b&&Nt(t,["translationConfig"],b),t}(n));const o=kt(e,["responseModalities"]);void 0!==t&&null!=o&&Nt(t,["setup","generationConfig","responseModalities"],o);const i=kt(e,["temperature"]);void 0!==t&&null!=i&&Nt(t,["setup","generationConfig","temperature"],i);const r=kt(e,["topP"]);void 0!==t&&null!=r&&Nt(t,["setup","generationConfig","topP"],r);const s=kt(e,["topK"]);void 0!==t&&null!=s&&Nt(t,["setup","generationConfig","topK"],s);const a=kt(e,["maxOutputTokens"]);void 0!==t&&null!=a&&Nt(t,["setup","generationConfig","maxOutputTokens"],a);const l=kt(e,["mediaResolution"]);void 0!==t&&null!=l&&Nt(t,["setup","generationConfig","mediaResolution"],l);const u=kt(e,["seed"]);void 0!==t&&null!=u&&Nt(t,["setup","generationConfig","seed"],u);const c=kt(e,["speechConfig"]);void 0!==t&&null!=c&&Nt(t,["setup","generationConfig","speechConfig"],_a(Dn(c)));const d=kt(e,["thinkingConfig"]);void 0!==t&&null!=d&&Nt(t,["setup","generationConfig","thinkingConfig"],d);const p=kt(e,["enableAffectiveDialog"]);void 0!==t&&null!=p&&Nt(t,["setup","generationConfig","enableAffectiveDialog"],p);const m=kt(e,["systemInstruction"]);void 0!==t&&null!=m&&Nt(t,["setup","systemInstruction"],ma(On(m)));const h=kt(e,["tools"]);if(void 0!==t&&null!=h){let e=xn(h);Array.isArray(e)&&(e=e.map(e=>Ea(Mn(e)))),Nt(t,["setup","tools"],e)}const f=kt(e,["sessionResumption"]);void 0!==t&&null!=f&&Nt(t,["setup","sessionResumption"],f);const v=kt(e,["inputAudioTranscription"]);void 0!==t&&null!=v&&Nt(t,["setup","inputAudioTranscription"],v);const g=kt(e,["outputAudioTranscription"]);void 0!==t&&null!=g&&Nt(t,["setup","outputAudioTranscription"],g);const _=kt(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&Nt(t,["setup","realtimeInputConfig"],_);const y=kt(e,["contextWindowCompression"]);void 0!==t&&null!=y&&Nt(t,["setup","contextWindowCompression"],y);const E=kt(e,["proactivity"]);void 0!==t&&null!=E&&Nt(t,["setup","proactivity"],E);const T=kt(e,["explicitVadSignal"]);void 0!==t&&null!=T&&Nt(t,["setup","explicitVadSignal"],T);const A=kt(e,["avatarConfig"]);void 0!==t&&null!=A&&Nt(t,["setup","avatarConfig"],A);const I=kt(e,["safetySettings"]);if(void 0!==t&&null!=I){let e=I;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["setup","safetySettings"],e)}const C=kt(e,["translationConfig"]);void 0!==t&&null!=C&&Nt(t,["setup","generationConfig","translationConfig"],C);const S=kt(e,["labels"]);return void 0!==t&&null!=S&&Nt(t,["setup","labels"],S),{}}(i,n)),n}(this.apiClient,O):function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["setup","model"],vn(e,o));const i=kt(t,["config"]);return null!=i&&Nt(n,["config"],function(e,t){const n=kt(e,["generationConfig"]);void 0!==t&&null!=n&&Nt(t,["setup","generationConfig"],n);const o=kt(e,["responseModalities"]);void 0!==t&&null!=o&&Nt(t,["setup","generationConfig","responseModalities"],o);const i=kt(e,["temperature"]);void 0!==t&&null!=i&&Nt(t,["setup","generationConfig","temperature"],i);const r=kt(e,["topP"]);void 0!==t&&null!=r&&Nt(t,["setup","generationConfig","topP"],r);const s=kt(e,["topK"]);void 0!==t&&null!=s&&Nt(t,["setup","generationConfig","topK"],s);const a=kt(e,["maxOutputTokens"]);void 0!==t&&null!=a&&Nt(t,["setup","generationConfig","maxOutputTokens"],a);const l=kt(e,["mediaResolution"]);void 0!==t&&null!=l&&Nt(t,["setup","generationConfig","mediaResolution"],l);const u=kt(e,["seed"]);void 0!==t&&null!=u&&Nt(t,["setup","generationConfig","seed"],u);const c=kt(e,["speechConfig"]);void 0!==t&&null!=c&&Nt(t,["setup","generationConfig","speechConfig"],Dn(c));const d=kt(e,["thinkingConfig"]);void 0!==t&&null!=d&&Nt(t,["setup","generationConfig","thinkingConfig"],d);const p=kt(e,["enableAffectiveDialog"]);void 0!==t&&null!=p&&Nt(t,["setup","generationConfig","enableAffectiveDialog"],p);const m=kt(e,["systemInstruction"]);void 0!==t&&null!=m&&Nt(t,["setup","systemInstruction"],pa(On(m)));const h=kt(e,["tools"]);if(void 0!==t&&null!=h){let e=xn(h);Array.isArray(e)&&(e=e.map(e=>ya(Mn(e)))),Nt(t,["setup","tools"],e)}const f=kt(e,["sessionResumption"]);void 0!==t&&null!=f&&Nt(t,["setup","sessionResumption"],function(e){const t={},n=kt(e,["handle"]);if(null!=n&&Nt(t,["handle"],n),void 0!==kt(e,["transparent"]))throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(f));const v=kt(e,["inputAudioTranscription"]);void 0!==t&&null!=v&&Nt(t,["setup","inputAudioTranscription"],v);const g=kt(e,["outputAudioTranscription"]);void 0!==t&&null!=g&&Nt(t,["setup","outputAudioTranscription"],g);const _=kt(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&Nt(t,["setup","realtimeInputConfig"],_);const y=kt(e,["contextWindowCompression"]);void 0!==t&&null!=y&&Nt(t,["setup","contextWindowCompression"],y);const E=kt(e,["proactivity"]);if(void 0!==t&&null!=E&&Nt(t,["setup","proactivity"],E),void 0!==kt(e,["explicitVadSignal"]))throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const T=kt(e,["avatarConfig"]);void 0!==t&&null!=T&&Nt(t,["setup","avatarConfig"],T);const A=kt(e,["safetySettings"]);if(void 0!==t&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["category"]);if(null!=n&&Nt(t,["category"],n),void 0!==kt(e,["method"]))throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["threshold"]);return null!=o&&Nt(t,["threshold"],o),t}(e))),Nt(t,["setup","safetySettings"],e)}const I=kt(e,["translationConfig"]);void 0!==t&&null!=I&&Nt(t,["setup","generationConfig","translationConfig"],I);const C=kt(e,["labels"]);return void 0!==t&&null!=C&&Nt(t,["setup","labels"],C),{}}(i,n)),n}(this.apiClient,O),delete C.config;const w=new ol(A,this.apiClient);A.send(JSON.stringify(C));try{await y}catch(R){throw A.close(),R}f=!0;for(const P of v)m.onmessage(P);return w}isCallableTool(e){return"callTool"in e&&"function"==typeof e.callTool}},nl={turnComplete:!0},ol=class{constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(null!==t.turns&&void 0!==t.turns){let n=[];try{n=Rn(t.turns),e.isVertexAI()||(n=n.map(e=>Ia(e)))}catch(Rr){throw new Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:n,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let n=[];if(null==t.functionResponses)throw new Error("functionResponses is required.");if(n=Array.isArray(t.functionResponses)?t.functionResponses:[t.functionResponses],0===n.length)throw new Error("functionResponses is required.");for(const o of n){if("object"!=typeof o||null===o||!("name"in o)||!("response"in o))throw new Error(`Could not parse function response, type '${typeof o}'.`);if(!e.isVertexAI()&&!("id"in o))throw new Error("FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.")}return{toolResponse:{functionResponses:n}}}sendClientContent(e){e=Object.assign(Object.assign({},nl),e);const t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};t=this.apiClient.isVertexAI()?{realtimeInput:ga(e)}:{realtimeInput:va(e)},this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(null==e.functionResponses)throw new Error("Tool response parameters are required.");const t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendContextUpdate(e){let t={};t=this.apiClient.isVertexAI()?{contextUpdate:fa(e)}:{contextUpdate:ha(e)},this.conn.send(JSON.stringify(t))}close(){this.conn.close()}};function il(e){var t,n,o;if(null===(t=null==e?void 0:e.automaticFunctionCalling)||void 0===t?void 0:t.disable)return!0;let i=!1;for(const s of null!==(n=null==e?void 0:e.tools)&&void 0!==n?n:[])if(rl(s)){i=!0;break}if(!i)return!0;const r=null===(o=null==e?void 0:e.automaticFunctionCalling)||void 0===o?void 0:o.maximumRemoteCalls;return!!(r&&(r<0||!Number.isInteger(r))||0==r)}function rl(e){return"callTool"in e&&"function"==typeof e.callTool}function sl(e){var t;const n=[];return(null===(t=null==e?void 0:e.config)||void 0===t?void 0:t.tools)?(e.config.tools.forEach((e,t)=>{if(rl(e))return;const o=e;o.functionDeclarations&&o.functionDeclarations.length>0&&n.push(t)}),n):n}function al(e){var t;return!(null===(t=null==e?void 0:e.automaticFunctionCalling)||void 0===t?void 0:t.ignoreCallHistory)}function ll(e,t=!0){return e?void 0===e.automaticContinuation||null===e.automaticContinuation?t:Boolean(e.automaticContinuation):t}function ul(e){return void 0===e||e===Ie.CONTINUATION}function cl(e,t,n,o=!1){return e&&!o&&Boolean(t)&&ul(n)}var dl=class{constructor(e){this.config=e,this.reconnectsWithoutProgress=0,this.hop=pl(void 0),this.enableContinuation=ll(e,!0)}startHop(){return this.hop=pl(this.resumeToken),hl(this.config,this.resumeToken)}observe(e){var t,n;const o=this.hop;if(o.receivedAnyChunk=!0,void 0!==e.promptFeedback&&null!==e.promptFeedback&&(o.hasPromptFeedback=!0),e.usageMetadata)if(this.accumulatedUsageAcrossHops){const t=Al(this.accumulatedUsageAcrossHops,e.usageMetadata);e=Object.assign(new Ht,e,{usageMetadata:t}),o.usage=t}else Tl(e.usageMetadata),o.usage=e.usageMetadata;const i=null===(t=e.candidates)||void 0===t?void 0:t[0];return i&&((null===(n=i.content)||void 0===n?void 0:n.parts)&&i.content.parts.length>0&&(o.hasYieldedContent=!0),void 0!==i.finishReason&&(o.finishReason=i.finishReason),i.continuationToken?o.token=i.continuationToken:void 0===i.finishReason||ul(i.finishReason)||(o.token=void 0),function(e,t,n){var o;const i=null===(o=e.candidates)||void 0===o?void 0:o[0];void 0!==(null==i?void 0:i.finishReason)&&cl(t,n,i.finishReason)&&(i.finishReason=void 0)}(e,this.enableContinuation,o.token)),e}endHop(e){const t=this.hop;if(t.usage&&(this.accumulatedUsageAcrossHops=t.usage),e&&(function(e,t){var n;return Boolean(null===(n=null==t?void 0:t.abortSignal)||void 0===n?void 0:n.aborted)||e instanceof Error&&"AbortError"===e.name}(e.error,this.config)||e.error instanceof po&&!t.receivedAnyChunk))throw e.error;const n=t.hasYieldedContent||Boolean(t.token)&&t.token!==t.startToken;if(e?this.lastError=e:n&&(this.lastError=void 0),[this.resumeToken,this.reconnectsWithoutProgress]=this.nextResumeToken(),cl(this.enableContinuation,this.resumeToken,t.finishReason,t.hasPromptFeedback))return!0;if(e)throw e.error;if(void 0===t.finishReason&&!t.hasPromptFeedback&&this.lastError)throw this.lastError.error;return!1}nextResumeToken(){const e=this.hop,t=this.reconnectsWithoutProgress;return void 0!==e.finishReason||e.hasPromptFeedback?e.finishReason===Ie.CONTINUATION&&!e.hasPromptFeedback&&e.token&&e.token!==e.startToken?[e.token,0]:[void 0,0]:e.token&&e.token!==e.startToken?[e.token,0]:e.hasYieldedContent||t>=3?[void 0,t]:[e.startToken,t+1]}};function pl(e){return{startToken:e,hasPromptFeedback:!1,hasYieldedContent:!1,receivedAnyChunk:!1}}function ml(e){var t;const n=null===(t=null==e?void 0:e.candidates)||void 0===t?void 0:t[0];if(null==n?void 0:n.continuationToken)return ul(n.finishReason)?n.continuationToken:void 0}function hl(e,t,n=!1){const o=void 0!==(null==e?void 0:e.automaticContinuation)&&null!==(null==e?void 0:e.automaticContinuation),i=n&&o;if(!t&&!i)return e;if(!e)return t?{continuationToken:t}:void 0;const r=Object.assign({},e);return t&&(r.continuationToken=t),i&&delete r.automaticContinuation,r}function fl(e,t){var n,o;const i=/* @__PURE__ */new Map,r=[];for(const s of[...e,...t]){const e=s.modality;i.has(e)||(i.set(e,0),r.push(e)),i.set(e,(null!==(n=i.get(e))&&void 0!==n?n:0)+(null!==(o=s.tokenCount)&&void 0!==o?o:0))}return r.map(e=>{var t;return{modality:e,tokenCount:null!==(t=i.get(e))&&void 0!==t?t:0}})}function vl(e,t){const n=/* @__PURE__ */new Map,o=[];for(const i of[...e,...t]){const e=i.category;n.has(e)||o.push(e),n.set(e,i)}return o.map(e=>n.get(e))}function gl(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(e instanceof Ut)return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype||e instanceof Ht||e instanceof Lt||e instanceof qt}function _l(e,t){return!!e.endsWith("TokensDetails")||t.length>0&&"object"==typeof t[0]&&null!==t[0]&&"modality"in t[0]}function yl(e,t){if(0===e.length)return t;if(0===t.length)return e.map(e=>Il(e,{},!0,!1));const n=[],o=Math.min(e.length,t.length);for(let i=0;i<o;i++)n.push(Il(e[i],t[i],!0,!1));return e.length>o&&n.push(...e.slice(o)),t.length>o&&n.push(...t.slice(o)),n}function El(e){var t;if(e)return null!==(t=e._initialPromptTokenCount)&&void 0!==t?t:e.promptTokenCount}function Tl(e,t){const n=null!=t?t:El(e);return void 0!==n&&Object.defineProperty(e,"_initialPromptTokenCount",{value:n,enumerable:!1,configurable:!0,writable:!0}),e instanceof qt||Object.prototype.hasOwnProperty.call(e,"initialPromptTokenCount")||Object.defineProperty(e,"initialPromptTokenCount",{get(){return El(this)},enumerable:!1,configurable:!0}),e}function Al(e,t){var n;if(!t)return e?Tl(e):e;if(!e)return Tl(t);const o=null!==(n=El(e))&&void 0!==n?n:El(t);return Tl(Il(e,t,!1,!0),o)}function Il(e,t,n=!1,o=!1){n&&(t=function(e,t){const n=t.groundingMetadata,o=null==n?void 0:n.groundingSupports;if(!Array.isArray(o)||0===o.length)return t;const i=e.content,r=Array.isArray(null==i?void 0:i.parts)?i.parts.length:0,s=e.groundingMetadata,a=Array.isArray(null==s?void 0:s.groundingChunks)?s.groundingChunks.length:0;if(0===r&&0===a)return t;const l=o.map(e=>{var t;if(!e||"object"!=typeof e)return e;const n=Object.assign({},e);return a>0&&Array.isArray(e.groundingChunkIndices)&&e.groundingChunkIndices.length>0&&(n.groundingChunkIndices=e.groundingChunkIndices.map(e=>e+a)),r>0&&e.segment&&"object"==typeof e.segment&&(n.segment=Object.assign(Object.assign({},e.segment),{partIndex:(null!==(t=e.segment.partIndex)&&void 0!==t?t:0)+r})),n});return Object.assign(Object.assign({},t),{groundingMetadata:Object.assign(Object.assign({},n),{groundingSupports:l})})}(e,t));const i={},r=/* @__PURE__ */new Set([...Object.keys(e),...Object.keys(t)]);for(const s of r){const r=e[s],a=t[s];if(!n||"continuationToken"!==s&&"finishReason"!==s&&"finishMessage"!==s)if(n||o||"candidates"!==s||!Array.isArray(r)){if("usageMetadata"===s){const e=Al(r,a);void 0!==e&&(i[s]=e);continue}null==a?void 0!==r&&(i[s]=r):null==r?i[s]=a:"number"==typeof r&&"number"==typeof a&&(o||"tokenCount"===s||s.endsWith("TokenCount")||s.endsWith("Count")||s.endsWith("Sum"))?i[s]=r+a:Array.isArray(r)&&Array.isArray(a)?_l(s,r)||_l(s,a)?i[s]=fl(r,a):i[s]="safetyRatings"===s?vl(r,a):[...r,...a]:gl(r)&&gl(a)?i[s]=Il(r,a,!1,"usageMetadata"===s||o):i[s]=a}else i[s]=yl(r,Array.isArray(a)?a:[]);else void 0!==a&&(i[s]=a)}return i}var Cl=class e extends Rt{constructor(t){super(),this.apiClient=t,this.embedContent=async e=>{if(!this.apiClient.isVertexAI()){const t=Yn(e.model)?Rn(e.contents):e.contents;return await this.embedContentInternal({model:e.model,contents:t,config:e.config})}if(function(e){var t;const n=null!==(t=e.split("/").pop())&&void 0!==t?t:e;return n.includes("gemini")||n.includes("maas")}(e.model)){const t=function(e,t){if(Yn(e)||Wn(e))return Rn(t);if(null==t||Array.isArray(t)&&0===t.length)throw new Error("contents are required");return Array.isArray(t)?t.map(e=>On(e)):[On(t)]}(e.model,e.contents);if(t.length>1){if(Wn(e.model))throw new Error("The embedContent API for this model only supports one content at a time.");const n={model:e.model,batchContents:t,embeddingApiType:nt.BATCH_EMBED_CONTENTS,config:e.config};return await this.embedContentInternal(n)}const n={model:e.model,content:t[0],embeddingApiType:nt.EMBED_CONTENT,config:e.config};return await this.embedContentInternal(n)}{const t={model:e.model,contents:e.contents,embeddingApiType:nt.PREDICT,config:e.config};return await this.embedContentInternal(t)}},this.generateContent=async e=>{var t,n,o,i,r;const s=await this.processParamsMaybeAddMcpUsage(e);if(this.maybeMoveToResponseJsonSchema(e),!function(e){var t,n,o;return null!==(o=null===(n=null===(t=e.config)||void 0===t?void 0:t.tools)||void 0===n?void 0:n.some(e=>rl(e)))&&void 0!==o&&o}(e)||il(e.config))return ll(e.config,!0)?await this.generateContentWithContinuation(s):await this.generateContentInternal(s);const a=sl(e);if(a.length>0){const e=a.map(e=>`tools[${e}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${e}.`)}let l,u;const c=Rn(s.contents),d=null!==(o=null===(n=null===(t=s.config)||void 0===t?void 0:t.automaticFunctionCalling)||void 0===n?void 0:n.maximumRemoteCalls)&&void 0!==o?o:10;let p=0;for(;p<d&&(l=await this.generateContentWithContinuation(s),l.functionCalls&&0!==l.functionCalls.length);){const t=l.candidates[0].content,n=[];for(const o of null!==(r=null===(i=e.config)||void 0===i?void 0:i.tools)&&void 0!==r?r:[])if(rl(o)){const e=await o.callTool(l.functionCalls);n.push(...e)}p++,u={role:"user",parts:n},s.contents=Rn(s.contents),s.contents.push(t),s.contents.push(u),al(s.config)&&(c.push(t),c.push(u))}return al(s.config)&&(l.automaticFunctionCallingHistory=c),l},this.generateContentStream=async e=>{var t,n,o,i,r;if(this.maybeMoveToResponseJsonSchema(e),il(e.config)){const t=await this.processParamsMaybeAddMcpUsage(e);return ll(e.config,!0)?await this.generateContentStreamWithContinuation(t):await this.generateContentStreamInternal(t)}const s=sl(e);if(s.length>0){const e=s.map(e=>`tools[${e}]`).join(", ");throw new Error(`Incompatible tools found at ${e}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}const a=null===(o=null===(n=null===(t=null==e?void 0:e.config)||void 0===t?void 0:t.toolConfig)||void 0===n?void 0:n.functionCallingConfig)||void 0===o?void 0:o.streamFunctionCallArguments,l=null===(r=null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.automaticFunctionCalling)||void 0===r?void 0:r.disable;if(a&&!l)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(e)},this.generateImages=async t=>(e.loggedGenerateImagesWarning||(e.loggedGenerateImagesWarning=!0),await this.generateImagesInternal(t).then(e=>{var t;let n;const o=[];if(null==e?void 0:e.generatedImages)for(const r of e.generatedImages)r&&(null==r?void 0:r.safetyAttributes)&&"Positive Prompt"===(null===(t=null==r?void 0:r.safetyAttributes)||void 0===t?void 0:t.contentType)?n=null==r?void 0:r.safetyAttributes:o.push(r);let i;return i=n?{generatedImages:o,positivePromptSafetyAttributes:n,sdkHttpResponse:e.sdkHttpResponse}:{generatedImages:o,sdkHttpResponse:e.sdkHttpResponse},i})),this.list=async e=>{var t;const n={config:Object.assign(Object.assign({},{queryBase:!0}),null==e?void 0:e.config)};if(this.apiClient.isVertexAI()&&!n.config.queryBase){if(null===(t=n.config)||void 0===t?void 0:t.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");n.config.filter="labels.tune-type:*"}return new to(Gt.PAGED_ITEM_MODELS,e=>this.listInternal(e),await this.listInternal(n),n)},this.editImage=async t=>{e.loggedEditImageWarning||(e.loggedEditImageWarning=!0);const n={model:t.model,prompt:t.prompt,referenceImages:[],config:t.config};return t.referenceImages&&t.referenceImages&&(n.referenceImages=t.referenceImages.map(e=>e.toReferenceImageAPI())),await this.editImageInternal(n)},this.upscaleImage=async e=>{let t={numberOfImages:1,mode:"upscale"};e.config&&(t=Object.assign(Object.assign({},t),e.config));const n={model:e.model,image:e.image,upscaleFactor:e.upscaleFactor,config:t};return await this.upscaleImageInternal(n)},this.generateVideos=async t=>{var n,o,i,r,s,a;if((t.prompt||t.image||t.video)&&t.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(t.prompt||t.image||t.video)&&(e.loggedGenerateVideosWarning||(e.loggedGenerateVideosWarning=!0)),this.apiClient.isVertexAI()||((null===(n=t.video)||void 0===n?void 0:n.uri)&&(null===(o=t.video)||void 0===o?void 0:o.videoBytes)?t.video={uri:t.video.uri,mimeType:t.video.mimeType}:(null===(r=null===(i=t.source)||void 0===i?void 0:i.video)||void 0===r?void 0:r.uri)&&(null===(a=null===(s=t.source)||void 0===s?void 0:s.video)||void 0===a?void 0:a.videoBytes)&&(t.source.video={uri:t.source.video.uri,mimeType:t.source.video.mimeType})),await this.generateVideosInternal(t)}}async generateContentWithContinuation(e){const t=ll(e.config,!0);let n;const o=[];for(;0===o.length||t&&Boolean(n);){const t=hl(e.config,n),i=t===e.config?e:Object.assign(Object.assign({},e),{config:t}),r=await this.generateContentInternal(i);o.push(r),n=ml(r)}return function(e){if(0===e.length)return new Ht;if(1===e.length)return e[0].usageMetadata&&Tl(e[0].usageMetadata),e[0];let t=e[0];for(let o=1;o<e.length;o++)t=Il(t,e[o],!1,!1);const n=new Ht;return Object.assign(n,t),n}(o)}async generateContentStreamWithContinuation(e){const t=new dl(e.config);return t.startHop(),function(e,n,o){return D(this,arguments,function*(){var i,r,s,a;let l=async()=>o;for(;;){let o;try{try{for(var u,c=!0,d=(r=void 0,M(yield k(l())));!(i=(u=yield k(d.next())).done);c=!0){a=u.value,c=!1;const e=a;yield yield k(t.observe(e))}}catch(p){r={error:p}}finally{try{c||i||!(s=d.return)||(yield k(s.call(d)))}finally{if(r)throw r.error}}}catch(m){o={error:m}}if(!t.endHop(o))return yield k(void 0);const h=Object.assign(Object.assign({},n),{config:t.startHop()});l=()=>e.generateContentStreamInternal(h)}})}(this,e,await this.generateContentStreamInternal(e))}maybeMoveToResponseJsonSchema(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 t,n,o;const i=null===(t=e.config)||void 0===t?void 0:t.tools;if(!i)return e;const r=await Promise.all(i.map(async e=>rl(e)?await e.tool():e)),s={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:r})};if(s.config.tools=r,e.config&&e.config.tools&&Wa(e.config.tools)){const t=null!==(o=null===(n=e.config.httpOptions)||void 0===n?void 0:n.headers)&&void 0!==o?o:{};let i=Object.assign({},t);0===Object.keys(i).length&&(i=this.apiClient.getDefaultHeaders()),Ya(i),s.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:i})}return s}async initAfcToolsMap(e){var t,n,o;const i=/* @__PURE__ */new Map;for(const r of null!==(n=null===(t=e.config)||void 0===t?void 0:t.tools)&&void 0!==n?n:[])if(rl(r)){const e=r,t=await e.tool();for(const n of null!==(o=t.functionDeclarations)&&void 0!==o?o:[]){if(!n.name)throw new Error("Function declaration name is required.");if(i.has(n.name))throw new Error(`Duplicate tool declaration name: ${n.name}`);i.set(n.name,e)}}return i}async processAfcStream(e){var t,n,o;const i=null!==(o=null===(n=null===(t=e.config)||void 0===t?void 0:t.automaticFunctionCalling)||void 0===n?void 0:n.maximumRemoteCalls)&&void 0!==o?o:10;let r=!1,s=0;return function(e,t,n){return D(this,arguments,function*(){for(var o,a,l,u,c,d;s<i;){r&&(s++,r=!1);const v=yield k(e.processParamsMaybeAddMcpUsage(n)),g=yield k(e.generateContentStreamWithContinuation(v)),_=[],y=[];try{for(var p,m=!0,h=(a=void 0,M(g));!(o=(p=yield k(h.next())).done);m=!0){u=p.value,m=!1;const e=u;if(yield yield k(e),e.candidates&&(null===(c=e.candidates[0])||void 0===c?void 0:c.content)){y.push(e.candidates[0].content);for(const n of null!==(d=e.candidates[0].content.parts)&&void 0!==d?d:[])if(s<i&&n.functionCall){if(!n.functionCall.name)throw new Error("Function call name was not returned by the model.");if(!t.has(n.functionCall.name))throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${t.keys()}, missing tool: ${n.functionCall.name}`);{const e=yield k(t.get(n.functionCall.name).callTool([n.functionCall]));_.push(...e)}}}}}catch(f){a={error:f}}finally{try{m||o||!(l=h.return)||(yield k(l.call(h)))}finally{if(a)throw a.error}}if(!(_.length>0))break;{r=!0;const e=new Ht;e.candidates=[{content:{role:"user",parts:_}}],yield yield k(e);const t=[];t.push(...y),t.push({role:"user",parts:_}),n.contents=Rn(n.contents).concat(t)}}})}(this,await this.initAfcToolsMap(e),e)}async generateContentInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=ba(this.apiClient,e);return s=Pt("{model}:generateContent",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=wa(e),n=new Ht;return Object.assign(n,t),n})}{const t=Sa(this.apiClient,e);return s=Pt("{model}:generateContent",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=Oa(e),n=new Ht;return Object.assign(n,t),n})}}async generateContentStreamInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=ba(this.apiClient,e);return s=Pt("{model}:streamGenerateContent?alt=sse",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.requestStream({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}),r.then(function(e){return D(this,arguments,function*(){var t,n,o,i;try{for(var r,s=!0,a=M(e);!(t=(r=yield k(a.next())).done);s=!0){i=r.value,s=!1;const e=i,t=wa(yield k(e.json()));t.sdkHttpResponse={headers:e.headers};const n=new Ht;Object.assign(n,t),yield yield k(n)}}catch(l){n={error:l}}finally{try{s||t||!(o=a.return)||(yield k(o.call(a)))}finally{if(n)throw n.error}}})})}{const t=Sa(this.apiClient,e);return s=Pt("{model}:streamGenerateContent?alt=sse",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.requestStream({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}),r.then(function(e){return D(this,arguments,function*(){var t,n,o,i;try{for(var r,s=!0,a=M(e);!(t=(r=yield k(a.next())).done);s=!0){i=r.value,s=!1;const e=i,t=Oa(yield k(e.json()));t.sdkHttpResponse={headers:e.headers};const n=new Ht;Object.assign(n,t),yield yield k(n)}}catch(l){n={error:l}}finally{try{s||t||!(o=a.return)||(yield k(o.call(a)))}finally{if(n)throw n.error}}})})}}async embedContentInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t,n){const o={},i=kt(t,["model"]);null!=i&&Nt(o,["_url","model"],vn(e,i));let r=kt(n,["embeddingApiType"]);if(void 0===r&&(r="PREDICT"),"PREDICT"===r){const n=kt(t,["contents"]);if(null!=n){let t=wn(e,n);Array.isArray(t)&&(t=t.map(e=>e)),Nt(o,["instances[]","content"],t)}}let s=kt(n,["embeddingApiType"]);if(void 0===s&&(s="PREDICT"),"EMBED_CONTENT"===s){const e=kt(t,["content"]);null!=e&&Nt(o,["content"],Ca(On(e)))}let a=kt(n,["embeddingApiType"]);if(void 0===a&&(a="PREDICT"),"BATCH_EMBED_CONTENTS"===a){const e=kt(t,["batchContents"]);if(null!=e){let t=Rn(e);Array.isArray(t)&&(t=t.map(e=>Ca(e))),Nt(o,["requests[]","content"],t)}}const l=kt(t,["config"]);return null!=l&&function(e,t,n){let o=kt(n,["embeddingApiType"]);if(void 0===o&&(o="PREDICT"),"PREDICT"===o){const n=kt(e,["taskType"]);void 0!==t&&null!=n&&Nt(t,["instances[]","task_type"],n)}else if("EMBED_CONTENT"===o){const n=kt(e,["taskType"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","taskType"],n)}else if("BATCH_EMBED_CONTENTS"===o){const n=kt(e,["taskType"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","taskType"],n)}let i=kt(n,["embeddingApiType"]);if(void 0===i&&(i="PREDICT"),"PREDICT"===i){const n=kt(e,["title"]);void 0!==t&&null!=n&&Nt(t,["instances[]","title"],n)}else if("EMBED_CONTENT"===i){const n=kt(e,["title"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","title"],n)}else if("BATCH_EMBED_CONTENTS"===i){const n=kt(e,["title"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","title"],n)}let r=kt(n,["embeddingApiType"]);if(void 0===r&&(r="PREDICT"),"PREDICT"===r){const n=kt(e,["outputDimensionality"]);void 0!==t&&null!=n&&Nt(t,["parameters","outputDimensionality"],n)}else if("EMBED_CONTENT"===r){const n=kt(e,["outputDimensionality"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","outputDimensionality"],n)}else if("BATCH_EMBED_CONTENTS"===r){const n=kt(e,["outputDimensionality"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","outputDimensionality"],n)}let s=kt(n,["embeddingApiType"]);if(void 0===s&&(s="PREDICT"),"PREDICT"===s){const n=kt(e,["mimeType"]);void 0!==t&&null!=n&&Nt(t,["instances[]","mimeType"],n)}let a=kt(n,["embeddingApiType"]);if(void 0===a&&(a="PREDICT"),"PREDICT"===a){const n=kt(e,["autoTruncate"]);void 0!==t&&null!=n&&Nt(t,["parameters","autoTruncate"],n)}else if("EMBED_CONTENT"===a){const n=kt(e,["autoTruncate"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","autoTruncate"],n)}else if("BATCH_EMBED_CONTENTS"===a){const n=kt(e,["autoTruncate"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","autoTruncate"],n)}let l=kt(n,["embeddingApiType"]);if(void 0===l&&(l="PREDICT"),"EMBED_CONTENT"===l){const n=kt(e,["documentOcr"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","documentOcr"],n)}else if("BATCH_EMBED_CONTENTS"===l){const n=kt(e,["documentOcr"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","documentOcr"],n)}let u=kt(n,["embeddingApiType"]);if(void 0===u&&(u="PREDICT"),"EMBED_CONTENT"===u){const n=kt(e,["audioTrackExtraction"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","audioTrackExtraction"],n)}else if("BATCH_EMBED_CONTENTS"===u){const n=kt(e,["audioTrackExtraction"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","audioTrackExtraction"],n)}}(l,o,n),o}(this.apiClient,e,e);let i="{model}:predict";return e.embeddingApiType===nt.BATCH_EMBED_CONTENTS?i="{model}:batchEmbedContents":e.embeddingApiType===nt.EMBED_CONTENT&&(i="{model}:embedContent"),s=Pt(i,o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(t=>{const n=function(e,t){const n={},o=kt(e,["sdkHttpResponse"]);null!=o&&Nt(n,["sdkHttpResponse"],o);const i=kt(e,["predictions[]","embeddings"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>Aa(e))),Nt(n,["embeddings"],e)}const r=kt(e,["metadata"]);null!=r&&Nt(n,["metadata"],r);const s=kt(e,["truncated"]);null!=s&&Nt(n,["truncated"],s);const a=kt(e,["usageMetadata"]);if(null!=a&&Nt(n,["usageMetadata"],function(e){const t={},n=kt(e,["candidatesTokenCount"]);null!=n&&Nt(t,["responseTokenCount"],n);const o=kt(e,["candidatesTokensDetails"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["responseTokensDetails"],e)}const i=kt(e,["cacheTokensDetails"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["cacheTokensDetails"],e)}const r=kt(e,["cachedContentTokenCount"]);null!=r&&Nt(t,["cachedContentTokenCount"],r);const s=kt(e,["promptTokenCount"]);null!=s&&Nt(t,["promptTokenCount"],s);const a=kt(e,["promptTokensDetails"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["promptTokensDetails"],e)}const l=kt(e,["thoughtsTokenCount"]);null!=l&&Nt(t,["thoughtsTokenCount"],l);const u=kt(e,["toolUsePromptTokenCount"]);null!=u&&Nt(t,["toolUsePromptTokenCount"],u);const c=kt(e,["toolUsePromptTokensDetails"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["toolUsePromptTokensDetails"],e)}const d=kt(e,["totalTokenCount"]);null!=d&&Nt(t,["totalTokenCount"],d);const p=kt(e,["trafficType"]);return null!=p&&Nt(t,["trafficType"],p),t}(a)),t&&"EMBED_CONTENT"===kt(t,["embeddingApiType"])){const t=kt(e,["embedding"]),o=kt(e,["usageMetadata"]),i=kt(e,["truncated"]);if(t){const e={};o&&o.promptTokenCount&&(e.tokenCount=o.promptTokenCount),o&&o.promptTokensDetails&&(e.tokensDetails=o.promptTokensDetails),i&&(e.truncated=i),t.statistics=e,Nt(n,["embeddings"],[t])}}else if(t&&"BATCH_EMBED_CONTENTS"===kt(t,["embeddingApiType"])){const t=kt(e,["embeddings"]);Array.isArray(t)&&Nt(n,["embeddings"],t.map(e=>Aa(e)))}return n}(t,e),o=new jt;return Object.assign(o,n),o})}{const t=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["contents"]);if(null!=i){let t=wn(e,i);Array.isArray(t)&&(t=t.map(e=>e)),Nt(n,["requests[]","content"],t)}const r=kt(t,["content"]);if(null!=r&&Ia(On(r)),void 0!==kt(t,["batchContents"]))throw new Error("batchContents parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(t,["config"]);null!=s&&function(e,t){const n=kt(e,["taskType"]);void 0!==t&&null!=n&&Nt(t,["requests[]","taskType"],n);const o=kt(e,["title"]);void 0!==t&&null!=o&&Nt(t,["requests[]","title"],o);const i=kt(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&Nt(t,["requests[]","outputDimensionality"],i),void 0!==kt(e,["mimeType"]))throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["autoTruncate"]))throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["documentOcr"]))throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["audioTrackExtraction"]))throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(s,n);const a=kt(t,["model"]);return void 0!==a&&Nt(n,["requests[]","model"],vn(e,a)),n}(this.apiClient,e);return s=Pt("{model}:batchEmbedContents",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["embeddings"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["embeddings"],e)}const i=kt(e,["metadata"]);null!=i&&Nt(t,["metadata"],i);const r=kt(e,["usageMetadata"]);return null!=r&&Nt(t,["usageMetadata"],r),t}(e),n=new jt;return Object.assign(n,t),n})}}async generateImagesInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["prompt"]);null!=i&&Nt(n,["instances[0]","prompt"],i);const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["outputGcsUri"]);void 0!==t&&null!=n&&Nt(t,["parameters","storageUri"],n);const o=kt(e,["negativePrompt"]);void 0!==t&&null!=o&&Nt(t,["parameters","negativePrompt"],o);const i=kt(e,["numberOfImages"]);void 0!==t&&null!=i&&Nt(t,["parameters","sampleCount"],i);const r=kt(e,["aspectRatio"]);void 0!==t&&null!=r&&Nt(t,["parameters","aspectRatio"],r);const s=kt(e,["guidanceScale"]);void 0!==t&&null!=s&&Nt(t,["parameters","guidanceScale"],s);const a=kt(e,["seed"]);void 0!==t&&null!=a&&Nt(t,["parameters","seed"],a);const l=kt(e,["safetyFilterLevel"]);void 0!==t&&null!=l&&Nt(t,["parameters","safetySetting"],l);const u=kt(e,["personGeneration"]);void 0!==t&&null!=u&&Nt(t,["parameters","personGeneration"],u);const c=kt(e,["includeSafetyAttributes"]);void 0!==t&&null!=c&&Nt(t,["parameters","includeSafetyAttributes"],c);const d=kt(e,["includeRaiReason"]);void 0!==t&&null!=d&&Nt(t,["parameters","includeRaiReason"],d);const p=kt(e,["language"]);void 0!==t&&null!=p&&Nt(t,["parameters","language"],p);const m=kt(e,["outputMimeType"]);void 0!==t&&null!=m&&Nt(t,["parameters","outputOptions","mimeType"],m);const h=kt(e,["outputCompressionQuality"]);void 0!==t&&null!=h&&Nt(t,["parameters","outputOptions","compressionQuality"],h);const f=kt(e,["addWatermark"]);void 0!==t&&null!=f&&Nt(t,["parameters","addWatermark"],f);const v=kt(e,["labels"]);void 0!==t&&null!=v&&Nt(t,["labels"],v);const g=kt(e,["imageSize"]);void 0!==t&&null!=g&&Nt(t,["parameters","sampleImageSize"],g);const _=kt(e,["enhancePrompt"]);void 0!==t&&null!=_&&Nt(t,["parameters","enhancePrompt"],_)}(r,n),n}(this.apiClient,e);return i=Pt("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["predictions"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Pa(e))),Nt(t,["generatedImages"],e)}const i=kt(e,["positivePromptSafetyAttributes"]);return null!=i&&Nt(t,["positivePromptSafetyAttributes"],xa(i)),t}(e),n=new Ft;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["prompt"]);null!=i&&Nt(n,["instances[0]","prompt"],i);const r=kt(t,["referenceImages"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["referenceImage"]);null!=n&&Nt(t,["referenceImage"],ka(n));const o=kt(e,["referenceId"]);null!=o&&Nt(t,["referenceId"],o);const i=kt(e,["referenceType"]);null!=i&&Nt(t,["referenceType"],i);const r=kt(e,["maskImageConfig"]);null!=r&&Nt(t,["maskImageConfig"],function(e){const t={},n=kt(e,["maskMode"]);null!=n&&Nt(t,["maskMode"],n);const o=kt(e,["segmentationClasses"]);null!=o&&Nt(t,["maskClasses"],o);const i=kt(e,["maskDilation"]);return null!=i&&Nt(t,["dilation"],i),t}(r));const s=kt(e,["controlImageConfig"]);null!=s&&Nt(t,["controlImageConfig"],function(e){const t={},n=kt(e,["controlType"]);null!=n&&Nt(t,["controlType"],n);const o=kt(e,["enableControlImageComputation"]);return null!=o&&Nt(t,["computeControl"],o),t}(s));const a=kt(e,["styleImageConfig"]);null!=a&&Nt(t,["styleImageConfig"],a);const l=kt(e,["subjectImageConfig"]);return null!=l&&Nt(t,["subjectImageConfig"],l),t}(e))),Nt(n,["instances[0]","referenceImages"],e)}const s=kt(t,["config"]);return null!=s&&function(e,t){const n=kt(e,["outputGcsUri"]);void 0!==t&&null!=n&&Nt(t,["parameters","storageUri"],n);const o=kt(e,["negativePrompt"]);void 0!==t&&null!=o&&Nt(t,["parameters","negativePrompt"],o);const i=kt(e,["numberOfImages"]);void 0!==t&&null!=i&&Nt(t,["parameters","sampleCount"],i);const r=kt(e,["aspectRatio"]);void 0!==t&&null!=r&&Nt(t,["parameters","aspectRatio"],r);const s=kt(e,["guidanceScale"]);void 0!==t&&null!=s&&Nt(t,["parameters","guidanceScale"],s);const a=kt(e,["seed"]);void 0!==t&&null!=a&&Nt(t,["parameters","seed"],a);const l=kt(e,["safetyFilterLevel"]);void 0!==t&&null!=l&&Nt(t,["parameters","safetySetting"],l);const u=kt(e,["personGeneration"]);void 0!==t&&null!=u&&Nt(t,["parameters","personGeneration"],u);const c=kt(e,["includeSafetyAttributes"]);void 0!==t&&null!=c&&Nt(t,["parameters","includeSafetyAttributes"],c);const d=kt(e,["includeRaiReason"]);void 0!==t&&null!=d&&Nt(t,["parameters","includeRaiReason"],d);const p=kt(e,["language"]);void 0!==t&&null!=p&&Nt(t,["parameters","language"],p);const m=kt(e,["outputMimeType"]);void 0!==t&&null!=m&&Nt(t,["parameters","outputOptions","mimeType"],m);const h=kt(e,["outputCompressionQuality"]);void 0!==t&&null!=h&&Nt(t,["parameters","outputOptions","compressionQuality"],h);const f=kt(e,["addWatermark"]);void 0!==t&&null!=f&&Nt(t,["parameters","addWatermark"],f);const v=kt(e,["labels"]);void 0!==t&&null!=v&&Nt(t,["labels"],v);const g=kt(e,["editMode"]);void 0!==t&&null!=g&&Nt(t,["parameters","editMode"],g);const _=kt(e,["baseSteps"]);void 0!==t&&null!=_&&Nt(t,["parameters","editConfig","baseSteps"],_)}(s,n),n}(this.apiClient,e);return i=Pt("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["predictions"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Pa(e))),Nt(t,["generatedImages"],e)}return t}(e),n=new Xt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["image"]);null!=i&&Nt(n,["instances[0]","image"],ka(i));const r=kt(t,["upscaleFactor"]);null!=r&&Nt(n,["parameters","upscaleConfig","upscaleFactor"],r);const s=kt(t,["config"]);return null!=s&&function(e,t){const n=kt(e,["outputGcsUri"]);void 0!==t&&null!=n&&Nt(t,["parameters","storageUri"],n);const o=kt(e,["safetyFilterLevel"]);void 0!==t&&null!=o&&Nt(t,["parameters","safetySetting"],o);const i=kt(e,["personGeneration"]);void 0!==t&&null!=i&&Nt(t,["parameters","personGeneration"],i);const r=kt(e,["includeRaiReason"]);void 0!==t&&null!=r&&Nt(t,["parameters","includeRaiReason"],r);const s=kt(e,["outputMimeType"]);void 0!==t&&null!=s&&Nt(t,["parameters","outputOptions","mimeType"],s);const a=kt(e,["outputCompressionQuality"]);void 0!==t&&null!=a&&Nt(t,["parameters","outputOptions","compressionQuality"],a);const l=kt(e,["enhanceInputImage"]);void 0!==t&&null!=l&&Nt(t,["parameters","upscaleConfig","enhanceInputImage"],l);const u=kt(e,["imagePreservationFactor"]);void 0!==t&&null!=u&&Nt(t,["parameters","upscaleConfig","imagePreservationFactor"],u);const c=kt(e,["labels"]);void 0!==t&&null!=c&&Nt(t,["labels"],c);const d=kt(e,["numberOfImages"]);void 0!==t&&null!=d&&Nt(t,["parameters","sampleCount"],d);const p=kt(e,["mode"]);void 0!==t&&null!=p&&Nt(t,["parameters","mode"],p)}(s,n),n}(this.apiClient,e);return i=Pt("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["predictions"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Pa(e))),Nt(t,["generatedImages"],e)}return t}(e),n=new Bt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["source"]);null!=i&&function(e,t){const n=kt(e,["prompt"]);void 0!==t&&null!=n&&Nt(t,["instances[0]","prompt"],n);const o=kt(e,["personImage"]);void 0!==t&&null!=o&&Nt(t,["instances[0]","personImage","image"],ka(o));const i=kt(e,["productImages"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["productImage"]);return null!=n&&Nt(t,["image"],ka(n)),t}(e))),Nt(t,["instances[0]","productImages"],e)}}(i,n);const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["numberOfImages"]);void 0!==t&&null!=n&&Nt(t,["parameters","sampleCount"],n);const o=kt(e,["baseSteps"]);void 0!==t&&null!=o&&Nt(t,["parameters","baseSteps"],o);const i=kt(e,["outputGcsUri"]);void 0!==t&&null!=i&&Nt(t,["parameters","storageUri"],i);const r=kt(e,["seed"]);void 0!==t&&null!=r&&Nt(t,["parameters","seed"],r);const s=kt(e,["safetyFilterLevel"]);void 0!==t&&null!=s&&Nt(t,["parameters","safetySetting"],s);const a=kt(e,["personGeneration"]);void 0!==t&&null!=a&&Nt(t,["parameters","personGeneration"],a);const l=kt(e,["addWatermark"]);void 0!==t&&null!=l&&Nt(t,["parameters","addWatermark"],l);const u=kt(e,["outputMimeType"]);void 0!==t&&null!=u&&Nt(t,["parameters","outputOptions","mimeType"],u);const c=kt(e,["outputCompressionQuality"]);void 0!==t&&null!=c&&Nt(t,["parameters","outputOptions","compressionQuality"],c);const d=kt(e,["enhancePrompt"]);void 0!==t&&null!=d&&Nt(t,["parameters","enhancePrompt"],d);const p=kt(e,["labels"]);void 0!==t&&null!=p&&Nt(t,["labels"],p)}(r,n),n}(this.apiClient,e);return i=Pt("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>Pa(e))),Nt(t,["generatedImages"],e)}return t}(e),n=new Vt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["source"]);null!=i&&function(e,t){const n=kt(e,["prompt"]);void 0!==t&&null!=n&&Nt(t,["instances[0]","prompt"],n);const o=kt(e,["image"]);void 0!==t&&null!=o&&Nt(t,["instances[0]","image"],ka(o));const i=kt(e,["scribbleImage"]);void 0!==t&&null!=i&&Nt(t,["instances[0]","scribble"],function(e){const t={},n=kt(e,["image"]);return null!=n&&Nt(t,["image"],ka(n)),t}(i))}(i,n);const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["mode"]);void 0!==t&&null!=n&&Nt(t,["parameters","mode"],n);const o=kt(e,["maxPredictions"]);void 0!==t&&null!=o&&Nt(t,["parameters","maxPredictions"],o);const i=kt(e,["confidenceThreshold"]);void 0!==t&&null!=i&&Nt(t,["parameters","confidenceThreshold"],i);const r=kt(e,["maskDilation"]);void 0!==t&&null!=r&&Nt(t,["parameters","maskDilation"],r);const s=kt(e,["binaryColorThreshold"]);void 0!==t&&null!=s&&Nt(t,["parameters","binaryColorThreshold"],s);const a=kt(e,["labels"]);void 0!==t&&null!=a&&Nt(t,["labels"],a)}(r,n),n}(this.apiClient,e);return i=Pt("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["_self"]);null!=n&&Nt(t,["mask"],Na(n));const o=kt(e,["labels"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["labels"],e)}return t}(e))),Nt(t,["generatedMasks"],e)}return t}(e),n=new Jt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);return null!=o&&Nt(n,["_url","name"],vn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>Ma(e))}{const t=function(e,t){const n={},o=kt(t,["model"]);return null!=o&&Nt(n,["_url","name"],vn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Da(e))}}async listInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["config"]);return null!=o&&function(e,t,n){const o=kt(t,["pageSize"]);void 0!==n&&null!=o&&Nt(n,["_query","pageSize"],o);const i=kt(t,["pageToken"]);void 0!==n&&null!=i&&Nt(n,["_query","pageToken"],i);const r=kt(t,["filter"]);void 0!==n&&null!=r&&Nt(n,["_query","filter"],r);const s=kt(t,["queryBase"]);void 0!==n&&null!=s&&Nt(n,["_url","models_url"],Hn(e,s))}(e,o,n),n}(this.apiClient,e);return s=Pt("{models_url}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["_self"]);if(null!=i){let e=jn(i);Array.isArray(e)&&(e=e.map(e=>Ma(e))),Nt(t,["models"],e)}return t}(e),n=new $t;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=kt(t,["config"]);return null!=o&&function(e,t,n){const o=kt(t,["pageSize"]);void 0!==n&&null!=o&&Nt(n,["_query","pageSize"],o);const i=kt(t,["pageToken"]);void 0!==n&&null!=i&&Nt(n,["_query","pageToken"],i);const r=kt(t,["filter"]);void 0!==n&&null!=r&&Nt(n,["_query","filter"],r);const s=kt(t,["queryBase"]);void 0!==n&&null!=s&&Nt(n,["_url","models_url"],Hn(e,s))}(e,o,n),n}(this.apiClient,e);return s=Pt("{models_url}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["_self"]);if(null!=i){let e=jn(i);Array.isArray(e)&&(e=e.map(e=>Da(e))),Nt(t,["models"],e)}return t}(e),n=new $t;return Object.assign(n,t),n})}}async update(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["displayName"]);void 0!==t&&null!=n&&Nt(t,["displayName"],n);const o=kt(e,["description"]);void 0!==t&&null!=o&&Nt(t,["description"],o);const i=kt(e,["defaultCheckpointId"]);void 0!==t&&null!=i&&Nt(t,["defaultCheckpointId"],i)}(i,n),n}(this.apiClient,e);return s=Pt("{model}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"PATCH",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>Ma(e))}{const t=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","name"],vn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["displayName"]);void 0!==t&&null!=n&&Nt(t,["displayName"],n);const o=kt(e,["description"]);void 0!==t&&null!=o&&Nt(t,["description"],o);const i=kt(e,["defaultCheckpointId"]);void 0!==t&&null!=i&&Nt(t,["defaultCheckpointId"],i)}(i,n),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"PATCH",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Da(e))}}async delete(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);return null!=o&&Nt(n,["_url","name"],vn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new Wt;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=kt(t,["model"]);return null!=o&&Nt(n,["_url","name"],vn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"DELETE",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new Wt;return Object.assign(n,t),n})}}async countTokens(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["contents"]);if(null!=i){let e=Rn(i);Array.isArray(e)&&(e=e.map(e=>Ca(e))),Nt(n,["contents"],e)}const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["systemInstruction"]);void 0!==t&&null!=n&&Nt(t,["systemInstruction"],Ca(On(n)));const o=kt(e,["tools"]);if(void 0!==t&&null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Ua(e))),Nt(t,["tools"],e)}const i=kt(e,["generationConfig"]);void 0!==t&&null!=i&&Nt(t,["generationConfig"],function(e){const t={},n=kt(e,["modelSelectionConfig"]);null!=n&&Nt(t,["modelConfig"],n);const o=kt(e,["responseJsonSchema"]);null!=o&&Nt(t,["responseJsonSchema"],o);const i=kt(e,["audioTranscriptionConfig"]);null!=i&&Nt(t,["audioTranscriptionConfig"],i);const r=kt(e,["audioTimestamp"]);null!=r&&Nt(t,["audioTimestamp"],r);const s=kt(e,["candidateCount"]);null!=s&&Nt(t,["candidateCount"],s);const a=kt(e,["enableAffectiveDialog"]);null!=a&&Nt(t,["enableAffectiveDialog"],a);const l=kt(e,["frequencyPenalty"]);null!=l&&Nt(t,["frequencyPenalty"],l);const u=kt(e,["logprobs"]);null!=u&&Nt(t,["logprobs"],u);const c=kt(e,["maxOutputTokens"]);null!=c&&Nt(t,["maxOutputTokens"],c);const d=kt(e,["mediaResolution"]);null!=d&&Nt(t,["mediaResolution"],d);const p=kt(e,["presencePenalty"]);null!=p&&Nt(t,["presencePenalty"],p);const m=kt(e,["responseFormat"]);if(null!=m){let e=m;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["responseFormat"],e)}const h=kt(e,["responseLogprobs"]);null!=h&&Nt(t,["responseLogprobs"],h);const f=kt(e,["responseMimeType"]);null!=f&&Nt(t,["responseMimeType"],f);const v=kt(e,["responseModalities"]);null!=v&&Nt(t,["responseModalities"],v);const g=kt(e,["responseSchema"]);null!=g&&Nt(t,["responseSchema"],g);const _=kt(e,["routingConfig"]);null!=_&&Nt(t,["routingConfig"],_);const y=kt(e,["seed"]);null!=y&&Nt(t,["seed"],y);const E=kt(e,["speechConfig"]);null!=E&&Nt(t,["speechConfig"],Ga(E));const T=kt(e,["stopSequences"]);null!=T&&Nt(t,["stopSequences"],T);const A=kt(e,["temperature"]);null!=A&&Nt(t,["temperature"],A);const I=kt(e,["thinkingConfig"]);null!=I&&Nt(t,["thinkingConfig"],I);const C=kt(e,["topK"]);null!=C&&Nt(t,["topK"],C);const S=kt(e,["topP"]);if(null!=S&&Nt(t,["topP"],S),void 0!==kt(e,["enableEnhancedCivicAnswers"]))throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const b=kt(e,["translationConfig"]);return null!=b&&Nt(t,["translationConfig"],b),t}(i))}(r,n),n}(this.apiClient,e);return s=Pt("{model}:countTokens",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["totalTokens"]);return null!=o&&Nt(t,["totalTokens"],o),t}(e),n=new Yt;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["contents"]);if(null!=i){let e=Rn(i);Array.isArray(e)&&(e=e.map(e=>Ia(e))),Nt(n,["contents"],e)}const r=kt(t,["config"]);return null!=r&&function(e){if(void 0!==kt(e,["systemInstruction"]))throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["tools"]))throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["generationConfig"]))throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(r),n}(this.apiClient,e);return s=Pt("{model}:countTokens",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["totalTokens"]);null!=o&&Nt(t,["totalTokens"],o);const i=kt(e,["cachedContentTokenCount"]);return null!=i&&Nt(t,["cachedContentTokenCount"],i),t}(e),n=new Yt;return Object.assign(n,t),n})}}async computeTokens(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["contents"]);if(null!=i){let e=Rn(i);Array.isArray(e)&&(e=e.map(e=>Ca(e))),Nt(n,["contents"],e)}return n}(this.apiClient,e);return i=Pt("{model}:computeTokens",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["tokensInfo"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["tokensInfo"],e)}return t}(e),n=new Kt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=Ra(this.apiClient,e);return i=Pt("{model}:predictLongRunning",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["videos"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["_self"]);return null!=n&&Nt(t,["video"],function(e){const t={},n=kt(e,["gcsUri"]);null!=n&&Nt(t,["uri"],n);const o=kt(e,["bytesBase64Encoded"]);null!=o&&Nt(t,["videoBytes"],Ln(o));const i=kt(e,["mimeType"]);return null!=i&&Nt(t,["mimeType"],i),t}(n)),t}(e))),Nt(t,["generatedVideos"],e)}const o=kt(e,["raiMediaFilteredCount"]);null!=o&&Nt(t,["raiMediaFilteredCount"],o);const i=kt(e,["raiMediaFilteredReasons"]);return null!=i&&Nt(t,["raiMediaFilteredReasons"],i),t}(s)),t}(e),n=new zt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};Cl.loggedGenerateImagesWarning=!1,Cl.loggedEditImageWarning=!1,Cl.loggedGenerateVideosWarning=!1;var Sl=class extends Rt{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){const t=e.operation,n=e.config;if(void 0===t.name||""===t.name)throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const e=t.name.split("/operations/")[0];let o;n&&"httpOptions"in n&&(o=n.httpOptions);const i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:e,config:{httpOptions:o}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{const e=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async get(e){const t=e.operation,n=e.config;if(void 0===t.name||""===t.name)throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const e=t.name.split("/operations/")[0];let o;n&&"httpOptions"in n&&(o=n.httpOptions);const i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:e,config:{httpOptions:o}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{const e=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=kt(e,["operationName"]);return null!=n&&Nt(t,["_url","operationName"],n),t}(e);return s=Pt("{operationName}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r}{const t=function(e){const t={},n=kt(e,["operationName"]);return null!=n&&Nt(t,["_url","operationName"],n),t}(e);return s=Pt("{operationName}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r}}async fetchPredictVideosOperationInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e){const t={},n=kt(e,["operationName"]);null!=n&&Nt(t,["operationName"],n);const o=kt(e,["resourceName"]);return null!=o&&Nt(t,["_url","resourceName"],o),t}(e);return i=Pt("{resourceName}:fetchPredictOperation",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function bl(e,t,n){const o=kt(t,["expireTime"]);void 0!==n&&null!=o&&Nt(n,["expireTime"],o);const i=kt(t,["newSessionExpireTime"]);void 0!==n&&null!=i&&Nt(n,["newSessionExpireTime"],i);const r=kt(t,["uses"]);void 0!==n&&null!=r&&Nt(n,["uses"],r);const s=kt(t,["liveConnectConstraints"]);void 0!==n&&null!=s&&Nt(n,["bidiGenerateContentSetup"],function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["setup","model"],vn(e,o));const i=kt(t,["config"]);return null!=i&&Nt(n,["config"],function(e,t){const n=kt(e,["generationConfig"]);void 0!==t&&null!=n&&Nt(t,["setup","generationConfig"],n);const o=kt(e,["responseModalities"]);void 0!==t&&null!=o&&Nt(t,["setup","generationConfig","responseModalities"],o);const i=kt(e,["temperature"]);void 0!==t&&null!=i&&Nt(t,["setup","generationConfig","temperature"],i);const r=kt(e,["topP"]);void 0!==t&&null!=r&&Nt(t,["setup","generationConfig","topP"],r);const s=kt(e,["topK"]);void 0!==t&&null!=s&&Nt(t,["setup","generationConfig","topK"],s);const a=kt(e,["maxOutputTokens"]);void 0!==t&&null!=a&&Nt(t,["setup","generationConfig","maxOutputTokens"],a);const l=kt(e,["mediaResolution"]);void 0!==t&&null!=l&&Nt(t,["setup","generationConfig","mediaResolution"],l);const u=kt(e,["seed"]);void 0!==t&&null!=u&&Nt(t,["setup","generationConfig","seed"],u);const c=kt(e,["speechConfig"]);void 0!==t&&null!=c&&Nt(t,["setup","generationConfig","speechConfig"],Dn(c));const d=kt(e,["thinkingConfig"]);void 0!==t&&null!=d&&Nt(t,["setup","generationConfig","thinkingConfig"],d);const p=kt(e,["enableAffectiveDialog"]);void 0!==t&&null!=p&&Nt(t,["setup","generationConfig","enableAffectiveDialog"],p);const m=kt(e,["systemInstruction"]);void 0!==t&&null!=m&&Nt(t,["setup","systemInstruction"],function(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);null!=n&&Nt(t,["mediaResolution"],n);const o=kt(e,["toolCall"]);null!=o&&Nt(t,["toolCall"],o);const i=kt(e,["toolResponse"]);null!=i&&Nt(t,["toolResponse"],i);const r=kt(e,["audioTranscription"]);null!=r&&Nt(t,["audioTranscription"],r);const s=kt(e,["codeExecutionResult"]);null!=s&&Nt(t,["codeExecutionResult"],s);const a=kt(e,["executableCode"]);null!=a&&Nt(t,["executableCode"],a);const l=kt(e,["fileData"]);null!=l&&Nt(t,["fileData"],l);const u=kt(e,["functionCall"]);null!=u&&Nt(t,["functionCall"],function(e){const t={},n=kt(e,["args"]);null!=n&&Nt(t,["args"],n);const o=kt(e,["id"]);null!=o&&Nt(t,["id"],o);const i=kt(e,["name"]);if(null!=i&&Nt(t,["name"],i),void 0!==kt(e,["partialArgs"]))throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(u));const c=kt(e,["functionResponse"]);null!=c&&Nt(t,["functionResponse"],c);const d=kt(e,["inlineData"]);null!=d&&Nt(t,["inlineData"],d);const p=kt(e,["text"]);null!=p&&Nt(t,["text"],p);const m=kt(e,["thought"]);null!=m&&Nt(t,["thought"],m);const h=kt(e,["thoughtSignature"]);null!=h&&Nt(t,["thoughtSignature"],h);const f=kt(e,["videoMetadata"]);null!=f&&Nt(t,["videoMetadata"],f);const v=kt(e,["partMetadata"]);null!=v&&Nt(t,["partMetadata"],v);const g=kt(e,["mediaProcessing"]);null!=g&&Nt(t,["mediaProcessing"],g);const _=kt(e,["speechMetadata"]);null!=_&&Nt(t,["speechMetadata"],_);const y=kt(e,["documentMetadata"]);null!=y&&Nt(t,["documentMetadata"],y);const E=kt(e,["spreadsheetMetadata"]);null!=E&&Nt(t,["spreadsheetMetadata"],E);const T=kt(e,["audioMetadata"]);return null!=T&&Nt(t,["audioMetadata"],T),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}(On(m)));const h=kt(e,["tools"]);if(void 0!==t&&null!=h){let e=xn(h);Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==kt(e,["retrieval"]))throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["googleMaps"]);null!=n&&Nt(t,["googleMaps"],function(e){const t={},n=kt(e,["authConfig"]);null!=n&&Nt(t,["authConfig"],function(e){const t={},n=kt(e,["apiKey"]);if(null!=n&&Nt(t,["apiKey"],n),void 0!==kt(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["authType"]))throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oauthConfig"]))throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oidcConfig"]))throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["enableWidget"]);if(null!=o&&Nt(t,["enableWidget"],o),void 0!==kt(e,["groundingTypes"]))throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["mcpServers"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mcpServers"],e)}const i=kt(e,["codeExecution"]);null!=i&&Nt(t,["codeExecution"],i);const r=kt(e,["computerUse"]);if(null!=r&&Nt(t,["computerUse"],r),void 0!==kt(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["exaAiSearch"]))throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const a=kt(e,["googleSearch"]);null!=a&&Nt(t,["googleSearch"],function(e){const t={};if(void 0!==kt(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["excludeDomains"]))throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["searchTypes"]);null!=n&&Nt(t,["searchTypes"],n);const o=kt(e,["timeRangeFilter"]);return null!=o&&Nt(t,["timeRangeFilter"],o),t}(a));const l=kt(e,["googleSearchRetrieval"]);if(null!=l&&Nt(t,["googleSearchRetrieval"],l),void 0!==kt(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=kt(e,["urlContext"]);null!=u&&Nt(t,["urlContext"],u);const c=kt(e,["fileSearch"]);return null!=c&&Nt(t,["fileSearch"],c),t}(Mn(e)))),Nt(t,["setup","tools"],e)}const f=kt(e,["sessionResumption"]);void 0!==t&&null!=f&&Nt(t,["setup","sessionResumption"],function(e){const t={},n=kt(e,["handle"]);if(null!=n&&Nt(t,["handle"],n),void 0!==kt(e,["transparent"]))throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(f));const v=kt(e,["inputAudioTranscription"]);void 0!==t&&null!=v&&Nt(t,["setup","inputAudioTranscription"],v);const g=kt(e,["outputAudioTranscription"]);void 0!==t&&null!=g&&Nt(t,["setup","outputAudioTranscription"],g);const _=kt(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&Nt(t,["setup","realtimeInputConfig"],_);const y=kt(e,["contextWindowCompression"]);void 0!==t&&null!=y&&Nt(t,["setup","contextWindowCompression"],y);const E=kt(e,["proactivity"]);if(void 0!==t&&null!=E&&Nt(t,["setup","proactivity"],E),void 0!==kt(e,["explicitVadSignal"]))throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const T=kt(e,["avatarConfig"]);void 0!==t&&null!=T&&Nt(t,["setup","avatarConfig"],T);const A=kt(e,["safetySettings"]);if(void 0!==t&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["category"]);if(null!=n&&Nt(t,["category"],n),void 0!==kt(e,["method"]))throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["threshold"]);return null!=o&&Nt(t,["threshold"],o),t}(e))),Nt(t,["setup","safetySettings"],e)}const I=kt(e,["translationConfig"]);void 0!==t&&null!=I&&Nt(t,["setup","generationConfig","translationConfig"],I);const C=kt(e,["labels"]);return void 0!==t&&null!=C&&Nt(t,["setup","labels"],C),{}}(i,n)),n}(e,s));const a=kt(t,["lockAdditionalFields"]);return void 0!==n&&null!=a&&Nt(n,["fieldMask"],a),{}}var Ol=class extends Rt{constructor(e){super(),this.apiClient=e}async create(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{const s=function(e,t){const n={},o=kt(t,["config"]);return null!=o&&Nt(n,["config"],bl(e,o,n)),n}(this.apiClient,e);i=Pt("auth_tokens",s._url),r=s._query,delete s.config,delete s._url,delete s._query;const a=function(e,t){let n=null;const o=e.bidiGenerateContentSetup;if("object"==typeof o&&null!==o&&"setup"in o){const t=o.setup;"object"==typeof t&&null!==t?(e.bidiGenerateContentSetup=t,n=t):delete e.bidiGenerateContentSetup}else void 0!==o&&delete e.bidiGenerateContentSetup;const i=e.fieldMask;if(n){const o=function(e){const t=[];for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const o=e[n];if("object"==typeof o&&null!=o&&!Array.isArray(o)&&Object.keys(o).length>0){const e=Object.keys(o).map(e=>`${n}.${e}`);t.push(...e)}else t.push(n)}return t.join(",")}(n);if(Array.isArray(null==t?void 0:t.lockAdditionalFields)&&0===(null==t?void 0:t.lockAdditionalFields.length))o?e.fieldMask=o:delete e.fieldMask;else if((null==t?void 0:t.lockAdditionalFields)&&t.lockAdditionalFields.length>0&&null!==i&&Array.isArray(i)&&i.length>0){const t=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let n=[];i.length>0&&(n=i.map(e=>t.includes(e)?`generationConfig.${e}`:e));const r=[];o&&r.push(o),n.length>0&&r.push(...n),r.length>0?e.fieldMask=r.join(","):delete e.fieldMask}else delete e.fieldMask}else null!==i&&Array.isArray(i)&&i.length>0?e.fieldMask=i.join(","):delete e.fieldMask;return e}(s,e.config);return o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}};var wl=class extends Rt{constructor(e){super(),this.apiClient=e,this.list=async e=>new to(Gt.PAGED_ITEM_DOCUMENTS,t=>this.listInternal({parent:e.parent,config:t.config}),await this.listInternal(e),e)}async get(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return i=Pt("{name}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async delete(e){var t,n;let o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const r=function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["_url","name"],n);const o=kt(e,["config"]);return null!=o&&function(e,t){const n=kt(e,["force"]);void 0!==t&&null!=n&&Nt(t,["_query","force"],n)}(o,t),t}(e);o=Pt("{name}",r._url),i=r._query,delete r._url,delete r._query,await this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(r),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal})}}async listInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["parent"]);null!=n&&Nt(t,["_url","parent"],n);const o=kt(e,["config"]);return null!=o&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o)}(o,t),t}(e);return i=Pt("{parent}/documents",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["documents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["documents"],e)}return t}(e),n=new on;return Object.assign(n,t),n})}}},Rl=class extends Rt{constructor(e,t=new wl(e)){super(),this.apiClient=e,this.documents=t,this.list=async(e={})=>new to(Gt.PAGED_ITEM_FILE_SEARCH_STORES,e=>this.listInternal(e),await this.listInternal(e),e)}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,t){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");const n=new URL(e,"http://dummy.com");let o=n.pathname;if(o.startsWith("/")&&(o=o.slice(1)),!o.includes("/media/"))throw new Error(`Invalid uri format: ${e}. Expected to contain /media/`);const i={};n.searchParams.forEach((e,t)=>{i[t]=e}),i.alt="media";const r=Object.assign({},null==t?void 0:t.httpOptions),s=await this.apiClient.request({path:o,httpMethod:"GET",queryParams:i,httpOptions:r});if(s instanceof Ut){const e=await s.responseInternal.arrayBuffer();return new Uint8Array(e)}throw new Error("Unexpected response type from downloadMedia")}async create(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e,t){const n={},o=kt(t,["config"]);return null!=o&&function(e,t,n){const o=kt(t,["displayName"]);void 0!==n&&null!=o&&Nt(n,["displayName"],o);const i=kt(t,["embeddingModel"]);void 0!==n&&null!=i&&Nt(n,["embeddingModel"],vn(e,i))}(e,o,n),n}(this.apiClient,e);return i=Pt("fileSearchStores",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async get(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return i=Pt("{name}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async delete(e){var t,n;let o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const r=function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["_url","name"],n);const o=kt(e,["config"]);return null!=o&&function(e,t){const n=kt(e,["force"]);void 0!==t&&null!=n&&Nt(t,["_query","force"],n)}(o,t),t}(e);o=Pt("{name}",r._url),i=r._query,delete r._url,delete r._query,await this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(r),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal})}}async listInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o)}(n,t),t}(e);return i=Pt("fileSearchStores",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["fileSearchStores"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["fileSearchStores"],e)}return t}(e),n=new rn;return Object.assign(n,t),n})}}async uploadToFileSearchStoreInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["fileSearchStoreName"]);null!=n&&Nt(t,["_url","file_search_store_name"],n);const o=kt(e,["config"]);return null!=o&&Ha(o,t),t}(e);return i=Pt("upload/{api_version}/{file_search_store_name}:uploadToFileSearchStore",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new sn;return Object.assign(n,t),n})}}async importFile(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["fileSearchStoreName"]);null!=n&&Nt(t,["_url","file_search_store_name"],n);const o=kt(e,["fileName"]);null!=o&&Nt(t,["fileName"],o);const i=kt(e,["config"]);return null!=i&&function(e,t){const n=kt(e,["customMetadata"]);if(void 0!==t&&null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["customMetadata"],e)}const o=kt(e,["chunkingConfig"]);void 0!==t&&null!=o&&Nt(t,["chunkingConfig"],o)}(i,t),t}(e);return i=Pt("{file_search_store_name}:importFile",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["parent"]);null!=o&&Nt(t,["parent"],o);const i=kt(e,["documentName"]);return null!=i&&Nt(t,["documentName"],i),t}(s)),t}(e),n=new an;return Object.assign(n,t),n})}}};function Pl(e,t){const n={},o=kt(e,["parts"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);if(null!=n&&Nt(t,["mediaResolution"],n),void 0!==kt(e,["toolCall"]))throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["toolResponse"]))throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=kt(e,["audioTranscription"]);null!=o&&Nt(t,["audioTranscription"],o);const i=kt(e,["codeExecutionResult"]);null!=i&&Nt(t,["codeExecutionResult"],i);const r=kt(e,["executableCode"]);null!=r&&Nt(t,["executableCode"],r);const s=kt(e,["fileData"]);null!=s&&Nt(t,["fileData"],s);const a=kt(e,["functionCall"]);null!=a&&Nt(t,["functionCall"],a);const l=kt(e,["functionResponse"]);null!=l&&Nt(t,["functionResponse"],function(e){const t={},n=kt(e,["id"]);null!=n&&Nt(t,["id"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["parts"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["fileData"]);null!=n&&Nt(t,["fileData"],n);const o=kt(e,["inlineData"]);if(null!=o&&Nt(t,["inlineData"],o),void 0!==kt(e,["mediaProcessing"]))throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const i=kt(e,["mediaResolution"]);null!=i&&Nt(t,["mediaResolution"],i);const r=kt(e,["videoMetadata"]);null!=r&&Nt(t,["videoMetadata"],r);const s=kt(e,["documentMetadata"]);null!=s&&Nt(t,["documentMetadata"],s);const a=kt(e,["spreadsheetMetadata"]);null!=a&&Nt(t,["spreadsheetMetadata"],a);const l=kt(e,["audioMetadata"]);return null!=l&&Nt(t,["audioMetadata"],l),t}(e))),Nt(t,["parts"],e)}const r=kt(e,["response"]);null!=r&&Nt(t,["response"],r);const s=kt(e,["scheduling"]);if(null!=s&&Nt(t,["scheduling"],s),void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(l));const u=kt(e,["inlineData"]);null!=u&&Nt(t,["inlineData"],u);const c=kt(e,["text"]);null!=c&&Nt(t,["text"],c);const d=kt(e,["thought"]);null!=d&&Nt(t,["thought"],d);const p=kt(e,["thoughtSignature"]);null!=p&&Nt(t,["thoughtSignature"],p);const m=kt(e,["videoMetadata"]);if(null!=m&&Nt(t,["videoMetadata"],m),void 0!==kt(e,["partMetadata"]))throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const h=kt(e,["mediaProcessing"]);null!=h&&Nt(t,["mediaProcessing"],h);const f=kt(e,["speechMetadata"]);null!=f&&Nt(t,["speechMetadata"],f);const v=kt(e,["documentMetadata"]);null!=v&&Nt(t,["documentMetadata"],v);const g=kt(e,["spreadsheetMetadata"]);null!=g&&Nt(t,["spreadsheetMetadata"],g);const _=kt(e,["audioMetadata"]);return null!=_&&Nt(t,["audioMetadata"],_),t}(e))),Nt(n,["parts"],e)}const i=kt(e,["role"]);return null!=i&&Nt(n,["role"],i),n}function Nl(e,t){const n={},o=kt(e,["epochCount"]);null!=o&&Nt(n,["epochCount"],o);const i=kt(e,["learningRateMultiplier"]);null!=i&&Nt(n,["learningRateMultiplier"],i);const r=kt(e,["adapterSize"]);null!=r&&Nt(n,["adapterSize"],r);const s=kt(e,["batchSize"]);null!=s&&Nt(n,["batchSize"],s);const a=kt(e,["learningRate"]);null!=a&&Nt(n,["learningRate"],a);const l=kt(e,["generationConfig"]);return null!=l&&Nt(n,["generationConfig"],function(e){const t={},n=kt(e,["modelConfig"]);null!=n&&Nt(t,["modelSelectionConfig"],n);const o=kt(e,["responseJsonSchema"]);null!=o&&Nt(t,["responseJsonSchema"],o);const i=kt(e,["audioTranscriptionConfig"]);null!=i&&Nt(t,["audioTranscriptionConfig"],i);const r=kt(e,["audioTimestamp"]);null!=r&&Nt(t,["audioTimestamp"],r);const s=kt(e,["candidateCount"]);null!=s&&Nt(t,["candidateCount"],s);const a=kt(e,["enableAffectiveDialog"]);null!=a&&Nt(t,["enableAffectiveDialog"],a);const l=kt(e,["frequencyPenalty"]);null!=l&&Nt(t,["frequencyPenalty"],l);const u=kt(e,["logprobs"]);null!=u&&Nt(t,["logprobs"],u);const c=kt(e,["maxOutputTokens"]);null!=c&&Nt(t,["maxOutputTokens"],c);const d=kt(e,["mediaResolution"]);null!=d&&Nt(t,["mediaResolution"],d);const p=kt(e,["presencePenalty"]);null!=p&&Nt(t,["presencePenalty"],p);const m=kt(e,["responseFormat"]);if(null!=m){let e=m;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["responseFormat"],e)}const h=kt(e,["responseLogprobs"]);null!=h&&Nt(t,["responseLogprobs"],h);const f=kt(e,["responseMimeType"]);null!=f&&Nt(t,["responseMimeType"],f);const v=kt(e,["responseModalities"]);null!=v&&Nt(t,["responseModalities"],v);const g=kt(e,["responseSchema"]);null!=g&&Nt(t,["responseSchema"],g);const _=kt(e,["routingConfig"]);null!=_&&Nt(t,["routingConfig"],_);const y=kt(e,["seed"]);null!=y&&Nt(t,["seed"],y);const E=kt(e,["speechConfig"]);null!=E&&Nt(t,["speechConfig"],E);const T=kt(e,["stopSequences"]);null!=T&&Nt(t,["stopSequences"],T);const A=kt(e,["temperature"]);null!=A&&Nt(t,["temperature"],A);const I=kt(e,["thinkingConfig"]);null!=I&&Nt(t,["thinkingConfig"],I);const C=kt(e,["topK"]);null!=C&&Nt(t,["topK"],C);const S=kt(e,["topP"]);null!=S&&Nt(t,["topP"],S);const b=kt(e,["translationConfig"]);return null!=b&&Nt(t,["translationConfig"],b),t}(l)),n}function kl(e,t){const n={},o=kt(e,["sdkHttpResponse"]);null!=o&&Nt(n,["sdkHttpResponse"],o);const i=kt(e,["name"]);null!=i&&Nt(n,["name"],i);const r=kt(e,["state"]);null!=r&&Nt(n,["state"],Un(r));const s=kt(e,["createTime"]);null!=s&&Nt(n,["createTime"],s);const a=kt(e,["startTime"]);null!=a&&Nt(n,["startTime"],a);const l=kt(e,["endTime"]);null!=l&&Nt(n,["endTime"],l);const u=kt(e,["updateTime"]);null!=u&&Nt(n,["updateTime"],u);const c=kt(e,["error"]);null!=c&&Nt(n,["error"],c);const d=kt(e,["description"]);null!=d&&Nt(n,["description"],d);const p=kt(e,["baseModel"]);null!=p&&Nt(n,["baseModel"],p);const m=kt(e,["tunedModel"]);null!=m&&Nt(n,["tunedModel"],m);const h=kt(e,["preTunedModel"]);null!=h&&Nt(n,["preTunedModel"],h);const f=kt(e,["supervisedTuningSpec"]);null!=f&&Nt(n,["supervisedTuningSpec"],f);const v=kt(e,["preferenceOptimizationSpec"]);null!=v&&Nt(n,["preferenceOptimizationSpec"],v);const g=kt(e,["distillationSamplingSpec"]);null!=g&&Nt(n,["distillationSamplingSpec"],function(e){const t={},n=kt(e,["promptDatasetUri"]);null!=n&&Nt(t,["promptDatasetUri"],n);const o=kt(e,["validationDatasetUri"]);null!=o&&Nt(t,["validationDatasetUri"],o);const i=kt(e,["baseTeacherModel"]);null!=i&&Nt(t,["baseTeacherModel"],i);const r=kt(e,["tunedTeacherModelSource"]);null!=r&&Nt(t,["tunedTeacherModelSource"],r);const s=kt(e,["hyperparameters"]);return null!=s&&Nt(t,["hyperparameters"],Nl(s)),t}(g));const _=kt(e,["distillationSpec"]);null!=_&&Nt(n,["distillationSpec"],function(e){const t={},n=kt(e,["baseTeacherModel"]);null!=n&&Nt(t,["baseTeacherModel"],n);const o=kt(e,["hyperParameters"]);null!=o&&Nt(t,["hyperParameters"],Nl(o));const i=kt(e,["pipelineRootDirectory"]);null!=i&&Nt(t,["pipelineRootDirectory"],i);const r=kt(e,["promptDatasetUri"]);null!=r&&Nt(t,["promptDatasetUri"],r);const s=kt(e,["studentModel"]);null!=s&&Nt(t,["studentModel"],s);const a=kt(e,["trainingDatasetUri"]);null!=a&&Nt(t,["trainingDatasetUri"],a);const l=kt(e,["tunedTeacherModelSource"]);null!=l&&Nt(t,["tunedTeacherModelSource"],l);const u=kt(e,["tuningMode"]);null!=u&&Nt(t,["tuningMode"],u);const c=kt(e,["validationDatasetUri"]);return null!=c&&Nt(t,["validationDatasetUri"],c),t}(_));const y=kt(e,["reinforcementTuningSpec"]);null!=y&&Nt(n,["reinforcementTuningSpec"],y);const E=kt(e,["tuningDataStats"]);null!=E&&Nt(n,["tuningDataStats"],E);const T=kt(e,["encryptionSpec"]);null!=T&&Nt(n,["encryptionSpec"],T);const A=kt(e,["partnerModelTuningSpec"]);null!=A&&Nt(n,["partnerModelTuningSpec"],A);const I=kt(e,["customBaseModel"]);null!=I&&Nt(n,["customBaseModel"],I);const C=kt(e,["evaluateDatasetRuns"]);if(null!=C){let e=C;Array.isArray(e)&&(e=e.map(e=>e)),Nt(n,["evaluateDatasetRuns"],e)}const S=kt(e,["experiment"]);null!=S&&Nt(n,["experiment"],S);const b=kt(e,["fullFineTuningSpec"]);null!=b&&Nt(n,["fullFineTuningSpec"],b);const O=kt(e,["labels"]);null!=O&&Nt(n,["labels"],O);const w=kt(e,["outputUri"]);null!=w&&Nt(n,["outputUri"],w);const R=kt(e,["pipelineJob"]);null!=R&&Nt(n,["pipelineJob"],R);const P=kt(e,["serviceAccount"]);null!=P&&Nt(n,["serviceAccount"],P);const N=kt(e,["tunedModelDisplayName"]);null!=N&&Nt(n,["tunedModelDisplayName"],N);const k=kt(e,["tuningJobMetadata"]);null!=k&&Nt(n,["tuningJobMetadata"],k);const D=kt(e,["tuningJobState"]);null!=D&&Nt(n,["tuningJobState"],D);const M=kt(e,["veoLoraTuningSpec"]);null!=M&&Nt(n,["veoLoraTuningSpec"],M);const x=kt(e,["veoTuningSpec"]);null!=x&&Nt(n,["veoTuningSpec"],x);const G=kt(e,["gcsMetricsUri"]);return null!=G&&Nt(n,["gcsMetricsUri"],G),n}function Dl(e,t){const n={},o=kt(e,["gcsUri"]);null!=o&&Nt(n,["validationDatasetUri"],o);const i=kt(e,["vertexDatasetResource"]);return null!=i&&Nt(n,["validationDatasetUri"],i),n}var Ml=class extends Rt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new to(Gt.PAGED_ITEM_TUNING_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.get=async e=>await this.getInternal(e),this.tune=async e=>{var t;if(this.apiClient.isVertexAI()){if(e.baseModel.startsWith("projects/")){const n={tunedModelName:e.baseModel};(null===(t=e.config)||void 0===t?void 0:t.preTunedModelCheckpointId)&&(n.checkpointId=e.config.preTunedModelCheckpointId);const o=Object.assign(Object.assign({},e),{preTunedModel:n});return o.baseModel=void 0,await this.tuneInternal(o)}{const t=Object.assign({},e);return await this.tuneInternal(t)}}{const t=Object.assign({},e),n=await this.tuneMldevInternal(t);let o="";return void 0!==n.metadata&&void 0!==n.metadata.tunedModel?o=n.metadata.tunedModel:void 0!==n.name&&n.name.includes("/operations/")&&(o=n.name.split("/operations/")[0]),{name:o,state:Fe.JOB_STATE_QUEUED}}}}async getInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>kl(e))}{const t=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["state"]);null!=i&&Nt(t,["state"],Un(i));const r=kt(e,["createTime"]);null!=r&&Nt(t,["createTime"],r);const s=kt(e,["tuningTask","startTime"]);null!=s&&Nt(t,["startTime"],s);const a=kt(e,["tuningTask","completeTime"]);null!=a&&Nt(t,["endTime"],a);const l=kt(e,["updateTime"]);null!=l&&Nt(t,["updateTime"],l);const u=kt(e,["description"]);null!=u&&Nt(t,["description"],u);const c=kt(e,["baseModel"]);null!=c&&Nt(t,["baseModel"],c);const d=kt(e,["_self"]);return null!=d&&Nt(t,["tunedModel"],function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["model"],n);const o=kt(e,["name"]);return null!=o&&Nt(t,["endpoint"],o),t}(d)),t}(e))}}async listInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o);const i=kt(e,["filter"]);void 0!==t&&null!=i&&Nt(t,["_query","filter"],i)}(n,t),t}(e);return i=Pt("tuningJobs",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["tuningJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>kl(e))),Nt(t,["tuningJobs"],e)}return t}(e),n=new Zt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return s=Pt("{name}:cancel",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new Qt;return Object.assign(n,t),n})}{const t=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return s=Pt("{name}:cancel",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new Qt;return Object.assign(n,t),n})}}async tuneInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(e,["baseModel"]);null!=o&&Nt(n,["baseModel"],o);const i=kt(e,["preTunedModel"]);null!=i&&Nt(n,["preTunedModel"],i);const r=kt(e,["trainingDataset"]);null!=r&&function(e,t,n){let o=kt(n,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){const n=kt(e,["gcsUri"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","trainingDatasetUri"],n)}else if("PREFERENCE_TUNING"===o){const n=kt(e,["gcsUri"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","trainingDatasetUri"],n)}else if("DISTILLATION"===o){const n=kt(e,["gcsUri"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","promptDatasetUri"],n)}else if("REINFORCEMENT_TUNING"===o){const n=kt(e,["gcsUri"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","trainingDatasetUri"],n)}let i=kt(n,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){const n=kt(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","trainingDatasetUri"],n)}else if("PREFERENCE_TUNING"===i){const n=kt(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","trainingDatasetUri"],n)}else if("DISTILLATION"===i){const n=kt(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","promptDatasetUri"],n)}else if("REINFORCEMENT_TUNING"===i){const n=kt(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","trainingDatasetUri"],n)}if(void 0!==kt(e,["examples"]))throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.")}(r,n,t);const s=kt(e,["config"]);return null!=s&&function(e,t,n){let o=kt(n,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){const n=kt(e,["validationDataset"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec"],Dl(n))}else if("PREFERENCE_TUNING"===o){const n=kt(e,["validationDataset"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec"],Dl(n))}else if("DISTILLATION"===o){const n=kt(e,["validationDataset"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec"],Dl(n))}else if("REINFORCEMENT_TUNING"===o){const n=kt(e,["validationDataset"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec"],Dl(n))}const i=kt(e,["tunedModelDisplayName"]);void 0!==t&&null!=i&&Nt(t,["tunedModelDisplayName"],i);const r=kt(e,["description"]);void 0!==t&&null!=r&&Nt(t,["description"],r);let s=kt(n,["config","method"]);if(void 0===s&&(s="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===s){const n=kt(e,["epochCount"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","hyperParameters","epochCount"],n)}else if("PREFERENCE_TUNING"===s){const n=kt(e,["epochCount"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],n)}else if("DISTILLATION"===s){const n=kt(e,["epochCount"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","hyperParameters","epochCount"],n)}else if("REINFORCEMENT_TUNING"===s){const n=kt(e,["epochCount"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","hyperParameters","epochCount"],n)}let a=kt(n,["config","method"]);if(void 0===a&&(a="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===a){const n=kt(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],n)}else if("PREFERENCE_TUNING"===a){const n=kt(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],n)}else if("DISTILLATION"===a){const n=kt(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","hyperParameters","learningRateMultiplier"],n)}else if("REINFORCEMENT_TUNING"===a){const n=kt(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],n)}let l=kt(n,["config","method"]);if(void 0===l&&(l="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===l){const n=kt(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","exportLastCheckpointOnly"],n)}else if("PREFERENCE_TUNING"===l){const n=kt(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],n)}else if("DISTILLATION"===l){const n=kt(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","exportLastCheckpointOnly"],n)}let u=kt(n,["config","method"]);if(void 0===u&&(u="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===u){const n=kt(e,["adapterSize"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","hyperParameters","adapterSize"],n)}else if("PREFERENCE_TUNING"===u){const n=kt(e,["adapterSize"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],n)}else if("DISTILLATION"===u){const n=kt(e,["adapterSize"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","hyperParameters","adapterSize"],n)}else if("REINFORCEMENT_TUNING"===u){const n=kt(e,["adapterSize"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","hyperParameters","adapterSize"],n)}let c=kt(n,["config","method"]);if(void 0===c&&(c="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===c){const n=kt(e,["tuningMode"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","tuningMode"],n)}else if("DISTILLATION"===c){const n=kt(e,["tuningMode"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","tuningMode"],n)}const d=kt(e,["customBaseModel"]);void 0!==t&&null!=d&&Nt(t,["customBaseModel"],d);let p=kt(n,["config","method"]);if(void 0===p&&(p="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===p){const n=kt(e,["batchSize"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","hyperParameters","batchSize"],n)}else if("DISTILLATION"===p){const n=kt(e,["batchSize"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","hyperParameters","batchSize"],n)}else if("REINFORCEMENT_TUNING"===p){const n=kt(e,["batchSize"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","hyperParameters","batchSize"],n)}let m=kt(n,["config","method"]);if(void 0===m&&(m="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===m){const n=kt(e,["learningRate"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","hyperParameters","learningRate"],n)}else if("DISTILLATION"===m){const n=kt(e,["learningRate"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","hyperParameters","learningRate"],n)}const h=kt(e,["labels"]);void 0!==t&&null!=h&&Nt(t,["labels"],h);const f=kt(e,["beta"]);void 0!==t&&null!=f&&Nt(t,["preferenceOptimizationSpec","hyperParameters","beta"],f);const v=kt(e,["baseTeacherModel"]);void 0!==t&&null!=v&&Nt(t,["distillationSpec","baseTeacherModel"],v);const g=kt(e,["tunedTeacherModelSource"]);void 0!==t&&null!=g&&Nt(t,["distillationSpec","tunedTeacherModelSource"],g);const _=kt(e,["sftLossWeightMultiplier"]);void 0!==t&&null!=_&&Nt(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],_);const y=kt(e,["outputUri"]);void 0!==t&&null!=y&&Nt(t,["outputUri"],y);const E=kt(e,["rewardConfig"]);void 0!==t&&null!=E&&Nt(t,["reinforcementTuningSpec","singleRewardConfig"],E);const T=kt(e,["compositeRewardConfig"]);void 0!==t&&null!=T&&Nt(t,["reinforcementTuningSpec","compositeRewardConfig"],T);const A=kt(e,["samplesPerPrompt"]);void 0!==t&&null!=A&&Nt(t,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],A);const I=kt(e,["evaluateInterval"]);void 0!==t&&null!=I&&Nt(t,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],I);const C=kt(e,["checkpointInterval"]);void 0!==t&&null!=C&&Nt(t,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],C);const S=kt(e,["maxOutputTokens"]);void 0!==t&&null!=S&&Nt(t,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],S);const b=kt(e,["thinkingLevel"]);void 0!==t&&null!=b&&Nt(t,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],b);const O=kt(e,["validationDatasetUri"]);void 0!==t&&null!=O&&Nt(t,["reinforcementTuningSpec","validationDatasetUri"],O);const w=kt(e,["encryptionSpec"]);void 0!==t&&null!=w&&Nt(t,["encryptionSpec"],w)}(s,n,t),n}(e,e);return i=Pt("tuningJobs",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>kl(e))}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["baseModel"]);null!=n&&Nt(t,["baseModel"],n);const o=kt(e,["preTunedModel"]);null!=o&&Nt(t,["preTunedModel"],o);const i=kt(e,["trainingDataset"]);null!=i&&function(e){const t={};if(void 0!==kt(e,["gcsUri"]))throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["vertexDatasetResource"]))throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["examples"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["examples","examples"],e)}}(i);const r=kt(e,["config"]);return null!=r&&function(e,t){if(void 0!==kt(e,["validationDataset"]))throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["tunedModelDisplayName"]);if(void 0!==t&&null!=n&&Nt(t,["displayName"],n),void 0!==kt(e,["description"]))throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["epochCount"]);void 0!==t&&null!=o&&Nt(t,["tuningTask","hyperparameters","epochCount"],o);const i=kt(e,["learningRateMultiplier"]);if(null!=i&&Nt({},["tuningTask","hyperparameters","learningRateMultiplier"],i),void 0!==kt(e,["exportLastCheckpointOnly"]))throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["preTunedModelCheckpointId"]))throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["adapterSize"]))throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["tuningMode"]))throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["customBaseModel"]))throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=kt(e,["batchSize"]);void 0!==t&&null!=r&&Nt(t,["tuningTask","hyperparameters","batchSize"],r);const s=kt(e,["learningRate"]);if(void 0!==t&&null!=s&&Nt(t,["tuningTask","hyperparameters","learningRate"],s),void 0!==kt(e,["labels"]))throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["beta"]))throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["baseTeacherModel"]))throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["tunedTeacherModelSource"]))throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["sftLossWeightMultiplier"]))throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["outputUri"]))throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["rewardConfig"]))throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["compositeRewardConfig"]))throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["samplesPerPrompt"]))throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["evaluateInterval"]))throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["checkpointInterval"]))throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["maxOutputTokens"]))throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["thinkingLevel"]))throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["validationDatasetUri"]))throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["encryptionSpec"]))throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(r,t),t}(e);return i=Pt("tunedModels",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["metadata"]);null!=i&&Nt(t,["metadata"],i);const r=kt(e,["done"]);null!=r&&Nt(t,["done"],r);const s=kt(e,["error"]);return null!=s&&Nt(t,["error"],s),t}(e))}}async validateReward(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e){const t={},n=kt(e,["parent"]);null!=n&&Nt(t,["_url","parent"],n);const o=kt(e,["sampleResponse"]);null!=o&&Nt(t,["sampleResponse"],Pl(o));const i=kt(e,["example"]);null!=i&&Nt(t,["example"],function(e){const t={},n=kt(e,["references"]);null!=n&&Nt(t,["references"],n);const o=kt(e,["contents"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Pl(e))),Nt(t,["contents"],e)}const i=kt(e,["systemInstruction"]);null!=i&&Nt(t,["systemInstruction"],Pl(i));const r=kt(e,["tools"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["retrieval"]);null!=n&&Nt(t,["retrieval"],n);const o=kt(e,["googleMaps"]);null!=o&&Nt(t,["googleMaps"],o);const i=kt(e,["mcpServers"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){if(void 0!==kt(e,["name"]))throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["streamableHttpTransport"]))throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}(e))),Nt(t,["mcpServers"],e)}const r=kt(e,["codeExecution"]);null!=r&&Nt(t,["codeExecution"],r);const s=kt(e,["computerUse"]);null!=s&&Nt(t,["computerUse"],s);const a=kt(e,["enterpriseWebSearch"]);null!=a&&Nt(t,["enterpriseWebSearch"],a);const l=kt(e,["exaAiSearch"]);null!=l&&Nt(t,["exaAiSearch"],l);const u=kt(e,["functionDeclarations"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const c=kt(e,["googleSearch"]);null!=c&&Nt(t,["googleSearch"],c);const d=kt(e,["googleSearchRetrieval"]);null!=d&&Nt(t,["googleSearchRetrieval"],d);const p=kt(e,["parallelAiSearch"]);null!=p&&Nt(t,["parallelAiSearch"],p);const m=kt(e,["urlContext"]);if(null!=m&&Nt(t,["urlContext"],m),void 0!==kt(e,["fileSearch"]))throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(e))),Nt(t,["tools"],e)}return t}(i));const r=kt(e,["singleRewardConfig"]);null!=r&&Nt(t,["singleRewardConfig"],r);const s=kt(e,["compositeRewardConfig"]);return null!=s&&Nt(t,["compositeRewardConfig"],s),t}(e);return i=Pt("{parent}/tuningJobs:validateReinforcementTuningReward",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["overallReward"]);null!=o&&Nt(t,["overallReward"],o);const i=kt(e,["error"]);null!=i&&Nt(t,["error"],i);const r=kt(e,["rewardInfoDetails"]);return null!=r&&Nt(t,["rewardInfoDetails"],r),t}(e),n=new en;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},xl=class{async download(e,t){throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.")}},Gl="x-goog-upload-status";async function Ul(e,t,n,o){var i,r,s;let a=t;const l=(null==o?void 0:o.baseUrl)||(null===(i=n.clientOptions.httpOptions)||void 0===i?void 0:i.baseUrl);if(l){const e=new URL(l),n=new URL(t);n.protocol=e.protocol,n.host=e.host,n.port=e.port,a=n.toString()}let u=0,c=0,d=new Ut(new Response),p="upload";for(u=e.size;c<u;){const t=Math.min(8388608,u-c),i=e.slice(c,c+t);c+t>=u&&(p+=", finalize");let l=0,m=1e3;for(;l<3;){const e=Object.assign(Object.assign({},(null==o?void 0:o.headers)||{}),{"X-Goog-Upload-Command":p,"X-Goog-Upload-Offset":String(c)});if(d=await n.request({path:"",body:i,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},o),{apiVersion:"",baseUrl:a,headers:e})}),null===(r=null==d?void 0:d.headers)||void 0===r?void 0:r[Gl])break;l++,await Ll(m),m*=2}if(c+=t,"active"!==(null===(s=null==d?void 0:d.headers)||void 0===s?void 0:s[Gl]))break;if(u<=c)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return d}function Ll(e){return new Promise(t=>setTimeout(t,e))}var ql=class{async upload(e,t,n,o){if("string"==typeof e)throw new Error("File path is not supported in browser uploader.");return await async function(e,t,n,o){var i;const r=await Ul(e,t,n,o),s=await(null==r?void 0:r.json());if("final"!==(null===(i=null==r?void 0:r.headers)||void 0===i?void 0:i[Gl]))throw new Error("Failed to upload file: Upload status is not finalized.");return s.file}(e,t,n,o)}async uploadToFileSearchStore(e,t,n,o){if("string"==typeof e)throw new Error("File path is not supported in browser uploader.");return await async function(e,t,n,o){var i;const r=await Ul(e,t,n,o),s=await(null==r?void 0:r.json());if("final"!==(null===(i=null==r?void 0:r.headers)||void 0===i?void 0:i[Gl]))throw new Error("Failed to upload file: Upload status is not finalized.");const a=xt(s),l=new fn;return Object.assign(l,a),l}(e,t,n,o)}async stat(e){if("string"==typeof e)throw new Error("File path is not supported in browser uploader.");return await async function(e){return{size:e.size,type:e.type}}(e)}},Hl=class{constructor(){this.supportsHeaders=!1}create(e,t,n){return new jl(e,t,n)}},jl=class{constructor(e,t,n){this.url=e,this.headers=t,this.callbacks=n}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(void 0===this.ws)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(void 0===this.ws)throw new Error("WebSocket is not connected");this.ws.close()}},Fl="x-goog-api-key",Xl=class{constructor(e){this.apiKey=e}async addAuthHeaders(e,t){if(null===e.get(Fl)){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(Fl,this.apiKey)}}},Bl=class{getNextGenClient(){const e=this.httpOptions;return void 0===this._nextGenClient&&(this._nextGenClient=Xs(this.apiClient,{timeout_ms:null==e?void 0:e.timeout})),null==e||e.extraBody,this._nextGenClient}get interactions(){return void 0!==this._interactions||(this._interactions=new Vs(this.apiClient,new Hl)),this._interactions}get webhooks(){return void 0!==this._webhooks||(this._webhooks=new $s(this.apiClient)),this._webhooks}get agents(){return void 0!==this._agents||(this._agents=new Js(this.apiClient)),this._agents}get triggers(){return void 0!==this._triggers||(this._triggers=new Ws(this.apiClient)),this._triggers}get environments(){return void 0!==this._environments||(this._environments=new la(this.apiClient)),this._environments}get credentials(){return void 0!==this._credentials||(this._credentials=new ua(this.apiClient)),this._credentials}get voices(){return void 0!==this._voices||(this._voices=new ca(this.apiClient)),this._voices}get decisions(){return void 0!==this._decisions||(this._decisions=new da(this.apiClient)),this._decisions}constructor(e={}){var t;if(null==e.apiKey)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=null!==(t=e.vertexai)&&void 0!==t&&t,this.apiKey=e.apiKey;const n=function(e,t){var n,o;if(!(null==e?void 0:e.baseUrl)){const e={geminiUrl:void 0,vertexUrl:void 0};return t?null!==(n=e.vertexUrl)&&void 0!==n?n:void 0:null!==(o=e.geminiUrl)&&void 0!==o?o:void 0}return e.baseUrl}(e.httpOptions,e.vertexai);n&&(e.httpOptions?e.httpOptions.baseUrl=n:e.httpOptions={baseUrl:n}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;const o=new Xl(this.apiKey);this.apiClient=new Va({auth:o,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:"gl-node/web",uploader:new ql,downloader:new xl}),this.models=new Cl(this.apiClient),this.live=new tl(this.apiClient,o,new Hl),this.batches=new no(this.apiClient),this.chats=new uo(this.models,this.apiClient),this.caches=new ro(this.apiClient),this.files=new ho(this.apiClient),this.operations=new Sl(this.apiClient),this.authTokens=new Ol(this.apiClient),this.tunings=new Ml(this.apiClient),this.fileSearchStores=new Rl(this.apiClient)}},Vl={THINKING_LEVEL_UNSPECIFIED:fe.THINKING_LEVEL_UNSPECIFIED,MINIMAL:fe.MINIMAL,LOW:fe.LOW,MEDIUM:fe.MEDIUM,HIGH:fe.HIGH,XHIGH:fe.XHIGH};function Jl(e,t){const n=e.thinkingLevelMap?.[t],o="string"==typeof n?n.toLowerCase():t;switch(o){case"minimal":case"low":case"medium":case"high":case"xhigh":return o;default:throw new Error(`Unsupported Google thinking level mapping for ${e.provider}/${e.id}: ${t} -> ${String(n)}`)}}function $l(e){const t=e.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(t)||(nu(t)??0)>=4||"gemini-flash-latest"===t||"gemini-flash-lite-latest"===t||/gemma-?4/.test(t)}function Wl(e){switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH";case"xhigh":return"XHIGH"}}function Yl(e,t,n){const o="xhigh"===t?"high":t,i=n?.[o];return void 0!==i?i:e.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[o]:e.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[o]:e.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[o]:-1}function Kl(e){return Vl[e]}function zl(e){return!0===e.thought}function Zl(e,t){return"string"==typeof t&&t.length>0?t:e}var Ql=/^[A-Za-z0-9+/]+={0,2}$/;function eu(e,t){return e&&function(e){return!!e&&e.length%4==0&&Ql.test(e)}(t)?t:void 0}function tu(e){const t=nu(e);return e.startsWith("claude-")||e.startsWith("gpt-oss-")||void 0!==t&&t>=3}function nu(e){const t=e.toLowerCase().match(/gemini(?:-live)?-(\d+)/);if(t)return Number.parseInt(t[1],10)}function ou(e){const t=nu(e);return void 0===t||t>=3}var iu=/* @__PURE__ */new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function ru(e){if("object"!=typeof e||null===e||Array.isArray(e))return e;const t={};for(const[n,o]of Object.entries(e))iu.has(n)||(t[n]=ru(o));return t}var su=/* @__PURE__ */new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]),au=/* @__PURE__ */new Set(["additionalProperties","unevaluatedProperties","propertyNames","items","prefixItems","additionalItems","unevaluatedItems","contains","allOf","anyOf","oneOf","not","if","then","else","contentSchema"]);function lu(e,t=!1){if(Array.isArray(e))return e.map(e=>lu(e));if("object"!=typeof e||null===e)return e;const n=Object.fromEntries(Object.entries(e).map(([e,n])=>t||au.has(e)?[e,lu(n)]:su.has(e)?[e,lu(n,!0)]:[e,n]));if(!t&&"const"in n&&void 0===n.enum){const e=n.const;"string"!=typeof e&&"number"!=typeof e||(delete n.const,n.enum=[e])}return n}function uu(e,t=!1,n=!0){if(0!==e.length)return[{functionDeclarations:e.map(e=>{const o=v(e,n),i=y(e,o);return{name:e.name,description:e.description,...t?{parameters:ru(i)}:{parametersJsonSchema:lu(i)}}})}]}function cu(e){switch(e){case"auto":default:return Te.AUTO;case"none":return Te.NONE;case"any":return Te.ANY}}function du(e,t){const n=[`${e} prompt blocked: ${t.blockReason??"unknown reason"}`];if(t.blockReasonMessage&&n.push(t.blockReasonMessage),t.safetyRatings?.length){const e=t.safetyRatings.flatMap(e=>e.category?[`${e.category}${e.probability?` (${e.probability})`:""}`]:[]);e.length>0&&n.push(`Safety rating${1===e.length?"":"s"}: ${e.join(", ")}`)}return n.join(". ")}function pu(e){switch(e){case Ie.STOP:return"stop";case Ie.MAX_TOKENS:case Ie.CONTINUATION:return"length";case Ie.BLOCKLIST:case Ie.PROHIBITED_CONTENT:case Ie.SPII:case Ie.SAFETY:case Ie.IMAGE_SAFETY:case Ie.IMAGE_PROHIBITED_CONTENT:case Ie.IMAGE_RECITATION:case Ie.IMAGE_OTHER:case Ie.RECITATION:case Ie.FINISH_REASON_UNSPECIFIED:case Ie.OTHER:case Ie.LANGUAGE:case Ie.MALFORMED_FUNCTION_CALL:case Ie.UNEXPECTED_TOOL_CALL:case Ie.TOO_MANY_TOOL_CALLS:case Ie.NO_IMAGE:case Ie.MISSING_THOUGHT_SIGNATURE:case Ie.MALFORMED_RESPONSE:case Ie.ESCALATION:case Ie.PUP_LIMITED_DISABLED:case Ie.MODEL_ARMOR:return"error";default:throw new Error(`Unhandled stop reason: ${e}`)}}var mu=0,hu=(e,t,g)=>{const y=new c,E=r(t);return(async()=>{const t={role:"assistant",content:[],api:"google-generative-ai",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{const c=g?.apiKey;if(!c)throw new Error(`No API key for provider: ${e.provider}`);const d=function(e,t,n,o,i){const r={fetch:i??globalThis.fetch};e.baseUrl&&(r.baseUrl=e.baseUrl,r.apiVersion="");const s=m(u(e,o),e.headers,n);return s&&(r.headers=s),new Bl({apiKey:t,httpOptions:r})}(e,c,g?.headers,g?.identity,g?.fetch);let p=function(e,t,o={}){const u=function(e,t){const n=l(r(t).messages),o=[],i=_(n,e,t=>tu(e.id)?t.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):t);for(const r of i)if("user"===r.role)if("string"==typeof r.content)o.push({role:"user",parts:[{text:f(r.content)}]});else{const e=r.content.map(e=>"text"===e.type?{text:f(e.text)}:{inlineData:{mimeType:e.mimeType,data:e.data}});if(0===e.length)continue;o.push({role:"user",parts:e})}else if("assistant"===r.role){const t=[],n=r.provider===e.provider&&r.model===e.id;for(const o of r.content)if("text"===o.type){const e=eu(n,o.textSignature);if(!(o.text&&""!==o.text.trim()||e))continue;t.push({text:f(o.text),...e&&{thoughtSignature:e}})}else if("thinking"===o.type)if(n){const e=eu(n,o.thinkingSignature);if(!(o.thinking&&""!==o.thinking.trim()||e))continue;t.push({thought:!0,text:f(o.thinking),...e&&{thoughtSignature:e}})}else{if(!o.thinking||""===o.thinking.trim())continue;t.push({text:f(o.thinking)})}else if("toolCall"===o.type){const i=eu(n,o.thoughtSignature),r={functionCall:{name:o.name,args:o.arguments??{},...tu(e.id)?{id:o.id}:{}},...i&&{thoughtSignature:i}};t.push(r)}if(0===t.length)continue;o.push({role:"model",parts:t})}else if("toolResult"===r.role){const t=r.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n=e.input.includes("image")?r.content.filter(e=>"image"===e.type):[],i=t.trim().length>0,s=n.length>0,a=ou(e.id),l=i?f(t):s?"(see attached image)":"",u=n.map(e=>({inlineData:{mimeType:e.mimeType,data:e.data}})),c=tu(e.id),d={functionResponse:{name:r.toolName,response:r.isError?{error:l}:{output:l},...s&&a&&{parts:u},...c?{id:r.toolCallId}:{}}},p=o[o.length-1];"user"===p?.role&&p.parts?.some(e=>e.functionResponse)?p.parts.push(d):o.push({role:"user",parts:[d]}),s&&!a&&o.push({role:"user",parts:[{text:"Tool result image:"},...u]})}return o}(e,t),c=s(t.messages),d=a(t.messages),p={};void 0!==o.temperature&&(p.temperature=o.temperature),void 0!==o.maxTokens&&(p.maxOutputTokens=o.maxTokens);const m=function(e){const t=nu(e.id);return e.compat?.supportsStrictMode??(void 0!==t&&t>=3)}(e),h=d.length>0?function(e,t,n){const o=e.some(e=>!0===v(e,n));return"none"===t||"any"===t?cu(t):o?Te.VALIDATED:t?cu(t):void 0}(d,o.toolChoice,m):void 0,g=c?n(c):"",y={...Object.keys(p).length>0&&p,...g&&{systemInstruction:f(g)},...d.length>0&&{tools:uu(d,!1,m)},...void 0!==h&&{toolConfig:{functionCallingConfig:{mode:h}}},automaticContinuation:!1};if(o.thinking?.enabled&&e.reasoning){const e={includeThoughts:!0};void 0!==o.thinking.level?e.thinkingLevel=Kl(o.thinking.level):void 0!==o.thinking.budgetTokens&&(e.thinkingBudget=o.thinking.budgetTokens),y.thinkingConfig=e}else e.reasoning&&o.thinking&&!o.thinking.enabled&&(y.thinkingConfig=function(e){if(!$l(e))return{thinkingBudget:0};const t=i(e,"off");return"off"===t?{thinkingBudget:0}:{thinkingLevel:Kl(Wl(Jl(e,t)))}}(e));if(o.signal){if(o.signal.aborted)throw new Error("Request aborted");y.abortSignal=o.signal}return{model:e.id,contents:u,config:y}}(e,E,g);const T=await(g?.onPayload?.(p,e));void 0!==T&&(p=T);const A=await function(e,t,n){return h(async()=>{try{return await d.models.generateContentStream(p)}catch(e){throw e instanceof Error&&"status"in e&&!("headers"in e)&&(e.headers=void 0),e}},{maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,signal:n?.signal,onErrorResponse:e=>n?.onResponse?.(e,t)})}(0,e,g);y.push({type:"start",partial:t});let I,C=null,S=0;const b=t.content,O=()=>b.length-1;for await(const n of A){await(g?.onProviderStreamEvent?.(n,e)),S++,n.promptFeedback?.blockReason&&(I??=du("Google",n.promptFeedback)),t.responseId||=n.responseId;const i=n.candidates?.[0];if(i?.content?.parts)for(const e of i.content.parts){if(void 0!==e.text){const n=zl(e);(!C||n&&"thinking"!==C.type||!n&&"text"!==C.type)&&(C&&("text"===C.type?y.push({type:"text_end",contentIndex:b.length-1,content:C.text,partial:t}):y.push({type:"thinking_end",contentIndex:O(),content:C.thinking,partial:t})),n?(C={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(C),y.push({type:"thinking_start",contentIndex:O(),partial:t})):(C={type:"text",text:""},t.content.push(C),y.push({type:"text_start",contentIndex:O(),partial:t}))),"thinking"===C.type?(C.thinking+=e.text,C.thinkingSignature=Zl(C.thinkingSignature,e.thoughtSignature),y.push({type:"thinking_delta",contentIndex:O(),delta:e.text,partial:t})):(C.text+=e.text,C.textSignature=Zl(C.textSignature,e.thoughtSignature),y.push({type:"text_delta",contentIndex:O(),delta:e.text,partial:t}))}if(e.functionCall){C&&("text"===C.type?y.push({type:"text_end",contentIndex:O(),content:C.text,partial:t}):y.push({type:"thinking_end",contentIndex:O(),content:C.thinking,partial:t}),C=null);const n=e.functionCall.id,o={type:"toolCall",id:!n||t.content.some(e=>"toolCall"===e.type&&e.id===n)?`${e.functionCall.name}_${Date.now()}_${++mu}`:n,name:e.functionCall.name||"",arguments:e.functionCall.args??{},...e.thoughtSignature&&{thoughtSignature:e.thoughtSignature}};t.content.push(o),y.push({type:"toolcall_start",contentIndex:O(),partial:t}),y.push({type:"toolcall_delta",contentIndex:O(),delta:JSON.stringify(o.arguments),partial:t}),y.push({type:"toolcall_end",contentIndex:O(),toolCall:o,partial:t})}}i?.finishReason&&(t.rawStopReason=i.finishReason,t.stopReason=pu(i.finishReason),t.content.some(e=>"toolCall"===e.type)&&"stop"===t.stopReason&&(t.stopReason="toolUse")),n.usageMetadata&&(t.usage={input:(n.usageMetadata.promptTokenCount||0)-(n.usageMetadata.cachedContentTokenCount||0),output:(n.usageMetadata.candidatesTokenCount||0)+(n.usageMetadata.thoughtsTokenCount||0),cacheRead:n.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:n.usageMetadata.thoughtsTokenCount||0,totalTokens:n.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},o(e,t.usage))}if(C&&("text"===C.type?y.push({type:"text_end",contentIndex:O(),content:C.text,partial:t}):y.push({type:"thinking_end",contentIndex:O(),content:C.thinking,partial:t})),g?.signal?.aborted)throw new Error("Request was aborted");if("pending"===t.stopReason){if(I)throw new Error(I);throw new Error(`Google stream ended without a finish reason after receiving ${S} ${1===S?"chunk":"chunks"}`)}if("aborted"===t.stopReason||"error"===t.stopReason){const e=t.rawStopReason?`Provider stopped with: ${t.rawStopReason}`:"An unknown error occurred";throw new Error(e)}y.push({type:"done",reason:t.stopReason,message:t}),y.end()}catch(c){t.stopReason=g?.signal?.aborted?"aborted":"error",t.errorMessage=p(d(c)),y.push({type:"error",reason:t.stopReason,error:t}),y.end()}})(),y},fu=(e,t,n)=>{const o=n?.apiKey;if(!o)throw new Error(`No API key for provider: ${e.provider}`);const r={...g(e,t,n,o),toolChoice:n?.toolChoice};if(!n?.reasoning)return hu(e,t,{...r,thinking:{enabled:!1}});const s=i(e,n.reasoning);if("off"===s)return hu(e,t,{...r,thinking:{enabled:!1}});const a=Jl(e,s);return $l(e)?hu(e,t,{...r,thinking:{enabled:!0,level:Wl(a)}}):hu(e,t,{...r,thinking:{enabled:!0,budgetTokens:Yl(e,a,n.thinkingBudgets)}})};export{hu as stream,fu as streamSimple};
1
+ void 0===globalThis.process&&(globalThis.process={env:{},platform:"browser",version:"",versions:{},browser:!0,nextTick:function(e){return Promise.resolve().then(e)}});import{o as e,t}from"./rolldown-runtime-WNHmnFyz.js";import{$ as n,F as o,I as i,L as r,U as s,V as a,Y as l,Z as u,rt as c}from"./LanguageSelect-vGM6rIrX.js";import{a as d,i as p,r as m,t as h}from"./provider-retry-CRfxeEog.js";import{_ as f,g as v,i as g,n as _,p as y}from"./transform-messages-BWDpoK0O.js";var E=/* @__PURE__ */t((e,t)=>{function n(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.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))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=/* @__PURE__ */(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(/* @__PURE__ */new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(void 0===n){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1)}var o=this;return this._timer=setTimeout(function(){o._attempts++,o._operationTimeoutCb&&(o._timeout=setTimeout(function(){o._operationTimeoutCb(o._attempts)},o._operationTimeout),o._options.unref&&o._timeout.unref()),o._fn(o._attempts)},n),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=/* @__PURE__ */(new Date).getTime(),this._fn(this._attempts)},n.prototype.try=function(e){this.attempt(e)},n.prototype.start=function(e){this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,n=0,o=0;o<this._errors.length;o++){var i=this._errors[o],r=i.message,s=(e[r]||0)+1;e[r]=s,s>=n&&(t=i,n=s)}return t}}),T=/* @__PURE__ */t(e=>{var t=E();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],i=0;i<t.retries;i++)o.push(this.createTimeout(i,t));return e&&e.forever&&!o.length&&o.push(this.createTimeout(i,t)),o.sort(function(e,t){return e-t}),o},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,o=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(o,t.maxTimeout)},e.wrap=function(t,n,o){if(n instanceof Array&&(o=n,n=null),!o)for(var i in o=[],t)"function"==typeof t[i]&&o.push(i);for(var r=0;r<o.length;r++){var s=o[r],a=t[s];t[s]=function(o){var i=e.operation(n),r=Array.prototype.slice.call(arguments,1),s=r.pop();r.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),s.apply(this,arguments))}),i.attempt(function(){o.apply(t,r)})}.bind(t,a),t[s].options=n}}}),A=/* @__PURE__ */t((e,t)=>{t.exports=T()}),I=/* @__PURE__ */t((e,t)=>{var n=A(),o=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],i=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},r=(e,t)=>new Promise((r,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};const a=n.operation(t);a.attempt(async n=>{try{r(await e(n))}catch(u){if(!(u instanceof Error))return void s(/* @__PURE__ */new TypeError(`Non-error was thrown: "${u}". You should only throw errors.`));if(u instanceof i)a.stop(),s(u.originalError);else if(u instanceof TypeError&&(l=u.message,!o.includes(l)))a.stop(),s(u);else{((e,t,n)=>{const o=n.retries-(t-1);e.attemptNumber=t,e.retriesLeft=o})(u,n,t);try{await t.onFailedAttempt(u)}catch(u){return void s(u)}a.retry(u)||s(a.mainError())}}var l})});t.exports=r,t.exports.default=r,t.exports.AbortError=i}),C=/* @__PURE__ */e(I(),1);function S(e){if(!e)return"";try{return JSON.stringify(e)}catch(Rr){return String(e)}}var b=class extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}},O=class e extends b{constructor(t,n,o,i){super(e.makeMessage(t,n,o)),this.status=t,this.headers=i,this.error=n,this.statusCode=t,this.body=S(n),this.contentType=(null==i?void 0:i.get("content-type"))||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(e,t,n){var o;const i=t&&null!==(r=t)&&"object"==typeof r&&!Array.isArray(r)&&"string"==typeof t.message?t.message:void 0;var r;const s=S(t);return`${e?`${e} `:""}${null!==(o=null!=i?i:n)&&void 0!==o?o:s||"An error occurred"}`}static generate(t,n,o,i){return t&&i?new e(t,n,o,i):new w({message:o,cause:n instanceof Error?n:void 0})}},w=class extends O{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.cause=t}},R=class extends w{constructor(e={}){var t;super({message:null!==(t=e.message)&&void 0!==t?t:"WebSocket connection error."}),this.closeCode=e.closeCode,this.httpStatus=e.httpStatus,this.serverCode=e.serverCode}},P=class extends w{constructor(e={}){var t;super({message:null!==(t=e.message)&&void 0!==t?t:"WebRTC connection error."}),this.closeCode=e.closeCode,this.httpStatus=e.httpStatus,this.serverCode=e.serverCode}};function N(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(n[o[i]]=e[o[i]])}return n}function k(e){return this instanceof k?(this.v=e,this):new k(e)}function D(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o,i=n.apply(e,t||[]),r=[];return o=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),o[Symbol.asyncIterator]=function(){return this},o;function s(e,t){i[e]&&(o[e]=function(t){return new Promise(function(n,o){r.push([e,t,n,o])>1||a(e,t)})},t&&(o[e]=t(o[e])))}function a(e,t){try{(n=i[e](t)).value instanceof k?Promise.resolve(n.value.v).then(l,u):c(r[0][2],n)}catch(o){c(r[0][3],o)}var n}function l(e){a("next",e)}function u(e){a("throw",e)}function c(e,t){e(t),r.shift(),r.length&&a(r[0][0],r[0][1])}}function M(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],o=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&o>=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},o("next"),o("throw"),o("return"),t[Symbol.asyncIterator]=function(){return this},t);function o(n){t[n]=e[n]&&function(t){return new Promise(function(o,i){!function(e,t,n,o){Promise.resolve(o).then(function(t){e({value:t,done:n})},t)}(o,i,(t=e[n](t)).done,t.value)})}}}var x=!1;function G(){x||(x=!0)}var U=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};function L(e){return"number"==typeof e&&Number.isInteger(e)&&e>=100&&e<=599?e:void 0}function q(e){var t,n,o;const i=null!==(n=null!==(t=L(e.httpStatus))&&void 0!==t?t:L(e.statusCode))&&void 0!==n?n:L(e.status);if(void 0!==i)return i;if(F(e.response)){const t=e.response,n=null!==(o=L(t.statusCode))&&void 0!==o?o:L(t.status);if(void 0!==n)return n}if("string"==typeof e.message){const t=/^Unexpected server response: (\d{3})$/.exec(e.message.trim());if(t)return L(Number(t[1]))}}function H(e){if(!F(e))return;const t=q(e);if(void 0!==t)return t;const n=e.error;return F(n)?q(n):void 0}var j=class{constructor(){this.values=[],this.readers=[],this.ended=!1}push(e){if(this.ended||this.failure)return;const t=this.readers.shift();t?t.resolve({done:!1,value:e}):this.values.push(e)}end(e=!1){if(!this.failure&&(e&&(this.values.length=0),!this.ended)){this.ended=!0;for(const e of this.readers.splice(0))e.resolve({done:!0,value:void 0})}}fail(e){if(!this.ended&&!this.failure){this.failure=e;for(const t of this.readers.splice(0))t.reject(e)}}next(){const e=this.values.shift();return void 0!==e?Promise.resolve({done:!1,value:e}):this.failure?Promise.reject(this.failure):this.ended?Promise.resolve({done:!0,value:void 0}):new Promise((e,t)=>{this.readers.push({resolve:e,reject:t})})}};function F(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function X(e){return"interaction.completed"===e||"interaction.canceled"===e||"interaction.cancelled"===e||"reconnection_required"===e}function B(e,t,n){V(e,t),e[t]=n}function V(e,t){for(const n of Object.keys(e))n.toLowerCase()===t.toLowerCase()&&delete e[n]}function J(e,t,n){var o,i,r,s,a,l,u,c;if(!t)throw new U("A non-empty interaction ID is required to connect.");const d=null!==(s=null!==(i=null!==(o=null==n?void 0:n.timeout_ms)&&void 0!==o?o:null==n?void 0:n.timeout)&&void 0!==i?i:null===(r=e.getTimeout)||void 0===r?void 0:r.call(e))&&void 0!==s?s:3e4;if(!Number.isFinite(d)||d<=0)throw new RangeError("timeout_ms must be positive and finite.");let p;const m=null!==(u=null!==(a=null==n?void 0:n.headers)&&void 0!==a?a:null===(l=null==n?void 0:n.fetch_options)||void 0===l?void 0:l.headers)&&void 0!==u?u:null===(c=null==n?void 0:n.fetchOptions)||void 0===c?void 0:c.headers;if(m)if(p={},m instanceof Headers)for(const[h,f]of Array.from(m.entries()))p[h]=f;else if(Array.isArray(m))for(const[h,f]of m)p[h]=f;else for(const h of Object.keys(m))p[h]=m[h];return{timeout:d,extraHeaders:p}}async function $(e,t,n,o){var i,r,s;const a=Object.assign(Object.assign({},o),null===(i=e.getDefaultHeaders)||void 0===i?void 0:i.call(e)),l=null===(r=e.getApiKey)||void 0===r?void 0:r.call(e);if(l)B(a,"x-goog-api-key",l);else for(const[u,c]of function(e){const t=[];return e.forEach((e,n)=>t.push([n,e])),t}(await e.getAuthHeaders(t)))B(a,u,c);for(const u of[null===(s=e.getHeaders)||void 0===s?void 0:s.call(e),n])for(const[e,t]of Object.entries(null!=u?u:{}))B(a,e,t);return(null==l?void 0:l.startsWith("auth_tokens/"))&&(V(a,"authorization"),B(a,"x-goog-api-key",l)),a}var W=class{constructor(e){this.queue=new j,this.detached=!1,this.terminal=!1,this.receiving=!1,G(),this.id=e}attach(e){this.socket=e}closeSocket(){const e=this.socket;this.socket=void 0;try{null==e||e.close()}catch(Rr){}}finishTerminal(){this.markTerminal(),this.closeSocket()}async finishClientCancel(){const e=this.socket;this.markTerminal(),(null==e?void 0:e.flush)?(this.pendingClose=e.flush().finally(()=>this.closeSocket()),await this.pendingClose):this.closeSocket()}handleMessage(e){if(this.detached||this.terminal||this.connectionError)return;const t=this.decodeFrameEvents(e);if(t)for(const n of t){if(!F(n)||"string"!=typeof n.event_type)return void this.failProtocol("Live interaction server events must have an event_type.");const e=n.event_type;if(this.queue.push(n),X(e))return void this.finishTerminal()}}markTerminal(){this.terminal=!0,this.queue.end()}decodeFrameEvents(e){const t=function(e){return"string"==typeof e?e:e instanceof ArrayBuffer?(new TextDecoder).decode(new Uint8Array(e)):ArrayBuffer.isView(e)?(new TextDecoder).decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):null}(e);if(null===t)return this.failProtocol("Live interaction server frames must contain UTF-8 JSON text."),null;let n;try{n=JSON.parse(t)}catch(Rr){return this.failProtocol("Live interaction server frames must contain valid JSON."),null}return F(n)&&Array.isArray(n.events)?n.events:[n]}newConnectionError(e){return new R(e)}failProtocol(e){const t=this.newConnectionError({message:e});this.connectionError=t,this.queue.fail(t),this.detach()}handleTransportError(){this.detached||this.terminal||this.connectionError||(this.connectionError=this.newConnectionError({message:"The live interaction connection closed with code 1006.",closeCode:1006}),this.queue.fail(this.connectionError),this.closeSocket())}handleClose(e=1006){this.detached||this.terminal?this.queue.end():this.connectionError||(this.connectionError=this.newConnectionError({message:`The live interaction connection closed with code ${e}.`,closeCode:e}),this.queue.fail(this.connectionError)),this.closeSocket()}ensureWritable(){if(this.connectionError)throw this.connectionError;if(this.terminal)throw new Error("This live interaction is already terminal.");if(this.detached)throw new Error("This live interaction is detached.");if(!this.socket)throw new Error("This live interaction is not connected.");return this.socket}sendEvent(e){var t;const n=this.ensureWritable(),o=JSON.stringify(e);try{n.send(o)}catch(i){if(i instanceof RangeError||i instanceof U)throw i;throw null!==(t=this.connectionError)&&void 0!==t||(this.connectionError=this.newConnectionError({message:"The live interaction connection closed with code 1006.",closeCode:1006})),this.queue.fail(this.connectionError),this.detach(),this.connectionError}}sendInitial(e){this.sendEvent(e)}async send(e){if("string"==typeof e)return void this.sendEvent({event_type:"input",content:[{type:"text",text:e}]});if(Array.isArray(e)){if(!e.length)throw new U("Empty client event batch.");const t=e.map(e=>z(e));return this.sendEvent({events:t}),void(t.some(e=>"interaction.cancel"===e.event_type)&&await this.finishClientCancel())}const t=z(e);"interaction.cancel"!==t.event_type||this.connectionError||!this.terminal?(this.sendEvent(t),"interaction.cancel"===t.event_type&&await this.finishClientCancel()):await this.pendingClose}receive(){return D(this,arguments,function*(){for(;;){if(this.receiving)throw new U("Only one receive iterator may be active at a time.");let e;this.receiving=!0;try{e=yield k(this.queue.next())}finally{this.receiving=!1}if(e.done)return yield k(void 0);yield yield k(e.value)}})}async complete(){if(this.connectionError)throw this.connectionError;this.terminal||this.sendEvent({event_type:"interaction.complete"})}async cancel(){await this.send({event_type:"interaction.cancel"})}detach(){var e;if(this.detached)return;const t=!this.terminal&&!this.connectionError;if(this.detached=!0,this.queue.end(!0),t)try{null===(e=this.socket)||void 0===e||e.send(JSON.stringify({event_type:"interaction.disconnect"}))}catch(n){}this.closeSocket()}},Y=Symbol.asyncDispose;Y&&(W.prototype[Y]=async function(){this.detach()});var K=class extends W{constructor(e){super(e)}};function z(e){if(!F(e))throw new U("Live client events must be JSON objects.");return e}var Z="events";function Q(e){return!!e&&("open"===e.readyState||void 0===e.readyState)}var ee=class extends W{constructor(e,t){super(e),this.transport=t}newConnectionError(e){return new P(e)}},te=class{get peerConnection(){return this._peerConnection}get dataChannel(){return this._dataChannel}constructor(e={}){var t,n,o;this._remoteTracks=[],this._audioEnabled=!0,this._videoEnabled=!0,this._audioMuteExplicitlySet=!1,this._videoMuteExplicitlySet=!1,this.audioSenders=[],this.videoSenders=[],this.connectGeneration=0,G(),this._mediaStream=null!==(t=e.mediaStream)&&void 0!==t?t:null,this._videoElement=null!==(n=e.videoElement)&&void 0!==n?n:null,this._audioElement=null!==(o=e.audioElement)&&void 0!==o?o:null,this._audioEnabled=this.computeInitialEnabled("audio"),this._videoEnabled=this.computeInitialEnabled("video"),this.onPeerConnectionCallback=e.onPeerConnection,this.rtcConfiguration=e.rtcConfiguration,this.peerConnectionFactory=e.peerConnectionFactory}computeInitialEnabled(e){if(!this._mediaStream)return!1;const t="audio"===e&&"function"==typeof this._mediaStream.getAudioTracks?this._mediaStream.getAudioTracks():"video"===e&&"function"==typeof this._mediaStream.getVideoTracks?this._mediaStream.getVideoTracks():this._mediaStream.getTracks().filter(t=>t.kind===e);return t.length>0&&t.some(e=>!1!==e.enabled)}get localMediaStream(){return this._mediaStream}get remoteMediaStream(){return this._remoteMediaStream}isAudioEnabled(){return this._audioEnabled}isVideoEnabled(){return this._videoEnabled}setVideoElement(e){const t=e;this._videoElement&&this._videoElement!==t&&(this._videoElement.srcObject=null),this._videoElement=t,this.syncMediaElements()}getVideoElement(){return this._videoElement}setAudioElement(e){const t=e;this._audioElement&&this._audioElement!==t&&(this._audioElement.srcObject=null),this._audioElement=t,this.syncMediaElements()}getAudioElement(){return this._audioElement}createStreamFromTracks(e){const t=globalThis;if("function"==typeof t.MediaStream)return new t.MediaStream(e);const n=[...e];return{getTracks:()=>[...n],getAudioTracks:()=>n.filter(e=>"audio"===e.kind),getVideoTracks:()=>n.filter(e=>"video"===e.kind),addTrack:e=>{n.includes(e)||n.push(e)}}}ensureStreamWithTracks(e,t){if(e&&"function"==typeof e.addTrack){const n=e.getTracks();for(const o of t)n.includes(o)||e.addTrack(o);return e}return this.createStreamFromTracks(t)}playMediaElement(e){var t;try{const n=null===(t=e.play)||void 0===t?void 0:t.call(e);null!=n&&"function"==typeof n.catch&&n.catch(()=>{})}catch(n){}}syncMediaElements(){if(0!==this._remoteTracks.length)if(this._audioElement){const e=this._remoteTracks.filter(e=>"audio"===e.kind);if(e.length>0&&(this._remoteAudioStream=this.ensureStreamWithTracks(this._remoteAudioStream,e),this._audioElement.srcObject!==this._remoteAudioStream&&(this._audioElement.srcObject=this._remoteAudioStream,this.playMediaElement(this._audioElement))),this._videoElement){const e=this._remoteTracks.filter(e=>"video"===e.kind);e.length>0?(this._remoteVideoStream=this.ensureStreamWithTracks(this._remoteVideoStream,e),this._videoElement.srcObject!==this._remoteVideoStream&&(this._videoElement.srcObject=this._remoteVideoStream,this.playMediaElement(this._videoElement))):null!==this._videoElement.srcObject&&void 0!==this._videoElement.srcObject&&(this._videoElement.srcObject=null)}}else this._videoElement&&this._remoteMediaStream&&this._videoElement.srcObject!==this._remoteMediaStream&&(this._videoElement.srcObject=this._remoteMediaStream,this.playMediaElement(this._videoElement));else this._videoElement&&this._remoteMediaStream&&!this._audioElement&&this._videoElement.srcObject!==this._remoteMediaStream&&(this._videoElement.srcObject=this._remoteMediaStream,this.playMediaElement(this._videoElement))}setAudioEnabled(e){if(this._audioMuteExplicitlySet=!0,this._audioEnabled=Boolean(e),this._mediaStream){const e="function"==typeof this._mediaStream.getAudioTracks?this._mediaStream.getAudioTracks():this._mediaStream.getTracks().filter(e=>"audio"===e.kind);for(const t of e)t.enabled=this._audioEnabled}for(const t of this.audioSenders)t.track&&(t.track.enabled=this._audioEnabled);return this._audioEnabled}setVideoEnabled(e){if(this._videoMuteExplicitlySet=!0,this._videoEnabled=Boolean(e),this._mediaStream){const e="function"==typeof this._mediaStream.getVideoTracks?this._mediaStream.getVideoTracks():this._mediaStream.getTracks().filter(e=>"video"===e.kind);for(const t of e)t.enabled=this._videoEnabled}for(const t of this.videoSenders)t.track&&(t.track.enabled=this._videoEnabled);return this._videoEnabled}validateAndSendOnChannel(e,t,n){var o;if(!e)throw new U("WebRTC data channel is not connected.");if(!Q(e))throw new U("WebRTC data channel is not open.");const i="number"==typeof(null===(o=null==t?void 0:t.sctp)||void 0===o?void 0:o.maxMessageSize)&&t.sctp.maxMessageSize>0?t.sctp.maxMessageSize:65536,r=(new TextEncoder).encode(n).byteLength;if(r>i)throw new RangeError(`WebRTC data channel message (${r} bytes) exceeds SCTP maxMessageSize (${i} bytes).`);e.send(n)}async connect(e,t,n,o={}){var i,r,s,a,l,u,c;if(!t)throw new U("A non-empty interaction ID is required to connect.");const d=null!==(i=o.timeoutMs)&&void 0!==i?i:3e4;if(!Number.isFinite(d)||d<=0)throw new RangeError("timeout_ms must be positive and finite.");const p=null!==(r=this.peerConnectionFactory)&&void 0!==r?r:function(){const e=globalThis;if("function"==typeof e.RTCPeerConnection){const t=e.RTCPeerConnection;return e=>new t(e)}}();if(!p)throw new U("Live Interactions WebRTC support requires a platform RTCPeerConnection or peerConnectionFactory.");const m=null!==(a=null===(s=e.getFetch)||void 0===s?void 0:s.call(e))&&void 0!==a?a:"function"==typeof globalThis.fetch?(e,t)=>null==t?globalThis.fetch(e):globalThis.fetch(e,t):void 0;if(!m)throw new U("Live Interactions WebRTC support requires a platform fetch implementation.");this.close();const h=++this.connectGeneration,f=function(e,t,n){if(e.isVertexAI())throw new U("Live Interactions WebRTC support is currently Gemini API only.");const o=e.getBaseUrl();if(!o)throw new U("Base URL must be set.");const i=new URL(o),r=(null!=n?n:e.getApiVersion()).replace(/^\/+|\/+$/g,"");return i.pathname=`${i.pathname.replace(/\/+$/g,"")}/${r}/interactions/${encodeURIComponent(t)}:webrtc`.replace(/\/{2,}/g,"/"),i.hash="",i.toString()}(e,t,o.apiVersion),v=p(this.rtcConfiguration);this._peerConnection=v,this.audioSenders=[],this.videoSenders=[];const g=/* @__PURE__ */new Set;let _,y,E,T=!1,A=!1,I=!1,C=!1;const S=new Promise((e,t)=>{y=e,E=t});S.catch(()=>{});const b=()=>{const e=this._dataChannel;if(e&&g.has(e)&&Q(e))return e;for(const t of g)if(Q(t))return t};let O;const R=(e=1e3,t=!0,o="The WebRTC connection attempt was superseded or closed.")=>{if(!T){T=!0,null==_||_.abort(),null==O||O(),O=void 0,this.activeAttemptCleanup===R&&(this.activeAttemptCleanup=void 0);for(const e of[...g])try{e.close()}catch(i){}if(g.clear(),this.connectGeneration===h)this.resetTransportState();else try{v.close()}catch(r){}C||(C=!0,E(new P({message:o,closeCode:e}))),t&&!A&&(A=!0,n.onclose({code:e}))}};this.activeAttemptCleanup=R;const N=e=>{if(g.has(e))return;g.add(e),e.binaryType="arraybuffer",this._dataChannel&&"open"===this._dataChannel.readyState||(this._dataChannel=e);const t=()=>{T||this.connectGeneration!==h||(this._dataChannel=e,C||(I=!0,C=!0,n.onopen(),y()))};e.onopen=t,e.onmessage=e=>{T||this.connectGeneration!==h||n.onmessage(e)},e.onerror=e=>{T||this.connectGeneration!==h||(I||C?n.onerror(e):(C=!0,E(new P({message:"WebRTC events data channel failed to open.",closeCode:1006}))))},e.onclose=()=>{if(g.delete(e),T||this.connectGeneration!==h)return;const t=b();t?this._dataChannel=t:R(1006,!0,"WebRTC events data channel closed before opening.")},"open"===e.readyState&&t()};try{let t;try{t=await async function(e,t,n){const o=await $(e,t,n);return B(o,"content-type","application/json"),o}(e,f,o.extraHeaders)}catch(k){throw new P({message:"Live authentication setup failed.",httpStatus:H(k)})}if(T||this.connectGeneration!==h)throw new P({message:"The WebRTC connection attempt was superseded or closed.",closeCode:1006});try{null===(l=this.onPeerConnectionCallback)||void 0===l||l.call(this,v)}catch(D){}const i=e=>{var t,n;if(this.connectGeneration===h){if(e.track&&!this._remoteTracks.includes(e.track))this._remoteTracks.push(e.track);else if(null===(t=e.streams)||void 0===t?void 0:t[0])for(const t of e.streams[0].getTracks())this._remoteTracks.includes(t)||this._remoteTracks.push(t);this._remoteTracks.length>0?(this._remoteMediaStream=this.ensureStreamWithTracks(this._remoteMediaStream,this._remoteTracks),this.syncMediaElements()):(null===(n=e.streams)||void 0===n?void 0:n[0])&&(this._remoteMediaStream=e.streams[0],this.syncMediaElements())}},r=e=>{if(this.connectGeneration!==h)return;const t=null==e?void 0:e.channel;t&&(void 0!==t.label&&""!==t.label&&t.label!==Z||N(t))},s=()=>{if(T||this.connectGeneration!==h)return;const e="failed"===v.connectionState||"failed"===v.iceConnectionState?"failed":"closed"===v.connectionState||"closed"===v.iceConnectionState?"closed":void 0;if(!e)return;const t="failed"===e&&I;R(1006,!t,`WebRTC peer connection ${e} during setup.`),t&&!A&&(A=!0,n.onerror(/* @__PURE__ */new Error("WebRTC peer connection failed.")),n.onclose({code:1006}))};v.addEventListener("track",i),v.addEventListener("connectionstatechange",s),v.addEventListener("iceconnectionstatechange",s),v.addEventListener("datachannel",r),O=()=>{v.removeEventListener("track",i),v.removeEventListener("connectionstatechange",s),v.removeEventListener("iceconnectionstatechange",s),v.removeEventListener("datachannel",r)};let a=!1,p=!1;if(this._mediaStream){const e=this._mediaStream.getTracks();for(const t of e){"audio"===t.kind?(a=!0,this._audioMuteExplicitlySet&&(t.enabled=this._audioEnabled)):"video"===t.kind&&(p=!0,this._videoMuteExplicitlySet&&(t.enabled=this._videoEnabled));const e=v.addTrack(t,this._mediaStream);e&&"object"==typeof e&&("audio"===t.kind?this.audioSenders.push(e):"video"===t.kind&&this.videoSenders.push(e))}}if("function"==typeof v.addTransceiver){if(!a){const e=v.addTransceiver("audio",{direction:"recvonly"});(null==e?void 0:e.sender)&&this.audioSenders.push(e.sender)}if(!p){const e=v.addTransceiver("video",{direction:"recvonly"});(null==e?void 0:e.sender)&&this.videoSenders.push(e.sender)}}N(v.createDataChannel(Z));const g=Date.now()+d,y=await v.createOffer();await v.setLocalDescription(y);const E=null!==(c=null===(u=v.localDescription)||void 0===u?void 0:u.sdp)&&void 0!==c?c:y.sdp;if(!E)throw new P({message:"RTCPeerConnection failed to produce an SDP offer."});if(T||this.connectGeneration!==h)throw new P({message:"The WebRTC connection attempt was superseded or closed.",closeCode:1006});const w=Math.max(1,g-Date.now());_="function"==typeof AbortController?new AbortController:void 0;const U=setTimeout(()=>{null==_||_.abort()},w);let L,q;try{L=await m(f,{method:"POST",headers:t,body:JSON.stringify({offer_sdp:E}),signal:null==_?void 0:_.signal})}catch(M){throw new P({message:"WebRTC SDP signaling request failed."})}finally{clearTimeout(U)}if(T||this.connectGeneration!==h)throw new P({message:"The WebRTC connection attempt was superseded or closed.",closeCode:1006});if(!L.ok){let e,t;try{const n=await L.json();F(n)&&F(n.error)&&(e=function(e){const t="number"==typeof e||"string"==typeof e?String(e):"";return/^[a-zA-Z0-9_.-]{1,64}$/.test(t)?t:void 0}(n.error.code),"string"==typeof n.error.message&&(t=n.error.message.trim()))}catch(x){}throw new P({message:t?`WebRTC SDP signaling failed with HTTP status ${L.status}: ${t}`:`WebRTC SDP signaling failed with HTTP status ${L.status}.`,httpStatus:L.status,serverCode:e})}try{q=await L.json()}catch(G){throw new P({message:"WebRTC SDP signaling response must be valid JSON."})}const j=F(q)&&"string"==typeof q.answer_sdp?q.answer_sdp:void 0;if(!j)throw new P({message:"WebRTC SDP signaling response is missing answer_sdp."});if(await v.setRemoteDescription({type:"answer",sdp:j}),T||this.connectGeneration!==h)throw new P({message:"The WebRTC connection attempt was superseded or closed.",closeCode:1006});if(!I){const e=Math.max(1,g-Date.now());await new Promise((t,n)=>{const o=setTimeout(()=>{C||(C=!0,n(new P({message:"Timed out waiting for WebRTC events data channel to open.",closeCode:1006})))},e);S.then(()=>{clearTimeout(o),t()},e=>{clearTimeout(o),n(e)})})}return{connect(){},send:e=>{var t;if(this.connectGeneration!==h)throw new Error("WebRTC data channel is not connected.");const n=null!==(t=b())&&void 0!==t?t:this._dataChannel;this.validateAndSendOnChannel(n,v,e)},flush:()=>{var e;return async function(e){if(!Q(e))return;const t=Date.now()+500;for(;Number(e.bufferedAmount)>0&&Q(e)&&Date.now()<t;)await new Promise(e=>setTimeout(e,10));Q(e)&&await new Promise(e=>setTimeout(e,50))}(null!==(e=b())&&void 0!==e?e:this._dataChannel)},close:()=>{R(1e3,!0)}}}catch(k){if(R(1006,!1),k instanceof w)throw k;throw new Error(k instanceof Error?k.message:"WebRTC live setup failed.")}}resetTransportState(){const e=this._peerConnection;this._dataChannel=void 0,this._peerConnection=void 0,this._remoteMediaStream=void 0,this._remoteAudioStream=void 0,this._remoteVideoStream=void 0,this._remoteTracks=[],this.audioSenders=[],this.videoSenders=[],this._videoElement&&(this._videoElement.srcObject=null),this._audioElement&&(this._audioElement.srcObject=null);try{null==e||e.close()}catch(Rr){}}close(){if(this.activeAttemptCleanup){const e=this.activeAttemptCleanup;this.activeAttemptCleanup=void 0,e(1e3,!0)}else this.resetTransportState();this.connectGeneration++}};var ne,oe,ie,re,se,ae,le,ue,ce,de,pe,me,he,fe,ve,ge,_e,ye,Ee,Te,Ae,Ie,Ce,Se,be,Oe,we,Re,Pe,Ne,ke,De,Me,xe,Ge,Ue,Le,qe,He,je,Fe,Xe,Be,Ve,Je,$e,We,Ye,Ke,ze,Ze,Qe,et,tt,nt,ot,it,rt,st,at,lt,ut,ct,dt,pt,mt,ht,ft,vt,gt,_t,yt,Et,Tt,At,It,Ct,St,bt,Ot,wt,Rt=class{};function Pt(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{if(t&&Object.prototype.hasOwnProperty.call(t,n)){const e=t[n];return null!=e?String(e):""}if("api_version"===n)return e;throw new Error(`Key '${n}' not found in valueMap.`)})}function Nt(e,t,n){for(let r=0;r<t.length-1;r++){const o=t[r];if(o.endsWith("[]")){const i=o.slice(0,-2);if(!(i in e)){if(!Array.isArray(n))throw new Error(`Value must be a list given an array path ${o}`);e[i]=Array.from({length:n.length},()=>({}))}if(Array.isArray(e[i])){const o=e[i];if(Array.isArray(n))for(let e=0;e<o.length;e++)Nt(o[e],t.slice(r+1),n[e]);else for(const e of o)Nt(e,t.slice(r+1),n)}return}if(o.endsWith("[0]")){const i=o.slice(0,-3);return i in e||(e[i]=[{}]),void Nt(e[i][0],t.slice(r+1),n)}e[o]&&"object"==typeof e[o]||(e[o]={}),e=e[o]}const o=t[t.length-1],i=e[o];if(void 0!==i){if(!n||"object"==typeof n&&0===Object.keys(n).length)return;if(n===i)return;if("object"!=typeof i||"object"!=typeof n||null===i||null===n)throw new Error(`Cannot set value for an existing key. Key: ${o}`);Object.assign(i,n)}else"_self"!==o||"object"!=typeof n||null===n||Array.isArray(n)?e[o]=n:Object.assign(e,n)}function kt(e,t,n=void 0){try{if(1===t.length&&"_self"===t[0])return e;for(let o=0;o<t.length;o++){if("object"!=typeof e||null===e)return n;const i=t[o];if(i.endsWith("[]")){const r=i.slice(0,-2);if(r in e){const i=e[r];return Array.isArray(i)?i.map(e=>kt(e,t.slice(o+1),n)):n}return n}e=e[i]}return e}catch(o){if(o instanceof TypeError)return n;throw o}}function Dt(e,t,n,o,i){if(o>=t.length)return;if("object"!=typeof e||null===e)return;const r=t[o];if(r.endsWith("[]")){const s=r.slice(0,-2),a=e;if(s in a&&Array.isArray(a[s]))for(const e of a[s])Dt(e,t,n,o+1,i)}else if("*"===r){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const t=e,r=Object.keys(t).filter(e=>!e.startsWith("_")&&!i.has(e)),s={};for(const e of r)s[e]=t[e];for(const[e,i]of Object.entries(s)){const r=[];for(const t of n.slice(o))"*"===t?r.push(e):r.push(t);Nt(t,r,i)}for(const e of r)delete t[e]}}else r in e&&Dt(e[r],t,n,o+1,i)}function Mt(e){if("string"!=typeof e)throw new Error("fromImageBytes must be a string");return e}function xt(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["parent"]);null!=o&&Nt(t,["parent"],o);const i=kt(e,["documentName"]);return null!=i&&Nt(t,["documentName"],i),t}(s)),t}!function(e){e.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",e.STATIC="STATIC",e.AGENTIC="AGENTIC"}(ne||(ne={})),function(e){e.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",e.OUTCOME_OK="OUTCOME_OK",e.OUTCOME_FAILED="OUTCOME_FAILED",e.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"}(oe||(oe={})),function(e){e.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",e.PYTHON="PYTHON"}(ie||(ie={})),function(e){e.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",e.SILENT="SILENT",e.WHEN_IDLE="WHEN_IDLE",e.INTERRUPT="INTERRUPT"}(re||(re={})),function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.STRING="STRING",e.NUMBER="NUMBER",e.INTEGER="INTEGER",e.BOOLEAN="BOOLEAN",e.ARRAY="ARRAY",e.OBJECT="OBJECT",e.NULL="NULL"}(se||(se={})),function(e){e.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",e.NO_AUTH="NO_AUTH",e.API_KEY_AUTH="API_KEY_AUTH",e.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",e.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",e.OAUTH="OAUTH",e.OIDC_AUTH="OIDC_AUTH"}(ae||(ae={})),function(e){e.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",e.HTTP_IN_QUERY="HTTP_IN_QUERY",e.HTTP_IN_HEADER="HTTP_IN_HEADER",e.HTTP_IN_PATH="HTTP_IN_PATH",e.HTTP_IN_BODY="HTTP_IN_BODY",e.HTTP_IN_COOKIE="HTTP_IN_COOKIE"}(le||(le={})),function(e){e.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",e.SIMPLE_SEARCH="SIMPLE_SEARCH",e.ELASTIC_SEARCH="ELASTIC_SEARCH"}(ue||(ue={})),function(e){e.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",e.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",e.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",e.COMMUNICATION_TOOL="COMMUNICATION_TOOL",e.ACCOUNT_CREATION="ACCOUNT_CREATION",e.DATA_MODIFICATION="DATA_MODIFICATION",e.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",e.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"}(ce||(ce={})),function(e){e.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",e.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",e.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",e.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"}(de||(de={})),function(e){e.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",e.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",e.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",e.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"}(pe||(pe={})),function(e){e.UNSPECIFIED="UNSPECIFIED",e.BLOCKING="BLOCKING",e.NON_BLOCKING="NON_BLOCKING"}(me||(me={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"}(he||(he={})),function(e){e.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH",e.XHIGH="XHIGH"}(fe||(fe={})),function(e){e.DONT_ALLOW="DONT_ALLOW",e.ALLOW_ADULT="ALLOW_ADULT",e.ALLOW_ALL="ALLOW_ALL"}(ve||(ve={})),function(e){e.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",e.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",e.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"}(ge||(ge={})),function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",e.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",e.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",e.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",e.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",e.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"}(_e||(_e={})),function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"}(ye||(ye={})),function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE",e.OFF="OFF"}(Ee||(Ee={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE",e.VALIDATED="VALIDATED"}(Te||(Te={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.VERBATIM="VERBATIM",e.SMART="SMART"}(Ae||(Ae={})),function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.IMAGE_SAFETY="IMAGE_SAFETY",e.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",e.IMAGE_OTHER="IMAGE_OTHER",e.NO_IMAGE="NO_IMAGE",e.IMAGE_RECITATION="IMAGE_RECITATION",e.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",e.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",e.MISSING_THOUGHT_SIGNATURE="MISSING_THOUGHT_SIGNATURE",e.MALFORMED_RESPONSE="MALFORMED_RESPONSE",e.ESCALATION="ESCALATION",e.PUP_LIMITED_DISABLED="PUP_LIMITED_DISABLED",e.CONTINUATION="CONTINUATION",e.MODEL_ARMOR="MODEL_ARMOR"}(Ie||(Ie={})),function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(Ce||(Ce={})),function(e){e.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"}(Se||(Se={})),function(e){e.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",e.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",e.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",e.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",e.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"}(be||(be={})),function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.IMAGE_SAFETY="IMAGE_SAFETY",e.MODEL_ARMOR="MODEL_ARMOR",e.JAILBREAK="JAILBREAK"}(Oe||(Oe={})),function(e){e.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",e.ON_DEMAND="ON_DEMAND",e.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",e.ON_DEMAND_FLEX="ON_DEMAND_FLEX",e.ON_DEMAND_OFFPEAK="ON_DEMAND_OFFPEAK",e.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"}(we||(we={})),function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"}(Re||(Re={})),function(e){e.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",e.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",e.EXPERIMENTAL="EXPERIMENTAL",e.PREVIEW="PREVIEW",e.STABLE="STABLE",e.LEGACY="LEGACY",e.DEPRECATED="DEPRECATED",e.RETIRED="RETIRED"}(Pe||(Pe={})),function(e){e.UNSPECIFIED="unspecified",e.FLEX="flex",e.STANDARD="standard",e.PRIORITY="priority"}(Ne||(Ne={})),function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"}(ke||(ke={})),function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.AUDIO="AUDIO",e.VIDEO="VIDEO"}(De||(De={})),function(e){e.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",e.INLINE="INLINE",e.URI="URI"}(Me||(Me={})),function(e){e.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",e.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",e.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",e.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",e.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",e.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",e.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",e.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",e.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",e.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",e.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",e.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",e.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",e.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"}(xe||(xe={})),function(e){e.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",e.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",e.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",e.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",e.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"}(Ge||(Ge={})),function(e){e.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",e.TUNING_MODE_FULL="TUNING_MODE_FULL",e.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"}(Ue||(Ue={})),function(e){e.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",e.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",e.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",e.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",e.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",e.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",e.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"}(Le||(Le={})),function(e){e.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",e.IDENTITY="IDENTITY",e.REGEX_EXTRACT="REGEX_EXTRACT"}(qe||(qe={})),function(e){e.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",e.REGEX_CONTAINS="REGEX_CONTAINS",e.PARTIAL_MATCH="PARTIAL_MATCH",e.EXACT_MATCH="EXACT_MATCH"}(He||(He={})),function(e){e.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(je||(je={})),function(e){e.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",e.JOB_STATE_QUEUED="JOB_STATE_QUEUED",e.JOB_STATE_PENDING="JOB_STATE_PENDING",e.JOB_STATE_RUNNING="JOB_STATE_RUNNING",e.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",e.JOB_STATE_FAILED="JOB_STATE_FAILED",e.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",e.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",e.JOB_STATE_PAUSED="JOB_STATE_PAUSED",e.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",e.JOB_STATE_UPDATING="JOB_STATE_UPDATING",e.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"}(Fe||(Fe={})),function(e){e.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",e.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",e.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",e.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",e.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",e.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"}(Xe||(Xe={})),function(e){e.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",e.AVERAGE="AVERAGE",e.MODE="MODE",e.STANDARD_DEVIATION="STANDARD_DEVIATION",e.VARIANCE="VARIANCE",e.MINIMUM="MINIMUM",e.MAXIMUM="MAXIMUM",e.MEDIAN="MEDIAN",e.PERCENTILE_P90="PERCENTILE_P90",e.PERCENTILE_P95="PERCENTILE_P95",e.PERCENTILE_P99="PERCENTILE_P99"}(Be||(Be={})),function(e){e.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",e.BASELINE="BASELINE",e.CANDIDATE="CANDIDATE",e.TIE="TIE"}(Ve||(Ve={})),function(e){e.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",e.LANDSCAPE="LANDSCAPE",e.PORTRAIT="PORTRAIT"}(Je||(Je={})),function(e){e.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",e.REGULAR="REGULAR",e.FAST="FAST"}($e||($e={})),function(e){e.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",e.TUNING_TASK_I2V="TUNING_TASK_I2V",e.TUNING_TASK_T2V="TUNING_TASK_T2V",e.TUNING_TASK_R2V="TUNING_TASK_R2V"}(We||(We={})),function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.STATE_PENDING="STATE_PENDING",e.STATE_ACTIVE="STATE_ACTIVE",e.STATE_FAILED="STATE_FAILED"}(Ye||(Ye={})),function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",e.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"}(Ke||(Ke={})),function(e){e.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",e.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",e.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",e.URL_CONTEXT="URL_CONTEXT",e.GOOGLE_MAPS="GOOGLE_MAPS",e.FILE_SEARCH="FILE_SEARCH",e.MEDIA_PROCESSING="MEDIA_PROCESSING"}(ze||(ze={})),function(e){e.CONTENT_LAYER_UNSPECIFIED="CONTENT_LAYER_UNSPECIFIED",e.PAGE_IMAGE="PAGE_IMAGE",e.PAGE_TEXT="PAGE_TEXT"}(Ze||(Ze={})),function(e){e.CONTENT_LAYER_UNSPECIFIED="CONTENT_LAYER_UNSPECIFIED",e.DATA="DATA",e.FORMULAS="FORMULAS",e.VISUAL="VISUAL"}(Qe||(Qe={})),function(e){e.COLLECTION="COLLECTION"}(et||(et={})),function(e){e.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",e.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",e.BALANCED="BALANCED",e.PRIORITIZE_COST="PRIORITIZE_COST"}(tt||(tt={})),function(e){e.PREDICT="PREDICT",e.EMBED_CONTENT="EMBED_CONTENT",e.BATCH_EMBED_CONTENTS="BATCH_EMBED_CONTENTS"}(nt||(nt={})),function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"}(ot||(ot={})),function(e){e.auto="auto",e.en="en",e.ja="ja",e.ko="ko",e.hi="hi",e.zh="zh",e.pt="pt",e.es="es"}(it||(it={})),function(e){e.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",e.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",e.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",e.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",e.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"}(rt||(rt={})),function(e){e.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",e.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",e.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",e.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"}(st||(st={})),function(e){e.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",e.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",e.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",e.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"}(at||(at={})),function(e){e.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",e.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",e.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",e.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",e.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",e.EDIT_MODE_STYLE="EDIT_MODE_STYLE",e.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",e.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"}(lt||(lt={})),function(e){e.FOREGROUND="FOREGROUND",e.BACKGROUND="BACKGROUND",e.PROMPT="PROMPT",e.SEMANTIC="SEMANTIC",e.INTERACTIVE="INTERACTIVE"}(ut||(ut={})),function(e){e.ASSET="ASSET",e.STYLE="STYLE"}(ct||(ct={})),function(e){e.INSERT="INSERT",e.REMOVE="REMOVE",e.REMOVE_STATIC="REMOVE_STATIC",e.OUTPAINT="OUTPAINT"}(dt||(dt={})),function(e){e.OPTIMIZED="OPTIMIZED",e.LOSSLESS="LOSSLESS"}(pt||(pt={})),function(e){e.CROP="CROP",e.PAD="PAD"}(mt||(mt={})),function(e){e.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",e.PREFERENCE_TUNING="PREFERENCE_TUNING",e.DISTILLATION="DISTILLATION",e.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"}(ht||(ht={})),function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.PROCESSING="PROCESSING",e.ACTIVE="ACTIVE",e.FAILED="FAILED"}(ft||(ft={})),function(e){e.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",e.UPLOADED="UPLOADED",e.GENERATED="GENERATED",e.REGISTERED="REGISTERED"}(vt||(vt={})),function(e){e.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.RESPONSE_REJECTED="RESPONSE_REJECTED",e.NEED_MORE_INPUT="NEED_MORE_INPUT",e.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",e.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",e.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",e.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",e.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",e.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",e.INPUT_OTHER="INPUT_OTHER",e.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",e.BLOCKLIST="BLOCKLIST",e.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",e.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",e.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",e.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",e.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",e.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",e.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",e.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",e.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",e.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",e.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",e.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",e.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",e.GENERATED_OTHER="GENERATED_OTHER",e.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"}(gt||(gt={})),function(e){e.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",e.IN_PROGRESS="IN_PROGRESS",e.REQUIRES_ACTION="REQUIRES_ACTION",e.IDLE="IDLE"}(_t||(_t={})),function(e){e.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",e.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",e.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"}(yt||(yt={})),function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.ACTIVITY_START="ACTIVITY_START",e.ACTIVITY_END="ACTIVITY_END"}(Et||(Et={})),function(e){e.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",e.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",e.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"}(Tt||(Tt={})),function(e){e.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",e.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",e.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"}(At||(At={})),function(e){e.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",e.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",e.NO_INTERRUPTION="NO_INTERRUPTION"}(It||(It={})),function(e){e.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",e.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",e.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",e.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"}(Ct||(Ct={})),function(e){e.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",e.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",e.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",e.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",e.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",e.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",e.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",e.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",e.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",e.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",e.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",e.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",e.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"}(St||(St={})),function(e){e.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",e.QUALITY="QUALITY",e.DIVERSITY="DIVERSITY",e.VOCALIZATION="VOCALIZATION"}(bt||(bt={})),function(e){e.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",e.PLAY="PLAY",e.PAUSE="PAUSE",e.STOP="STOP",e.RESET_CONTEXT="RESET_CONTEXT"}(Ot||(Ot={})),function(e){e.CONTENT_LAYER_UNSPECIFIED="CONTENT_LAYER_UNSPECIFIED",e.FRAMES="FRAMES",e.AUDIO="AUDIO",e.TRANSCRIPT="TRANSCRIPT"}(wt||(wt={}));var Gt,Ut=class{constructor(e){const t={};for(const n of e.headers.entries())t[n[0]]=n[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}},Lt=class{},qt=class{},Ht=class{get text(){var e,t,n,o,i,r,s,a;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;let l="",u=!1;const c=[];for(const d of null!==(a=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)&&void 0!==a?a:[]){for(const[e,t]of Object.entries(d))"text"===e||"thought"===e||"thoughtSignature"===e||null===t&&void 0===t||c.push(e);if("string"==typeof d.text){if("boolean"==typeof d.thought&&d.thought)continue;u=!0,l+=d.text}}return c.length,u?l:void 0}get data(){var e,t,n,o,i,r,s,a;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;let l="";const u=[];for(const c of null!==(a=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)&&void 0!==a?a:[]){for(const[e,t]of Object.entries(c))"inlineData"===e||null===t&&void 0===t||u.push(e);c.inlineData&&"string"==typeof c.inlineData.data&&(l+=atob(c.inlineData.data))}return u.length,l.length>0?btoa(l):void 0}get functionCalls(){var e,t,n,o,i,r,s,a;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;const l=null===(a=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)||void 0===a?void 0:a.filter(e=>e.functionCall).map(e=>e.functionCall).filter(e=>void 0!==e);return 0!==(null==l?void 0:l.length)?l:void 0}get executableCode(){var e,t,n,o,i,r,s,a,l;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;const u=null===(a=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)||void 0===a?void 0:a.filter(e=>e.executableCode).map(e=>e.executableCode).filter(e=>void 0!==e);return 0!==(null==u?void 0:u.length)?null===(l=null==u?void 0:u[0])||void 0===l?void 0:l.code:void 0}get codeExecutionResult(){var e,t,n,o,i,r,s,a,l;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;const u=null===(a=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)||void 0===a?void 0:a.filter(e=>e.codeExecutionResult).map(e=>e.codeExecutionResult).filter(e=>void 0!==e);return 0!==(null==u?void 0:u.length)?null===(l=null==u?void 0:u[0])||void 0===l?void 0:l.output:void 0}get initialPromptTokenCount(){var e;if(this.usageMetadata)return null!==(e=this.usageMetadata._initialPromptTokenCount)&&void 0!==e?e:this.usageMetadata.promptTokenCount}},jt=class{},Ft=class{},Xt=class{},Bt=class{},Vt=class{},Jt=class{},$t=class{},Wt=class{},Yt=class{},Kt=class{},zt=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const o=new e;let i;const r=t;return i=n?function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["videos"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["_self"]);return null!=n&&Nt(t,["video"],function(e){const t={},n=kt(e,["gcsUri"]);null!=n&&Nt(t,["uri"],n);const o=kt(e,["bytesBase64Encoded"]);null!=o&&Nt(t,["videoBytes"],Mt(o));const i=kt(e,["mimeType"]);return null!=i&&Nt(t,["mimeType"],i),t}(n)),t}(e))),Nt(t,["generatedVideos"],e)}const o=kt(e,["raiMediaFilteredCount"]);null!=o&&Nt(t,["raiMediaFilteredCount"],o);const i=kt(e,["raiMediaFilteredReasons"]);return null!=i&&Nt(t,["raiMediaFilteredReasons"],i),t}(s)),t}(r):function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response","generateVideoResponse"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["generatedSamples"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["video"]);return null!=n&&Nt(t,["video"],function(e){const t={},n=kt(e,["uri"]);null!=n&&Nt(t,["uri"],n);const o=kt(e,["encodedVideo"]);null!=o&&Nt(t,["videoBytes"],Mt(o));const i=kt(e,["encoding"]);return null!=i&&Nt(t,["mimeType"],i),t}(n)),t}(e))),Nt(t,["generatedVideos"],e)}const o=kt(e,["raiMediaFilteredCount"]);null!=o&&Nt(t,["raiMediaFilteredCount"],o);const i=kt(e,["raiMediaFilteredReasons"]);return null!=i&&Nt(t,["raiMediaFilteredReasons"],i),t}(s)),t}(r),Object.assign(o,i),o}},Zt=class{},Qt=class{},en=class{},tn=class{},nn=class{},on=class{},rn=class{},sn=class{},an=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const o=new e,i=function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["parent"]);null!=o&&Nt(t,["parent"],o);const i=kt(e,["documentName"]);return null!=i&&Nt(t,["documentName"],i),t}(s)),t}(t);return Object.assign(o,i),o}},ln=class{},un=class{},cn=class{},dn=class{},pn=class{},mn=class{get text(){var e,t,n;let o="",i=!1;const r=[];for(const s of null!==(n=null===(t=null===(e=this.serverContent)||void 0===e?void 0:e.modelTurn)||void 0===t?void 0:t.parts)&&void 0!==n?n:[]){for(const[e,t]of Object.entries(s))"text"!==e&&"thought"!==e&&null!==t&&r.push(e);if("string"==typeof s.text){if("boolean"==typeof s.thought&&s.thought)continue;i=!0,o+=s.text}}return r.length,i?o:void 0}get data(){var e,t,n;let o="";const i=[];for(const r of null!==(n=null===(t=null===(e=this.serverContent)||void 0===e?void 0:e.modelTurn)||void 0===t?void 0:t.parts)&&void 0!==n?n:[]){for(const[e,t]of Object.entries(r))"inlineData"!==e&&null!==t&&i.push(e);r.inlineData&&"string"==typeof r.inlineData.data&&(o+=atob(r.inlineData.data))}return i.length,o.length>0?btoa(o):void 0}},hn=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},fn=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const o=new e,i=xt(t);return Object.assign(o,i),o}};function vn(e,t){if(!t||"string"!=typeof t)throw new Error("model is required and must be a string");if(t.includes("..")||t.includes("?")||t.includes("&"))throw new Error("invalid model parameter");if(e.isVertexAI()){if(t.startsWith("publishers/")||t.startsWith("projects/")||t.startsWith("models/"))return t;if(t.indexOf("/")>=0){const e=t.split("/",2);return`publishers/${e[0]}/models/${e[1]}`}return`publishers/google/models/${t}`}return t.startsWith("models/")||t.startsWith("tunedModels/")?t:`models/${t}`}function gn(e,t){const n=vn(e,t);return n?n.startsWith("publishers/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/${n}`:n.startsWith("models/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${n}`:n:""}function _n(e){return Array.isArray(e)?e.map(e=>yn(e)):[yn(e)]}function yn(e){if("object"==typeof e&&null!==e)return e;throw new Error("Could not parse input as Blob. Unsupported blob type: "+typeof e)}function En(e){const t=yn(e);if(t.mimeType&&t.mimeType.startsWith("image/"))return t;throw new Error(`Unsupported mime type: ${t.mimeType}`)}function Tn(e){const t=yn(e);if(t.mimeType&&t.mimeType.startsWith("audio/"))return t;throw new Error(`Unsupported mime type: ${t.mimeType}`)}function An(e){if(null==e)throw new Error("PartUnion is required");if("object"==typeof e)return e;if("string"==typeof e)return{text:e};throw new Error("Unsupported part type: "+typeof e)}function In(e){if(null==e||Array.isArray(e)&&0===e.length)throw new Error("PartListUnion is required");return Array.isArray(e)?e.map(e=>An(e)):[An(e)]}function Cn(e){return null!=e&&"object"==typeof e&&"parts"in e&&Array.isArray(e.parts)}function Sn(e){return null!=e&&"object"==typeof e&&"functionCall"in e}function bn(e){return null!=e&&"object"==typeof e&&"functionResponse"in e}function On(e){if(null==e)throw new Error("ContentUnion is required");return Cn(e)?e:{role:"user",parts:In(e)}}function wn(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap(e=>{const t=On(e);return t.parts&&t.parts.length>0&&void 0!==t.parts[0].text?[t.parts[0].text]:[]});if(e.isVertexAI()){const e=On(t);return e.parts&&e.parts.length>0&&void 0!==e.parts[0].text?[e.parts[0].text]:[]}return Array.isArray(t)?t.map(e=>On(e)):[On(t)]}function Rn(e){if(null==e||Array.isArray(e)&&0===e.length)throw new Error("contents are required");if(!Array.isArray(e)){if(Sn(e)||bn(e))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[On(e)]}const t=[],n=[],o=Cn(e[0]);for(const i of e){const e=Cn(i);if(e!=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(e)t.push(i);else{if(Sn(i)||bn(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||t.push({role:"user",parts:In(n)}),t}function Pn(e){const t={},n=["items"],o=["anyOf"],i=["properties"];if(e.type&&e.anyOf)throw new Error("type and anyOf cannot be both populated.");const r=e.anyOf;null!=r&&2==r.length&&("null"===r[0].type?(t.nullable=!0,e=r[1]):"null"===r[1].type&&(t.nullable=!0,e=r[0])),e.type instanceof Array&&function(e,t){e.includes("null")&&(t.nullable=!0);const n=e.filter(e=>"null"!==e);if(1===n.length)t.type=Object.values(se).includes(n[0].toUpperCase())?n[0].toUpperCase():se.TYPE_UNSPECIFIED;else{t.anyOf=[];for(const e of n)t.anyOf.push({type:Object.values(se).includes(e.toUpperCase())?e.toUpperCase():se.TYPE_UNSPECIFIED})}}(e.type,t);for(const[s,a]of Object.entries(e))if(null!=a)if("type"==s){if("null"===a)throw new Error("type: null can not be the only possible type for the field.");if(a instanceof Array)continue;t.type=Object.values(se).includes(a.toUpperCase())?a.toUpperCase():se.TYPE_UNSPECIFIED}else if(n.includes(s))t[s]=Pn(a);else if(o.includes(s)){const e=[];for(const n of a)"null"!=n.type?e.push(Pn(n)):t.nullable=!0;t[s]=e}else if(i.includes(s)){const e={};for(const[t,n]of Object.entries(a))e[t]=Pn(n);t[s]=e}else{if("additionalProperties"===s)continue;t[s]=a}return t}function Nn(e){return Pn(e)}function kn(e){if("object"==typeof e)return e;if("string"==typeof e)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};throw new Error("Unsupported speechConfig type: "+typeof e)}function Dn(e){if("multiSpeakerVoiceConfig"in e)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return e}function Mn(e){if(e.functionDeclarations)for(const t of e.functionDeclarations)t.parameters&&(Object.keys(t.parameters).includes("$schema")?t.parametersJsonSchema||(t.parametersJsonSchema=t.parameters,delete t.parameters):t.parameters=Pn(t.parameters)),t.response&&(Object.keys(t.response).includes("$schema")?t.responseJsonSchema||(t.responseJsonSchema=t.response,delete t.response):t.response=Pn(t.response));return e}function xn(e){if(null==e)throw new Error("tools is required");if(!Array.isArray(e))throw new Error("tools is required and must be an array of Tools");const t=[];for(const n of e)t.push(n);return t}function Gn(e,t){if("string"!=typeof t)throw new Error("name must be a string");return function(e,t,n,o=1){const i=!t.startsWith(`${n}/`)&&t.split("/").length===o;return e.isVertexAI()?t.startsWith("projects/")?t:t.startsWith("locations/")?`projects/${e.getProject()}/${t}`:t.startsWith(`${n}/`)?`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`:i?`projects/${e.getProject()}/locations/${e.getLocation()}/${n}/${t}`:t:i?`${n}/${t}`:t}(e,t,"cachedContents")}function Un(e){switch(e){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 e}}function Ln(e){return Mt(e)}function qn(e){var t;let n;var o;if(null!=(o=e)&&"object"==typeof o&&"name"in o&&(n=e.name),!(function(e){return null!=e&&"object"==typeof e&&"uri"in e}(e)&&(n=e.uri,void 0===n)||function(e){return null!=e&&"object"==typeof e&&"video"in e}(e)&&(n=null===(t=e.video)||void 0===t?void 0:t.uri,void 0===n))){if("string"==typeof e&&(n=e),void 0===n)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){const e=n.split("files/")[1].match(/[a-z0-9]+/);if(null===e)throw new Error(`Could not extract file name from URI ${n}`);n=e[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function Hn(e,t){let n;return n=e.isVertexAI()?t?"publishers/google/models":"models":t?"models":"tunedModels",n}function jn(e){for(const t of["models","tunedModels","publisherModels"])if(Fn(e,t))return e[t];return[]}function Fn(e,t){return null!==e&&"object"==typeof e&&t in e}function Xn(e,t={}){const n=e,o={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(o.responseJsonSchema=n.outputSchema),t.behavior&&(o.behavior=t.behavior),{functionDeclarations:[o]}}function Bn(e,t){let n;if("string"==typeof t)if(e.isVertexAI())if(t.startsWith("gs://"))n={format:"jsonl",gcsUri:[t]};else if(t.startsWith("bq://"))n={format:"bigquery",bigqueryUri:t};else{if(!/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(t))throw new Error(`Unsupported string source for Vertex AI: ${t}`);n={format:"vertex-dataset",vertexDatasetName:t}}else{if(!t.startsWith("files/"))throw new Error(`Unsupported string source for Gemini API: ${t}`);n={fileName:t}}else if(Array.isArray(t)){if(e.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:t}}else n=t;const o=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,i=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(e.isVertexAI()){if(i>0||1!==o)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(o>0||1!==i)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function Vn(e){if("object"!=typeof e||null===e)return{};const t=e,n=t.inlinedResponses;if("object"!=typeof n||null===n)return e;const o=n.inlinedResponses;if(!Array.isArray(o)||0===o.length)return e;let i=!1;for(const r of o){if("object"!=typeof r||null===r)continue;const e=r.response;if("object"==typeof e&&null!==e&&void 0!==e.embedding){i=!0;break}}return i&&(t.inlinedEmbedContentResponses=t.inlinedResponses,delete t.inlinedResponses),e}function Jn(e,t){const n=t;if(!e.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 $n(e){return"BATCH_STATE_UNSPECIFIED"===e?"JOB_STATE_UNSPECIFIED":"BATCH_STATE_PENDING"===e?"JOB_STATE_PENDING":"BATCH_STATE_RUNNING"===e?"JOB_STATE_RUNNING":"BATCH_STATE_SUCCEEDED"===e?"JOB_STATE_SUCCEEDED":"BATCH_STATE_FAILED"===e?"JOB_STATE_FAILED":"BATCH_STATE_CANCELLED"===e?"JOB_STATE_CANCELLED":"BATCH_STATE_EXPIRED"===e?"JOB_STATE_EXPIRED":e}function Wn(e){var t;return(null!==(t=e.split("/").pop())&&void 0!==t?t:e).includes("maas")}function Yn(e){var t;const n=null!==(t=e.split("/").pop())&&void 0!==t?t:e;return n.includes("gemini")&&!n.startsWith("gemini-embedding-001")&&!n.startsWith("gemini-embedding-exp")}function Kn(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata","displayName"]);null!=o&&Nt(t,["displayName"],o);const i=kt(e,["metadata","state"]);null!=i&&Nt(t,["state"],$n(i));const r=kt(e,["metadata","createTime"]);null!=r&&Nt(t,["createTime"],r);const s=kt(e,["metadata","endTime"]);null!=s&&Nt(t,["endTime"],s);const a=kt(e,["metadata","updateTime"]);null!=a&&Nt(t,["updateTime"],a);const l=kt(e,["metadata","model"]);null!=l&&Nt(t,["model"],l);const u=kt(e,["metadata","output"]);return null!=u&&Nt(t,["dest"],function(e){const t={},n=kt(e,["responsesFile"]);null!=n&&Nt(t,["fileName"],n);const o=kt(e,["inlinedResponses","inlinedResponses"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["response"]);null!=n&&Nt(t,["response"],function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["candidates"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["content"]);null!=n&&Nt(t,["content"],n);const o=kt(e,["citationMetadata"]);null!=o&&Nt(t,["citationMetadata"],function(e){const t={},n=kt(e,["citationSources"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["citations"],e)}return t}(o));const i=kt(e,["tokenCount"]);null!=i&&Nt(t,["tokenCount"],i);const r=kt(e,["finishReason"]);null!=r&&Nt(t,["finishReason"],r);const s=kt(e,["groundingMetadata"]);null!=s&&Nt(t,["groundingMetadata"],s);const a=kt(e,["avgLogprobs"]);null!=a&&Nt(t,["avgLogprobs"],a);const l=kt(e,["index"]);null!=l&&Nt(t,["index"],l);const u=kt(e,["logprobsResult"]);null!=u&&Nt(t,["logprobsResult"],u);const c=kt(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["safetyRatings"],e)}const d=kt(e,["urlContextMetadata"]);null!=d&&Nt(t,["urlContextMetadata"],d);const p=kt(e,["continuationToken"]);return null!=p&&Nt(t,["continuationToken"],p),t}(e))),Nt(t,["candidates"],e)}const i=kt(e,["modelVersion"]);null!=i&&Nt(t,["modelVersion"],i);const r=kt(e,["promptFeedback"]);null!=r&&Nt(t,["promptFeedback"],r);const s=kt(e,["responseId"]);null!=s&&Nt(t,["responseId"],s);const a=kt(e,["usageMetadata"]);null!=a&&Nt(t,["usageMetadata"],a);const l=kt(e,["modelStatus"]);return null!=l&&Nt(t,["modelStatus"],l),t}(n));const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["error"]);null!=i&&Nt(t,["error"],i);const r=t.response;if(null!=r){const e=new Ht;Object.assign(e,r),t.response=e}return t}(e))),Nt(t,["inlinedResponses"],e)}const i=kt(e,["inlinedEmbedContentResponses","inlinedResponses"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["inlinedEmbedContentResponses"],e)}return t}(Vn(u))),t}function zn(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["displayName"]);null!=o&&Nt(t,["displayName"],o);const i=kt(e,["state"]);null!=i&&Nt(t,["state"],$n(i));const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["createTime"]);null!=s&&Nt(t,["createTime"],s);const a=kt(e,["startTime"]);null!=a&&Nt(t,["startTime"],a);const l=kt(e,["endTime"]);null!=l&&Nt(t,["endTime"],l);const u=kt(e,["updateTime"]);null!=u&&Nt(t,["updateTime"],u);const c=kt(e,["model"]);null!=c&&Nt(t,["model"],c);const d=kt(e,["inputConfig"]);null!=d&&Nt(t,["src"],function(e){const t={},n=kt(e,["instancesFormat"]);null!=n&&Nt(t,["format"],n);const o=kt(e,["gcsSource","uris"]);null!=o&&Nt(t,["gcsUri"],o);const i=kt(e,["bigquerySource","inputUri"]);null!=i&&Nt(t,["bigqueryUri"],i);const r=kt(e,["vertexMultimodalDatasetSource","datasetName"]);return null!=r&&Nt(t,["vertexDatasetName"],r),t}(d));const p=kt(e,["outputConfig"]);null!=p&&Nt(t,["dest"],function(e){const t={},n=kt(e,["predictionsFormat"]);null!=n&&Nt(t,["format"],n);const o=kt(e,["gcsDestination","outputUriPrefix"]);null!=o&&Nt(t,["gcsUri"],o);const i=kt(e,["bigqueryDestination","outputUri"]);null!=i&&Nt(t,["bigqueryUri"],i);const r=kt(e,["vertexMultimodalDatasetDestination"]);return null!=r&&Nt(t,["vertexDataset"],function(e){const t={},n=kt(e,["bigqueryDestination","outputUri"]);null!=n&&Nt(t,["bigqueryDestination"],n);const o=kt(e,["displayName"]);return null!=o&&Nt(t,["displayName"],o),t}(r)),t}(Vn(p)));const m=kt(e,["outputInfo"]);null!=m&&Nt(t,["outputInfo"],m);const h=kt(e,["completionStats"]);return null!=h&&Nt(t,["completionStats"],h),t}function Zn(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);null!=n&&Nt(t,["mediaResolution"],n);const o=kt(e,["toolCall"]);null!=o&&Nt(t,["toolCall"],o);const i=kt(e,["toolResponse"]);null!=i&&Nt(t,["toolResponse"],i);const r=kt(e,["audioTranscription"]);null!=r&&Nt(t,["audioTranscription"],r);const s=kt(e,["codeExecutionResult"]);null!=s&&Nt(t,["codeExecutionResult"],s);const a=kt(e,["executableCode"]);null!=a&&Nt(t,["executableCode"],a);const l=kt(e,["fileData"]);null!=l&&Nt(t,["fileData"],l);const u=kt(e,["functionCall"]);null!=u&&Nt(t,["functionCall"],function(e){const t={},n=kt(e,["args"]);null!=n&&Nt(t,["args"],n);const o=kt(e,["id"]);null!=o&&Nt(t,["id"],o);const i=kt(e,["name"]);if(null!=i&&Nt(t,["name"],i),void 0!==kt(e,["partialArgs"]))throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(u));const c=kt(e,["functionResponse"]);null!=c&&Nt(t,["functionResponse"],c);const d=kt(e,["inlineData"]);null!=d&&Nt(t,["inlineData"],d);const p=kt(e,["text"]);null!=p&&Nt(t,["text"],p);const m=kt(e,["thought"]);null!=m&&Nt(t,["thought"],m);const h=kt(e,["thoughtSignature"]);null!=h&&Nt(t,["thoughtSignature"],h);const f=kt(e,["videoMetadata"]);null!=f&&Nt(t,["videoMetadata"],f);const v=kt(e,["partMetadata"]);null!=v&&Nt(t,["partMetadata"],v);const g=kt(e,["mediaProcessing"]);null!=g&&Nt(t,["mediaProcessing"],g);const _=kt(e,["speechMetadata"]);null!=_&&Nt(t,["speechMetadata"],_);const y=kt(e,["documentMetadata"]);null!=y&&Nt(t,["documentMetadata"],y);const E=kt(e,["spreadsheetMetadata"]);null!=E&&Nt(t,["spreadsheetMetadata"],E);const T=kt(e,["audioMetadata"]);return null!=T&&Nt(t,["audioMetadata"],T),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}function Qn(e,t){const n=kt(e,["displayName"]);void 0!==t&&null!=n&&Nt(t,["displayName"],n);const o=kt(e,["dest"]);if(void 0!==t&&null!=o&&Nt(t,["outputConfig"],function(e){const t={},n=kt(e,["format"]);null!=n&&Nt(t,["predictionsFormat"],n);const o=kt(e,["gcsUri"]);null!=o&&Nt(t,["gcsDestination","outputUriPrefix"],o);const i=kt(e,["bigqueryUri"]);null!=i&&Nt(t,["bigqueryDestination","outputUri"],i);const r=kt(e,["vertexDataset"]);if(null!=r&&Nt(t,["vertexMultimodalDatasetDestination"],function(e){const t={},n=kt(e,["bigqueryDestination"]);null!=n&&Nt(t,["bigqueryDestination","outputUri"],n);const o=kt(e,["displayName"]);return null!=o&&Nt(t,["displayName"],o),t}(r)),void 0!==kt(e,["fileName"]))throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["inlinedResponses"]))throw new Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["inlinedEmbedContentResponses"]))throw new Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(function(e){if("string"!=typeof e)return e;const t=e;if(t.startsWith("gs://"))return{format:"jsonl",gcsUri:t};if(t.startsWith("bq://"))return{format:"bigquery",bigqueryUri:t};throw new Error(`Unsupported destination: ${t}`)}(o))),void 0!==kt(e,["webhookConfig"]))throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}function eo(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["src"]);null!=i&&Nt(n,["batch","inputConfig"],function(e,t){const n={};if(void 0!==kt(t,["format"]))throw new Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(t,["gcsUri"]))throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(t,["bigqueryUri"]))throw new Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(t,["vertexDatasetName"]))throw new Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(t,["fileName"]);null!=o&&Nt(n,["fileName"],o);const i=kt(t,["inlinedRequests"]);if(null!=i){let t=i;Array.isArray(t)&&(t=t.map(t=>function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["request","model"],vn(e,o));const i=kt(t,["contents"]);if(null!=i){let e=Rn(i);Array.isArray(e)&&(e=e.map(e=>Zn(e))),Nt(n,["request","contents"],e)}const r=kt(t,["metadata"]);null!=r&&Nt(n,["metadata"],r);const s=kt(t,["config"]);return null!=s&&Nt(n,["request","generationConfig"],function(e,t,n){const o={},i=kt(t,["serviceTier"]);void 0!==n&&null!=i&&Nt(n,["serviceTier"],i);const r=kt(t,["systemInstruction"]);void 0!==n&&null!=r&&Nt(n,["systemInstruction"],Zn(On(r)));const s=kt(t,["temperature"]);null!=s&&Nt(o,["temperature"],s);const a=kt(t,["topP"]);null!=a&&Nt(o,["topP"],a);const l=kt(t,["topK"]);null!=l&&Nt(o,["topK"],l);const u=kt(t,["candidateCount"]);null!=u&&Nt(o,["candidateCount"],u);const c=kt(t,["maxOutputTokens"]);null!=c&&Nt(o,["maxOutputTokens"],c);const d=kt(t,["stopSequences"]);null!=d&&Nt(o,["stopSequences"],d);const p=kt(t,["responseLogprobs"]);null!=p&&Nt(o,["responseLogprobs"],p);const m=kt(t,["logprobs"]);null!=m&&Nt(o,["logprobs"],m);const h=kt(t,["presencePenalty"]);null!=h&&Nt(o,["presencePenalty"],h);const f=kt(t,["frequencyPenalty"]);null!=f&&Nt(o,["frequencyPenalty"],f);const v=kt(t,["seed"]);null!=v&&Nt(o,["seed"],v);const g=kt(t,["responseMimeType"]);null!=g&&Nt(o,["responseMimeType"],g);const _=kt(t,["responseSchema"]);null!=_&&Nt(o,["responseSchema"],Nn(_));const y=kt(t,["responseJsonSchema"]);if(null!=y&&Nt(o,["responseJsonSchema"],y),void 0!==kt(t,["routingConfig"]))throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(t,["modelSelectionConfig"]))throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const E=kt(t,["safetySettings"]);if(void 0!==n&&null!=E){let e=E;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["category"]);if(null!=n&&Nt(t,["category"],n),void 0!==kt(e,["method"]))throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["threshold"]);return null!=o&&Nt(t,["threshold"],o),t}(e))),Nt(n,["safetySettings"],e)}const T=kt(t,["tools"]);if(void 0!==n&&null!=T){let e=xn(T);Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==kt(e,["retrieval"]))throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["googleMaps"]);null!=n&&Nt(t,["googleMaps"],function(e){const t={},n=kt(e,["authConfig"]);null!=n&&Nt(t,["authConfig"],function(e){const t={},n=kt(e,["apiKey"]);if(null!=n&&Nt(t,["apiKey"],n),void 0!==kt(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["authType"]))throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oauthConfig"]))throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oidcConfig"]))throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["enableWidget"]);if(null!=o&&Nt(t,["enableWidget"],o),void 0!==kt(e,["groundingTypes"]))throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["mcpServers"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mcpServers"],e)}const i=kt(e,["codeExecution"]);null!=i&&Nt(t,["codeExecution"],i);const r=kt(e,["computerUse"]);if(null!=r&&Nt(t,["computerUse"],r),void 0!==kt(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["exaAiSearch"]))throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const a=kt(e,["googleSearch"]);null!=a&&Nt(t,["googleSearch"],function(e){const t={};if(void 0!==kt(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["excludeDomains"]))throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["searchTypes"]);null!=n&&Nt(t,["searchTypes"],n);const o=kt(e,["timeRangeFilter"]);return null!=o&&Nt(t,["timeRangeFilter"],o),t}(a));const l=kt(e,["googleSearchRetrieval"]);if(null!=l&&Nt(t,["googleSearchRetrieval"],l),void 0!==kt(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=kt(e,["urlContext"]);null!=u&&Nt(t,["urlContext"],u);const c=kt(e,["fileSearch"]);return null!=c&&Nt(t,["fileSearch"],c),t}(Mn(e)))),Nt(n,["tools"],e)}const A=kt(t,["toolConfig"]);void 0!==n&&null!=A&&Nt(n,["toolConfig"],function(e){const t={},n=kt(e,["functionCallingConfig"]);null!=n&&Nt(t,["functionCallingConfig"],function(e){const t={},n=kt(e,["allowedFunctionNames"]);null!=n&&Nt(t,["allowedFunctionNames"],n);const o=kt(e,["mode"]);if(null!=o&&Nt(t,["mode"],o),void 0!==kt(e,["streamFunctionCallArguments"]))throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["retrievalConfig"]);null!=o&&Nt(t,["retrievalConfig"],o);const i=kt(e,["includeServerSideToolInvocations"]);return null!=i&&Nt(t,["includeServerSideToolInvocations"],i),t}(A));const I=kt(t,["labels"]);void 0!==n&&null!=I&&Nt(n,["labels"],I);const C=kt(t,["cachedContent"]);void 0!==n&&null!=C&&Nt(n,["cachedContent"],Gn(e,C));const S=kt(t,["responseModalities"]);null!=S&&Nt(o,["responseModalities"],S);const b=kt(t,["mediaResolution"]);null!=b&&Nt(o,["mediaResolution"],b);const O=kt(t,["speechConfig"]);if(null!=O&&Nt(o,["speechConfig"],kn(O)),void 0!==kt(t,["audioTimestamp"]))throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const w=kt(t,["thinkingConfig"]);null!=w&&Nt(o,["thinkingConfig"],w);const R=kt(t,["audioTranscriptionConfig"]);null!=R&&Nt(o,["audioTranscriptionConfig"],R);const P=kt(t,["imageConfig"]);null!=P&&Nt(o,["imageConfig"],function(e){const t={},n=kt(e,["aspectRatio"]);null!=n&&Nt(t,["aspectRatio"],n);const o=kt(e,["imageSize"]);if(null!=o&&Nt(t,["imageSize"],o),void 0!==kt(e,["personGeneration"]))throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["outputMimeType"]))throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["outputCompressionQuality"]))throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["imageOutputOptions"]))throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["prominentPeople"]))throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(P));const N=kt(t,["enableEnhancedCivicAnswers"]);if(null!=N&&Nt(o,["enableEnhancedCivicAnswers"],N),void 0!==kt(t,["modelArmorConfig"]))throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const k=kt(t,["continuationToken"]);if(void 0!==n&&null!=k&&Nt(n,["continuationToken"],k),void 0!==kt(t,["generationOutputConfig"]))throw new Error("generationOutputConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const D=kt(t,["store"]);return void 0!==n&&null!=D&&Nt(n,["store"],D),o}(e,s,kt(n,["request"],{}))),n}(e,t))),Nt(n,["requests","requests"],t)}return n}(e,Bn(e,i)));const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["displayName"]);if(void 0!==t&&null!=n&&Nt(t,["batch","displayName"],n),void 0!==kt(e,["dest"]))throw new Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["webhookConfig"]);void 0!==t&&null!=o&&Nt(t,["batch","webhookConfig"],o)}(r,n),n}!function(e){e.PAGED_ITEM_BATCH_JOBS="batchJobs",e.PAGED_ITEM_MODELS="models",e.PAGED_ITEM_TUNING_JOBS="tuningJobs",e.PAGED_ITEM_FILES="files",e.PAGED_ITEM_CACHED_CONTENTS="cachedContents",e.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",e.PAGED_ITEM_DOCUMENTS="documents",e.PAGED_ITEM_SKILLS="skills"}(Gt||(Gt={}));var to=class{constructor(e,t,n,o){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,n,o)}init(e,t,n){var o,i;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=null==t?void 0:t.sdkHttpResponse,this.idxInternal=0;let r={config:{}};r=n&&0!==Object.keys(n).length?"object"==typeof n?Object.assign({},n):n:{config:{}},r.config&&(r.config.pageToken=t.nextPageToken),this.paramsInternal=r,this.pageInternalSize=null!==(i=null===(o=r.config)||void 0===o?void 0:o.pageSize)&&void 0!==i?i: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())return{value:void 0,done:!0};await this.nextPage()}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 void 0!==(null===(e=this.params.config)||void 0===e?void 0:e.pageToken)}},no=class extends Rt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new to(Gt.PAGED_ITEM_BATCH_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.create=async e=>(this.apiClient.isVertexAI()&&(e.config=this.formatDestination(e.src,e.config)),this.createInternal(e)),this.createEmbeddings=async e=>{if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(e)}}createInlinedGenerateContentRequest(e){const t=eo(this.apiClient,e),n=Pt("{model}:batchGenerateContent",t._url),o=t.batch.inputConfig.requests,i=o.requests,r=[];for(const s of i){const e=Object.assign({},s);if(e.systemInstruction){const t=e.systemInstruction;delete e.systemInstruction;const n=e.request;n.systemInstruction=t,e.request=n}r.push(e)}return o.requests=r,delete t.config,delete t._url,delete t._query,{path:n,body:t}}getGcsUri(e){return"string"==typeof e?e.startsWith("gs://")?e:void 0:!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0?e.gcsUri[0]:void 0}getBigqueryUri(e){return"string"==typeof e?e.startsWith("bq://")?e:void 0:Array.isArray(e)?void 0:e.bigqueryUri}formatDestination(e,t){const n=t?Object.assign({},t):{},o=Date.now().toString();if(n.displayName||(n.displayName=`genaiBatchJob_${o}`),void 0===n.dest){const t=this.getGcsUri(e),i=this.getBigqueryUri(e);if(t)t.endsWith(".jsonl")?n.dest=`${t.slice(0,-6)}/dest`:n.dest=`${t}_dest_${o}`;else{if(!i)throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.");n.dest=`${i}_dest_${o}`}}return n}async createInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["model"],vn(e,o));const i=kt(t,["src"]);null!=i&&Nt(n,["inputConfig"],function(e){const t={},n=kt(e,["format"]);null!=n&&Nt(t,["instancesFormat"],n);const o=kt(e,["gcsUri"]);null!=o&&Nt(t,["gcsSource","uris"],o);const i=kt(e,["bigqueryUri"]);null!=i&&Nt(t,["bigquerySource","inputUri"],i);const r=kt(e,["vertexDatasetName"]);if(null!=r&&Nt(t,["vertexMultimodalDatasetSource","datasetName"],r),void 0!==kt(e,["fileName"]))throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["inlinedRequests"]))throw new Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(Bn(e,i)));const r=kt(t,["config"]);return null!=r&&Qn(r,n),n}(this.apiClient,e);return s=Pt("batchPredictionJobs",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>zn(e))}{const t=eo(this.apiClient,e);return s=Pt("{model}:batchGenerateContent",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Kn(e))}}async createEmbeddingsInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["src"]);null!=i&&Nt(n,["batch","inputConfig"],function(e,t){const n={},o=kt(t,["fileName"]);null!=o&&Nt(n,["file_name"],o);const i=kt(t,["inlinedRequests"]);return null!=i&&Nt(n,["requests"],function(e,t){const n={},o=kt(t,["contents"]);if(null!=o){let t=wn(e,o);Array.isArray(t)&&(t=t.map(e=>e)),Nt(n,["requests[]","request","content"],t)}const i=kt(t,["config"]);return null!=i&&(Nt(n,["_self"],function(e,t){const n=kt(e,["taskType"]);void 0!==t&&null!=n&&Nt(t,["requests[]","taskType"],n);const o=kt(e,["title"]);void 0!==t&&null!=o&&Nt(t,["requests[]","title"],o);const i=kt(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&Nt(t,["requests[]","outputDimensionality"],i),void 0!==kt(e,["mimeType"]))throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["autoTruncate"]))throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["documentOcr"]))throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["audioTrackExtraction"]))throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return{}}(i,n)),function(e){for(const[t,n]of Object.entries({"requests[].*":"requests[].request.*"})){const o=t.split("."),i=n.split("."),r=/* @__PURE__ */new Set;let s=-1;for(let e=0;e<o.length;e++)if("*"===o[e]){s=e;break}if(-1!==s&&i.length>s)for(let e=s;e<i.length;e++){const t=i[e];"*"===t||t.endsWith("[]")||t.endsWith("[0]")||r.add(t)}Dt(e,o,i,0,r)}}(n)),n}(e,i)),n}(e,i));const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["displayName"]);void 0!==t&&null!=n&&Nt(t,["batch","displayName"],n)}(r,n),n}(this.apiClient,e);return i=Pt("{model}:asyncBatchEmbedContent",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>Kn(e))}}async get(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);return s=Pt("batchPredictionJobs/{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>zn(e))}{const t=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);return s=Pt("batches/{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Kn(e))}}async cancel(e){var t,n,o,i;let r="",s={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);r=Pt("batchPredictionJobs/{name}:cancel",o._url),s=o._query,delete o._url,delete o._query,await this.apiClient.request({path:r,queryParams:s,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal})}else{const t=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);r=Pt("batches/{name}:cancel",t._url),s=t._query,delete t._url,delete t._query,await this.apiClient.request({path:r,queryParams:s,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal})}}async listInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o);const i=kt(e,["filter"]);void 0!==t&&null!=i&&Nt(t,["_query","filter"],i)}(n,t),t}(e);return s=Pt("batchPredictionJobs",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["batchPredictionJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>zn(e))),Nt(t,["batchJobs"],e)}return t}(e),n=new pn;return Object.assign(n,t),n})}{const t=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);if(void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o),void 0!==kt(e,["filter"]))throw new Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(n,t),t}(e);return s=Pt("batches",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["operations"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>Kn(e))),Nt(t,["batchJobs"],e)}return t}(e),n=new pn;return Object.assign(n,t),n})}}async delete(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);return s=Pt("batchPredictionJobs/{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);return null!=r&&Nt(t,["error"],r),t}(e))}{const t=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Jn(e,o)),n}(this.apiClient,e);return s=Pt("batches/{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"DELETE",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);return null!=r&&Nt(t,["error"],r),t}(e))}}};function oo(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);null!=n&&Nt(t,["mediaResolution"],n);const o=kt(e,["toolCall"]);null!=o&&Nt(t,["toolCall"],o);const i=kt(e,["toolResponse"]);null!=i&&Nt(t,["toolResponse"],i);const r=kt(e,["audioTranscription"]);null!=r&&Nt(t,["audioTranscription"],r);const s=kt(e,["codeExecutionResult"]);null!=s&&Nt(t,["codeExecutionResult"],s);const a=kt(e,["executableCode"]);null!=a&&Nt(t,["executableCode"],a);const l=kt(e,["fileData"]);null!=l&&Nt(t,["fileData"],l);const u=kt(e,["functionCall"]);null!=u&&Nt(t,["functionCall"],function(e){const t={},n=kt(e,["args"]);null!=n&&Nt(t,["args"],n);const o=kt(e,["id"]);null!=o&&Nt(t,["id"],o);const i=kt(e,["name"]);if(null!=i&&Nt(t,["name"],i),void 0!==kt(e,["partialArgs"]))throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(u));const c=kt(e,["functionResponse"]);null!=c&&Nt(t,["functionResponse"],c);const d=kt(e,["inlineData"]);null!=d&&Nt(t,["inlineData"],d);const p=kt(e,["text"]);null!=p&&Nt(t,["text"],p);const m=kt(e,["thought"]);null!=m&&Nt(t,["thought"],m);const h=kt(e,["thoughtSignature"]);null!=h&&Nt(t,["thoughtSignature"],h);const f=kt(e,["videoMetadata"]);null!=f&&Nt(t,["videoMetadata"],f);const v=kt(e,["partMetadata"]);null!=v&&Nt(t,["partMetadata"],v);const g=kt(e,["mediaProcessing"]);null!=g&&Nt(t,["mediaProcessing"],g);const _=kt(e,["speechMetadata"]);null!=_&&Nt(t,["speechMetadata"],_);const y=kt(e,["documentMetadata"]);null!=y&&Nt(t,["documentMetadata"],y);const E=kt(e,["spreadsheetMetadata"]);null!=E&&Nt(t,["spreadsheetMetadata"],E);const T=kt(e,["audioMetadata"]);return null!=T&&Nt(t,["audioMetadata"],T),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}function io(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);if(null!=n&&Nt(t,["mediaResolution"],n),void 0!==kt(e,["toolCall"]))throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["toolResponse"]))throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=kt(e,["audioTranscription"]);null!=o&&Nt(t,["audioTranscription"],o);const i=kt(e,["codeExecutionResult"]);null!=i&&Nt(t,["codeExecutionResult"],i);const r=kt(e,["executableCode"]);null!=r&&Nt(t,["executableCode"],r);const s=kt(e,["fileData"]);null!=s&&Nt(t,["fileData"],s);const a=kt(e,["functionCall"]);null!=a&&Nt(t,["functionCall"],a);const l=kt(e,["functionResponse"]);null!=l&&Nt(t,["functionResponse"],function(e){const t={},n=kt(e,["id"]);null!=n&&Nt(t,["id"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["parts"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["fileData"]);null!=n&&Nt(t,["fileData"],n);const o=kt(e,["inlineData"]);if(null!=o&&Nt(t,["inlineData"],o),void 0!==kt(e,["mediaProcessing"]))throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const i=kt(e,["mediaResolution"]);null!=i&&Nt(t,["mediaResolution"],i);const r=kt(e,["videoMetadata"]);null!=r&&Nt(t,["videoMetadata"],r);const s=kt(e,["documentMetadata"]);null!=s&&Nt(t,["documentMetadata"],s);const a=kt(e,["spreadsheetMetadata"]);null!=a&&Nt(t,["spreadsheetMetadata"],a);const l=kt(e,["audioMetadata"]);return null!=l&&Nt(t,["audioMetadata"],l),t}(e))),Nt(t,["parts"],e)}const r=kt(e,["response"]);null!=r&&Nt(t,["response"],r);const s=kt(e,["scheduling"]);if(null!=s&&Nt(t,["scheduling"],s),void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(l));const u=kt(e,["inlineData"]);null!=u&&Nt(t,["inlineData"],u);const c=kt(e,["text"]);null!=c&&Nt(t,["text"],c);const d=kt(e,["thought"]);null!=d&&Nt(t,["thought"],d);const p=kt(e,["thoughtSignature"]);null!=p&&Nt(t,["thoughtSignature"],p);const m=kt(e,["videoMetadata"]);if(null!=m&&Nt(t,["videoMetadata"],m),void 0!==kt(e,["partMetadata"]))throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const h=kt(e,["mediaProcessing"]);null!=h&&Nt(t,["mediaProcessing"],h);const f=kt(e,["speechMetadata"]);null!=f&&Nt(t,["speechMetadata"],f);const v=kt(e,["documentMetadata"]);null!=v&&Nt(t,["documentMetadata"],v);const g=kt(e,["spreadsheetMetadata"]);null!=g&&Nt(t,["spreadsheetMetadata"],g);const _=kt(e,["audioMetadata"]);return null!=_&&Nt(t,["audioMetadata"],_),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}var ro=class extends Rt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new to(Gt.PAGED_ITEM_CACHED_CONTENTS,e=>this.listInternal(e),await this.listInternal(e),e)}async create(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["model"],gn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["ttl"]);void 0!==t&&null!=n&&Nt(t,["ttl"],n);const o=kt(e,["expireTime"]);void 0!==t&&null!=o&&Nt(t,["expireTime"],o);const i=kt(e,["displayName"]);void 0!==t&&null!=i&&Nt(t,["displayName"],i);const r=kt(e,["contents"]);if(void 0!==t&&null!=r){let e=Rn(r);Array.isArray(e)&&(e=e.map(e=>io(e))),Nt(t,["contents"],e)}const s=kt(e,["systemInstruction"]);void 0!==t&&null!=s&&Nt(t,["systemInstruction"],io(On(s)));const a=kt(e,["tools"]);if(void 0!==t&&null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["retrieval"]);null!=n&&Nt(t,["retrieval"],n);const o=kt(e,["googleMaps"]);null!=o&&Nt(t,["googleMaps"],o);const i=kt(e,["mcpServers"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){if(void 0!==kt(e,["name"]))throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["streamableHttpTransport"]))throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}(e))),Nt(t,["mcpServers"],e)}const r=kt(e,["codeExecution"]);null!=r&&Nt(t,["codeExecution"],r);const s=kt(e,["computerUse"]);null!=s&&Nt(t,["computerUse"],s);const a=kt(e,["enterpriseWebSearch"]);null!=a&&Nt(t,["enterpriseWebSearch"],a);const l=kt(e,["exaAiSearch"]);null!=l&&Nt(t,["exaAiSearch"],l);const u=kt(e,["functionDeclarations"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const c=kt(e,["googleSearch"]);null!=c&&Nt(t,["googleSearch"],c);const d=kt(e,["googleSearchRetrieval"]);null!=d&&Nt(t,["googleSearchRetrieval"],d);const p=kt(e,["parallelAiSearch"]);null!=p&&Nt(t,["parallelAiSearch"],p);const m=kt(e,["urlContext"]);if(null!=m&&Nt(t,["urlContext"],m),void 0!==kt(e,["fileSearch"]))throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(e))),Nt(t,["tools"],e)}const l=kt(e,["toolConfig"]);void 0!==t&&null!=l&&Nt(t,["toolConfig"],function(e){const t={},n=kt(e,["functionCallingConfig"]);null!=n&&Nt(t,["functionCallingConfig"],n);const o=kt(e,["retrievalConfig"]);if(null!=o&&Nt(t,["retrievalConfig"],o),void 0!==kt(e,["includeServerSideToolInvocations"]))throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(l));const u=kt(e,["kmsKeyName"]);void 0!==t&&null!=u&&Nt(t,["encryption_spec","kmsKeyName"],u)}(i,n),n}(this.apiClient,e);return s=Pt("cachedContents",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>e)}{const t=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["model"],gn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["ttl"]);void 0!==t&&null!=n&&Nt(t,["ttl"],n);const o=kt(e,["expireTime"]);void 0!==t&&null!=o&&Nt(t,["expireTime"],o);const i=kt(e,["displayName"]);void 0!==t&&null!=i&&Nt(t,["displayName"],i);const r=kt(e,["contents"]);if(void 0!==t&&null!=r){let e=Rn(r);Array.isArray(e)&&(e=e.map(e=>oo(e))),Nt(t,["contents"],e)}const s=kt(e,["systemInstruction"]);void 0!==t&&null!=s&&Nt(t,["systemInstruction"],oo(On(s)));const a=kt(e,["tools"]);if(void 0!==t&&null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==kt(e,["retrieval"]))throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["googleMaps"]);null!=n&&Nt(t,["googleMaps"],function(e){const t={},n=kt(e,["authConfig"]);null!=n&&Nt(t,["authConfig"],function(e){const t={},n=kt(e,["apiKey"]);if(null!=n&&Nt(t,["apiKey"],n),void 0!==kt(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["authType"]))throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oauthConfig"]))throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oidcConfig"]))throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["enableWidget"]);if(null!=o&&Nt(t,["enableWidget"],o),void 0!==kt(e,["groundingTypes"]))throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["mcpServers"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mcpServers"],e)}const i=kt(e,["codeExecution"]);null!=i&&Nt(t,["codeExecution"],i);const r=kt(e,["computerUse"]);if(null!=r&&Nt(t,["computerUse"],r),void 0!==kt(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["exaAiSearch"]))throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const a=kt(e,["googleSearch"]);null!=a&&Nt(t,["googleSearch"],function(e){const t={};if(void 0!==kt(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["excludeDomains"]))throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["searchTypes"]);null!=n&&Nt(t,["searchTypes"],n);const o=kt(e,["timeRangeFilter"]);return null!=o&&Nt(t,["timeRangeFilter"],o),t}(a));const l=kt(e,["googleSearchRetrieval"]);if(null!=l&&Nt(t,["googleSearchRetrieval"],l),void 0!==kt(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=kt(e,["urlContext"]);null!=u&&Nt(t,["urlContext"],u);const c=kt(e,["fileSearch"]);return null!=c&&Nt(t,["fileSearch"],c),t}(e))),Nt(t,["tools"],e)}const l=kt(e,["toolConfig"]);if(void 0!==t&&null!=l&&Nt(t,["toolConfig"],function(e){const t={},n=kt(e,["functionCallingConfig"]);null!=n&&Nt(t,["functionCallingConfig"],function(e){const t={},n=kt(e,["allowedFunctionNames"]);null!=n&&Nt(t,["allowedFunctionNames"],n);const o=kt(e,["mode"]);if(null!=o&&Nt(t,["mode"],o),void 0!==kt(e,["streamFunctionCallArguments"]))throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["retrievalConfig"]);null!=o&&Nt(t,["retrievalConfig"],o);const i=kt(e,["includeServerSideToolInvocations"]);return null!=i&&Nt(t,["includeServerSideToolInvocations"],i),t}(l)),void 0!==kt(e,["kmsKeyName"]))throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(i,n),n}(this.apiClient,e);return s=Pt("cachedContents",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>e)}}async get(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Gn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>e)}{const t=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Gn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>e)}}async delete(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Gn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new tn;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=kt(t,["name"]);return null!=o&&Nt(n,["_url","name"],Gn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"DELETE",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new tn;return Object.assign(n,t),n})}}async update(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["name"]);null!=o&&Nt(n,["_url","name"],Gn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["ttl"]);void 0!==t&&null!=n&&Nt(t,["ttl"],n);const o=kt(e,["expireTime"]);void 0!==t&&null!=o&&Nt(t,["expireTime"],o)}(i,n),n}(this.apiClient,e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"PATCH",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>e)}{const t=function(e,t){const n={},o=kt(t,["name"]);null!=o&&Nt(n,["_url","name"],Gn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["ttl"]);void 0!==t&&null!=n&&Nt(t,["ttl"],n);const o=kt(e,["expireTime"]);void 0!==t&&null!=o&&Nt(t,["expireTime"],o)}(i,n),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"PATCH",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>e)}}async listInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o)}(n,t),t}(e);return s=Pt("cachedContents",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["cachedContents"],e)}return t}(e),n=new nn;return Object.assign(n,t),n})}{const t=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o)}(n,t),t}(e);return s=Pt("cachedContents",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["cachedContents"],e)}return t}(e),n=new nn;return Object.assign(n,t),n})}}};function so(e){var t;if(null==e.candidates||0===e.candidates.length)return!1;const n=null===(t=e.candidates[0])||void 0===t?void 0:t.content;return void 0!==n&&ao(n)}function ao(e){if(void 0===e.parts||0===e.parts.length)return!1;for(const t of e.parts)if(void 0===t||0===Object.keys(t).length)return!1;return!0}function lo(e){if(void 0===e||0===e.length)return[];const t=[],n=e.length;let o=0;for(;o<n;)if("user"===e[o].role)t.push(e[o]),o++;else{const i=[];let r=!0;for(;o<n&&"model"===e[o].role;)i.push(e[o]),r&&!ao(e[o])&&(r=!1),o++;r?t.push(...i):t.pop()}return t}var uo=class{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new co(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},co=class{constructor(e,t,n,o={},i=[]){this.apiClient=e,this.modelsModule=t,this.model=n,this.config=o,this.history=i,this.sendPromise=Promise.resolve(),function(e){if(0!==e.length)for(const t of e)if("user"!==t.role&&"model"!==t.role)throw new Error(`Role must be user or model, but got ${t.role}.`)}(i)}async sendMessage(e){var t;await this.sendPromise;const n=On(e.message),o=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(n),config:null!==(t=e.config)&&void 0!==t?t:this.config});return this.sendPromise=(async()=>{var e,t,i;const r=await o,s=null===(t=null===(e=r.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content,a=r.automaticFunctionCallingHistory,l=this.getHistory(!0).length;let u=[];null!=a&&(u=null!==(i=a.slice(l))&&void 0!==i?i:[]);const c=s?[s]:[];this.recordHistory(n,c,u)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),o}async sendMessageStream(e){var t;await this.sendPromise;const n=On(e.message),o=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(n),config:null!==(t=e.config)&&void 0!==t?t:this.config});this.sendPromise=o.then(()=>{}).catch(()=>{});const i=await o;return this.processStreamResponse(i,n)}getHistory(e=!1){const t=e?lo(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return D(this,arguments,function*(){var n,o,i,r,s,a,l,u;const c=[];let d=!0,p=!1;try{for(var m,h=!0,f=M(e);!(n=(m=yield k(f.next())).done);h=!0){r=m.value,h=!1;const e=r;if(so(e)){const t=null===(a=null===(s=e.candidates)||void 0===s?void 0:s[0])||void 0===a?void 0:a.content;void 0!==t&&c.push(t)}else d=!1;void 0!==(null===(u=null===(l=e.candidates)||void 0===l?void 0:l[0])||void 0===u?void 0:u.finishReason)&&(p=!0),yield yield k(e)}}catch(v){o={error:v}}finally{try{h||n||!(i=f.return)||(yield k(i.call(f)))}finally{if(o)throw o.error}}this.recordHistory(t,d&&p?c:[])})}recordHistory(e,t,n){let o=[];t.length>0&&t.every(e=>void 0!==e.role)?o=t:o.push({role:"model",parts:[]}),n&&n.length>0?this.history.push(...lo(n)):this.history.push(e),this.history.push(...o)}},po=class e extends Error{constructor(t){super(t.message),this.name="ApiError",this.status=t.status,Object.setPrototypeOf(this,e.prototype)}},mo=class e extends Error{constructor(t){var n;super(t.message,{cause:t.cause}),this.name="ContinuationInterruptedError",void 0===this.cause&&(this.cause=t.cause),this.partialInteraction=t.partialInteraction,this.continuationToken=t.continuationToken,this.interactionId=t.interactionId,this.continuationIds=[...null!==(n=t.continuationIds)&&void 0!==n?n:[]],Object.setPrototypeOf(this,e.prototype)}};var ho=class extends Rt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new to(Gt.PAGED_ITEM_FILES,e=>this.listInternal(e),await this.listInternal(e),e)}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(e=>e)}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 t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o)}(n,t),t}(e);return i=Pt("files",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["files"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["files"],e)}return t}(e),n=new ln;return Object.assign(n,t),n})}}async createInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["file"]);return null!=n&&Nt(t,["file"],n),t}(e);return i=Pt("upload/{api_version}/files",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new un;return Object.assign(n,t),n})}}async get(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","file"],qn(n)),t}(e);return i=Pt("files/{file}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async delete(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","file"],qn(n)),t}(e);return i=Pt("files/{file}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new cn;return Object.assign(n,t),n})}}async registerFilesInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["uris"]);return null!=n&&Nt(t,["uris"],n),t}(e);return i=Pt("files:register",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["files"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["files"],e)}return t}(e),n=new dn;return Object.assign(n,t),n})}}},fo=/* @__PURE__ */new Set([void 0,"in_progress","requires_continuation"]),vo=/* @__PURE__ */new Set(["interaction.created","interaction.status_update"]),go={cached_tokens_by_modality:["modality","tokens"],input_tokens_by_modality:["modality","tokens"],output_tokens_by_modality:["modality","tokens"],tool_use_tokens_by_modality:["modality","tokens"],grounding_tool_count:["type","count"]},_o=!1;function yo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Eo(e,t){return yo(e)?e[t]:void 0}function To(e){return"string"==typeof e&&e?e:void 0}function Ao(e){return"number"==typeof e&&Number.isInteger(e)}function Io(e){return null==e}var Co=class e extends Error{constructor(t){super(t),this.name="ContinuationTimeoutError",Object.setPrototypeOf(this,e.prototype)}},So=class{constructor(e,t={}){var n,o;this.timeoutMs=e,this.now=null!==(n=t.now)&&void 0!==n?n:Date.now,(null===(o=t.enabled)||void 0===o||o)&&"number"==typeof e&&Number.isFinite(e)&&(this.deadlineMs=this.now()+e)}get bounded(){return void 0!==this.deadlineMs}remainingMs(){if(void 0!==this.deadlineMs)return this.deadlineMs-this.now()}expired(){const e=this.remainingMs();return void 0!==e&&e<=0}hopTimeoutMs(){const e=this.remainingMs();return void 0===e?this.timeoutMs:Math.max(1,Math.ceil(e))}check(){if(this.expired())throw new Co(`interactions.create() timed out after ${this.timeoutMs} ms before automatic continuation finished. Increase the timeout (it bounds the whole call, across continuation hops) or resume from the continuation_token.`)}};function bo(e,t,n){return void 0===t?e.body:function(e,t,n){if(!n||!1===e.store)return Object.assign(Object.assign({},e),{continuation_token:t});const{input:o}=e,i=N(e,["input"]);return Object.assign(Object.assign({},i),{continuation_token:t,previous_interaction_id:n})}(e.body,t,n)}function Oo(){_o||(_o=!0)}function wo(e,t,n){const o=Eo(e,"event_type");if("error"===o)return["error",void 0];const i=Eo(e,"interaction");if(null!=i){const e=To(Eo(i,"status"));e&&(t=e);const r=To(Eo(i,"continuation_token"));("interaction.completed"===o||r)&&(n=r)}const r=To(Eo(e,"status"));r&&(t=r);const s=To(Eo(e,"continuation_token"));return s&&(n=s),[t,n]}function Ro(e,t){return!!t&&fo.has(e)}var Po=class{constructor(e){this.options=e,this.hopIds=[],this.noProgressReconnects=0,this.nextToken=e.initialContinuationToken,this.initialToken=e.initialContinuationToken,this.hop={startToken:this.nextToken,startTokenOwnerId:void 0,token:this.nextToken,tokenOwnerId:void 0,interactionId:void 0,status:void 0,streamOpened:!1,contentSinceCheckpoint:!1}}startHop(e=!1){return this.hop={startToken:this.nextToken,startTokenOwnerId:this.nextTokenOwnerId,token:this.nextToken,tokenOwnerId:this.nextTokenOwnerId,interactionId:void 0,status:void 0,streamOpened:e,contentSinceCheckpoint:!1},[this.nextToken,this.nextTokenOwnerId]}markStreamOpened(){this.hop.streamOpened=!0}observe(e){const t=this.hop;t.streamOpened=!0;const n=function(e){var t;return null!==(t=To(Eo(e,"interaction_id")))&&void 0!==t?t:To(Eo(Eo(e,"interaction"),"id"))}(e);n&&(t.interactionId=n,this.hopIds.includes(n)||this.hopIds.push(n));const o=t.token;return[t.status,t.token]=wo(e,t.status,t.token),t.token&&t.token!==o&&(t.tokenOwnerId=t.interactionId),t.contentSinceCheckpoint=function(e,t){const n=Eo(e,"event_type");return"interaction.status_update"===n?!To(Eo(e,"continuation_token"))&&t:"interaction.completed"!==n&&("string"!=typeof n||!vo.has(n)||t)}(e,t.contentSinceCheckpoint),e}canResumeHop(){const e=this.hop;return!e.contentSinceCheckpoint&&Ro(e.status,e.token)}fail(e){const t=this.hop,n=Ro(t.status,t.token)?t.token:void 0;return n&&n!==this.initialToken?new mo({message:`Automatic continuation of the stream was interrupted: ${No(e.error)}. The continuationToken can be used to resume (output yielded after a mid-hop checkpoint is re-generated).`,cause:e.error,partialInteraction:void 0,continuationToken:n,interactionId:!1!==this.options.store?t.tokenOwnerId:void 0,continuationIds:[...this.hopIds]}):e.error}endHop(e){var t,n;const o=this.hop;if(e&&(e.error instanceof Co||(null===(n=(t=this.options).isFatalError)||void 0===n?void 0:n.call(t,e.error))))throw this.fail(e);if(e&&!o.streamOpened&&!this.options.isConnectionError(e.error))throw this.fail(e);if(!this.canResumeHop()){if(e)throw this.fail(e);return!1}if("requires_continuation"===o.status&&o.token===o.startToken){if(e)throw this.fail(e);return!1}var i,r,s,a;if(this.noProgressReconnects=(i=this.noProgressReconnects,r=o.status,s=o.startToken,a=o.token,"requires_continuation"===r||a!==s?0:i+1),0===this.noProgressReconnects&&(this.lastError=void 0),e&&(this.lastError=e),this.noProgressReconnects>3){if(this.lastError)throw this.fail(this.lastError);return!1}return this.nextToken=o.token,this.nextTokenOwnerId=o.tokenOwnerId,!0}};function No(e){return e instanceof Error?e.message||e.name:String(e)}async function ko(e){if(null==e?void 0:e.return)try{await e.return()}catch(Rr){}}function Do(e){if("requires_continuation"===Eo(e,"status"))return To(Eo(e,"continuation_token"))}function Mo(e,t){const n=Do(e);if(n!==t)return n}function xo(e){return yo(e)&&Array.isArray(e.steps)?e:void 0}function Go(e,t,n,o){const i=Lo(t,o),r=!1!==o.store&&!1!==Eo(t[0],"store");return new mo({message:`Automatic continuation was interrupted after ${t.length} completed hop(s): ${No(e)}. The partial interaction (status 'requires_continuation') and its continuationToken can be used to resume.`,cause:e,partialInteraction:i,continuationToken:n,interactionId:r?To(Eo(t[t.length-1],"id")):void 0,continuationIds:Uo(t)})}function Uo(e){const t=[];for(const n of e){const e=Eo(n,"continuation_ids");if(Array.isArray(e))for(const n of e)To(n)&&t.push(n);const o=To(Eo(n,"id"));o&&t.push(o)}return Array.from(new Set(t))}function Lo(e,t={}){var n,o;const i=null!==(n=t.normalizeInteraction)&&void 0!==n?n:xo,r=null!==(o=t.finalizeInteraction)&&void 0!==o?o:e=>e,s=e[e.length-1],a=i(s);if(!a)return s;const l=[];e.forEach((e,t)=>{let n=Eo(e,"steps");Array.isArray(n)&&(t>0&&(n=function(e){let t=0;for(;t<e.length&&"user_input"===Eo(e[t],"type");)t++;return e.slice(t)}(n)),l.push(...n))});const u=Object.assign(Object.assign({},a),{steps:l,continuation_ids:Uo(e)});if(e.length>1)for(const d of["previous_interaction_id","created","input"]){const t=Eo(e[0],d);void 0===t?delete u[d]:u[d]=t}const c=function(e){if(0===e.length)return;const t=e[0],n=e[e.length-1],o=[];for(const a of e)for(const e of Object.keys(a))o.includes(e)||o.push(e);const i={};for(const a of o){if("initial_input_tokens"===a)continue;const t=e.map(e=>e[a]).filter(e=>!Io(e));if(0!==t.length)if(t.every(Ao))i[a]=t.reduce((e,t)=>e+t,0);else if(a in go&&t.every(e=>Array.isArray(e))){const[e,n]=go[a];i[a]=qo(t,e,n)}}const r=Io(t.initial_input_tokens)?t.total_input_tokens:t.initial_input_tokens,s=Object.assign(Object.assign({},n),i);return Io(r)?delete s.initial_input_tokens:s.initial_input_tokens=r,s}(e.map(e=>Eo(e,"usage")).filter(yo));return void 0!==c&&(u.usage=c),r(u)}function qo(e,t,n){const o=/* @__PURE__ */new Map;for(const i of e)for(const e of i){const i=Eo(e,t),r=Eo(e,n),s=o.get(i);if(void 0===s){o.set(i,e);continue}const a=Eo(s,n);Ao(a)&&Ao(r)&&yo(s)&&o.set(i,Object.assign(Object.assign({},s),{[n]:a+r}))}return Array.from(o.values())}var Ho=Object.prototype.hasOwnProperty;function jo(e,t){const n=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(t={}){return e.replace(n,function(e,n){if(!Ho.call(t,n))throw new Error(`Parameter '${n}' is required`);const o=t[n];if("string"!=typeof o&&"number"!=typeof o)throw new Error(`Parameter '${n}' must be a string or number`);return`${o}`}).replace(/^\/+/,"")}}var Fo=["https://generativelanguage.googleapis.com"],Xo="speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai",Bo=void 0;function Vo(){var e,t,n,o,i,r;if(Bo)return Bo;const s=globalThis;let a={};return a="Deno"in globalThis?null!==(o=null===(n=null===(t=null===(e=s.Deno)||void 0===e?void 0:e.env)||void 0===t?void 0:t.toObject)||void 0===n?void 0:n.call(t))&&void 0!==o?o:{}:null!==(r=null===(i=s.process)||void 0===i?void 0:i.env)&&void 0!==r?r:{},Bo=a}var Jo=Symbol.for("undici.globalDispatcher.1"),$o=class{constructor(e){this.options=e}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(e){return function(e){var t,n;const o={};for(const[r,s]of e){const e=r.toLowerCase();"authorization"!==e&&"x-goog-api-key"!==e&&(o[r]=s)}const i={access_token:null!==(t=e.get("authorization"))&&void 0!==t?t:void 0,api_key:null!==(n=e.get("x-goog-api-key"))&&void 0!==n?n:void 0,default_headers:Object.keys(o).length?o:void 0};return ei(i)?i:void 0}(await this.options.getAuthHeaders(e))}},Wo=class{beforeCreateRequest(e,t){var n;const o=Object.assign({},null!==(n=t.options)&&void 0!==n?n:{});return!function(){var e,t;return"string"==typeof(null===(t=null===(e=globalThis.process)||void 0===e?void 0:e.versions)||void 0===t?void 0:t.node)}()||function(e){if(!e||"object"!=typeof e)return!1;if("options"in e){const t=e.options;return Boolean(null==t?void 0:t.fetcher)}return!0}(e.options.http_client)||"dispatcher"in o||(o.dispatcher={dispatch(e,t){const n=globalThis[Jo];if(!n||"function"!=typeof n.dispatch)throw new TypeError("Undici globalDispatcher is not available in this Node.js runtime.");return n.dispatch(Object.assign(Object.assign({},e),{headersTimeout:0,bodyTimeout:0}),t)}}),Object.assign(Object.assign({},t),{url:Yo(t.url),options:o})}async beforeRequest(e,t){if(zo(t.headers,function(e){var t,n;return Qo(e)?null!==(n=null===(t=e.getDefaultHeaders)||void 0===t?void 0:t.call(e))&&void 0!==n?n:e.defaultHeaders:Zo(e)?e.default_headers:void 0}(e.security_source)),function(e,t){void 0!==e.options.user_project&&null===t.get("x-goog-user-project")&&t.set("x-goog-user-project",e.options.user_project)}(e,t.headers),null!==(n=t.headers).get("authorization")||null!==n.get("x-goog-api-key"))return t;var n;const o=await async function(e,t){if(Qo(e))return e.resolveGoogleGenAISecurity(t);const n="function"==typeof e?await e():e;return Zo(n)?Ko(n):Ko(void 0)}(e.security_source,t.url);return zo(t.headers,null==o?void 0:o.default_headers),function(e,t){var n;t&&(t.api_key?e.set("x-goog-api-key",t.api_key):t.access_token&&e.set("Authorization","bearer "===(n=t.access_token).slice(0,7).toLowerCase()?n:`Bearer ${n}`))}(t.headers,o),t}};function Yo(e){const[,t,...n]=e.pathname.split("/");if(!t)return e;const o=decodeURIComponent(t);if(!o.includes("/"))return e;const i=new URL(e);return i.pathname=`/${o}/${n.join("/")}`,i}function Ko(e){var t,n;const o=Vo(),i=Object.assign(Object.assign({},e),{api_key:null!==(t=null==e?void 0:e.api_key)&&void 0!==t?t:o.GOOGLE_GENAI_API_KEY,access_token:null!==(n=null==e?void 0:e.access_token)&&void 0!==n?n:o.GOOGLE_GENAI_ACCESS_TOKEN});return ei(i)?i:void 0}function zo(e,t){if(t)for(const[n,o]of new Headers(t)){const t=e.get(n);(null===t||"user-agent"===n.toLowerCase()&&t===Xo)&&e.set(n,o)}}function Zo(e){return"object"==typeof e&&null!==e}function Qo(e){return"object"==typeof e&&null!==e&&"resolveGoogleGenAISecurity"in e&&"function"==typeof e.resolveGoogleGenAISecurity}function ei(e){return void 0!==e.api_key||void 0!==e.access_token||void 0!==e.default_headers}var ti=class extends Error{constructor(e,t){let n=e;(null==t?void 0:t.cause)&&(n+=`: ${t.cause}`),super(n,t),this.name="HTTPClientError",void 0===this.cause&&(this.cause=null==t?void 0:t.cause)}},ni=class extends ti{constructor(){super(...arguments),this.name="UnexpectedClientError"}},oi=class extends ti{constructor(){super(...arguments),this.name="InvalidRequestError"}},ii=class extends ti{constructor(){super(...arguments),this.name="RequestAbortedError"}},ri=class extends ti{constructor(){super(...arguments),this.name="RequestTimeoutError"}},si=class extends ti{constructor(){super(...arguments),this.name="ConnectionError"}},ai=class extends Error{constructor(e,t){var n,o,i,r;super(e),this.statusCode=null===(n=null==t?void 0:t.response)||void 0===n?void 0:n.status,this.body=null!==(o=null==t?void 0:t.body)&&void 0!==o?o:"",this.headers=null===(i=null==t?void 0:t.response)||void 0===i?void 0:i.headers,this.contentType=(null===(r=null==t?void 0:t.response)||void 0===r?void 0:r.headers.get("content-type"))||"",this.rawResponse=null==t?void 0:t.response,this.name="GoogleGenAiError",Object.setPrototypeOf(this,new.target.prototype)}};function li(e,t,n,o){return e&&o?400===e?new di(e,t,n,o):401===e?new pi(e,t,n,o):403===e?new mi(e,t,n,o):404===e?new hi(e,t,n,o):409===e?new fi(e,t,n,o):422===e?new vi(e,t,n,o):429===e?new gi(e,t,n,o):e>=500?new _i(e,t,n,o):new O(e,t,n,o):new w({message:n,cause:t instanceof Error?t:void 0})}O.generate=li;var ui=class extends O{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ci=class extends w{constructor({message:e}={}){super({message:e||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}},di=class extends O{},pi=class extends O{},mi=class extends O{},hi=class extends O{},fi=class extends O{},vi=class extends O{},gi=class extends O{},_i=class extends O{};function yi(e){return"object"==typeof(t=e)&&null!==t&&O.prototype.isPrototypeOf(t)?e:function(e){return e instanceof ai||e instanceof Error&&"number"==typeof e.statusCode&&"string"==typeof e.body}(e)?function(e){const t=function(e){const t=Ti(e,"data$");if(t&&"object"==typeof t)return t;try{const t=JSON.parse(e.body);if(t&&"object"==typeof t)return t}catch(Rr){}const n=Ti(e,"error");return n&&"object"==typeof n?n:void 0}(e),n=li(e.statusCode,t,e.message,e.headers);return Ai(n,"body",e.body),Ai(n,"contentType",e.contentType),Ai(n,"rawResponse",e.rawResponse),Ai(n,"statusCode",e.statusCode),Ai(n,"cause",e),n}(e):function(e){return e instanceof ti||e instanceof Error&&Ei.has(e.name)}(e)?function(e){return e instanceof ri||"RequestTimeoutError"===e.name?new ci({message:e.message}):e instanceof ii||"RequestAbortedError"===e.name?new ui({message:e.message}):(e instanceof si||e.name,new w({message:e.message,cause:e}))}(e):e;var t}var Ei=/* @__PURE__ */new Set(["HTTPClientError","UnexpectedClientError","InvalidRequestError","RequestAbortedError","RequestTimeoutError","ConnectionError"]);function Ti(e,t){return e&&"object"==typeof e?e[t]:void 0}function Ai(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!1})}function Ii(e){try{return JSON.parse(e)}catch(Rr){return e}}var Ci=function(e,t){const n=new ReadableStream(e,t);return Object.setPrototypeOf(n,Object.getPrototypeOf(this)),n};Ci.prototype=ReadableStream.prototype;var Si=class extends Ci{constructor(e,t,n){var o;const i=e.getReader();let r=/* @__PURE__ */new Uint8Array(4096),s=0,a=0;const l={eventId:void 0},u=null===(o=null==n?void 0:n.dataRequired)||void 0===o||o;super({async pull(e){try{for(;;){const n=Pi(r,s,a);if(!n){a=Math.max(0,s-Ri+1);const t=await i.read();if(t.done)return e.close();if(s+t.value.length>r.length){const e=new Uint8Array(Math.max(2*r.length,s+t.value.length));e.set(r.subarray(0,s)),r=e}r.set(t.value,s),s+=t.value.length;continue}const o=r.slice(0,n.index);if(r.copyWithin(0,n.index+n.length,s),s-=n.index+n.length,r.length>4096&&s<=r.length>>2){const e=new Uint8Array(Math.max(4096,2*s));e.set(r.subarray(0,s)),r=e}a=0;const c=Ni(o,t,l,u);if(c&&!c.done)return e.enqueue(c.value);if(null==c?void 0:c.done)return await i.cancel("done"),e.close()}}catch(n){e.error(n),await i.cancel(n)}},cancel:e=>i.cancel(e)})}[Symbol.asyncIterator](e){const t=ReadableStream.prototype[Symbol.asyncIterator];if("function"==typeof t)return t.call(this,e);const n=this.getReader(),o={next:async()=>{const e=await n.read();return e.done?(n.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}},throw:async e=>(await n.cancel(e),n.releaseLock(),{done:!0,value:void 0}),return:async()=>(await n.cancel("done"),n.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},i=Symbol.asyncDispose;return i&&(o[i]=async()=>{var e;await(null===(e=o.return)||void 0===e?void 0:e.call(o))}),o}values(e){return this[Symbol.asyncIterator](e)}},bi=13,Oi=10,wi=[[bi,Oi,bi,Oi],[bi,Oi,bi],[bi,Oi,Oi],[bi,bi,Oi],[Oi,bi,Oi],[bi,bi],[Oi,bi],[Oi,Oi]],Ri=wi.reduce((e,t)=>Math.max(e,t.length),0);function Pi(e,t,n){for(let o=n;o<t;o++)if(e[o]===bi||e[o]===Oi)for(const n of wi){if(o+n.length>t)continue;let i=!0;for(let t=0;t<n.length;t++)if(e[o+t]!==n[t]){i=!1;break}if(i)return{index:o,length:n.length}}return null}function Ni(e,t,n,o){const i=(new TextDecoder).decode(e).split(/\r\n|\r|\n/),r=[],s={};let a=!0;for(const l of i){if(!l||l.startsWith(":"))continue;a=!1;const e=l.indexOf(":");let t=l,o="";e>0&&(t=l.slice(0,e),o=" "===l[e+1]?l.slice(e+2):l.slice(e+1)),"data"===t?r.push(o):"event"===t?s.event=o:"id"!==t||o.includes("\0")?"retry"===t&&/^\d+$/.test(o)&&(s.retry=Number(o)):n.eventId=o}if(!a){if(s.id=n.eventId,r.length)s.data=r.join("\n");else if(o)return;return t(s)}}var ki=(e,t)=>null==t?fetch(e):fetch(e,t),Di=class e{constructor(e={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=e,this.fetcher=e.fetcher||ki}async request(e){let t=e;for(const o of this.requestHooks){const e=await o(t);e&&(t=e)}try{const e=await this.fetcher(t);for(const n of this.responseHooks)await n(e,t);return e}catch(n){for(const e of this.requestErrorHooks)await e(n,t);throw n}}addHook(...e){if("beforeRequest"===e[0])this.requestHooks.push(e[1]);else if("requestError"===e[0])this.requestErrorHooks.push(e[1]);else{if("response"!==e[0])throw new Error(`Invalid hook type: ${e[0]}`);this.responseHooks.push(e[1])}return this}removeHook(...e){let t;if("beforeRequest"===e[0])t=this.requestHooks;else if("requestError"===e[0])t=this.requestErrorHooks;else{if("response"!==e[0])throw new Error(`Invalid hook type: ${e[0]}`);t=this.responseHooks}const n=t.findIndex(t=>t===e[1]);return n>=0&&t.splice(n,1),this}clone(){const t=new e(this.options);return t.requestHooks=this.requestHooks.slice(),t.requestErrorHooks=this.requestErrorHooks.slice(),t.responseHooks=this.responseHooks.slice(),t}},Mi=/\s*;\s*/g;function xi(e,t){var n;if("*"===t)return!0;let o=(null===(n=e.headers.get("content-type"))||void 0===n?void 0:n.trim())||"application/octet-stream";o=o.toLowerCase();const[i="",...r]=t.toLowerCase().trim().split(Mi);if(2!==i.split("/").length)return!1;const[s="",...a]=o.split(Mi),[l="",u=""]=s.split("/");if(!l||!u)return!1;if("*/*"!==i&&s!==i&&`${l}/*`!==i&&`*/${u}`!==i)return!1;if(a.length<r.length)return!1;const c=new Set(a);for(const d of r)if(!c.has(d))return!1;return!0}var Gi=/* @__PURE__ */new RegExp("^[0-9]xx$","i");function Ui(e,t){const n=`${e.status}`,o=Array.isArray(t)?t:[t];return!!o.length&&o.some(e=>{const t=`${e}`;if("default"===t)return!0;if(!Gi.test(`${t}`))return t===n;const o=t.charAt(0);if(!o)throw new Error("Invalid status code range");const i=n.charAt(0);if(!i)throw new Error(`Invalid response status code: ${n}`);return i===o})}function Li(e,t,n){return Ui(e,t)&&xi(e,n)}function qi(e){if("object"!=typeof e||null==e)return!1;const t=e instanceof TypeError&&e.message.toLowerCase().startsWith("failed to fetch"),n=e instanceof TypeError&&e.message.toLowerCase().startsWith("fetch failed"),o="name"in e&&"ConnectionError"===e.name,i="code"in e&&"string"==typeof e.code&&"econnreset"===e.code.toLowerCase();return t||n||i||o}function Hi(e){if("object"!=typeof e||null==e)return!1;const t="name"in e&&"TimeoutError"===e.name,n="code"in e&&23===e.code,o="code"in e&&"string"==typeof e.code&&"econnaborted"===e.code.toLowerCase();return t||n||o}var ji=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];for(const e of[])"sdkInit"in e&&this.registerSDKInitHook(e),"beforeCreateRequest"in e&&this.registerBeforeCreateRequestHook(e),"beforeRequest"in e&&this.registerBeforeRequestHook(e),"afterSuccess"in e&&this.registerAfterSuccessHook(e),"afterError"in e&&this.registerAfterErrorHook(e);!function(e){const t=new Wo;e.registerBeforeCreateRequestHook(t),e.registerBeforeRequestHook(t)}(this)}registerSDKInitHook(e){this.sdkInitHooks.push(e)}registerBeforeCreateRequestHook(e){this.beforeCreateRequestHooks.push(e)}registerBeforeRequestHook(e){this.beforeRequestHooks.push(e)}registerAfterSuccessHook(e){this.afterSuccessHooks.push(e)}registerAfterErrorHook(e){this.afterErrorHooks.push(e)}sdkInit(e){return this.sdkInitHooks.reduce((e,t)=>t.sdkInit(e),e)}beforeCreateRequest(e,t){let n=t;for(const o of this.beforeCreateRequestHooks)n=o.beforeCreateRequest(e,n);return n}async beforeRequest(e,t){let n=t;for(const o of this.beforeRequestHooks)n=await o.beforeRequest(e,n);return n}async afterSuccess(e,t){let n=t;for(const o of this.afterSuccessHooks)n=await o.afterSuccess(e,n);return n}async afterError(e,t,n){let o=t,i=n;for(const r of this.afterErrorHooks){const t=await r.afterError(e,o,i);o=t.response,i=t.error}return{response:o,error:i}}};function Fi(e){return{ok:!0,value:e}}function Xi(e){return{ok:!1,error:e}}function Bi(e){return btoa(String.fromCodePoint(...e))}function Vi(...e){const t=[];for(const n of e)n&&t.push(n);switch(t.length){case 0:case 1:return t[0]||null;default:return"any"in AbortSignal&&"function"==typeof AbortSignal.any?AbortSignal.any(t):function(e){const t=new AbortController,n=t.signal;if(!e.length)return t.signal;if(1===e.length)return e[0]||t.signal;for(const r of e)if(r.aborted)return r;function o(){t.abort(this.reason),function(){for(const e of i){const t=e.deref();t&&t.removeEventListener("abort",o)}}()}const i=[];for(const r of e)i.push(new WeakRef(r)),r.addEventListener("abort",o);return n}(t)}}function Ji(e){const t={};for(const[n,o]of Object.entries(e))void 0!==o&&(t[n]=o);return t}function $i(e){if(null===e||"object"!=typeof e)return!1;if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);if(null===t||t===Object.prototype)return!0;try{return null===Object.getPrototypeOf(t)}catch(Rr){return!1}}var Wi=/%(2[346bcf]|3[abdf]|40|5[bd])/gi;function Yi(e,t){return Ki(e,"percentExceptReserved"===t?"percent":t)}function Ki(e,t){switch(t){case"percent":return encodeURIComponent(e);case"percentExceptReserved":return encodeURIComponent(e).replace(Wi,e=>decodeURIComponent(e));default:return e}}var zi=(e,t,n)=>{let o="";const i=(null==n?void 0:n.explode)?er(e,t):[[e,t]];if(i.every(([e,t])=>null==t))return;const r=e=>Ki(e,null==n?void 0:n.charEncoding),s=e=>r(tr(e)),a=r(",");return i.forEach(([e,t])=>{var i,l;let u="",c=null;null!=t&&(c=Array.isArray(t)?null===(i=or(t,e=>`${s(e)}`))||void 0===i?void 0:i.join(a):$i(t)?null===(l=ir(Object.entries(t),([e,t])=>`${r(e)}${a}${s(t)}`))||void 0===l?void 0:l.join(a):`${s(t)}`,null!=c&&(u=`${Yi(e,null==n?void 0:n.charEncoding)}=${c}`,u&&"="!==u&&(o+=`&${u}`)))}),o.slice(1)};function Zi(e,t,n){if(void 0===t)return;const o=Ki(JSON.stringify(t,nr),null==n?void 0:n.charEncoding);return(null==n?void 0:n.explode)?o:`${Yi(e,null==n?void 0:n.charEncoding)}=${o}`}var Qi=(e,t,n)=>{let o="";const i=(null==n?void 0:n.explode)?er(e,t):[[e,t]];if(i.every(([e,t])=>null==t))return;const r=e=>Ki(e,null==n?void 0:n.charEncoding),s=e=>r(tr(e));return i.forEach(([e,i])=>{var a;let l="";if(null!=i){if(Array.isArray(i))l=null===(a=or(i,e=>`${s(e)}`))||void 0===a?void 0:a.join(",");else if($i(i)){const e=ir(Object.entries(i),([e,t])=>`,${r(e)},${s(t)}`);l=null==e?void 0:e.join("").slice(1)}else l=`${(null==n?void 0:n.explode)&&$i(t)?`${e}=`:""}${s(i)}`;o+=l?`,${l}`:""}}),o.slice(1)};function er(e,t){return Array.isArray(t)?t.map(t=>[e,t]):$i(t)?Object.entries(null!=t?t:{}).map(([e,t])=>[e,t]):[[e,t]]}function tr(e){return null==e?"":e instanceof Date?e.toISOString():e instanceof Uint8Array?Bi(e):"object"==typeof e?JSON.stringify(e,nr):`${e}`}function nr(e,t){return t instanceof Uint8Array?Bi(t):t}function or(e,t){const n=e.reduce((e,n)=>{if(null==n)return e;const o=t(n);return null==o||e.push(o),e},[]);return n.length?n:null}function ir(e,t){const n=[];for(const[o,i]of e){if(null==i)continue;const e=t([o,i]);null!=e&&n.push(e)}return n.length?n:null}var rr,sr=(rr=zi,function(e,t){var n,o,i;const r=Object.assign(Object.assign({},t),{explode:null===(n=null==t?void 0:t.explode)||void 0===n||n,charEncoding:null!==(o=null==t?void 0:t.charEncoding)&&void 0!==o?o:"percent"}),s=new Set(null!==(i=null==t?void 0:t.allowEmptyValue)&&void 0!==i?i:[]);return function(...e){return e.filter(Boolean).join("&")}(...Object.entries(e).map(([e,t])=>s.has(e)&&(null==t||""===t||Array.isArray(t)&&0===t.length)?`${encodeURIComponent(e)}=`:rr(e,t,r)))}),ar={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},lr=class e extends Error{constructor(t,n){let o=t;(null==n?void 0:n.cause)&&(o+=`: ${n.cause}`),super(o,n),this.name="PermanentError",void 0===this.cause&&(this.cause=null==n?void 0:n.cause),Object.setPrototypeOf(this,e.prototype)}},ur=class e extends Error{constructor(t,n){super(t),this.response=n,this.name="TemporaryError",Object.setPrototypeOf(this,e.prototype)}};function cr(e,t){return async n=>{try{const o=await e(n);if(function(e,t){const n=`${e.status}`;return t.some(e=>{if(!dr.test(e))return e===n;const t=e.charAt(0);if(!t)throw new Error("Invalid status code range");const o=n.charAt(0);if(!o)throw new Error(`Invalid response status code: ${n}`);return o===t})}(o,t.statusCodes))throw new ur("Response failed with retryable status code",o);return o}catch(o){if(o instanceof ur)throw o;if(t.retryConnectionErrors&&(Hi(o)||qi(o)))throw o;throw new lr("Permanent error",{cause:o})}}}var dr=/* @__PURE__ */new RegExp("^[0-9]xx$","i");function pr(e){const t=e.headers.get("retry-after-ms");if(t){const e=Number(t);if(Number.isFinite(e)&&e>=0)return e}const n=e.headers.get("retry-after")||"";if(!n)return 0;const o=Number(n);if(Number.isInteger(o))return 1e3*o;const i=Date.parse(n);if(Number.isInteger(i)){const e=i-Date.now();return e>0?Math.ceil(e):0}return 0}async function mr(e){return new Promise(t=>setTimeout(t,e))}var hr="undefined"==typeof globalThis?null:globalThis,fr="object"==typeof hr&&null!=hr&&"importScripts"in hr&&"function"==typeof hr.importScripts||"undefined"!=typeof navigator&&"serviceWorker"in navigator||"object"==typeof window&&void 0!==window.document,vr=class{constructor(e={}){const t=e;"object"==typeof t&&null!=t&&"hooks"in t&&t.hooks instanceof ji?this._hooks=t.hooks:this._hooks=new ji;const n=new Di;e.http_client=e.http_client||n;const o=function(e){var t;let n=e.server_url;if(!n){const o=null!==(t=e.server_idx)&&void 0!==t?t:0;if(o<0||o>=Fo.length)throw new Error(`Invalid server index ${o}`);n=Fo[o]||""}const o=jo(n)({});return new URL(o)}(e=this._hooks.sdkInit(e));o&&(o.pathname=o.pathname.replace(/\/+$/,"")+"/"),this._baseURL=o,this._httpClient=e.http_client||n,this._options=Object.assign(Object.assign({},function(e){var t,n;const o=Object.assign({},e),i=Vo();return void 0!==i.GOOGLE_GENAI_API_VERSION&&(null!==(t=o.api_version)&&void 0!==t||(o.api_version=i.GOOGLE_GENAI_API_VERSION)),void 0!==i.GOOGLE_GENAI_USER_PROJECT&&(null!==(n=o.user_project)&&void 0!==n||(o.user_project=i.GOOGLE_GENAI_USER_PROJECT)),o}(e)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&Vo().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(e,t,n){var o,i,r,s,a;const{method:l,path:u,query:c,headers:d,security:p}=t,m=null!==(o=t.baseURL)&&void 0!==o?o:this._baseURL;if(!m)return Xi(new oi("No base URL provided for operation"));const h=new URL(m);let f;u?(h.pathname=h.pathname.replace(/\/+$/,"")+"/",f=new URL(u,h),!f.search&&h.search&&(f.search=h.search)):f=h,f.hash="";const v=e=>Object.entries(e).map(([e,t])=>{if(null==t)return;const n=$i(t)?JSON.stringify(t):t;return zi(e,n,{explode:Array.isArray(n),charEncoding:"percent"})}).filter(e=>void 0!==e).join("&"),g=[c||"",v((null==n?void 0:n.extra_query)||{}),v((null==p?void 0:p.queryParams)||{})].reduce((e,t)=>{if(!t)return e;const n=new Set(t.split("&").filter(e=>""!==e).map(e=>{var t;return null!==(t=e.split("=")[0])&&void 0!==t?t:""}));return[...e.split("&").filter(e=>{var t;return""!==e&&!n.has(null!==(t=e.split("=")[0])&&void 0!==t?t:"")}),t].join("&")},f.search.slice(1));g&&(f.search=`?${g}`);const _=new Headers(d),y=null==p?void 0:p.basic.username,E=null==p?void 0:p.basic.password;if(null!=y||null!=E){const e=Bi(function(e){return(new TextEncoder).encode(e)}([y||"",E||""].join(":")));_.set("Authorization",`Basic ${e}`)}const T=new Headers((null==p?void 0:p.headers)||{});for(const[R,P]of T)_.set(R,P);let A=_.get("cookie")||"";for(const[R,P]of Object.entries((null==p?void 0:p.cookies)||{}))A+=`; ${R}=${P}`;A=A.startsWith("; ")?A.slice(2):A,_.set("cookie",A);const I=new Headers(null!==(i=null==n?void 0:n.headers)&&void 0!==i?i:null===(r=null==n?void 0:n.fetch_options)||void 0===r?void 0:r.headers);for(const[R,P]of I)_.set(R,P);fr||_.set(null!==(s=t.uaHeader)&&void 0!==s?s:"user-agent",null!==(a=t.userAgent)&&void 0!==a?a:Xo);let C=t.body;const S=Object.fromEntries(Object.entries((null==n?void 0:n.extra_body)||{}).filter(([,e])=>void 0!==e));if(Object.keys(S).length>0){const e=new Headers(d).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(e)||"string"!=typeof C&&null!=C)return Xi(new oi("extra_body can only be merged into JSON object request bodies"));let t;try{t=C?JSON.parse(C):{}}catch(w){return Xi(new oi("extra_body can only be merged into JSON object request bodies",{cause:w}))}if(!$i(t))return Xi(new oi("extra_body can only be merged into JSON object request bodies"));C=JSON.stringify(Object.assign(Object.assign({},t),S)),_.delete("content-length")}const b=Object.assign(Object.assign({},null==n?void 0:n.fetch_options),n);let O;!(null==b?void 0:b.signal)&&null!=t.timeout_ms&&t.timeout_ms>0&&(e.timeout_ms=t.timeout_ms),t.body instanceof ReadableStream&&Object.assign(b,{duplex:"half"});try{O=this._hooks.beforeCreateRequest(e,{url:f,options:Object.assign(Object.assign({},b),{body:null!=C?C:null,headers:_,method:l})})}catch(w){return Xi(new ni("Create request hook failed to execute",{cause:w}))}return Fi(new Request(O.url,O.options))}async _do(e,t){const{context:n,isErrorStatusCode:o}=t,i=n.timeout_ms;return async function(e,t){var n;switch(t.config.strategy){case"backoff":return async function(e,t){const{maxElapsedTime:n,initialInterval:o,exponent:i,maxInterval:r}=t,s=Date.now();let a=0;for(;;)try{return await e(a)}catch(l){if(l instanceof lr)throw l.cause;if(Date.now()-s>n){if(l instanceof ur)return l.response;throw l}let e=0;l instanceof ur&&(e=pr(l.response)),e<=0&&(e=o*Math.pow(a,i)+1e3*Math.random()),await mr(Math.min(e,r)),a++}}(cr(e,{statusCodes:t.statusCodes,retryConnectionErrors:!!t.config.retryConnectionErrors}),null!==(n=t.config.backoff)&&void 0!==n?n:ar);case"attempt-count-backoff":return async function(e,t,n){let o=0;for(;;)try{return await e(o)}catch(i){if(i instanceof lr)throw i.cause;if(o>=n.maxRetries){if(i instanceof ur)return i.response;throw i}let e=0;i instanceof ur&&(e=pr(i.response)),e<=0&&(e=t.initialInterval*Math.pow(t.exponent,o)*(1-.25*Math.random())),await mr(Math.min(e,t.maxInterval)),o++}}(cr(e,{statusCodes:t.statusCodes,retryConnectionErrors:!!t.config.retryConnectionErrors}),Object.assign(Object.assign({},ar),t.config.backoff),t.config);default:return await e(0)}}(async()=>{var t;const r=e.clone();let s=r;if(null!=i&&i>0){const e=AbortSignal.timeout(i),n=null!==(t=Vi(r.signal,e))&&void 0!==t?t:e;s=new Request(r,{signal:n})}const a=await this._hooks.beforeRequest(n,s);await async function(e,t){if(!e)return;const n=t.headers.get("content-type"),o=(null==n?void 0:n.split(";")[0])||"";e.group(`> Request: ${t.method} ${t.url}`),e.group("Headers:");for(const[i,r]of t.headers.entries())e.log(`${i}: ${r}`);switch(e.groupEnd(),e.group("Body:"),!0){case gr.test(o):e.log(await t.clone().json());break;case o.startsWith("text/"):e.log(await t.clone().text());break;case"multipart/form-data"===o:{const n=await t.clone().formData();for(const[t,o]of n){const n=o instanceof Blob?"<Blob>":o;e.log(`${t}: ${n}`)}break}default:e.log(`<${n}>`)}e.groupEnd(),e.groupEnd()}(this._logger,a).catch(e=>{var t;return null===(t=this._logger)||void 0===t?void 0:t.log("Failed to log request:",e)});let l=await this._httpClient.request(a);try{if(o(l.status)){const e=await this._hooks.afterError(n,l,null);if(e.error)throw e.error;l=e.response||l}else l=await this._hooks.afterSuccess(n,l)}finally{await async function(e,t,n){if(!e)return;const o=t.headers.get("content-type"),i=(null==o?void 0:o.split(";")[0])||"";e.group(`< Response: ${n.method} ${n.url}`),e.log("Status Code:",t.status,t.statusText),e.group("Headers:");for(const[r,s]of t.headers.entries())e.log(`${r}: ${s}`);switch(e.groupEnd(),e.group("Body:"),!0){case xi(t,"application/json")||gr.test(i)&&!_r.test(i):e.log(await t.clone().json());break;case xi(t,"application/jsonl")||_r.test(i):case xi(t,"text/event-stream"):e.log(`<${o}>`);break;case xi(t,"text/*"):e.log(await t.clone().text());break;case xi(t,"multipart/form-data"):{const n=await t.clone().formData();for(const[t,o]of n){const n=o instanceof Blob?"<Blob>":o;e.log(`${t}: ${n}`)}break}default:e.log(`<${o}>`)}e.groupEnd(),e.groupEnd()}(this._logger,l,a).catch(e=>{var t;return null===(t=this._logger)||void 0===t?void 0:t.log("Failed to log response:",e)})}return l},{config:t.retryConfig,statusCodes:t.retryCodes}).then(e=>Fi(e),e=>{switch(!0){case function(e){if("object"!=typeof e||null==e)return!1;const t="name"in e&&"AbortError"===e.name,n="code"in e&&20===e.code,o="code"in e&&"string"==typeof e.code&&"econnaborted"===e.code.toLowerCase();return t||n||o}(e):return Xi(new ii("Request aborted by client",{cause:e}));case Hi(e):return Xi(new ri("Request timed out",{cause:e}));case qi(e):return Xi(new si("Unable to make request",{cause:e}));default:return Xi(new ni("Unexpected HTTP client error",{cause:e}))}})}},gr=/^(application|text)\/([^+]+\+)*json.*/,_r=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/,yr=class extends ai{constructor(e,t){e&&(e+=": "),e+=`Status ${t.response.status}`;const n=t.response.headers.get("content-type")||'""';"application/json"!==n&&(e+=` Content-Type ${n.includes(" ")?`"${n}"`:n}`);const o=t.body||'""';e+=o.length>100?"\n":". ";let i=o;o.length>1e4&&(i=`${o.substring(0,1e4)}...and ${o.length-1e4} more chars`),super(e=(e+=`Body: ${i}`).trim(),t),this.name="GoogleGenAiDefaultError",Object.setPrototypeOf(this,new.target.prototype)}},Er={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function Tr(e,t,n){return Object.assign(Object.assign({},n),{err:!0,enc:"json",codes:e,errorClass:t})}function Ar(e,t){return Object.assign(Object.assign({},t),{enc:"json",codes:e})}function Ir(e,t,n){return Object.assign(Object.assign(Object.assign({},n),{enc:"sse",codes:e}),t?{sse:t}:{})}function Cr(e,t){return Object.assign(Object.assign({},t),{enc:"nil",codes:e})}function Sr(e){return{enc:"fail",codes:e}}function br(...e){return async function(t,n,o){let i,r;for(const p of e){const{codes:e}=p,n="ctype"in p?p.ctype:Er[p.enc];if(n&&Li(t,e,n)){r=p;break}if(!n&&Ui(t,e)){r=p;break}}if(!r)return[{ok:!1,error:new yr("Unexpected Status or Content-Type",{response:t,request:n,body:await t.text().catch(()=>"")})},i];const s=r.enc;let a="";switch(s){case"json":a=await t.text();try{i=JSON.parse(a)}catch(d){if(!("err"in r))throw d;i=a}break;case"jsonl":case"stream":i=t.body;break;case"bytes":i=new Uint8Array(await t.arrayBuffer());break;case"text":case"fail":a=await t.text(),i=a;break;case"sse":if(t.body){const e="sse"in r&&r.sse||{};i=function(e,t={}){var n,o;const i=!0===t.flattened,r=null!==(n=t.sentinel)&&void 0!==n?n:"";return new Si(e,e=>""!==r&&e.data===r?{done:!0,value:void 0}:i?{done:!1,value:null==e.data?void 0:Ii(e.data)}:{done:!1,value:Object.assign(Object.assign({},e),{data:null==e.data?e.data:Ii(e.data)})},{dataRequired:null===(o=t.dataRequired)||void 0===o||o})}(t.body,e)}else i=null;break;case"nil":a=await t.text(),i=void 0;break;default:throw new Error(`Unsupported response type: ${s}`)}if("fail"===r.enc)return[{ok:!1,error:new yr("API error occurred",{request:n,response:t,body:a})},i];const l=r.key||(null==o?void 0:o.resultKey);let u;const c=r.hdrs?{headers:wr(t.headers)}:null;return u="err"in r?Object.assign(Object.assign(Object.assign({},null==o?void 0:o.extraFields),c),$i(i)?i:null):l?Object.assign(Object.assign(Object.assign({},null==o?void 0:o.extraFields),c),{[l]:i}):r.hdrs?Object.assign(Object.assign(Object.assign({},null==o?void 0:o.extraFields),c),$i(i)?i:null):i,"err"in r?[{ok:!1,error:r.errorClass?new r.errorClass(u,{request:n,response:t,body:a}):u},i]:[{ok:!0,value:u},i]}}var Or=/, */;function wr(e){const t={};for(const[n,o]of e.entries())t[n]=o.split(Or);return t}var Rr,Pr=class e extends Error{constructor(e,t){super(t),this.code=e,this.name="SecurityError"}static incomplete(){return new e("incomplete","Security requirements not met in order to perform the operation")}static unrecognizedType(t){return new e("unrecognized_security_type",`Unrecognised security type: ${t}`)}};function Nr(e,t){var n,o;return function(...e){const t={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},n=e.find(e=>e.every(e=>{if(null==e.value)return!1;if("http:basic"===e.type)return null!=e.value.username||null!=e.value.password;if("http:custom"===e.type)return null;if("oauth2:password"===e.type)return"string"==typeof e.value&&!!e.value;if("oauth2:client_credentials"===e.type)return"string"==typeof e.value?!!e.value:null!=e.value.client_id||null!=e.value.client_secret;if("string"==typeof e.value)return!!e.value;throw new Error(`Unrecognized security type: ${e.type} (value type: ${typeof e.value})`)}));return null==n?null:(n.forEach(e=>{if(null==e.value)return;const{type:n}=e;switch(n){case"apiKey:header":t.headers[e.fieldName]=e.value;break;case"apiKey:query":t.queryParams[e.fieldName]=e.value;break;case"apiKey:cookie":t.cookies[e.fieldName]=e.value;break;case"http:basic":!function(e,t){null!=t.value&&(e.basic=t.value)}(t,e);break;case"http:custom":case"oauth2:client_credentials":break;case"http:bearer":case"oauth2":case"oauth2:password":case"openIdConnect":!function(e,t){if("string"!=typeof t.value||!t.value)return;let n=t.value;"bearer "!==n.slice(0,7).toLowerCase()&&(n=`Bearer ${n}`),void 0!==t.fieldName&&(e.headers[t.fieldName]=n)}(t,e);break;default:throw Pr.unrecognizedType(n)}}),t)}([{fieldName:"accessToken",type:"http:custom",value:null!==(n=null==e?void 0:e.access_token)&&void 0!==n?n:Vo().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:null!==(o=null==e?void 0:e.api_key)&&void 0!==o?o:Vo().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:null==e?void 0:e.default_headers}])}async function kr(e){if(null!=e)return"function"==typeof e?e():e}var Dr=class e{constructor(e,t){this[Rr]="APIPromise",this._promise=e instanceof Promise?e:Promise.resolve(e),this._unwrapped=e instanceof Promise?null:Promise.resolve(e[0]),this._callSource=null!=t?t:null}_getUnwrapped(){var e;return null!==(e=this._unwrapped)&&void 0!==e?e:this._unwrapped=this._promise.then(([e])=>e)}then(e,t){return this._promise.then(e?([t])=>e(t):void 0,t)}catch(e){return this._getUnwrapped().catch(e)}finally(e){return this._getUnwrapped().finally(e)}$inspect(){return this._promise}asResponse(){var e;return(null!==(e=this._callSource)&&void 0!==e?e:this._callSource=this._promise.then(([,e])=>e)).then(e=>{if(!e.response)throw new Error("APIPromise.asResponse: response unavailable");return e.response})}async withResponse(){const[[e],t]=await Promise.all([this._promise,this.asResponse()]);return{data:e,response:t}}_thenUnwrap(t){var n;const o=this._promise.then(([e,n])=>[t(e),n]);return o.catch(()=>{}),new e(o,null!==(n=this._callSource)&&void 0!==n?n:void 0)}};function Mr(e){const t=e.$inspect(),n=t.then(([e,t])=>{if(!e.ok)throw e.error;return[e.value,t]}),o=t.then(([e,t])=>{var n;if(!e.ok&&!(null===(n=t.response)||void 0===n?void 0:n.ok))throw e.error;return t});return n.catch(()=>{}),o.catch(()=>{}),new Dr(n,o)}function xr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/agents")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function Gr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:Qi("agentsId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/agents/{agentsId}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Ur(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),agentsId:Qi("agentsId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/agents/{agentsId}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Lr(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={api_version:t,page_size:n,page_token:o,parent:i},c={api_version:Qi("api_version",null!==(s=null==u?void 0:u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/agents")(c),p=sr({page_size:null==u?void 0:u.page_size,page_token:null==u?void 0:u.page_token,parent:null==u?void 0:u.parent}),m=new Headers(Ji({Accept:"application/json"})),h=Nr(await kr(e._options.security)),f={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},v=e._createRequest(f,{security:h,method:"GET",baseURL:null==r?void 0:r.server_url,path:d,headers:m,query:p,body:null,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];const g=v.value,_=await e._do(g,{context:f,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:f.retry_config,retryCodes:f.retry_codes});if(!_.ok)return[_,{status:"request-error",request:g}];const y=_.value,[E]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(y,g);return E.ok,[E,{status:"complete",request:g,response:y}]}(e,t,n,o,i,r))}Rr=Symbol.toStringTag;var qr=class extends vr{list(e,t){return Mr(Lr(this,null==e?void 0:e.api_version,null==e?void 0:e.page_size,null==e?void 0:e.page_token,null==e?void 0:e.parent,t))}create(e,t){const{api_version:n}=e;return Mr(xr(this,N(e,["api_version"]),n,t))}delete(e,t,n){return Mr(Gr(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(Ur(this,e,null==t?void 0:t.api_version,n))}};function Hr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/credentials")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateCredential",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function jr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/credentials/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteCredential",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Fr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/credentials/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetCredential",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Xr(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={api_version:t,page_size:n,page_token:o},u={api_version:Qi("api_version",null!==(r=null==l?void 0:l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/credentials")(u),d=sr({page_size:null==l?void 0:l.page_size,page_token:null==l?void 0:l.page_token}),p=new Headers(Ji({Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"ListCredentials",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"GET",baseURL:null==i?void 0:i.server_url,path:c,headers:p,query:d,body:null,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}function Br(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={id:t,body:n,api_version:o,update_mask:i},c=Zi("body",u.body,{explode:!0}),d={api_version:Qi("api_version",null!==(s=u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",u.id,{explode:!1,charEncoding:"percent"})},p=jo("/{api_version}/credentials/{id}")(d),m=sr({update_mask:u.update_mask}),h=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),f=Nr(await kr(e._options.security)),v={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"UpdateCredential",o_auth2_scopes:null,resolved_security:f,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},g=e._createRequest(v,{security:f,method:"PATCH",baseURL:null==r?void 0:r.server_url,path:p,headers:h,query:m,body:c,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!g.ok)return[g,{status:"invalid"}];const _=g.value,y=await e._do(_,{context:v,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!y.ok)return[y,{status:"request-error",request:_}];const E=y.value,[T]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(E,_);return T.ok,[T,{status:"complete",request:_,response:E}]}(e,t,n,o,i,r))}var Vr=class extends vr{list(e,t){return Mr(Xr(this,null==e?void 0:e.api_version,null==e?void 0:e.page_size,null==e?void 0:e.page_token,t))}create(e,t){const{api_version:n}=e;return Mr(Hr(this,N(e,["api_version"]),n,t))}delete(e,t,n){return Mr(jr(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(Fr(this,e,null==t?void 0:t.api_version,n))}update(e,t,n){const{api_version:o,update_mask:i}=t;return Mr(Br(this,e,N(t,["api_version","update_mask"]),o,i,n))}};function Jr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/decisions")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateDecision",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}var $r=class extends vr{create(e,t,n){return Mr(Jr(this,e,t,n))}};function Wr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/environments")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function Yr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/environments/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Kr(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/environments/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function zr(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={api_version:t,mode:n,page_size:o,page_token:i},c={api_version:Qi("api_version",null!==(s=null==u?void 0:u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/environments")(c),p=sr({mode:null==u?void 0:u.mode,page_size:null==u?void 0:u.page_size,page_token:null==u?void 0:u.page_token}),m=new Headers(Ji({Accept:"application/json"})),h=Nr(await kr(e._options.security)),f={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},v=e._createRequest(f,{security:h,method:"GET",baseURL:null==r?void 0:r.server_url,path:d,headers:m,query:p,body:null,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];const g=v.value,_=await e._do(g,{context:f,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:f.retry_config,retryCodes:f.retry_codes});if(!_.ok)return[_,{status:"request-error",request:g}];const y=_.value,[E]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(y,g);return E.ok,[E,{status:"complete",request:g,response:y}]}(e,t,n,o,i,r))}function Zr(e,t,n,o,i,r,s,a){return new Dr(async function(e,t,n,o,i,r,s,a){var l,u,c;const d={environment:t,path:n,api_version:o,page_size:i,page_token:r,recursive:s},p={api_version:Qi("api_version",null!==(l=d.api_version)&&void 0!==l?l:e._options.api_version,{explode:!1,charEncoding:"percent"}),environment:Qi("environment",d.environment,{explode:!1,charEncoding:"percent"}),path:Qi("path",d.path,{explode:!1,charEncoding:"percentExceptReserved"})},m=jo("/{api_version}/environments/{environment}/files/{path}")(p),h=sr({page_size:d.page_size,page_token:d.page_token,recursive:d.recursive}),f=new Headers(Ji({Accept:"application/json"})),v=Nr(await kr(e._options.security)),g={options:e._options,base_url:null!==(c=null!==(u=null==a?void 0:a.server_url)&&void 0!==u?u:e._baseURL)&&void 0!==c?c:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:(null==a?void 0:a.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==a?void 0:a.retry_codes)||["408","409","429","5XX"]},_=e._createRequest(g,{security:v,method:"GET",baseURL:null==a?void 0:a.server_url,path:m,headers:f,query:h,body:null,userAgent:e._options.user_agent,timeout_ms:(null==a?void 0:a.timeout_ms)||e._options.timeout_ms||-1},a);if(!_.ok)return[_,{status:"invalid"}];const y=_.value,E=await e._do(y,{context:g,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];const T=E.value,[A]=await br(Ar(200),Sr("4XX"),Sr("5XX"))(T,y);return A.ok,[A,{status:"complete",request:y,response:T}]}(e,t,n,o,i,r,s,a))}var Qr=class extends vr{list(e,t,n,o){return Mr(Zr(this,e,t,null==n?void 0:n.api_version,null==n?void 0:n.page_size,null==n?void 0:n.page_token,null==n?void 0:n.recursive,o))}};function es(e,t,n,o,i,r,s,a,l,u,c){return new Dr(async function(e,t,n,o,i,r,s,a,l,u,c){var d,p,m;const h={environment:t,path:n,"X-Goog-Upload-Command":o,"X-Goog-Upload-Header-Content-Length":i,"X-Goog-Upload-Header-Content-Type":r,"X-Goog-Upload-Protocol":s,api_version:a,extract:l,overwrite:u},f={api_version:Qi("api_version",null!==(d=h.api_version)&&void 0!==d?d:e._options.api_version,{explode:!1,charEncoding:"percent"}),environment:Qi("environment",h.environment,{explode:!1,charEncoding:"percent"}),path:Qi("path",h.path,{explode:!1,charEncoding:"percentExceptReserved"})},v=jo("/upload/{api_version}/environments/{environment}/files/{path}")(f),g=sr({extract:h.extract,overwrite:h.overwrite}),_=new Headers(Ji({Accept:"*/*","X-Goog-Upload-Command":Qi("X-Goog-Upload-Command",h["X-Goog-Upload-Command"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Length":Qi("X-Goog-Upload-Header-Content-Length",h["X-Goog-Upload-Header-Content-Length"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Type":Qi("X-Goog-Upload-Header-Content-Type",h["X-Goog-Upload-Header-Content-Type"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Protocol":Qi("X-Goog-Upload-Protocol",h["X-Goog-Upload-Protocol"],{explode:!1,charEncoding:"none"})})),y=Nr(await kr(e._options.security)),E={options:e._options,base_url:null!==(m=null!==(p=null==c?void 0:c.server_url)&&void 0!==p?p:e._baseURL)&&void 0!==m?m:"",operation_id:"StartEnvironmentFileUpload",o_auth2_scopes:null,resolved_security:y,security_source:e._options.security,retry_config:(null==c?void 0:c.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==c?void 0:c.retry_codes)||["408","409","429","5XX"]},T=e._createRequest(E,{security:y,method:"PUT",baseURL:null==c?void 0:c.server_url,path:v,headers:_,query:g,body:null,userAgent:e._options.user_agent,timeout_ms:(null==c?void 0:c.timeout_ms)||e._options.timeout_ms||-1},c);if(!T.ok)return[T,{status:"invalid"}];const A=T.value,I=await e._do(A,{context:E,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:E.retry_config,retryCodes:E.retry_codes});if(!I.ok)return[I,{status:"request-error",request:A}];const C=I.value,S={httpMeta:{response:C,request:A}},[b]=await br(Cr(200,{hdrs:!0}),Sr("4XX"),Sr("5XX"))(C,A,{extraFields:S});return b.ok,[b,{status:"complete",request:A,response:C}]}(e,t,n,o,i,r,s,a,l,u,c))}var ts=class extends vr{startUpload(e,t,n,o){return Mr(es(this,e,t,n["X-Goog-Upload-Command"],n["X-Goog-Upload-Header-Content-Length"],n["X-Goog-Upload-Header-Content-Type"],n["X-Goog-Upload-Protocol"],n.api_version,n.extract,n.overwrite,o))}},ns=class extends vr{get internal(){var e;return null!==(e=this._internal)&&void 0!==e?e:this._internal=new ts(this._options)}get files(){var e;return null!==(e=this._files)&&void 0!==e?e:this._files=new Qr(this._options)}listEnvironments(e,t){return Mr(zr(this,null==e?void 0:e.api_version,null==e?void 0:e.mode,null==e?void 0:e.page_size,null==e?void 0:e.page_token,t))}createEnvironment(e,t,n){return Mr(Wr(this,e,t,n))}deleteEnvironment(e,t,n){return Mr(Yr(this,e,null==t?void 0:t.api_version,n))}getEnvironment(e,t,n){return Mr(Kr(this,e,null==t?void 0:t.api_version,n))}},os=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdServerError"}},is=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="CancelInteractionByIdClientError"}},rs=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="CreateInteractionServerError"}},ss=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="CreateInteractionClientError"}},as=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="DeleteInteractionServerError"}},ls=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="DeleteInteractionClientError"}},us=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="GetInteractionByIdServerError"}},cs=class extends ai{constructor(e,t){var n;super((null===(n=e.error)||void 0===n?void 0:n.message)||`API error occurred: ${JSON.stringify(e)}`,t),this.data$=e,this.error=e.error,this.name="GetInteractionByIdClientError"}};function ds(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:Qi("interactionsId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/interactions/{interactionsId}/cancel")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"POST",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,g={httpMeta:{response:v,request:h}},[_]=await br(Ar(200),Tr("4XX",is),Tr("5XX",os))(v,h,{extraFields:g});return _.ok,[_,{status:"complete",request:h,response:v}]}(e,t,n,o))}function ps(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s,a;const l={body:t,api_version:n},u=l,c=Zi("body",u.body,{explode:!0}),d={api_version:Qi("api_version",null!==(i=u.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},p=jo("/{api_version}/interactions")(d),m=new Headers(Ji({"Content-Type":"application/json",Accept:(null===(r=null==l?void 0:l.body)||void 0===r?void 0:r.stream)?"text/event-stream":"application/json"})),h=Nr(await kr(e._options.security)),f={options:e._options,base_url:null!==(a=null!==(s=null==o?void 0:o.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},v=e._createRequest(f,{security:h,method:"POST",baseURL:null==o?void 0:o.server_url,path:p,headers:m,body:c,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!v.ok)return[v,{status:"invalid"}];const g=v.value,_=await e._do(g,{context:f,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:f.retry_config,retryCodes:f.retry_codes});if(!_.ok)return[_,{status:"request-error",request:g}];const y=_.value,E={httpMeta:{response:y,request:g}},[T]=await br(Ar(200),Ir(200,{sentinel:"[DONE]",flattened:!0}),Tr("4XX",ss),Tr("5XX",rs))(y,g,{extraFields:E});return T.ok,[T,{status:"complete",request:g,response:y}]}(e,t,n,o))}function ms(e,t,n,o,i,r,s){return new Dr(async function(e,t,n,o,i,r,s){var a,l,u;const c={id:t,api_version:n,include_input:o,last_event_id:i,stream:r},d=c,p={api_version:Qi("api_version",null!==(a=d.api_version)&&void 0!==a?a:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:Qi("interactionsId",d.id,{explode:!1,charEncoding:"percent"})},m=jo("/{api_version}/interactions/{interactionsId}")(p),h=sr({include_input:d.include_input,last_event_id:d.last_event_id,stream:d.stream}),f=new Headers(Ji({Accept:(null==c?void 0:c.stream)?"text/event-stream":"application/json"})),v=Nr(await kr(e._options.security)),g={options:e._options,base_url:null!==(u=null!==(l=null==s?void 0:s.server_url)&&void 0!==l?l:e._baseURL)&&void 0!==u?u:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:v,security_source:e._options.security,retry_config:(null==s?void 0:s.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==s?void 0:s.retry_codes)||["408","409","429","5XX"]},_=e._createRequest(g,{security:v,method:"GET",baseURL:null==s?void 0:s.server_url,path:m,headers:f,query:h,body:null,userAgent:e._options.user_agent,timeout_ms:(null==s?void 0:s.timeout_ms)||e._options.timeout_ms||-1},s);if(!_.ok)return[_,{status:"invalid"}];const y=_.value,E=await e._do(y,{context:g,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:g.retry_config,retryCodes:g.retry_codes});if(!E.ok)return[E,{status:"request-error",request:y}];const T=E.value,A={httpMeta:{response:T,request:y}},[I]=await br(Ar(200),Ir(200,{sentinel:"[DONE]",flattened:!0}),Tr("4XX",cs),Tr("5XX",us))(T,y,{extraFields:A});return I.ok,[I,{status:"complete",request:y,response:T}]}(e,t,n,o,i,r,s))}function hs(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={interaction_id:t,body:n,api_version:o},u=Zi("body",l.body,{explode:!0}),c={api_version:Qi("api_version",null!==(r=l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:Qi("interactionsId",l.interaction_id,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/interactions/{interactionsId}/auth_tokens")(c),p=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"CreateInteractionAuthToken",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"POST",baseURL:null==i?void 0:i.server_url,path:d,headers:p,body:u,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}function fs(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={interaction_id:t,auth_token:n,api_version:o},u={api_version:Qi("api_version",null!==(r=l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"}),auth_tokensId:Qi("auth_tokensId",l.auth_token,{explode:!1,charEncoding:"percent"}),interactionsId:Qi("interactionsId",l.interaction_id,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/interactions/{interactionsId}/auth_tokens/{auth_tokensId}")(u),d=new Headers(Ji({Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"DeleteInteractionAuthToken",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"DELETE",baseURL:null==i?void 0:i.server_url,path:c,headers:d,body:null,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o,i))}var vs=class extends vr{create(e,t,n){const{api_version:o}=t;return Mr(hs(this,e,N(t,["api_version"]),o,n))}delete(e,t,n,o){return Mr(fs(this,e,t,null==n?void 0:n.api_version,o))}},gs=class extends vr{get auth_tokens(){var e;return null!==(e=this._auth_tokens)&&void 0!==e?e:this._auth_tokens=new vs(this._options)}create(e,t){const{api_version:n}=e;return Mr(ps(this,N(e,["api_version"]),n,t))}delete(e,t,n){return Mr(function(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),interactionsId:Qi("interactionsId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/interactions/{interactionsId}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,g={httpMeta:{response:v,request:h}},[_]=await br(Cr(200),Tr("4XX",ls),Tr("5XX",as))(v,h,{extraFields:g});return _.ok,[_,{status:"complete",request:h,response:v}]}(e,t,n,o))}(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(ms(this,e,null==t?void 0:t.api_version,null==t?void 0:t.include_input,null==t?void 0:t.last_event_id,null==t?void 0:t.stream,n))}cancel(e,t,n){return Mr(ds(this,e,null==t?void 0:t.api_version,n))}};function _s(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/triggers")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function ys(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/triggers/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Es(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/triggers/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Ts(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={trigger_id:t,api_version:n,page_size:o,page_token:i},c={api_version:Qi("api_version",null!==(s=u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:Qi("triggerId",u.trigger_id,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/triggers/{triggerId}/executions")(c),p=sr({page_size:u.page_size,page_token:u.page_token}),m=new Headers(Ji({Accept:"application/json"})),h=Nr(await kr(e._options.security)),f={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},v=e._createRequest(f,{security:h,method:"GET",baseURL:null==r?void 0:r.server_url,path:d,headers:m,query:p,body:null,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];const g=v.value,_=await e._do(g,{context:f,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:f.retry_config,retryCodes:f.retry_codes});if(!_.ok)return[_,{status:"request-error",request:g}];const y=_.value,[E]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(y,g);return E.ok,[E,{status:"complete",request:g,response:y}]}(e,t,n,o,i,r))}function As(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={api_version:t,filter:n,page_size:o,page_token:i},c={api_version:Qi("api_version",null!==(s=null==u?void 0:u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/triggers")(c),p=sr({filter:null==u?void 0:u.filter,page_size:null==u?void 0:u.page_size,page_token:null==u?void 0:u.page_token}),m=new Headers(Ji({Accept:"application/json"})),h=Nr(await kr(e._options.security)),f={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:h,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},v=e._createRequest(f,{security:h,method:"GET",baseURL:null==r?void 0:r.server_url,path:d,headers:m,query:p,body:null,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!v.ok)return[v,{status:"invalid"}];const g=v.value,_=await e._do(g,{context:f,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:f.retry_config,retryCodes:f.retry_codes});if(!_.ok)return[_,{status:"request-error",request:g}];const y=_.value,[E]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(y,g);return E.ok,[E,{status:"complete",request:g,response:y}]}(e,t,n,o,i,r))}function Is(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={trigger_id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),triggerId:Qi("triggerId",a.trigger_id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/triggers/{triggerId}/executions")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"POST",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Cs(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={id:t,body:n,api_version:o},u=Zi("body",l.body,{explode:!0}),c={api_version:Qi("api_version",null!==(r=l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",l.id,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/triggers/{id}")(c),p=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"PATCH",baseURL:null==i?void 0:i.server_url,path:d,headers:p,body:u,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}var Ss=class extends vr{list(e,t){return Mr(As(this,null==e?void 0:e.api_version,null==e?void 0:e.filter,null==e?void 0:e.page_size,null==e?void 0:e.page_token,t))}create(e,t){const{api_version:n}=e;return Mr(_s(this,N(e,["api_version"]),n,t))}delete(e,t,n){return Mr(ys(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(Es(this,e,null==t?void 0:t.api_version,n))}update(e,t,n){const{api_version:o}=t;return Mr(Cs(this,e,N(t,["api_version"]),o,n))}listExecutions(e,t,n){return Mr(Ts(this,e,null==t?void 0:t.api_version,null==t?void 0:t.page_size,null==t?void 0:t.page_token,n))}run(e,t,n){return Mr(Is(this,e,null==t?void 0:t.api_version,n))}};function bs(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/voices")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateVoice",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function Os(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:Qi("voicesId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/voices/{voicesId}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteVoice",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function ws(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),voicesId:Qi("voicesId",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/voices/{voicesId}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetVoice",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Rs(e,t,n,o,i,r,s,a,l,u,c,d,p,m){return new Dr(async function(e,t,n,o,i,r,s,a,l,u,c,d,p,m){var h,f,v;const g={api_version:t,accent:n,contexts:o,gender:i,language_code:r,page_size:s,page_token:a,persona:l,pitch:u,region_code:c,search:d,type:p},_={api_version:Qi("api_version",null!==(h=null==g?void 0:g.api_version)&&void 0!==h?h:e._options.api_version,{explode:!1,charEncoding:"percent"})},y=jo("/{api_version}/voices")(_),E=sr({accent:null==g?void 0:g.accent,context:null==g?void 0:g.contexts,gender:null==g?void 0:g.gender,language_code:null==g?void 0:g.language_code,page_size:null==g?void 0:g.page_size,page_token:null==g?void 0:g.page_token,persona:null==g?void 0:g.persona,pitch:null==g?void 0:g.pitch,region_code:null==g?void 0:g.region_code,search:null==g?void 0:g.search,type:null==g?void 0:g.type}),T=new Headers(Ji({Accept:"application/json"})),A=Nr(await kr(e._options.security)),I={options:e._options,base_url:null!==(v=null!==(f=null==m?void 0:m.server_url)&&void 0!==f?f:e._baseURL)&&void 0!==v?v:"",operation_id:"ListVoices",o_auth2_scopes:null,resolved_security:A,security_source:e._options.security,retry_config:(null==m?void 0:m.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==m?void 0:m.retry_codes)||["408","409","429","5XX"]},C=e._createRequest(I,{security:A,method:"GET",baseURL:null==m?void 0:m.server_url,path:y,headers:T,query:E,body:null,userAgent:e._options.user_agent,timeout_ms:(null==m?void 0:m.timeout_ms)||e._options.timeout_ms||-1},m);if(!C.ok)return[C,{status:"invalid"}];const S=C.value,b=await e._do(S,{context:I,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:I.retry_config,retryCodes:I.retry_codes});if(!b.ok)return[b,{status:"request-error",request:S}];const O=b.value,[w]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(O,S);return w.ok,[w,{status:"complete",request:S,response:O}]}(e,t,n,o,i,r,s,a,l,u,c,d,p,m))}var Ps=class extends vr{list(e,t){return Mr(Rs(this,null==e?void 0:e.api_version,null==e?void 0:e.accent,null==e?void 0:e.contexts,null==e?void 0:e.gender,null==e?void 0:e.language_code,null==e?void 0:e.page_size,null==e?void 0:e.page_token,null==e?void 0:e.persona,null==e?void 0:e.pitch,null==e?void 0:e.region_code,null==e?void 0:e.search,null==e?void 0:e.type,t))}create(e,t,n){return Mr(bs(this,e,t,n))}delete(e,t,n){return Mr(Os(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(ws(this,e,null==t?void 0:t.api_version,n))}};function Ns(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={body:t,api_version:n},l=Zi("body",a.body,{explode:!0}),u={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/webhooks")(u),d=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),p=Nr(await kr(e._options.security)),m={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:p,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},h=e._createRequest(m,{security:p,method:"POST",baseURL:null==o?void 0:o.server_url,path:c,headers:d,body:l,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!h.ok)return[h,{status:"invalid"}];const f=h.value,v=await e._do(f,{context:m,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:m.retry_config,retryCodes:m.retry_codes});if(!v.ok)return[v,{status:"request-error",request:f}];const g=v.value,[_]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(g,f);return _.ok,[_,{status:"complete",request:f,response:g}]}(e,t,n,o))}function ks(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/webhooks/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"DELETE",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Ds(e,t,n,o){return new Dr(async function(e,t,n,o){var i,r,s;const a={id:t,api_version:n},l={api_version:Qi("api_version",null!==(i=a.api_version)&&void 0!==i?i:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",a.id,{explode:!1,charEncoding:"percent"})},u=jo("/{api_version}/webhooks/{id}")(l),c=new Headers(Ji({Accept:"application/json"})),d=Nr(await kr(e._options.security)),p={options:e._options,base_url:null!==(s=null!==(r=null==o?void 0:o.server_url)&&void 0!==r?r:e._baseURL)&&void 0!==s?s:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:d,security_source:e._options.security,retry_config:(null==o?void 0:o.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==o?void 0:o.retry_codes)||["408","409","429","5XX"]},m=e._createRequest(p,{security:d,method:"GET",baseURL:null==o?void 0:o.server_url,path:u,headers:c,body:null,userAgent:e._options.user_agent,timeout_ms:(null==o?void 0:o.timeout_ms)||e._options.timeout_ms||-1},o);if(!m.ok)return[m,{status:"invalid"}];const h=m.value,f=await e._do(h,{context:p,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:p.retry_config,retryCodes:p.retry_codes});if(!f.ok)return[f,{status:"request-error",request:h}];const v=f.value,[g]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(v,h);return g.ok,[g,{status:"complete",request:h,response:v}]}(e,t,n,o))}function Ms(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={api_version:t,page_size:n,page_token:o},u={api_version:Qi("api_version",null!==(r=null==l?void 0:l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"})},c=jo("/{api_version}/webhooks")(u),d=sr({page_size:null==l?void 0:l.page_size,page_token:null==l?void 0:l.page_token}),p=new Headers(Ji({Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"GET",baseURL:null==i?void 0:i.server_url,path:c,headers:p,query:d,body:null,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}function xs(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={id:t,api_version:n,body:o},u=Zi("body",l.body,{explode:!0}),c={api_version:Qi("api_version",null!==(r=l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",l.id,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/webhooks/{id}:ping")(c),p=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"POST",baseURL:null==i?void 0:i.server_url,path:d,headers:p,body:u,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}function Gs(e,t,n,o,i){return new Dr(async function(e,t,n,o,i){var r,s,a;const l={id:t,body:n,api_version:o},u=Zi("body",l.body,{explode:!0}),c={api_version:Qi("api_version",null!==(r=l.api_version)&&void 0!==r?r:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",l.id,{explode:!1,charEncoding:"percent"})},d=jo("/{api_version}/webhooks/{id}:rotateSigningSecret")(c),p=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),m=Nr(await kr(e._options.security)),h={options:e._options,base_url:null!==(a=null!==(s=null==i?void 0:i.server_url)&&void 0!==s?s:e._baseURL)&&void 0!==a?a:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:m,security_source:e._options.security,retry_config:(null==i?void 0:i.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==i?void 0:i.retry_codes)||["408","409","429","5XX"]},f=e._createRequest(h,{security:m,method:"POST",baseURL:null==i?void 0:i.server_url,path:d,headers:p,body:u,userAgent:e._options.user_agent,timeout_ms:(null==i?void 0:i.timeout_ms)||e._options.timeout_ms||-1},i);if(!f.ok)return[f,{status:"invalid"}];const v=f.value,g=await e._do(v,{context:h,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:h.retry_config,retryCodes:h.retry_codes});if(!g.ok)return[g,{status:"request-error",request:v}];const _=g.value,[y]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(_,v);return y.ok,[y,{status:"complete",request:v,response:_}]}(e,t,n,o,i))}function Us(e,t,n,o,i,r){return new Dr(async function(e,t,n,o,i,r){var s,a,l;const u={id:t,body:n,api_version:o,update_mask:i},c=Zi("body",u.body,{explode:!0}),d={api_version:Qi("api_version",null!==(s=u.api_version)&&void 0!==s?s:e._options.api_version,{explode:!1,charEncoding:"percent"}),id:Qi("id",u.id,{explode:!1,charEncoding:"percent"})},p=jo("/{api_version}/webhooks/{id}")(d),m=sr({update_mask:u.update_mask}),h=new Headers(Ji({"Content-Type":"application/json",Accept:"application/json"})),f=Nr(await kr(e._options.security)),v={options:e._options,base_url:null!==(l=null!==(a=null==r?void 0:r.server_url)&&void 0!==a?a:e._baseURL)&&void 0!==l?l:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:f,security_source:e._options.security,retry_config:(null==r?void 0:r.retries)||e._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:(null==r?void 0:r.retry_codes)||["408","409","429","5XX"]},g=e._createRequest(v,{security:f,method:"PATCH",baseURL:null==r?void 0:r.server_url,path:p,headers:h,query:m,body:c,userAgent:e._options.user_agent,timeout_ms:(null==r?void 0:r.timeout_ms)||e._options.timeout_ms||-1},r);if(!g.ok)return[g,{status:"invalid"}];const _=g.value,y=await e._do(_,{context:v,isErrorStatusCode:e=>Ui({status:e},["4XX","5XX"]),retryConfig:v.retry_config,retryCodes:v.retry_codes});if(!y.ok)return[y,{status:"request-error",request:_}];const E=y.value,[T]=await br(Sr("4XX"),Sr("5XX"),Ar("default"))(E,_);return T.ok,[T,{status:"complete",request:_,response:E}]}(e,t,n,o,i,r))}var Ls=class extends vr{list(e,t){return Mr(Ms(this,null==e?void 0:e.api_version,null==e?void 0:e.page_size,null==e?void 0:e.page_token,t))}create(e,t){const{api_version:n}=e;return Mr(Ns(this,N(e,["api_version"]),n,t))}delete(e,t,n){return Mr(ks(this,e,null==t?void 0:t.api_version,n))}get(e,t,n){return Mr(Ds(this,e,null==t?void 0:t.api_version,n))}update(e,t,n){const{api_version:o,update_mask:i}=t;return Mr(Us(this,e,N(t,["api_version","update_mask"]),o,i,n))}ping(e,t,n,o){return Mr(xs(this,e,t,n,o))}rotateSigningSecret(e,t,n,o){return Mr(Gs(this,e,t,n,o))}},qs=class extends vr{get environments(){var e;return null!==(e=this._environments)&&void 0!==e?e:this._environments=new ns(this._options)}get agents(){var e;return null!==(e=this._agents)&&void 0!==e?e:this._agents=new qr(this._options)}get credentials(){var e;return null!==(e=this._credentials)&&void 0!==e?e:this._credentials=new Vr(this._options)}get decisions(){var e;return null!==(e=this._decisions)&&void 0!==e?e:this._decisions=new $r(this._options)}get interactions(){var e;return null!==(e=this._interactions)&&void 0!==e?e:this._interactions=new gs(this._options)}get triggers(){var e;return null!==(e=this._triggers)&&void 0!==e?e:this._triggers=new Ss(this._options)}get voices(){var e;return null!==(e=this._voices)&&void 0!==e?e:this._voices=new Ps(this._options)}get webhooks(){var e;return null!==(e=this._webhooks)&&void 0!==e?e:this._webhooks=new Ls(this._options)}},Hs=/* @__PURE__ */new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function js(e){const t=e.getBaseUrl();if(!t)throw new Error("Base URL must be set.");return t.replace(/\/+$/,"")}function Fs(e){const t=e.getApiVersion().replace(/^\/+|\/+$/g,""),n=e.getProject(),o=e.getLocation();return e.isVertexAI()&&t&&n&&o?`${t}/projects/${encodeURIComponent(n)}/locations/${encodeURIComponent(o)}`:t}function Xs(e,t={}){var n,o,i,r,s,a,l,u,c,d;const{timeout:p}=t,m=N(t,["timeout"]),h=m.http_client||null===(n=e.getFetch)||void 0===n?void 0:n.call(e),f=null!==(o=m.http_client)&&void 0!==o?o:h?new Di({fetcher:h}):void 0,v=null!==(r=null!==(i=m.timeout_ms)&&void 0!==i?i:p)&&void 0!==r?r:null===(s=e.getTimeout)||void 0===s?void 0:s.call(e);return new qs(Object.assign(Object.assign({},m),{http_client:f,api_version:null!==(a=m.api_version)&&void 0!==a?a:Fs(e),security:null!==(l=m.security)&&void 0!==l?l:new $o({defaultHeaders:Object.assign(Object.assign({},null===(u=e.getDefaultHeaders)||void 0===u?void 0:u.call(e)),null===(c=e.getHeaders)||void 0===c?void 0:c.call(e)),getAuthHeaders:t=>e.getAuthHeaders(t)}),server_url:null!==(d=m.server_url)&&void 0!==d?d:js(e),timeout_ms:v}))}var Bs=class{constructor(e,t=()=>!1){this.resolveClient=e,this.isVertexAI=t}async create(e,t={},n){if(G(),this.isVertexAI())throw new U("Live Interactions is currently Gemini API only.");const o=null!=t?t:{},{api_version:i}=o,r=N(o,["api_version"]);return Ks(hs(this.resolveClient(i),e,r,i,Ys(n)))}async delete(e,t,n={},o){if(G(),this.isVertexAI())throw new U("Live Interactions is currently Gemini API only.");const i=t.startsWith("auth_tokens/")?t.slice(12):t;return Ks(fs(this.resolveClient(null==n?void 0:n.api_version),e,i,null==n?void 0:n.api_version,Ys(o)))}},Vs=class{constructor(e,t){this.parentClient=e,this.webSocketFactory=t,this.authTokens=new Bs(e=>this.getClient(e),()=>this.parentClient.isVertexAI())}async create(e,t){var n;const{api_version:o,automatic_continuation:i}=e,r=function(e,t){const n=!0===e.background,o=!0===e.stream;if(n&&!1===t)throw new Error("automatic_continuation: false cannot be used with background: true.");const i=!1!==(null==t||t)&&!n&&!function(e){return!Io(Eo(e,"agent"))||!Io(Eo(e,"agent_config"))}(e);return{body:e,stream:o,callerToken:To(e.continuation_token),enableContinuation:i}}(N(e,["api_version","automatic_continuation"]),i),s=new So(null!==(n=null==t?void 0:t.timeout_ms)&&void 0!==n?n:null==t?void 0:t.timeout,{enabled:r.enableContinuation}),a=()=>{if(!s.bounded)return t;const e=null!=t?t:{},{timeout:n}=e,o=N(e,["timeout"]);return Object.assign(Object.assign({},o),{timeout_ms:s.hopTimeoutMs()})},l=this.getClient(o);if(r.stream){const e=async(e,t)=>Zs(await zs(()=>l.interactions.create(Object.assign(Object.assign({},bo(r,e,t)),{stream:!0,api_version:o}),Ys(a(),!0)))),t=await e();return r.enableContinuation?ea(function(e,t,n){return D(this,arguments,function*(){var o,i;const r=null!==(o=n.deadline)&&void 0!==o?o:new So(void 0),s=null!==(i=n.wrapIterationError)&&void 0!==i?i:e=>e,a=new Po({initialContinuationToken:n.initialContinuationToken,isConnectionError:n.isConnectionError,isFatalError:n.isFatalError,store:n.store});let l,u=!0;try{for(;;){const[n,o]=a.startHop(u);let i;if(u)u=!1,l=e[Symbol.asyncIterator]();else{yield k(ko(l)),l=void 0;try{r.check();const e=yield k(t(n,o));a.markStreamOpened(),l=e[Symbol.asyncIterator]()}catch(c){i={error:c}}}if(!i&&l)for(;;){let e;try{r.check(),e=yield k(l.next())}catch(c){i={error:c instanceof Co?c:s(c)};break}if(e.done)break;yield yield k(a.observe(e.value))}if(!a.endHop(i))break}}finally{yield k(ko(l))}})}(t,e,{initialContinuationToken:r.callerToken,isConnectionError:e=>e instanceof w&&!(e instanceof ui),isFatalError:e=>e instanceof ui,wrapIterationError:Qs,deadline:s,store:!1!==r.body.store})):r.callerToken?t:ea(function(e){return D(this,arguments,function*(){var t,n,o,i;let r,s;try{for(var a,l=!0,u=M(e);!(t=(a=yield k(u.next())).done);l=!0){i=a.value,l=!1;const e=i;[r,s]=wo(e,r,s),yield yield k(e)}}catch(c){n={error:c}}finally{try{l||t||!(o=u.return)||(yield k(o.call(u)))}finally{if(n)throw n.error}}"requires_continuation"===r&&s&&Oo()})}(t))}const u=async(e,t)=>Ks(ps(l,bo(r,e,t),o,Ys(a()))),c=await u();if(r.enableContinuation)return await async function(e,t,n={}){var o;const i=null!==(o=n.deadline)&&void 0!==o?o:new So(void 0),r=[e];let s=n.initialContinuationToken;for(;;){const e=Mo(r[r.length-1],s);if(!e)return Lo(r,n);let o;try{i.check(),o=await t(e,To(Eo(r[r.length-1],"id")))}catch(a){throw Go(a,r,e,n)}r.push(o),s=e}}(c,u,{initialContinuationToken:r.callerToken,normalizeInteraction:oa,finalizeInteraction:ra,deadline:s,store:!1!==r.body.store});const d=na(c);return r.callerToken||Do(d)&&Oo(),d}connect(e,t={},n){return G(),"webrtc"===t.transport||t.transport instanceof te?function(e,t,n={},o){return async function(e,t,n={},o){G();const{timeout:i,extraHeaders:r}=J(e,t,o);return async function(e,t,n,o){const i=new ee(t,n);try{const r=await n.connect(e,t,{onopen:()=>{},onerror:()=>i.handleTransportError(),onmessage:e=>i.handleMessage(null==e?void 0:e.data),onclose:e=>{var t;return i.handleClose(null!==(t=null==e?void 0:e.code)&&void 0!==t?t:1e3)}},{apiVersion:o.apiVersion,extraHeaders:o.extraHeaders,timeoutMs:o.timeoutMs});return i.attach(r),i}catch(r){if(i.detach(),r instanceof w||r instanceof U)throw r;throw new P({message:"Failed to complete WebRTC live setup."})}}(e,t,n.transport instanceof te?n.transport:new te,{apiVersion:n.api_version,extraHeaders:r,timeoutMs:i})}(e,t,n,o)}(this.parentClient,e,t,n):function(e,t,n,o={},i){return async function(e,t,n,o={},i,r){var s;G();const{timeout:a,extraHeaders:l}=J(e,n,i);if(!t)throw new U("Live Interactions WebSocket support requires a platform WebSocket factory.");const u=null===(s=e.getApiKey)||void 0===s?void 0:s.call(e),c=(null==u?void 0:u.startsWith("auth_tokens/"))?u:void 0,d=!1===t.supportsHeaders;if(d){if(void 0===c)throw new U("Browser WebSocket connections cannot send authentication headers; pass an auth token as apiKey to the GoogleGenAI client.");if(l&&Object.keys(l).length>0)throw new U("Browser WebSocket connections cannot send extra_headers.")}const p=d?c:void 0,m=function(e,t,n){var o;if(e.isVertexAI())throw new U("Live Interactions is currently Gemini API only.");const i=null===(o=e.getWebsocketBaseUrl)||void 0===o?void 0:o.call(e);if(!i)throw new U("WebSocket base URL is required.");const r=new URL(i),s=null!=t?t:e.getApiVersion();return r.pathname=`${r.pathname.replace(/\/+$/g,"")}/${s}/interactions/live`,void 0!==n&&r.searchParams.set("auth_token",n),r.toString()}(e,o.api_version,p);let h;try{h=await async function(e,t,n,o,i){const r=await $(e,t,n,{"api-revision":i});return void 0!==o&&(V(r,"authorization"),V(r,"x-goog-api-key")),r}(e,m,l,p,r)}catch(v){throw new R({message:"Live authentication setup failed.",httpStatus:H(v)})}const f=new K(n);await new Promise((e,n)=>{let o,i=!1,r=!1;const l=()=>{void 0!==o&&clearTimeout(o)},u=(e={closeCode:1006})=>{i||r||(r=!0,l(),n(new R({message:"WebSocket upgrade failed.",closeCode:e.closeCode,httpStatus:e.httpStatus})),f.detach())},c=t.create(m,h,{onopen:()=>{r||(i=!0,r=!0,l(),e())},onerror:e=>{if(i)f.handleTransportError();else{const t=H(e);u(void 0!==t?{httpStatus:t}:{closeCode:1006})}},onmessage:e=>f.handleMessage(null==e?void 0:e.data),onclose:e=>{const t="number"==typeof(null==e?void 0:e.code)?e.code:1006;i||u({closeCode:t}),f.handleClose(t)}});f.attach(c);try{o=setTimeout(()=>{u({closeCode:1006});try{c.close()}catch(s){}},a),c.connect();const e=c.ws;"blob"===(null==e?void 0:e.binaryType)&&(e.binaryType="arraybuffer")}catch(v){const t=H(v);u(void 0!==t?{httpStatus:t}:{closeCode:1006})}});try{return f.sendInitial({event_type:"interaction.connect",id:n}),f}catch(v){if(f.detach(),v instanceof w)throw v;throw new R({message:"Failed to send live setup."})}}(e,t,n,o,i,"2026-05-20")}(this.parentClient,this.webSocketFactory,e,t,n)}async get(e,t={},n){const{api_version:o,stream:i=!1,last_event_id:r,include_input:s}=null!=t?t:{};return!0===i?Zs(await zs(()=>this.getClient(o).interactions.get(e,{stream:i,last_event_id:r,include_input:s,api_version:o},Ys(n,!0)))):na(await Ks(ms(this.getClient(o),e,o,s,r,i,Ys(n))))}async delete(e,t={},n){return zs(()=>this.getClient(null==t?void 0:t.api_version).interactions.delete(e,{api_version:null==t?void 0:t.api_version},Ys(n)))}async cancel(e,t={},n){return na(await Ks(ds(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n))))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}},Js=class{constructor(e){this.parentClient=e}async create(e={},t){const n=null!=e?e:{},{api_version:o}=n,i=N(n,["api_version"]);return Ks(xr(this.getClient(o),i,o,Ys(t)))}async list(e={},t){const{api_version:n,page_size:o,page_token:i,parent:r}=null!=e?e:{};return Ks(Lr(this.getClient(n),n,o,i,r,Ys(t)))}async get(e,t={},n){return Ks(Ur(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async delete(e,t={},n){return Ks(Gr(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}},$s=class{constructor(e){this.parentClient=e}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(Ns(this.getClient(),o,n,Ys(t)))}async list(e={},t){const{api_version:n,page_size:o,page_token:i}=null!=e?e:{};return Ks(Ms(this.getClient(),n,o,i,Ys(t)))}async get(e,t={},n){return Ks(Ds(this.getClient(),e,null==t?void 0:t.api_version,Ys(n)))}async update(e,t={},n){const o=null!=t?t:{},{api_version:i,update_mask:r}=o,s=N(o,["api_version","update_mask"]);return Ks(Us(this.getClient(),e,s,i,r,Ys(n)))}async delete(e,t={},n){return Ks(ks(this.getClient(),e,null==t?void 0:t.api_version,Ys(n)))}async rotateSigningSecret(e,t={},n){const o=null!=t?t:{},{api_version:i}=o,r=N(o,["api_version"]);return Ks(Gs(this.getClient(),e,r,i,Ys(n)))}async ping(e,t=void 0,n){const{api_version:o,body:i}=null!=t?t:{};return Ks(xs(this.getClient(),e,o,i,Ys(n)))}getClient(){var e;return null!==(e=this.sdk)&&void 0!==e||(this.sdk=Xs(this.parentClient)),this.sdk}},Ws=class{constructor(e){this.parentClient=e}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(_s(this.getClient(n),o,n,Ys(t)))}async list(e={},t){const{api_version:n,filter:o,page_size:i,page_token:r}=null!=e?e:{};return Ks(As(this.getClient(n),n,o,i,r,Ys(t)))}async get(e,t={},n){return Ks(Es(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async update(e,t,n){const{api_version:o}=t,i=N(t,["api_version"]);return Ks(Cs(this.getClient(o),e,i,o,Ys(n)))}async delete(e,t={},n){return Ks(ys(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async run(e,t={},n){return Ks(Is(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async listExecutions(e,t={},n){const{api_version:o,page_size:i,page_token:r}=null!=t?t:{};return Ks(Ts(this.getClient(o),e,o,i,r,Ys(n)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}};function Ys(e,t=!1){var n,o,i,r;if(!e&&!t)return;const s=null!=e?e:{},{timeout:a,maxRetries:l,defaultBaseURL:u,query:c,body:d,fetchOptions:p}=s,m=N(s,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),h=Object.assign({},m);ia(c)&&(h.extra_query=c),ia(d)&&(h.extra_body=d);const f=null!==(n=m.fetch_options)&&void 0!==n?n:p;f&&(h.fetch_options=f);const v=null!==(o=m.server_url)&&void 0!==o?o:u;v&&(h.server_url=v);const g=null!==(i=m.timeout_ms)&&void 0!==i?i:a;if(void 0!==g&&(h.timeout_ms=g),void 0!==l&&(h.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries:l}),t){const e=new Headers(null!==(r=h.headers)&&void 0!==r?r:null==f?void 0:f.headers);e.set("Accept","text/event-stream"),h.headers=e}return h}async function Ks(e){const[t,n]=await e.$inspect();if(!t.ok)throw yi(t.error);return function(e,t){return ia(e)&&"complete"===t.status?Object.assign(Object.assign({},e),{sdkHttpResponse:ta(t.response,e)}):e}(t.value,n)}async function zs(e){try{return await e()}catch(t){throw yi(t)}}function Zs(e){const t=e;return new Proxy(e,{get(e,n){if(n!==Symbol.asyncIterator){const t=Reflect.get(e,n,e);return"function"==typeof t?t.bind(e):t}return function(){const e=t[Symbol.asyncIterator]();return{async next(...t){try{return await e.next(...t)}catch(n){throw yi(n)}},async return(t){if(!e.return)return{done:!0,value:t};try{return await e.return(t)}catch(n){throw yi(n)}},async throw(t){if(!e.throw)throw yi(t);try{return await e.throw(t)}catch(n){throw yi(n)}},[Symbol.asyncIterator](){return this}}}}})}function Qs(e){const t=yi(e);if(t instanceof O||t instanceof Co)return t;if(t instanceof Error&&"AbortError"===t.name)return new ui({message:t.message});const n=t instanceof Error?t.message:String(t);return new w({message:n,cause:t})}function ea(e){const t=e[Symbol.asyncIterator](),n=new ReadableStream({async pull(e){const n=await t.next();n.done?e.close():e.enqueue(n.value)},async cancel(){var e;await(null===(e=t.return)||void 0===e?void 0:e.call(t))}},{highWaterMark:0});return Object.setPrototypeOf(n,Si.prototype),n}function ta(e,t){const n={};for(const[o,i]of e.headers.entries())n[o]=i;return{headers:n,responseInternal:e,json:async()=>t}}function na(e){const t=oa(e);return t?ra(t):e}function oa(e){if(ia(e)){if(Array.isArray(e.steps))return e;if(function(e){const t=e.model;return"string"==typeof t&&Hs.has(t)}(e)){const t=e.outputs;if(Array.isArray(t)){const{outputs:n}=e,o=N(e,["outputs"]);return Object.assign(Object.assign({},o),{steps:[{type:"model_output",content:t}]})}}return Object.assign(Object.assign({},e),{steps:[]})}}function ia(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ra(e){var t,n;const o=function(e){return Object.assign(Object.assign({},e),{created:sa(e.created),updated:sa(e.updated)})}(e),i=null!==(t=o.steps)&&void 0!==t?t:[],r=[];let s,a,l,u=!1;e:for(let d=i.length-1;d>=0;d--){const e=i[d];if("user_input"===e.type)break;if("thought"===e.type)continue;if("model_output"!==e.type){if(u)break;continue}if(!e.content)continue;const t=e.content;for(let o=t.length-1;o>=0;o--){const e=t[o];if("text"===e.type)u=!0,r.push(null!==(n=e.text)&&void 0!==n?n:"");else if(u)break e}}for(let d=i.length-1;d>=0;d--){const e=i[d];if("user_input"===e.type)break;if("model_output"===e.type&&e.content)for(let t=e.content.length-1;t>=0;t--){const n=e.content[t];"image"!==n.type||s||(s=n),"audio"!==n.type||a||(a=n),"video"!==n.type||l||(l=n)}}const c=r.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},o),c&&{output_text:c}),s?{output_image:s}:{}),a?{output_audio:a}:{}),l?{output_video:l}:{})}function sa(e){return e instanceof Date?e.toISOString():e}var aa=class{constructor(e,t){this.resolveClient=e,this.parentClient=t}async list(e,t){return Ks(Zr(this.resolveClient(e.api_version),e.environment,e.path,e.api_version,e.page_size,e.page_token,e.recursive,Ys(t)))}async download(e,t){var n,o;const i=e.environment;if(!i)throw new Error("environment is required.");const r=`${i.startsWith("environments/")?i:`environments/${i}`}/files/${e.path.replace(/^\/+/,"")}`,s=this.parentClient;if(!s||"function"!=typeof s.request)throw new Error("apiClient is required to download files.");const a=await s.request({path:r,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:Object.assign(Object.assign({},null==t?void 0:t.httpOptions),{apiVersion:null!==(n=e.api_version)&&void 0!==n?n:null===(o=null==t?void 0:t.httpOptions)||void 0===o?void 0:o.apiVersion})});if(a&&a.responseInternal&&"function"==typeof a.responseInternal.arrayBuffer){const e=await a.responseInternal.arrayBuffer();return new Uint8Array(e)}throw new Error("Unexpected response type from download")}async upload(e,t){var n,o,i,r,s,a,l,u;const c=e.environment;if(!c)throw new Error("environment is required.");c.startsWith("environments/");const d=e.path.replace(/^\/+/,""),p=this.parentClient;if(!p||"function"!=typeof p.request)throw new Error("apiClient is required to upload files.");let m,h=0,f=e.mime_type;if("string"==typeof e.file){let t;try{const n=globalThis.require;n&&(t=n("fs").readFileSync(e.file))}catch(S){}if(!t&&void 0!==globalThis.process)try{const i=null!==(o=null===(n=globalThis.process.mainModule)||void 0===n?void 0:n.require)&&void 0!==o?o:globalThis.require;i&&(t=i("fs").readFileSync(e.file))}catch(b){}if(!t)throw new Error(`Unable to read file from path "${e.file}". File path string inputs are only supported in Node.js environments.`);m=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),h=m.byteLength,f||(f={txt:"text/plain",json:"application/json",js:"text/javascript",mjs:"text/javascript",ts:"text/plain",py:"text/x-python",html:"text/html",htm:"text/html",css:"text/css",csv:"text/csv",xml:"application/xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip"}[(v=e.file).slice(v.lastIndexOf(".")+1).toLowerCase()])}else if("undefined"!=typeof Blob&&e.file instanceof Blob)m=e.file,h=e.file.size,!f&&e.file.type&&(f=e.file.type);else if(e.file instanceof Uint8Array||e.file instanceof ArrayBuffer)m=e.file instanceof ArrayBuffer?new Uint8Array(e.file):e.file,h=m.byteLength;else{if(void 0===globalThis.Buffer||"function"!=typeof globalThis.Buffer.isBuffer||!globalThis.Buffer.isBuffer(e.file))throw new Error("Unsupported file type for upload.");{const t=e.file;m=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),h=m.byteLength}}var v;f||(f="application/octet-stream");const g=c.startsWith("environments/")?c.replace(/^environments\//,""):c,[_,y]=await es(this.resolveClient(e.api_version),g,d,"start",h,f,"resumable",e.api_version,e.extract,e.overwrite,Ys(t)).$inspect();if(!_.ok)throw yi(_.error);const E="complete"===y.status?null!==(s=null===(r=null===(i=y.response)||void 0===i?void 0:i.headers)||void 0===r?void 0:r.get("x-goog-upload-url"))&&void 0!==s?s:null===(l=null===(a=y.response)||void 0===a?void 0:a.headers)||void 0===l?void 0:l.get("X-Goog-Upload-URL"):void 0;if(!E)throw new Error("Failed to get upload URL from upload handshake response.");let T,A=0;const I=m instanceof Blob?m:new Blob([m]);for(;A<h||0===h&&0===A;){const e=Math.min(A+8388608,h),n=I.slice(A,e),o=e>=h,i=o?"upload, finalize":"upload";if(T=await p.request({path:"",body:n,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},null==t?void 0:t.httpOptions),{apiVersion:"",baseUrl:E,headers:Object.assign(Object.assign({},(null===(u=null==t?void 0:t.httpOptions)||void 0===u?void 0:u.headers)||{}),{"X-Goog-Upload-Command":i,"X-Goog-Upload-Offset":`${A}`})})}),A=e,o)break}let C;if(T&&"function"==typeof T.json?C=await T.json():T&&T.responseInternal&&"function"==typeof T.responseInternal.json&&(C=await T.responseInternal.json()),C&&"object"==typeof C){if(Array.isArray(C.files))return C;if(C.name||C.path)return{files:[C]};if(C.file&&"object"==typeof C.file)return{files:[C.file]}}return C}},la=class{constructor(e){this.parentClient=e,this.files=new aa(e=>this.getClient(e),this.parentClient)}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(Wr(this.getClient(n),o,n,Ys(t)))}async list(e={},t){const{api_version:n,mode:o,page_size:i,page_token:r}=null!=e?e:{};return Ks(zr(this.getClient(n),n,o,i,r,Ys(t)))}async get(e,t={},n){return Ks(Kr(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async delete(e,t={},n){return Ks(Yr(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}},ua=class{constructor(e){this.parentClient=e}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(Hr(this.getClient(n),o,n,Ys(t)))}async list(e={},t){const{api_version:n,page_size:o,page_token:i}=null!=e?e:{};return Ks(Xr(this.getClient(n),n,o,i,Ys(t)))}async get(e,t={},n){return Ks(Fr(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async update(e,t,n){const{api_version:o,update_mask:i}=t,r=N(t,["api_version","update_mask"]);return Ks(Br(this.getClient(o),e,r,o,i,Ys(n)))}async delete(e,t={},n){return Ks(jr(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}},ca=class{constructor(e){this.parentClient=e}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(bs(this.getClient(n),o,n,Ys(t)))}async list(e={},t){const{api_version:n,accent:o,contexts:i,gender:r,language_code:s,page_size:a,page_token:l,persona:u,pitch:c,region_code:d,search:p,type:m}=null!=e?e:{};return Ks(Rs(this.getClient(n),n,o,i,r,s,a,l,u,c,d,p,m,Ys(t)))}async get(e,t={},n){return Ks(ws(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}async delete(e,t={},n){return Ks(Os(this.getClient(null==t?void 0:t.api_version),e,null==t?void 0:t.api_version,Ys(n)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}},da=class{constructor(e){this.parentClient=e}async create(e,t){const{api_version:n}=e,o=N(e,["api_version"]);return Ks(Jr(this.getClient(n),o,n,Ys(t)))}getClient(e){var t;return e?Xs(this.parentClient,{api_version:e}):(null!==(t=this.sdk)&&void 0!==t||(this.sdk=Xs(this.parentClient)),this.sdk)}};function pa(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);null!=n&&Nt(t,["mediaResolution"],n);const o=kt(e,["toolCall"]);null!=o&&Nt(t,["toolCall"],o);const i=kt(e,["toolResponse"]);null!=i&&Nt(t,["toolResponse"],i);const r=kt(e,["audioTranscription"]);null!=r&&Nt(t,["audioTranscription"],r);const s=kt(e,["codeExecutionResult"]);null!=s&&Nt(t,["codeExecutionResult"],s);const a=kt(e,["executableCode"]);null!=a&&Nt(t,["executableCode"],a);const l=kt(e,["fileData"]);null!=l&&Nt(t,["fileData"],l);const u=kt(e,["functionCall"]);null!=u&&Nt(t,["functionCall"],function(e){const t={},n=kt(e,["args"]);null!=n&&Nt(t,["args"],n);const o=kt(e,["id"]);null!=o&&Nt(t,["id"],o);const i=kt(e,["name"]);if(null!=i&&Nt(t,["name"],i),void 0!==kt(e,["partialArgs"]))throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(u));const c=kt(e,["functionResponse"]);null!=c&&Nt(t,["functionResponse"],c);const d=kt(e,["inlineData"]);null!=d&&Nt(t,["inlineData"],d);const p=kt(e,["text"]);null!=p&&Nt(t,["text"],p);const m=kt(e,["thought"]);null!=m&&Nt(t,["thought"],m);const h=kt(e,["thoughtSignature"]);null!=h&&Nt(t,["thoughtSignature"],h);const f=kt(e,["videoMetadata"]);null!=f&&Nt(t,["videoMetadata"],f);const v=kt(e,["partMetadata"]);null!=v&&Nt(t,["partMetadata"],v);const g=kt(e,["mediaProcessing"]);null!=g&&Nt(t,["mediaProcessing"],g);const _=kt(e,["speechMetadata"]);null!=_&&Nt(t,["speechMetadata"],_);const y=kt(e,["documentMetadata"]);null!=y&&Nt(t,["documentMetadata"],y);const E=kt(e,["spreadsheetMetadata"]);null!=E&&Nt(t,["spreadsheetMetadata"],E);const T=kt(e,["audioMetadata"]);return null!=T&&Nt(t,["audioMetadata"],T),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}function ma(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);if(null!=n&&Nt(t,["mediaResolution"],n),void 0!==kt(e,["toolCall"]))throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["toolResponse"]))throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=kt(e,["audioTranscription"]);null!=o&&Nt(t,["audioTranscription"],o);const i=kt(e,["codeExecutionResult"]);null!=i&&Nt(t,["codeExecutionResult"],i);const r=kt(e,["executableCode"]);null!=r&&Nt(t,["executableCode"],r);const s=kt(e,["fileData"]);null!=s&&Nt(t,["fileData"],s);const a=kt(e,["functionCall"]);null!=a&&Nt(t,["functionCall"],a);const l=kt(e,["functionResponse"]);null!=l&&Nt(t,["functionResponse"],function(e){const t={},n=kt(e,["id"]);null!=n&&Nt(t,["id"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["parts"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["fileData"]);null!=n&&Nt(t,["fileData"],n);const o=kt(e,["inlineData"]);if(null!=o&&Nt(t,["inlineData"],o),void 0!==kt(e,["mediaProcessing"]))throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const i=kt(e,["mediaResolution"]);null!=i&&Nt(t,["mediaResolution"],i);const r=kt(e,["videoMetadata"]);null!=r&&Nt(t,["videoMetadata"],r);const s=kt(e,["documentMetadata"]);null!=s&&Nt(t,["documentMetadata"],s);const a=kt(e,["spreadsheetMetadata"]);null!=a&&Nt(t,["spreadsheetMetadata"],a);const l=kt(e,["audioMetadata"]);return null!=l&&Nt(t,["audioMetadata"],l),t}(e))),Nt(t,["parts"],e)}const r=kt(e,["response"]);null!=r&&Nt(t,["response"],r);const s=kt(e,["scheduling"]);if(null!=s&&Nt(t,["scheduling"],s),void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(l));const u=kt(e,["inlineData"]);null!=u&&Nt(t,["inlineData"],u);const c=kt(e,["text"]);null!=c&&Nt(t,["text"],c);const d=kt(e,["thought"]);null!=d&&Nt(t,["thought"],d);const p=kt(e,["thoughtSignature"]);null!=p&&Nt(t,["thoughtSignature"],p);const m=kt(e,["videoMetadata"]);if(null!=m&&Nt(t,["videoMetadata"],m),void 0!==kt(e,["partMetadata"]))throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const h=kt(e,["mediaProcessing"]);null!=h&&Nt(t,["mediaProcessing"],h);const f=kt(e,["speechMetadata"]);null!=f&&Nt(t,["speechMetadata"],f);const v=kt(e,["documentMetadata"]);null!=v&&Nt(t,["documentMetadata"],v);const g=kt(e,["spreadsheetMetadata"]);null!=g&&Nt(t,["spreadsheetMetadata"],g);const _=kt(e,["audioMetadata"]);return null!=_&&Nt(t,["audioMetadata"],_),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}function ha(e){const t={},n=kt(e,["systemInstruction"]);null!=n&&Nt(t,["systemInstruction"],pa(On(n)));const o=kt(e,["tools"]);return null!=o&&Nt(t,["tools"],function(e){const t={},n=kt(e,["tools"]);if(null!=n){let e=xn(n);Array.isArray(e)&&(e=e.map(e=>ya(Mn(e)))),Nt(t,["tools"],e)}return t}(o)),t}function fa(e){const t={},n=kt(e,["systemInstruction"]);null!=n&&Nt(t,["systemInstruction"],ma(On(n)));const o=kt(e,["tools"]);return null!=o&&Nt(t,["tools"],function(e){const t={},n=kt(e,["tools"]);if(null!=n){let e=xn(n);Array.isArray(e)&&(e=e.map(e=>Ea(Mn(e)))),Nt(t,["tools"],e)}return t}(o)),t}function va(e){const t={},n=kt(e,["media"]);if(null!=n){let e=_n(n);Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mediaChunks"],e)}const o=kt(e,["audio"]);null!=o&&Nt(t,["audio"],Tn(o));const i=kt(e,["audioStreamEnd"]);null!=i&&Nt(t,["audioStreamEnd"],i);const r=kt(e,["video"]);null!=r&&Nt(t,["video"],En(r));const s=kt(e,["text"]);null!=s&&Nt(t,["text"],s);const a=kt(e,["activityStart"]);null!=a&&Nt(t,["activityStart"],a);const l=kt(e,["activityEnd"]);return null!=l&&Nt(t,["activityEnd"],l),t}function ga(e){const t={},n=kt(e,["media"]);if(null!=n){let e=_n(n);Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mediaChunks"],e)}const o=kt(e,["audio"]);null!=o&&Nt(t,["audio"],Tn(o));const i=kt(e,["audioStreamEnd"]);null!=i&&Nt(t,["audioStreamEnd"],i);const r=kt(e,["video"]);null!=r&&Nt(t,["video"],En(r));const s=kt(e,["text"]);null!=s&&Nt(t,["text"],s);const a=kt(e,["activityStart"]);null!=a&&Nt(t,["activityStart"],a);const l=kt(e,["activityEnd"]);return null!=l&&Nt(t,["activityEnd"],l),t}function _a(e){const t={},n=kt(e,["voiceConfig"]);null!=n&&Nt(t,["voiceConfig"],Ta(n));const o=kt(e,["languageCode"]);null!=o&&Nt(t,["languageCode"],o);const i=kt(e,["multiSpeakerVoiceConfig"]);return null!=i&&Nt(t,["multiSpeakerVoiceConfig"],function(e){const t={},n=kt(e,["speakerVoiceConfigs"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["speaker"]);null!=n&&Nt(t,["speaker"],n);const o=kt(e,["voiceConfig"]);return null!=o&&Nt(t,["voiceConfig"],Ta(o)),t}(e))),Nt(t,["speakerVoiceConfigs"],e)}return t}(i)),t}function ya(e){const t={};if(void 0!==kt(e,["retrieval"]))throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["googleMaps"]);null!=n&&Nt(t,["googleMaps"],function(e){const t={},n=kt(e,["authConfig"]);null!=n&&Nt(t,["authConfig"],function(e){const t={},n=kt(e,["apiKey"]);if(null!=n&&Nt(t,["apiKey"],n),void 0!==kt(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["authType"]))throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oauthConfig"]))throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oidcConfig"]))throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["enableWidget"]);if(null!=o&&Nt(t,["enableWidget"],o),void 0!==kt(e,["groundingTypes"]))throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["mcpServers"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mcpServers"],e)}const i=kt(e,["codeExecution"]);null!=i&&Nt(t,["codeExecution"],i);const r=kt(e,["computerUse"]);if(null!=r&&Nt(t,["computerUse"],r),void 0!==kt(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["exaAiSearch"]))throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const a=kt(e,["googleSearch"]);null!=a&&Nt(t,["googleSearch"],function(e){const t={};if(void 0!==kt(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["excludeDomains"]))throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["searchTypes"]);null!=n&&Nt(t,["searchTypes"],n);const o=kt(e,["timeRangeFilter"]);return null!=o&&Nt(t,["timeRangeFilter"],o),t}(a));const l=kt(e,["googleSearchRetrieval"]);if(null!=l&&Nt(t,["googleSearchRetrieval"],l),void 0!==kt(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=kt(e,["urlContext"]);null!=u&&Nt(t,["urlContext"],u);const c=kt(e,["fileSearch"]);return null!=c&&Nt(t,["fileSearch"],c),t}function Ea(e){const t={},n=kt(e,["retrieval"]);null!=n&&Nt(t,["retrieval"],n);const o=kt(e,["googleMaps"]);null!=o&&Nt(t,["googleMaps"],o);const i=kt(e,["mcpServers"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){if(void 0!==kt(e,["name"]))throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["streamableHttpTransport"]))throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}(e))),Nt(t,["mcpServers"],e)}const r=kt(e,["codeExecution"]);null!=r&&Nt(t,["codeExecution"],r);const s=kt(e,["computerUse"]);null!=s&&Nt(t,["computerUse"],s);const a=kt(e,["enterpriseWebSearch"]);null!=a&&Nt(t,["enterpriseWebSearch"],a);const l=kt(e,["exaAiSearch"]);null!=l&&Nt(t,["exaAiSearch"],l);const u=kt(e,["functionDeclarations"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const c=kt(e,["googleSearch"]);null!=c&&Nt(t,["googleSearch"],c);const d=kt(e,["googleSearchRetrieval"]);null!=d&&Nt(t,["googleSearchRetrieval"],d);const p=kt(e,["parallelAiSearch"]);null!=p&&Nt(t,["parallelAiSearch"],p);const m=kt(e,["urlContext"]);if(null!=m&&Nt(t,["urlContext"],m),void 0!==kt(e,["fileSearch"]))throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}function Ta(e){const t={},n=kt(e,["replicatedVoiceConfig"]);null!=n&&Nt(t,["replicatedVoiceConfig"],function(e){const t={},n=kt(e,["mimeType"]);null!=n&&Nt(t,["mimeType"],n);const o=kt(e,["voiceSampleAudio"]);if(null!=o&&Nt(t,["voiceSampleAudio"],o),void 0!==kt(e,["consentAudio"]))throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["voiceConsentSignature"]))throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(n));const o=kt(e,["prebuiltVoiceConfig"]);null!=o&&Nt(t,["prebuiltVoiceConfig"],o);const i=kt(e,["voice"]);return null!=i&&Nt(t,["voice"],i),t}function Aa(e,t){const n={},o=kt(e,["values"]);null!=o&&Nt(n,["values"],o);const i=kt(e,["statistics"]);return null!=i&&Nt(n,["statistics"],function(e){const t={},n=kt(e,["truncated"]);null!=n&&Nt(t,["truncated"],n);const o=kt(e,["token_count"]);null!=o&&Nt(t,["tokenCount"],o);const i=kt(e,["tokensDetails"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["tokensDetails"],e)}return t}(i)),n}function Ia(e,t){const n={},o=kt(e,["parts"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);null!=n&&Nt(t,["mediaResolution"],n);const o=kt(e,["toolCall"]);null!=o&&Nt(t,["toolCall"],o);const i=kt(e,["toolResponse"]);null!=i&&Nt(t,["toolResponse"],i);const r=kt(e,["audioTranscription"]);null!=r&&Nt(t,["audioTranscription"],r);const s=kt(e,["codeExecutionResult"]);null!=s&&Nt(t,["codeExecutionResult"],s);const a=kt(e,["executableCode"]);null!=a&&Nt(t,["executableCode"],a);const l=kt(e,["fileData"]);null!=l&&Nt(t,["fileData"],l);const u=kt(e,["functionCall"]);null!=u&&Nt(t,["functionCall"],function(e){const t={},n=kt(e,["args"]);null!=n&&Nt(t,["args"],n);const o=kt(e,["id"]);null!=o&&Nt(t,["id"],o);const i=kt(e,["name"]);if(null!=i&&Nt(t,["name"],i),void 0!==kt(e,["partialArgs"]))throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(u));const c=kt(e,["functionResponse"]);null!=c&&Nt(t,["functionResponse"],c);const d=kt(e,["inlineData"]);null!=d&&Nt(t,["inlineData"],d);const p=kt(e,["text"]);null!=p&&Nt(t,["text"],p);const m=kt(e,["thought"]);null!=m&&Nt(t,["thought"],m);const h=kt(e,["thoughtSignature"]);null!=h&&Nt(t,["thoughtSignature"],h);const f=kt(e,["videoMetadata"]);null!=f&&Nt(t,["videoMetadata"],f);const v=kt(e,["partMetadata"]);null!=v&&Nt(t,["partMetadata"],v);const g=kt(e,["mediaProcessing"]);null!=g&&Nt(t,["mediaProcessing"],g);const _=kt(e,["speechMetadata"]);null!=_&&Nt(t,["speechMetadata"],_);const y=kt(e,["documentMetadata"]);null!=y&&Nt(t,["documentMetadata"],y);const E=kt(e,["spreadsheetMetadata"]);null!=E&&Nt(t,["spreadsheetMetadata"],E);const T=kt(e,["audioMetadata"]);return null!=T&&Nt(t,["audioMetadata"],T),t}(e))),Nt(n,["parts"],e)}const i=kt(e,["role"]);return null!=i&&Nt(n,["role"],i),n}function Ca(e,t){const n={},o=kt(e,["parts"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);if(null!=n&&Nt(t,["mediaResolution"],n),void 0!==kt(e,["toolCall"]))throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["toolResponse"]))throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=kt(e,["audioTranscription"]);null!=o&&Nt(t,["audioTranscription"],o);const i=kt(e,["codeExecutionResult"]);null!=i&&Nt(t,["codeExecutionResult"],i);const r=kt(e,["executableCode"]);null!=r&&Nt(t,["executableCode"],r);const s=kt(e,["fileData"]);null!=s&&Nt(t,["fileData"],s);const a=kt(e,["functionCall"]);null!=a&&Nt(t,["functionCall"],a);const l=kt(e,["functionResponse"]);null!=l&&Nt(t,["functionResponse"],function(e){const t={},n=kt(e,["id"]);null!=n&&Nt(t,["id"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["parts"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["fileData"]);null!=n&&Nt(t,["fileData"],n);const o=kt(e,["inlineData"]);if(null!=o&&Nt(t,["inlineData"],o),void 0!==kt(e,["mediaProcessing"]))throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const i=kt(e,["mediaResolution"]);null!=i&&Nt(t,["mediaResolution"],i);const r=kt(e,["videoMetadata"]);null!=r&&Nt(t,["videoMetadata"],r);const s=kt(e,["documentMetadata"]);null!=s&&Nt(t,["documentMetadata"],s);const a=kt(e,["spreadsheetMetadata"]);null!=a&&Nt(t,["spreadsheetMetadata"],a);const l=kt(e,["audioMetadata"]);return null!=l&&Nt(t,["audioMetadata"],l),t}(e))),Nt(t,["parts"],e)}const r=kt(e,["response"]);null!=r&&Nt(t,["response"],r);const s=kt(e,["scheduling"]);if(null!=s&&Nt(t,["scheduling"],s),void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(l));const u=kt(e,["inlineData"]);null!=u&&Nt(t,["inlineData"],u);const c=kt(e,["text"]);null!=c&&Nt(t,["text"],c);const d=kt(e,["thought"]);null!=d&&Nt(t,["thought"],d);const p=kt(e,["thoughtSignature"]);null!=p&&Nt(t,["thoughtSignature"],p);const m=kt(e,["videoMetadata"]);if(null!=m&&Nt(t,["videoMetadata"],m),void 0!==kt(e,["partMetadata"]))throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const h=kt(e,["mediaProcessing"]);null!=h&&Nt(t,["mediaProcessing"],h);const f=kt(e,["speechMetadata"]);null!=f&&Nt(t,["speechMetadata"],f);const v=kt(e,["documentMetadata"]);null!=v&&Nt(t,["documentMetadata"],v);const g=kt(e,["spreadsheetMetadata"]);null!=g&&Nt(t,["spreadsheetMetadata"],g);const _=kt(e,["audioMetadata"]);return null!=_&&Nt(t,["audioMetadata"],_),t}(e))),Nt(n,["parts"],e)}const i=kt(e,["role"]);return null!=i&&Nt(n,["role"],i),n}function Sa(e,t,n){const o={},i=kt(t,["model"]);null!=i&&Nt(o,["_url","model"],vn(e,i));const r=kt(t,["contents"]);if(null!=r){let e=Rn(r);Array.isArray(e)&&(e=e.map(e=>Ia(e))),Nt(o,["contents"],e)}const s=kt(t,["config"]);return null!=s&&Nt(o,["generationConfig"],function(e,t,n){const o={},i=kt(t,["serviceTier"]);void 0!==n&&null!=i&&Nt(n,["serviceTier"],i);const r=kt(t,["systemInstruction"]);void 0!==n&&null!=r&&Nt(n,["systemInstruction"],Ia(On(r)));const s=kt(t,["temperature"]);null!=s&&Nt(o,["temperature"],s);const a=kt(t,["topP"]);null!=a&&Nt(o,["topP"],a);const l=kt(t,["topK"]);null!=l&&Nt(o,["topK"],l);const u=kt(t,["candidateCount"]);null!=u&&Nt(o,["candidateCount"],u);const c=kt(t,["maxOutputTokens"]);null!=c&&Nt(o,["maxOutputTokens"],c);const d=kt(t,["stopSequences"]);null!=d&&Nt(o,["stopSequences"],d);const p=kt(t,["responseLogprobs"]);null!=p&&Nt(o,["responseLogprobs"],p);const m=kt(t,["logprobs"]);null!=m&&Nt(o,["logprobs"],m);const h=kt(t,["presencePenalty"]);null!=h&&Nt(o,["presencePenalty"],h);const f=kt(t,["frequencyPenalty"]);null!=f&&Nt(o,["frequencyPenalty"],f);const v=kt(t,["seed"]);null!=v&&Nt(o,["seed"],v);const g=kt(t,["responseMimeType"]);null!=g&&Nt(o,["responseMimeType"],g);const _=kt(t,["responseSchema"]);null!=_&&Nt(o,["responseSchema"],Nn(_));const y=kt(t,["responseJsonSchema"]);if(null!=y&&Nt(o,["responseJsonSchema"],y),void 0!==kt(t,["routingConfig"]))throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(t,["modelSelectionConfig"]))throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const E=kt(t,["safetySettings"]);if(void 0!==n&&null!=E){let e=E;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["category"]);if(null!=n&&Nt(t,["category"],n),void 0!==kt(e,["method"]))throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["threshold"]);return null!=o&&Nt(t,["threshold"],o),t}(e))),Nt(n,["safetySettings"],e)}const T=kt(t,["tools"]);if(void 0!==n&&null!=T){let e=xn(T);Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==kt(e,["retrieval"]))throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["googleMaps"]);null!=n&&Nt(t,["googleMaps"],function(e){const t={},n=kt(e,["authConfig"]);null!=n&&Nt(t,["authConfig"],function(e){const t={},n=kt(e,["apiKey"]);if(null!=n&&Nt(t,["apiKey"],n),void 0!==kt(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["authType"]))throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oauthConfig"]))throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oidcConfig"]))throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["enableWidget"]);if(null!=o&&Nt(t,["enableWidget"],o),void 0!==kt(e,["groundingTypes"]))throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["mcpServers"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mcpServers"],e)}const i=kt(e,["codeExecution"]);null!=i&&Nt(t,["codeExecution"],i);const r=kt(e,["computerUse"]);if(null!=r&&Nt(t,["computerUse"],r),void 0!==kt(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["exaAiSearch"]))throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const a=kt(e,["googleSearch"]);null!=a&&Nt(t,["googleSearch"],function(e){const t={};if(void 0!==kt(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["excludeDomains"]))throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["searchTypes"]);null!=n&&Nt(t,["searchTypes"],n);const o=kt(e,["timeRangeFilter"]);return null!=o&&Nt(t,["timeRangeFilter"],o),t}(a));const l=kt(e,["googleSearchRetrieval"]);if(null!=l&&Nt(t,["googleSearchRetrieval"],l),void 0!==kt(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=kt(e,["urlContext"]);null!=u&&Nt(t,["urlContext"],u);const c=kt(e,["fileSearch"]);return null!=c&&Nt(t,["fileSearch"],c),t}(Mn(e)))),Nt(n,["tools"],e)}const A=kt(t,["toolConfig"]);void 0!==n&&null!=A&&Nt(n,["toolConfig"],function(e){const t={},n=kt(e,["functionCallingConfig"]);null!=n&&Nt(t,["functionCallingConfig"],function(e){const t={},n=kt(e,["allowedFunctionNames"]);null!=n&&Nt(t,["allowedFunctionNames"],n);const o=kt(e,["mode"]);if(null!=o&&Nt(t,["mode"],o),void 0!==kt(e,["streamFunctionCallArguments"]))throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["retrievalConfig"]);null!=o&&Nt(t,["retrievalConfig"],o);const i=kt(e,["includeServerSideToolInvocations"]);return null!=i&&Nt(t,["includeServerSideToolInvocations"],i),t}(A));const I=kt(t,["labels"]);void 0!==n&&null!=I&&Nt(n,["labels"],I);const C=kt(t,["cachedContent"]);void 0!==n&&null!=C&&Nt(n,["cachedContent"],Gn(e,C));const S=kt(t,["responseModalities"]);null!=S&&Nt(o,["responseModalities"],S);const b=kt(t,["mediaResolution"]);null!=b&&Nt(o,["mediaResolution"],b);const O=kt(t,["speechConfig"]);if(null!=O&&Nt(o,["speechConfig"],kn(O)),void 0!==kt(t,["audioTimestamp"]))throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const w=kt(t,["thinkingConfig"]);null!=w&&Nt(o,["thinkingConfig"],w);const R=kt(t,["audioTranscriptionConfig"]);null!=R&&Nt(o,["audioTranscriptionConfig"],R);const P=kt(t,["imageConfig"]);null!=P&&Nt(o,["imageConfig"],function(e){const t={},n=kt(e,["aspectRatio"]);null!=n&&Nt(t,["aspectRatio"],n);const o=kt(e,["imageSize"]);if(null!=o&&Nt(t,["imageSize"],o),void 0!==kt(e,["personGeneration"]))throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["outputMimeType"]))throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["outputCompressionQuality"]))throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["imageOutputOptions"]))throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["prominentPeople"]))throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(P));const N=kt(t,["enableEnhancedCivicAnswers"]);if(null!=N&&Nt(o,["enableEnhancedCivicAnswers"],N),void 0!==kt(t,["modelArmorConfig"]))throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const k=kt(t,["continuationToken"]);if(void 0!==n&&null!=k&&Nt(n,["continuationToken"],k),void 0!==kt(t,["generationOutputConfig"]))throw new Error("generationOutputConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const D=kt(t,["store"]);return void 0!==n&&null!=D&&Nt(n,["store"],D),o}(e,s,o)),o}function ba(e,t,n){const o={},i=kt(t,["model"]);null!=i&&Nt(o,["_url","model"],vn(e,i));const r=kt(t,["contents"]);if(null!=r){let e=Rn(r);Array.isArray(e)&&(e=e.map(e=>Ca(e))),Nt(o,["contents"],e)}const s=kt(t,["config"]);return null!=s&&Nt(o,["generationConfig"],function(e,t,n){const o={},i=kt(t,["serviceTier"]);void 0!==n&&null!=i&&Nt(n,["serviceTier"],i);const r=kt(t,["systemInstruction"]);void 0!==n&&null!=r&&Nt(n,["systemInstruction"],Ca(On(r)));const s=kt(t,["temperature"]);null!=s&&Nt(o,["temperature"],s);const a=kt(t,["topP"]);null!=a&&Nt(o,["topP"],a);const l=kt(t,["topK"]);null!=l&&Nt(o,["topK"],l);const u=kt(t,["candidateCount"]);null!=u&&Nt(o,["candidateCount"],u);const c=kt(t,["maxOutputTokens"]);null!=c&&Nt(o,["maxOutputTokens"],c);const d=kt(t,["stopSequences"]);null!=d&&Nt(o,["stopSequences"],d);const p=kt(t,["responseLogprobs"]);null!=p&&Nt(o,["responseLogprobs"],p);const m=kt(t,["logprobs"]);null!=m&&Nt(o,["logprobs"],m);const h=kt(t,["presencePenalty"]);null!=h&&Nt(o,["presencePenalty"],h);const f=kt(t,["frequencyPenalty"]);null!=f&&Nt(o,["frequencyPenalty"],f);const v=kt(t,["seed"]);null!=v&&Nt(o,["seed"],v);const g=kt(t,["responseMimeType"]);null!=g&&Nt(o,["responseMimeType"],g);const _=kt(t,["responseSchema"]);null!=_&&Nt(o,["responseSchema"],Nn(_));const y=kt(t,["responseJsonSchema"]);null!=y&&Nt(o,["responseJsonSchema"],y);const E=kt(t,["routingConfig"]);null!=E&&Nt(o,["routingConfig"],E);const T=kt(t,["modelSelectionConfig"]);null!=T&&Nt(o,["modelConfig"],T);const A=kt(t,["safetySettings"]);if(void 0!==n&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>e)),Nt(n,["safetySettings"],e)}const I=kt(t,["tools"]);if(void 0!==n&&null!=I){let e=xn(I);Array.isArray(e)&&(e=e.map(e=>Ua(Mn(e)))),Nt(n,["tools"],e)}const C=kt(t,["toolConfig"]);void 0!==n&&null!=C&&Nt(n,["toolConfig"],function(e){const t={},n=kt(e,["functionCallingConfig"]);null!=n&&Nt(t,["functionCallingConfig"],n);const o=kt(e,["retrievalConfig"]);if(null!=o&&Nt(t,["retrievalConfig"],o),void 0!==kt(e,["includeServerSideToolInvocations"]))throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(C));const S=kt(t,["labels"]);void 0!==n&&null!=S&&Nt(n,["labels"],S);const b=kt(t,["cachedContent"]);void 0!==n&&null!=b&&Nt(n,["cachedContent"],Gn(e,b));const O=kt(t,["responseModalities"]);null!=O&&Nt(o,["responseModalities"],O);const w=kt(t,["mediaResolution"]);null!=w&&Nt(o,["mediaResolution"],w);const R=kt(t,["speechConfig"]);null!=R&&Nt(o,["speechConfig"],Ga(kn(R)));const P=kt(t,["audioTimestamp"]);null!=P&&Nt(o,["audioTimestamp"],P);const N=kt(t,["thinkingConfig"]);null!=N&&Nt(o,["thinkingConfig"],N);const k=kt(t,["audioTranscriptionConfig"]);null!=k&&Nt(o,["audioTranscriptionConfig"],k);const D=kt(t,["imageConfig"]);if(null!=D&&Nt(o,["imageConfig"],function(e){const t={},n=kt(e,["aspectRatio"]);null!=n&&Nt(t,["aspectRatio"],n);const o=kt(e,["imageSize"]);null!=o&&Nt(t,["imageSize"],o);const i=kt(e,["personGeneration"]);null!=i&&Nt(t,["personGeneration"],i);const r=kt(e,["outputMimeType"]);null!=r&&Nt(t,["imageOutputOptions","mimeType"],r);const s=kt(e,["outputCompressionQuality"]);null!=s&&Nt(t,["imageOutputOptions","compressionQuality"],s);const a=kt(e,["imageOutputOptions"]);null!=a&&Nt(t,["imageOutputOptions"],a);const l=kt(e,["prominentPeople"]);return null!=l&&Nt(t,["prominentPeople"],l),t}(D)),void 0!==kt(t,["enableEnhancedCivicAnswers"]))throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const M=kt(t,["modelArmorConfig"]);void 0!==n&&null!=M&&Nt(n,["modelArmorConfig"],M);const x=kt(t,["continuationToken"]);void 0!==n&&null!=x&&Nt(n,["continuationToken"],x);const G=kt(t,["generationOutputConfig"]);if(void 0!==n&&null!=G&&Nt(n,["outputConfig"],G),void 0!==kt(t,["store"]))throw new Error("store parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return o}(e,s,o)),o}function Oa(e,t){const n={},o=kt(e,["sdkHttpResponse"]);null!=o&&Nt(n,["sdkHttpResponse"],o);const i=kt(e,["candidates"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["content"]);null!=n&&Nt(t,["content"],n);const o=kt(e,["citationMetadata"]);null!=o&&Nt(t,["citationMetadata"],function(e){const t={},n=kt(e,["citationSources"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["citations"],e)}return t}(o));const i=kt(e,["tokenCount"]);null!=i&&Nt(t,["tokenCount"],i);const r=kt(e,["finishReason"]);null!=r&&Nt(t,["finishReason"],r);const s=kt(e,["groundingMetadata"]);null!=s&&Nt(t,["groundingMetadata"],s);const a=kt(e,["avgLogprobs"]);null!=a&&Nt(t,["avgLogprobs"],a);const l=kt(e,["index"]);null!=l&&Nt(t,["index"],l);const u=kt(e,["logprobsResult"]);null!=u&&Nt(t,["logprobsResult"],u);const c=kt(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["safetyRatings"],e)}const d=kt(e,["urlContextMetadata"]);null!=d&&Nt(t,["urlContextMetadata"],d);const p=kt(e,["continuationToken"]);return null!=p&&Nt(t,["continuationToken"],p),t}(e))),Nt(n,["candidates"],e)}const r=kt(e,["modelVersion"]);null!=r&&Nt(n,["modelVersion"],r);const s=kt(e,["promptFeedback"]);null!=s&&Nt(n,["promptFeedback"],s);const a=kt(e,["responseId"]);null!=a&&Nt(n,["responseId"],a);const l=kt(e,["usageMetadata"]);null!=l&&Nt(n,["usageMetadata"],l);const u=kt(e,["modelStatus"]);return null!=u&&Nt(n,["modelStatus"],u),n}function wa(e,t){const n={},o=kt(e,["sdkHttpResponse"]);null!=o&&Nt(n,["sdkHttpResponse"],o);const i=kt(e,["candidates"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(n,["candidates"],e)}const r=kt(e,["createTime"]);null!=r&&Nt(n,["createTime"],r);const s=kt(e,["modelVersion"]);null!=s&&Nt(n,["modelVersion"],s);const a=kt(e,["promptFeedback"]);null!=a&&Nt(n,["promptFeedback"],a);const l=kt(e,["responseId"]);null!=l&&Nt(n,["responseId"],l);const u=kt(e,["usageMetadata"]);return null!=u&&Nt(n,["usageMetadata"],u),n}function Ra(e,t,n){const o={},i=kt(t,["model"]);null!=i&&Nt(o,["_url","model"],vn(e,i));const r=kt(t,["prompt"]);null!=r&&Nt(o,["instances[0]","prompt"],r);const s=kt(t,["image"]);null!=s&&Nt(o,["instances[0]","image"],ka(s));const a=kt(t,["video"]);null!=a&&Nt(o,["instances[0]","video"],La(a));const l=kt(t,["source"]);null!=l&&function(e,t){const n=kt(e,["prompt"]);void 0!==t&&null!=n&&Nt(t,["instances[0]","prompt"],n);const o=kt(e,["image"]);void 0!==t&&null!=o&&Nt(t,["instances[0]","image"],ka(o));const i=kt(e,["video"]);void 0!==t&&null!=i&&Nt(t,["instances[0]","video"],La(i))}(l,o);const u=kt(t,["config"]);return null!=u&&function(e,t){const n=kt(e,["numberOfVideos"]);void 0!==t&&null!=n&&Nt(t,["parameters","sampleCount"],n);const o=kt(e,["outputGcsUri"]);void 0!==t&&null!=o&&Nt(t,["parameters","storageUri"],o);const i=kt(e,["fps"]);void 0!==t&&null!=i&&Nt(t,["parameters","fps"],i);const r=kt(e,["durationSeconds"]);void 0!==t&&null!=r&&Nt(t,["parameters","durationSeconds"],r);const s=kt(e,["seed"]);void 0!==t&&null!=s&&Nt(t,["parameters","seed"],s);const a=kt(e,["aspectRatio"]);void 0!==t&&null!=a&&Nt(t,["parameters","aspectRatio"],a);const l=kt(e,["resolution"]);void 0!==t&&null!=l&&Nt(t,["parameters","resolution"],l);const u=kt(e,["personGeneration"]);void 0!==t&&null!=u&&Nt(t,["parameters","personGeneration"],u);const c=kt(e,["pubsubTopic"]);void 0!==t&&null!=c&&Nt(t,["parameters","pubsubTopic"],c);const d=kt(e,["negativePrompt"]);void 0!==t&&null!=d&&Nt(t,["parameters","negativePrompt"],d);const p=kt(e,["enhancePrompt"]);void 0!==t&&null!=p&&Nt(t,["parameters","enhancePrompt"],p);const m=kt(e,["generateAudio"]);void 0!==t&&null!=m&&Nt(t,["parameters","generateAudio"],m);const h=kt(e,["lastFrame"]);void 0!==t&&null!=h&&Nt(t,["instances[0]","lastFrame"],ka(h));const f=kt(e,["referenceImages"]);if(void 0!==t&&null!=f){let e=f;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["image"]);null!=n&&Nt(t,["image"],ka(n));const o=kt(e,["referenceType"]);return null!=o&&Nt(t,["referenceType"],o),t}(e))),Nt(t,["instances[0]","referenceImages"],e)}const v=kt(e,["mask"]);void 0!==t&&null!=v&&Nt(t,["instances[0]","mask"],function(e){const t={},n=kt(e,["image"]);null!=n&&Nt(t,["_self"],ka(n));const o=kt(e,["maskMode"]);return null!=o&&Nt(t,["maskMode"],o),t}(v));const g=kt(e,["compressionQuality"]);void 0!==t&&null!=g&&Nt(t,["parameters","compressionQuality"],g);const _=kt(e,["labels"]);if(void 0!==t&&null!=_&&Nt(t,["labels"],_),void 0!==kt(e,["webhookConfig"]))throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const y=kt(e,["resizeMode"]);void 0!==t&&null!=y&&Nt(t,["parameters","resizeMode"],y)}(u,o),o}function Pa(e,t){const n={},o=kt(e,["_self"]);null!=o&&Nt(n,["image"],Na(o));const i=kt(e,["raiFilteredReason"]);null!=i&&Nt(n,["raiFilteredReason"],i);const r=kt(e,["_self"]);null!=r&&Nt(n,["safetyAttributes"],xa(r));const s=kt(e,["prompt"]);return null!=s&&Nt(n,["enhancedPrompt"],s),n}function Na(e,t){const n={},o=kt(e,["gcsUri"]);null!=o&&Nt(n,["gcsUri"],o);const i=kt(e,["bytesBase64Encoded"]);null!=i&&Nt(n,["imageBytes"],Ln(i));const r=kt(e,["mimeType"]);return null!=r&&Nt(n,["mimeType"],r),n}function ka(e,t){const n={},o=kt(e,["gcsUri"]);null!=o&&Nt(n,["gcsUri"],o);const i=kt(e,["imageBytes"]);null!=i&&Nt(n,["bytesBase64Encoded"],Ln(i));const r=kt(e,["mimeType"]);return null!=r&&Nt(n,["mimeType"],r),n}function Da(e,t){const n={},o=kt(e,["name"]);null!=o&&Nt(n,["name"],o);const i=kt(e,["displayName"]);null!=i&&Nt(n,["displayName"],i);const r=kt(e,["description"]);null!=r&&Nt(n,["description"],r);const s=kt(e,["version"]);null!=s&&Nt(n,["version"],s);const a=kt(e,["_self"]);null!=a&&Nt(n,["tunedModelInfo"],function(e){const t={},n=kt(e,["baseModel"]);null!=n&&Nt(t,["baseModel"],n);const o=kt(e,["createTime"]);null!=o&&Nt(t,["createTime"],o);const i=kt(e,["updateTime"]);return null!=i&&Nt(t,["updateTime"],i),t}(a));const l=kt(e,["inputTokenLimit"]);null!=l&&Nt(n,["inputTokenLimit"],l);const u=kt(e,["outputTokenLimit"]);null!=u&&Nt(n,["outputTokenLimit"],u);const c=kt(e,["supportedGenerationMethods"]);null!=c&&Nt(n,["supportedActions"],c);const d=kt(e,["temperature"]);null!=d&&Nt(n,["temperature"],d);const p=kt(e,["maxTemperature"]);null!=p&&Nt(n,["maxTemperature"],p);const m=kt(e,["topP"]);null!=m&&Nt(n,["topP"],m);const h=kt(e,["topK"]);null!=h&&Nt(n,["topK"],h);const f=kt(e,["thinking"]);return null!=f&&Nt(n,["thinking"],f),n}function Ma(e,t){const n={},o=kt(e,["name"]);null!=o&&Nt(n,["name"],o);const i=kt(e,["displayName"]);null!=i&&Nt(n,["displayName"],i);const r=kt(e,["description"]);null!=r&&Nt(n,["description"],r);const s=kt(e,["versionId"]);null!=s&&Nt(n,["version"],s);const a=kt(e,["deployedModels"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["endpoint"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["deployedModelId"]);return null!=o&&Nt(t,["deployedModelId"],o),t}(e))),Nt(n,["endpoints"],e)}const l=kt(e,["labels"]);null!=l&&Nt(n,["labels"],l);const u=kt(e,["_self"]);null!=u&&Nt(n,["tunedModelInfo"],function(e){const t={},n=kt(e,["labels","google-vertex-llm-tuning-base-model-id"]);null!=n&&Nt(t,["baseModel"],n);const o=kt(e,["createTime"]);null!=o&&Nt(t,["createTime"],o);const i=kt(e,["updateTime"]);return null!=i&&Nt(t,["updateTime"],i),t}(u));const c=kt(e,["defaultCheckpointId"]);null!=c&&Nt(n,["defaultCheckpointId"],c);const d=kt(e,["checkpoints"]);if(null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),Nt(n,["checkpoints"],e)}return n}function xa(e,t){const n={},o=kt(e,["safetyAttributes","categories"]);null!=o&&Nt(n,["categories"],o);const i=kt(e,["safetyAttributes","scores"]);null!=i&&Nt(n,["scores"],i);const r=kt(e,["contentType"]);return null!=r&&Nt(n,["contentType"],r),n}function Ga(e,t){const n={},o=kt(e,["voiceConfig"]);null!=o&&Nt(n,["voiceConfig"],qa(o));const i=kt(e,["languageCode"]);null!=i&&Nt(n,["languageCode"],i);const r=kt(e,["multiSpeakerVoiceConfig"]);return null!=r&&Nt(n,["multiSpeakerVoiceConfig"],function(e){const t={},n=kt(e,["speakerVoiceConfigs"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["speaker"]);null!=n&&Nt(t,["speaker"],n);const o=kt(e,["voiceConfig"]);return null!=o&&Nt(t,["voiceConfig"],qa(o)),t}(e))),Nt(t,["speakerVoiceConfigs"],e)}return t}(r)),n}function Ua(e,t){const n={},o=kt(e,["retrieval"]);null!=o&&Nt(n,["retrieval"],o);const i=kt(e,["googleMaps"]);null!=i&&Nt(n,["googleMaps"],i);const r=kt(e,["mcpServers"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>function(e){if(void 0!==kt(e,["name"]))throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["streamableHttpTransport"]))throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}(e))),Nt(n,["mcpServers"],e)}const s=kt(e,["codeExecution"]);null!=s&&Nt(n,["codeExecution"],s);const a=kt(e,["computerUse"]);null!=a&&Nt(n,["computerUse"],a);const l=kt(e,["enterpriseWebSearch"]);null!=l&&Nt(n,["enterpriseWebSearch"],l);const u=kt(e,["exaAiSearch"]);null!=u&&Nt(n,["exaAiSearch"],u);const c=kt(e,["functionDeclarations"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),Nt(n,["functionDeclarations"],e)}const d=kt(e,["googleSearch"]);null!=d&&Nt(n,["googleSearch"],d);const p=kt(e,["googleSearchRetrieval"]);null!=p&&Nt(n,["googleSearchRetrieval"],p);const m=kt(e,["parallelAiSearch"]);null!=m&&Nt(n,["parallelAiSearch"],m);const h=kt(e,["urlContext"]);if(null!=h&&Nt(n,["urlContext"],h),void 0!==kt(e,["fileSearch"]))throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return n}function La(e,t){const n={},o=kt(e,["uri"]);null!=o&&Nt(n,["gcsUri"],o);const i=kt(e,["videoBytes"]);null!=i&&Nt(n,["bytesBase64Encoded"],Ln(i));const r=kt(e,["mimeType"]);return null!=r&&Nt(n,["mimeType"],r),n}function qa(e,t){const n={},o=kt(e,["replicatedVoiceConfig"]);null!=o&&Nt(n,["replicatedVoiceConfig"],function(e){const t={},n=kt(e,["mimeType"]);null!=n&&Nt(t,["mimeType"],n);const o=kt(e,["voiceSampleAudio"]);if(null!=o&&Nt(t,["voiceSampleAudio"],o),void 0!==kt(e,["consentAudio"]))throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["voiceConsentSignature"]))throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(o));const i=kt(e,["prebuiltVoiceConfig"]);null!=i&&Nt(n,["prebuiltVoiceConfig"],i);const r=kt(e,["voice"]);return null!=r&&Nt(n,["voice"],r),n}function Ha(e,t){const n=kt(e,["mimeType"]);void 0!==t&&null!=n&&Nt(t,["mimeType"],n);const o=kt(e,["displayName"]);void 0!==t&&null!=o&&Nt(t,["displayName"],o);const i=kt(e,["customMetadata"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["customMetadata"],e)}const r=kt(e,["chunkingConfig"]);return void 0!==t&&null!=r&&Nt(t,["chunkingConfig"],r),{}}var ja="x-goog-api-client",Fa=/* @__PURE__ */new Set(["us","eu"]),Xa=Symbol.for("undici.globalDispatcher.1"),Ba=[408,429,500,502,503,504],Va=class{constructor(e){var t,n,o,i;this.clientOptions=Object.assign({},e),this.customBaseUrl=null===(t=e.httpOptions)||void 0===t?void 0:t.baseUrl;const r={};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 t=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!t?(r.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||"global"===this.clientOptions.location?r.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&Fa.has(this.clientOptions.location)?r.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(r.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),r.apiVersion=null!==(n=this.clientOptions.apiVersion)&&void 0!==n?n:"v1beta1"}else this.clientOptions.apiKey,r.apiVersion=null!==(i=null!==(o=this.clientOptions.apiVersion)&&void 0!==o?o:void 0)&&void 0!==i?i:"v1",r.baseUrl="https://generativelanguage.googleapis.com/";r.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=r,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(r,e.httpOptions))}isVertexAI(){var e;return null!==(e=this.clientOptions.vertexai)&&void 0!==e&&e}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&&void 0!==this.clientOptions.httpOptions.apiVersion)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.baseUrl)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&&void 0!==this.clientOptions.httpOptions.headers)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getFetch(){var e;return null===(e=this.clientOptions.httpOptions)||void 0===e?void 0:e.fetch}getTimeout(){var e;return null===(e=this.clientOptions.httpOptions)||void 0===e?void 0:e.timeout}getRequestUrlInternal(e){if(!e||void 0===e.baseUrl||void 0===e.apiVersion)throw new Error("HTTP options are not correctly set.");const t=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&""!==e.apiVersion&&t.push(e.apiVersion),t.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const e=this.getBaseUrl(),t=new URL(e);return t.protocol="http:"==t.protocol?"ws":"wss",t.toString()}setBaseUrl(e){if(!this.clientOptions.httpOptions)throw new Error("HTTP options are not correctly set.");this.clientOptions.httpOptions.baseUrl=e}resolveApiVersionInPath(e,t){const n="{api_version}";return""!==t?e.replaceAll(n,t):e.replaceAll(`${n}/`,"").replaceAll(`/${n}`,"").replaceAll(n,"")}constructUrl(e,t,n){if(e.includes("{api_version}")){if(!t||void 0===t.baseUrl||void 0===t.apiVersion)throw new Error("HTTP options are not correctly set.");const o=[t.baseUrl.endsWith("/")?t.baseUrl.slice(0,-1):t.baseUrl];n&&o.push(this.getBaseResourcePath());const i=this.resolveApiVersionInPath(e,t.apiVersion);return""!==i&&o.push(i),new URL(`${o.join("/")}`)}const o=[this.getRequestUrlInternal(t)];return n&&o.push(this.getBaseResourcePath()),""!==e&&o.push(e),new URL(`${o.join("/")}`)}shouldPrependVertexProjectPath(e,t){return!(t.baseUrl&&t.baseUrlResourceScope===et.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||e.path.startsWith("projects/")||"GET"===e.httpMethod&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const n=this.shouldPrependVertexProjectPath(e,t),o=this.constructUrl(e.path,t,n);if(e.queryParams)for(const[r,s]of Object.entries(e.queryParams))o.searchParams.append(r,String(s));let i={};if("GET"===e.httpMethod){if(e.body&&"{}"!==e.body)throw new Error("Request body should be empty for GET request, but got non empty request body")}else i.body=e.body;return i=await this.includeExtraHttpOptionsToRequestInit(i,t,o.toString()),this.unaryApiCall(o,i,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal,t.fetch)}patchHttpOptions(e,t){const n=JSON.parse(JSON.stringify(e));e.fetch&&(n.fetch=e.fetch);for(const[o,i]of Object.entries(t))"object"==typeof i?n[o]=Object.assign(Object.assign({},n[o]),i):void 0!==i&&(n[o]=i);return n}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const n=this.shouldPrependVertexProjectPath(e,t),o=this.constructUrl(e.path,t,n);o.searchParams.has("alt")&&"sse"===o.searchParams.get("alt")||o.searchParams.set("alt","sse");let i={};return i.body=e.body,i=await this.includeExtraHttpOptionsToRequestInit(i,t,o.toString()),this.streamApiCall(o,i,e.httpMethod,t.retryOptions,t.timeout,e.abortSignal,t.fetch)}async includeExtraHttpOptionsToRequestInit(e,t,n){return!function(){var e,t;return"string"==typeof(null===(t=null===(e=globalThis.process)||void 0===e?void 0:e.versions)||void 0===t?void 0:t.node)}()||(null==t?void 0:t.fetch)||"dispatcher"in e||(e.dispatcher={dispatch(e,t){let n=globalThis[Xa];if(n||"undefined"==typeof Headers||(new Headers,n=globalThis[Xa]),!n||"function"!=typeof n.dispatch)throw new Error("Undici globalDispatcher is not available.");return n.dispatch(Object.assign(Object.assign({},e),{headersTimeout:0,bodyTimeout:0}),t)}}),t&&null!==t.extraBody&&function(e,t){if(!t||0===Object.keys(t).length)return;if(e.body instanceof Blob)return;let n={};if("string"==typeof e.body&&e.body.length>0)try{const t=JSON.parse(e.body);if("object"!=typeof t||null===t||Array.isArray(t))return;n=t}catch(i){return}const o=function e(t,n){const o=Object.assign({},t);for(const i in n)if(Object.prototype.hasOwnProperty.call(n,i)){const t=n[i],r=o[i];t&&"object"==typeof t&&!Array.isArray(t)&&r&&"object"==typeof r&&!Array.isArray(r)?o[i]=e(r,t):o[i]=t}return o}(n,t);e.body=JSON.stringify(o)}(e,t.extraBody),e.headers=await this.getHeadersInternal(t,n),e}async unaryApiCall(e,t,n,o,i,r,s){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n}),o,i,r,s).then(async e=>(await $a(e),new Ut(e))).catch(e=>{throw e instanceof Error?e:new Error(`exception ${e} sending request`,{cause:e})})}async streamApiCall(e,t,n,o,i,r,s){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n}),o,i,r,s).then(async e=>(await $a(e),this.processStreamResponse(e))).catch(e=>{throw e instanceof Error?e:new Error(`exception ${e} sending request`,{cause:e})})}processStreamResponse(e){return D(this,arguments,function*(){var t;const n=null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.getReader(),o=new TextDecoder("utf-8");if(!n)throw new Error("Response body is empty");try{let t="";const r="data:",s=["\n\n","\r\r","\r\n\r\n"];for(;;){const{done:a,value:l}=yield k(n.read());if(a){if(t.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}const u=o.decode(l,{stream:!0});Ja(u),t+=u;let c=-1,d=0;for(;;){c=-1,d=0;for(const e of s){const n=t.indexOf(e);-1!==n&&(-1===c||n<c)&&(c=n,d=e.length)}if(-1===c)break;const n=t.substring(0,c);t=t.substring(c+d);const o=n.trim();if(o.startsWith(r)){const t=o.substring(5).trim();Ja(t);try{const n=new Response(t,{headers:null==e?void 0:e.headers,status:null==e?void 0:e.status,statusText:null==e?void 0:e.statusText});yield yield k(new Ut(n))}catch(i){throw new Error(`exception parsing stream chunk ${t}. ${i}`)}}}}}finally{n.releaseLock()}})}async apiCall(e,t,n,o,i,r){var s,a,l,u,c,d;const p=null!=r?r:fetch,m=null!==(s=null==n?void 0:n.httpStatusCodes)&&void 0!==s?s:Ba,h=async()=>{const r=function(e,t){if(!(e&&e>0||t))return{signal:void 0,dispose:()=>{}};const n=new AbortController;let o;e&&e>0&&(o=setTimeout(()=>n.abort(),e),o&&"function"==typeof o.unref&&o.unref());const i=()=>n.abort();return t&&(t.aborted?n.abort():t.addEventListener("abort",i)),{signal:n.signal,dispose:()=>{void 0!==o&&clearTimeout(o),null==t||t.removeEventListener("abort",i)}}}(o,i);let s;try{s=await p(e,Object.assign(Object.assign({},t),{signal:r.signal}))}catch(a){throw r.dispose(),a}if(!n||s.ok||!m.includes(s.status))return s;try{await $a(s)}finally{r.dispose()}return s};if(!n)return h();const f=Math.max(1,null!==(a=n.attempts)&&void 0!==a?a:5),v=Math.round(1e3*(null!==(l=n.initialDelay)&&void 0!==l?l:1)),g=Math.max(v,Math.round(1e3*(null!==(u=n.maxDelay)&&void 0!==u?u:60)));return(0,C.default)(h,{retries:f-1,factor:null!==(c=n.expBase)&&void 0!==c?c:2,minTimeout:v,maxTimeout:g,randomize:(null!==(d=n.jitter)&&void 0!==d?d:1)>0,onFailedAttempt:e=>{var t;if(null==i?void 0:i.aborted)throw null!==(t=e.error)&&void 0!==t?t:e}})}getDefaultHeaders(){const e={},t="google-genai-sdk/3.6.1 "+this.clientOptions.userAgentExtra;return e["User-Agent"]=t,e[ja]=t,e["Content-Type"]="application/json",e}async getHeadersInternal(e,t){const n=new Headers;if(e&&e.headers)for(const[o,i]of Object.entries(e.headers))n.append(o,i);return(null==e?void 0:e.timeout)&&e.timeout>0&&n.append("X-Server-Timeout",String(Math.ceil(e.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(n,t),n}getFileName(e){var t;let n="";return"string"==typeof e&&(n=e.replace(/[/\\]+$/,""),n=null!==(t=n.split(/[/\\]/).pop())&&void 0!==t?t:""),n}async uploadFile(e,t){var n;const o={};null!=t&&(o.mimeType=t.mimeType,o.name=t.name,o.displayName=t.displayName),o.name&&!o.name.startsWith("files/")&&(o.name=`files/${o.name}`);const i=this.clientOptions.uploader,r=await i.stat(e);o.sizeBytes=String(r.size);const s=null!==(n=null==t?void 0:t.mimeType)&&void 0!==n?n:r.type;if(void 0===s||""===s)throw new Error("Can not determine mimeType. Please provide mimeType in the config.");o.mimeType=s;const a={file:o},l=this.getFileName(e),u=await this.fetchUploadUrl("upload/{api_version}/files",o.sizeBytes,o.mimeType,l,a,null==t?void 0:t.httpOptions);return i.upload(e,u,this)}async uploadFileToFileSearchStore(e,t,n){var o;const i=this.clientOptions.uploader,r=await i.stat(t),s=String(r.size),a=null!==(o=null==n?void 0:n.mimeType)&&void 0!==o?o:r.type;if(void 0===a||""===a)throw new Error("Can not determine mimeType. Please provide mimeType in the config.");const l=`upload/{api_version}/${e}:uploadToFileSearchStore`,u=this.getFileName(t),c={};null!=n&&Ha(n,c);const d=await this.fetchUploadUrl(l,s,a,u,c,null==n?void 0:n.httpOptions);return i.uploadToFileSearchStore(t,d,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,t,n,o,i,r){var s;const a=Object.assign(Object.assign({},r),{headers:Object.assign(Object.assign(Object.assign({},null==r?void 0:r.headers),{"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${n}`}),o?{"X-Goog-Upload-File-Name":o}:{})}),l=await this.request({path:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:a});if(!l||!(null==l?void 0:l.headers))throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");const u=null===(s=null==l?void 0:l.headers)||void 0===s?void 0:s["x-goog-upload-url"];if(void 0===u)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return u}};function Ja(e){try{const t=JSON.parse(e);if(null!==t&&"object"==typeof t&&"error"in t&&null!==t.error&&"object"==typeof t.error){const e=t.error,n=e.status,o=e.code,i=`got status: ${n}. ${JSON.stringify(t)}`;if("number"==typeof o&&o>=400&&o<600)throw new po({message:i,status:o})}}catch(t){if("ApiError"===(null==t?void 0:t.name))throw t}}async function $a(e){var t;if(void 0===e)throw new Error("response is undefined");if(!e.ok){const n=e.status;let o;o=(null===(t=e.headers.get("content-type"))||void 0===t?void 0:t.includes("application/json"))?await e.json():{error:{message:await e.text(),code:e.status,status:e.statusText}};const i=JSON.stringify(o);if(n>=400&&n<600)throw new po({message:i,status:n});throw new Error(i)}}function Wa(e){for(const t of e){if(Ka(t))return!0;if("object"==typeof t&&"inputSchema"in t)return!0}return!1}function Ya(e){var t;const n=null!==(t=e[ja])&&void 0!==t?t:"";e[ja]=(n+" mcp_used/unknown").trimStart()}function Ka(e){return null!==e&&"object"==typeof e&&e instanceof Za}function za(e){return D(this,arguments,function*(e,t=100){let n,o=0;for(;o<t;){const t=yield k(e.listTools({cursor:n}));for(const e of t.tools)yield yield k(e),o++;if(!t.nextCursor)break;n=t.nextCursor}})}var Za=class e{constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(t,n){return new e(t,n)}async initialize(){var e,t,n,o;if(this.mcpTools.length>0)return;const i={},r=[];for(const c of this.mcpClients)try{for(var s,a=!0,l=(t=void 0,M(za(c)));!(e=(s=await l.next()).done);a=!0){o=s.value,a=!1;const e=o;r.push(e);const t=e.name;if(i[t])throw new Error(`Duplicate function name ${t} found in MCP tools. Please ensure function names are unique.`);i[t]=c}}catch(u){t={error:u}}finally{try{a||e||!(n=l.return)||await n.call(l)}finally{if(t)throw t.error}}this.mcpTools=r,this.functionNameToMcpClient=i}async tool(){return await this.initialize(),function(e,t={}){const n=[],o=/* @__PURE__ */new Set;for(const i of e){const e=i.name;if(o.has(e))throw new Error(`Duplicate function name ${e} found in MCP tools. Please ensure function names are unique.`);o.add(e);const r=Xn(i,t);r.functionDeclarations&&n.push(...r.functionDeclarations)}return{functionDeclarations:n}}(this.mcpTools,this.config)}async callTool(e){await this.initialize();const t=[];for(const n of e)if(n.name in this.functionNameToMcpClient){const e=this.functionNameToMcpClient[n.name];let o;this.config.timeout&&(o={timeout:this.config.timeout});const i=await e.callTool({name:n.name,arguments:n.args},void 0,o);t.push({functionResponse:{name:n.name,response:i.isError?{error:i}:i}})}return t}},Qa=class{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n}async connect(e){var t,n;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");const o=this.apiClient.getWebsocketBaseUrl(),i=this.apiClient.getApiVersion(),r=function(e){const t=new Headers;for(const[n,o]of Object.entries(e))t.append(n,o);return t}(this.apiClient.getDefaultHeaders()),s=`${o}/ws/google.ai.generativelanguage.${i}.GenerativeService.BidiGenerateMusic?key=${this.apiClient.getApiKey()}`;let a=()=>{};const l=new Promise(e=>{a=e}),u=e.callbacks,c=(this.apiClient,{onopen:function(){a({})},onmessage:e=>{!async function(e,t,n){const o=new hn;let i;i=n.data instanceof Blob?JSON.parse(await n.data.text()):JSON.parse(n.data),Object.assign(o,i),t(o)}(0,u.onmessage,e)},onerror:null!==(t=null==u?void 0:u.onerror)&&void 0!==t?t:function(e){},onclose:null!==(n=null==u?void 0:u.onclose)&&void 0!==n?n:function(e){}}),d=this.webSocketFactory.create(s,function(e){const t={};return e.forEach((e,n)=>{t[n]=e}),t}(r),c);d.connect(),await l;const p={setup:{model:vn(this.apiClient,e.model)}};return d.send(JSON.stringify(p)),new el(d,this.apiClient)}},el=class{constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||0===Object.keys(e.weightedPrompts).length)throw new Error("Weighted prompts must be set and contain at least one entry.");const t=function(e){const t={},n=kt(e,["weightedPrompts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["weightedPrompts"],e)}return t}(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});const t=function(e){const t={},n=kt(e,["musicGenerationConfig"]);return null!=n&&Nt(t,["musicGenerationConfig"],n),t}(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){const t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(Ot.PLAY)}pause(){this.sendPlaybackControl(Ot.PAUSE)}stop(){this.sendPlaybackControl(Ot.STOP)}resetContext(){this.sendPlaybackControl(Ot.RESET_CONTEXT)}close(){this.conn.close()}},tl=class{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n,this.music=new Qa(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,n,o,i;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 r=this.apiClient.getWebsocketBaseUrl(),s=this.apiClient.getApiVersion();let a;const l=this.apiClient.getHeaders();e.config&&e.config.tools&&Wa(e.config.tools)&&Ya(l);const u=function(e){const t=new Headers;for(const[n,o]of Object.entries(e))t.append(n,o);return t}(l);if(this.apiClient.isVertexAI()){const e=this.apiClient.getProject(),t=this.apiClient.getLocation(),n=this.apiClient.getApiKey(),o=!!e&&!!t||!!n;this.apiClient.getCustomBaseUrl()&&!o?a=r:(a=`${r}/ws/google.cloud.aiplatform.${s}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(u,a))}else{const e=this.apiClient.getApiKey();let t="BidiGenerateContent",n="key";(null==e?void 0:e.startsWith("auth_tokens/"))&&(t="BidiGenerateContentConstrained",n="access_token"),a=`${r}/ws/google.ai.generativelanguage.${s}.GenerativeService.${t}?${n}=${e}`}let c=()=>{},d=()=>{};const p=new Promise((e,t)=>{c=e,d=t});p.catch(()=>{});const m=e.callbacks,h=this.apiClient;let f=!1;const v=[];let g=()=>{},_=()=>{};const y=new Promise((e,t)=>{g=e,_=t});y.catch(()=>{});const E=e=>{d(e),_(e)},T={onopen:function(){var e;null===(e=null==m?void 0:m.onopen)||void 0===e||e.call(m),c({})},onmessage:e=>{!async function(e,t,n){const o=new mn;let i;i=n.data instanceof Blob?await n.data.text():n.data instanceof ArrayBuffer?(new TextDecoder).decode(n.data):n.data;const r=JSON.parse(i);if(e.isVertexAI()){const e=function(e){const t={},n=kt(e,["setupComplete"]);null!=n&&Nt(t,["setupComplete"],n);const o=kt(e,["serverContent"]);null!=o&&Nt(t,["serverContent"],o);const i=kt(e,["toolCall"]);null!=i&&Nt(t,["toolCall"],i);const r=kt(e,["toolCallCancellation"]);null!=r&&Nt(t,["toolCallCancellation"],r);const s=kt(e,["usageMetadata"]);null!=s&&Nt(t,["usageMetadata"],function(e){const t={},n=kt(e,["candidatesTokenCount"]);null!=n&&Nt(t,["responseTokenCount"],n);const o=kt(e,["candidatesTokensDetails"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["responseTokensDetails"],e)}const i=kt(e,["cacheTokensDetails"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["cacheTokensDetails"],e)}const r=kt(e,["cachedContentTokenCount"]);null!=r&&Nt(t,["cachedContentTokenCount"],r);const s=kt(e,["promptTokenCount"]);null!=s&&Nt(t,["promptTokenCount"],s);const a=kt(e,["promptTokensDetails"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["promptTokensDetails"],e)}const l=kt(e,["thoughtsTokenCount"]);null!=l&&Nt(t,["thoughtsTokenCount"],l);const u=kt(e,["toolUsePromptTokenCount"]);null!=u&&Nt(t,["toolUsePromptTokenCount"],u);const c=kt(e,["toolUsePromptTokensDetails"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["toolUsePromptTokensDetails"],e)}const d=kt(e,["totalTokenCount"]);null!=d&&Nt(t,["totalTokenCount"],d);const p=kt(e,["trafficType"]);return null!=p&&Nt(t,["trafficType"],p),t}(s));const a=kt(e,["goAway"]);null!=a&&Nt(t,["goAway"],a);const l=kt(e,["sessionResumptionUpdate"]);null!=l&&Nt(t,["sessionResumptionUpdate"],l);const u=kt(e,["voiceActivityDetectionSignal"]);null!=u&&Nt(t,["voiceActivityDetectionSignal"],u);const c=kt(e,["voiceActivity"]);return null!=c&&Nt(t,["voiceActivity"],function(e){const t={},n=kt(e,["type"]);null!=n&&Nt(t,["voiceActivityType"],n);const o=kt(e,["audioOffset"]);return null!=o&&Nt(t,["audioOffset"],o),t}(c)),t}(r);Object.assign(o,e)}else Object.assign(o,r);var s;(s=o).setupComplete&&!w.setupComplete&&(w.setupComplete=s.setupComplete,g({})),f?m.onmessage(s):v.push(s)}(h,0,e)},onerror:e=>{var t;try{null===(t=null==m?void 0:m.onerror)||void 0===t||t.call(m,e)}finally{E(/* @__PURE__ */new Error(`Live connection failed before setup completed: ${(null==e?void 0:e.message)||"WebSocket error"}`))}},onclose:e=>{var t,n;try{null===(t=null==m?void 0:m.onclose)||void 0===t||t.call(m,e)}finally{E(/* @__PURE__ */new Error(`Live connection closed before setup completed (code ${null!==(n=null==e?void 0:e.code)&&void 0!==n?n:1006}): ${(null==e?void 0:e.reason)||"Abnormal closure."}`))}}},A=this.webSocketFactory.create(a,function(e){const t={};return e.forEach((e,n)=>{t[n]=e}),t}(u),T);A.connect(),await p;let I=vn(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&I.startsWith("publishers/")){const e=this.apiClient.getProject(),t=this.apiClient.getLocation();e&&t&&(I=`projects/${e}/locations/${t}/`+I)}let C={};this.apiClient.isVertexAI()&&void 0===(null===(t=e.config)||void 0===t?void 0:t.responseModalities)&&(void 0===e.config?e.config={responseModalities:[De.AUDIO]}:e.config.responseModalities=[De.AUDIO]),null===(n=e.config)||void 0===n||n.generationConfig;const S=null!==(i=null===(o=e.config)||void 0===o?void 0:o.tools)&&void 0!==i?i:[],b=[];for(const P of S)if(this.isCallableTool(P)){const e=P;b.push(await e.tool())}else b.push(P);b.length>0&&(e.config.tools=b);const O={model:I,config:e.config,callbacks:e.callbacks};C=this.apiClient.isVertexAI()?function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["setup","model"],vn(e,o));const i=kt(t,["config"]);return null!=i&&Nt(n,["config"],function(e,t){const n=kt(e,["generationConfig"]);void 0!==t&&null!=n&&Nt(t,["setup","generationConfig"],function(e){const t={},n=kt(e,["modelSelectionConfig"]);null!=n&&Nt(t,["modelConfig"],n);const o=kt(e,["responseJsonSchema"]);null!=o&&Nt(t,["responseJsonSchema"],o);const i=kt(e,["audioTranscriptionConfig"]);null!=i&&Nt(t,["audioTranscriptionConfig"],i);const r=kt(e,["audioTimestamp"]);null!=r&&Nt(t,["audioTimestamp"],r);const s=kt(e,["candidateCount"]);null!=s&&Nt(t,["candidateCount"],s);const a=kt(e,["enableAffectiveDialog"]);null!=a&&Nt(t,["enableAffectiveDialog"],a);const l=kt(e,["frequencyPenalty"]);null!=l&&Nt(t,["frequencyPenalty"],l);const u=kt(e,["logprobs"]);null!=u&&Nt(t,["logprobs"],u);const c=kt(e,["maxOutputTokens"]);null!=c&&Nt(t,["maxOutputTokens"],c);const d=kt(e,["mediaResolution"]);null!=d&&Nt(t,["mediaResolution"],d);const p=kt(e,["presencePenalty"]);null!=p&&Nt(t,["presencePenalty"],p);const m=kt(e,["responseFormat"]);if(null!=m){let e=m;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["responseFormat"],e)}const h=kt(e,["responseLogprobs"]);null!=h&&Nt(t,["responseLogprobs"],h);const f=kt(e,["responseMimeType"]);null!=f&&Nt(t,["responseMimeType"],f);const v=kt(e,["responseModalities"]);null!=v&&Nt(t,["responseModalities"],v);const g=kt(e,["responseSchema"]);null!=g&&Nt(t,["responseSchema"],g);const _=kt(e,["routingConfig"]);null!=_&&Nt(t,["routingConfig"],_);const y=kt(e,["seed"]);null!=y&&Nt(t,["seed"],y);const E=kt(e,["speechConfig"]);null!=E&&Nt(t,["speechConfig"],_a(E));const T=kt(e,["stopSequences"]);null!=T&&Nt(t,["stopSequences"],T);const A=kt(e,["temperature"]);null!=A&&Nt(t,["temperature"],A);const I=kt(e,["thinkingConfig"]);null!=I&&Nt(t,["thinkingConfig"],I);const C=kt(e,["topK"]);null!=C&&Nt(t,["topK"],C);const S=kt(e,["topP"]);if(null!=S&&Nt(t,["topP"],S),void 0!==kt(e,["enableEnhancedCivicAnswers"]))throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const b=kt(e,["translationConfig"]);return null!=b&&Nt(t,["translationConfig"],b),t}(n));const o=kt(e,["responseModalities"]);void 0!==t&&null!=o&&Nt(t,["setup","generationConfig","responseModalities"],o);const i=kt(e,["temperature"]);void 0!==t&&null!=i&&Nt(t,["setup","generationConfig","temperature"],i);const r=kt(e,["topP"]);void 0!==t&&null!=r&&Nt(t,["setup","generationConfig","topP"],r);const s=kt(e,["topK"]);void 0!==t&&null!=s&&Nt(t,["setup","generationConfig","topK"],s);const a=kt(e,["maxOutputTokens"]);void 0!==t&&null!=a&&Nt(t,["setup","generationConfig","maxOutputTokens"],a);const l=kt(e,["mediaResolution"]);void 0!==t&&null!=l&&Nt(t,["setup","generationConfig","mediaResolution"],l);const u=kt(e,["seed"]);void 0!==t&&null!=u&&Nt(t,["setup","generationConfig","seed"],u);const c=kt(e,["speechConfig"]);void 0!==t&&null!=c&&Nt(t,["setup","generationConfig","speechConfig"],_a(Dn(c)));const d=kt(e,["thinkingConfig"]);void 0!==t&&null!=d&&Nt(t,["setup","generationConfig","thinkingConfig"],d);const p=kt(e,["enableAffectiveDialog"]);void 0!==t&&null!=p&&Nt(t,["setup","generationConfig","enableAffectiveDialog"],p);const m=kt(e,["systemInstruction"]);void 0!==t&&null!=m&&Nt(t,["setup","systemInstruction"],ma(On(m)));const h=kt(e,["tools"]);if(void 0!==t&&null!=h){let e=xn(h);Array.isArray(e)&&(e=e.map(e=>Ea(Mn(e)))),Nt(t,["setup","tools"],e)}const f=kt(e,["sessionResumption"]);void 0!==t&&null!=f&&Nt(t,["setup","sessionResumption"],f);const v=kt(e,["inputAudioTranscription"]);void 0!==t&&null!=v&&Nt(t,["setup","inputAudioTranscription"],v);const g=kt(e,["outputAudioTranscription"]);void 0!==t&&null!=g&&Nt(t,["setup","outputAudioTranscription"],g);const _=kt(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&Nt(t,["setup","realtimeInputConfig"],_);const y=kt(e,["contextWindowCompression"]);void 0!==t&&null!=y&&Nt(t,["setup","contextWindowCompression"],y);const E=kt(e,["proactivity"]);void 0!==t&&null!=E&&Nt(t,["setup","proactivity"],E);const T=kt(e,["explicitVadSignal"]);void 0!==t&&null!=T&&Nt(t,["setup","explicitVadSignal"],T);const A=kt(e,["avatarConfig"]);void 0!==t&&null!=A&&Nt(t,["setup","avatarConfig"],A);const I=kt(e,["safetySettings"]);if(void 0!==t&&null!=I){let e=I;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["setup","safetySettings"],e)}const C=kt(e,["translationConfig"]);void 0!==t&&null!=C&&Nt(t,["setup","generationConfig","translationConfig"],C);const S=kt(e,["labels"]);return void 0!==t&&null!=S&&Nt(t,["setup","labels"],S),{}}(i,n)),n}(this.apiClient,O):function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["setup","model"],vn(e,o));const i=kt(t,["config"]);return null!=i&&Nt(n,["config"],function(e,t){const n=kt(e,["generationConfig"]);void 0!==t&&null!=n&&Nt(t,["setup","generationConfig"],n);const o=kt(e,["responseModalities"]);void 0!==t&&null!=o&&Nt(t,["setup","generationConfig","responseModalities"],o);const i=kt(e,["temperature"]);void 0!==t&&null!=i&&Nt(t,["setup","generationConfig","temperature"],i);const r=kt(e,["topP"]);void 0!==t&&null!=r&&Nt(t,["setup","generationConfig","topP"],r);const s=kt(e,["topK"]);void 0!==t&&null!=s&&Nt(t,["setup","generationConfig","topK"],s);const a=kt(e,["maxOutputTokens"]);void 0!==t&&null!=a&&Nt(t,["setup","generationConfig","maxOutputTokens"],a);const l=kt(e,["mediaResolution"]);void 0!==t&&null!=l&&Nt(t,["setup","generationConfig","mediaResolution"],l);const u=kt(e,["seed"]);void 0!==t&&null!=u&&Nt(t,["setup","generationConfig","seed"],u);const c=kt(e,["speechConfig"]);void 0!==t&&null!=c&&Nt(t,["setup","generationConfig","speechConfig"],Dn(c));const d=kt(e,["thinkingConfig"]);void 0!==t&&null!=d&&Nt(t,["setup","generationConfig","thinkingConfig"],d);const p=kt(e,["enableAffectiveDialog"]);void 0!==t&&null!=p&&Nt(t,["setup","generationConfig","enableAffectiveDialog"],p);const m=kt(e,["systemInstruction"]);void 0!==t&&null!=m&&Nt(t,["setup","systemInstruction"],pa(On(m)));const h=kt(e,["tools"]);if(void 0!==t&&null!=h){let e=xn(h);Array.isArray(e)&&(e=e.map(e=>ya(Mn(e)))),Nt(t,["setup","tools"],e)}const f=kt(e,["sessionResumption"]);void 0!==t&&null!=f&&Nt(t,["setup","sessionResumption"],function(e){const t={},n=kt(e,["handle"]);if(null!=n&&Nt(t,["handle"],n),void 0!==kt(e,["transparent"]))throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(f));const v=kt(e,["inputAudioTranscription"]);void 0!==t&&null!=v&&Nt(t,["setup","inputAudioTranscription"],v);const g=kt(e,["outputAudioTranscription"]);void 0!==t&&null!=g&&Nt(t,["setup","outputAudioTranscription"],g);const _=kt(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&Nt(t,["setup","realtimeInputConfig"],_);const y=kt(e,["contextWindowCompression"]);void 0!==t&&null!=y&&Nt(t,["setup","contextWindowCompression"],y);const E=kt(e,["proactivity"]);if(void 0!==t&&null!=E&&Nt(t,["setup","proactivity"],E),void 0!==kt(e,["explicitVadSignal"]))throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const T=kt(e,["avatarConfig"]);void 0!==t&&null!=T&&Nt(t,["setup","avatarConfig"],T);const A=kt(e,["safetySettings"]);if(void 0!==t&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["category"]);if(null!=n&&Nt(t,["category"],n),void 0!==kt(e,["method"]))throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["threshold"]);return null!=o&&Nt(t,["threshold"],o),t}(e))),Nt(t,["setup","safetySettings"],e)}const I=kt(e,["translationConfig"]);void 0!==t&&null!=I&&Nt(t,["setup","generationConfig","translationConfig"],I);const C=kt(e,["labels"]);return void 0!==t&&null!=C&&Nt(t,["setup","labels"],C),{}}(i,n)),n}(this.apiClient,O),delete C.config;const w=new ol(A,this.apiClient);A.send(JSON.stringify(C));try{await y}catch(R){throw A.close(),R}f=!0;for(const P of v)m.onmessage(P);return w}isCallableTool(e){return"callTool"in e&&"function"==typeof e.callTool}},nl={turnComplete:!0},ol=class{constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(null!==t.turns&&void 0!==t.turns){let n=[];try{n=Rn(t.turns),e.isVertexAI()||(n=n.map(e=>Ia(e)))}catch(Rr){throw new Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:n,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let n=[];if(null==t.functionResponses)throw new Error("functionResponses is required.");if(n=Array.isArray(t.functionResponses)?t.functionResponses:[t.functionResponses],0===n.length)throw new Error("functionResponses is required.");for(const o of n){if("object"!=typeof o||null===o||!("name"in o)||!("response"in o))throw new Error(`Could not parse function response, type '${typeof o}'.`);if(!e.isVertexAI()&&!("id"in o))throw new Error("FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.")}return{toolResponse:{functionResponses:n}}}sendClientContent(e){e=Object.assign(Object.assign({},nl),e);const t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};t=this.apiClient.isVertexAI()?{realtimeInput:ga(e)}:{realtimeInput:va(e)},this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(null==e.functionResponses)throw new Error("Tool response parameters are required.");const t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendContextUpdate(e){let t={};t=this.apiClient.isVertexAI()?{contextUpdate:fa(e)}:{contextUpdate:ha(e)},this.conn.send(JSON.stringify(t))}close(){this.conn.close()}};function il(e){var t,n,o;if(null===(t=null==e?void 0:e.automaticFunctionCalling)||void 0===t?void 0:t.disable)return!0;let i=!1;for(const s of null!==(n=null==e?void 0:e.tools)&&void 0!==n?n:[])if(rl(s)){i=!0;break}if(!i)return!0;const r=null===(o=null==e?void 0:e.automaticFunctionCalling)||void 0===o?void 0:o.maximumRemoteCalls;return!!(r&&(r<0||!Number.isInteger(r))||0==r)}function rl(e){return"callTool"in e&&"function"==typeof e.callTool}function sl(e){var t;const n=[];return(null===(t=null==e?void 0:e.config)||void 0===t?void 0:t.tools)?(e.config.tools.forEach((e,t)=>{if(rl(e))return;const o=e;o.functionDeclarations&&o.functionDeclarations.length>0&&n.push(t)}),n):n}function al(e){var t;return!(null===(t=null==e?void 0:e.automaticFunctionCalling)||void 0===t?void 0:t.ignoreCallHistory)}function ll(e,t=!0){return e?void 0===e.automaticContinuation||null===e.automaticContinuation?t:Boolean(e.automaticContinuation):t}function ul(e){return void 0===e||e===Ie.CONTINUATION}function cl(e,t,n,o=!1){return e&&!o&&Boolean(t)&&ul(n)}var dl=class{constructor(e){this.config=e,this.reconnectsWithoutProgress=0,this.hop=pl(void 0),this.enableContinuation=ll(e,!0)}startHop(){return this.hop=pl(this.resumeToken),hl(this.config,this.resumeToken)}observe(e){var t,n;const o=this.hop;if(o.receivedAnyChunk=!0,void 0!==e.promptFeedback&&null!==e.promptFeedback&&(o.hasPromptFeedback=!0),e.usageMetadata)if(this.accumulatedUsageAcrossHops){const t=Al(this.accumulatedUsageAcrossHops,e.usageMetadata);e=Object.assign(new Ht,e,{usageMetadata:t}),o.usage=t}else Tl(e.usageMetadata),o.usage=e.usageMetadata;const i=null===(t=e.candidates)||void 0===t?void 0:t[0];return i&&((null===(n=i.content)||void 0===n?void 0:n.parts)&&i.content.parts.length>0&&(o.hasYieldedContent=!0),void 0!==i.finishReason&&(o.finishReason=i.finishReason),i.continuationToken?o.token=i.continuationToken:void 0===i.finishReason||ul(i.finishReason)||(o.token=void 0),function(e,t,n){var o;const i=null===(o=e.candidates)||void 0===o?void 0:o[0];void 0!==(null==i?void 0:i.finishReason)&&cl(t,n,i.finishReason)&&(i.finishReason=void 0)}(e,this.enableContinuation,o.token)),e}endHop(e){const t=this.hop;if(t.usage&&(this.accumulatedUsageAcrossHops=t.usage),e&&(function(e,t){var n;return Boolean(null===(n=null==t?void 0:t.abortSignal)||void 0===n?void 0:n.aborted)||e instanceof Error&&"AbortError"===e.name}(e.error,this.config)||e.error instanceof po&&!t.receivedAnyChunk))throw e.error;const n=t.hasYieldedContent||Boolean(t.token)&&t.token!==t.startToken;if(e?this.lastError=e:n&&(this.lastError=void 0),[this.resumeToken,this.reconnectsWithoutProgress]=this.nextResumeToken(),cl(this.enableContinuation,this.resumeToken,t.finishReason,t.hasPromptFeedback))return!0;if(e)throw e.error;if(void 0===t.finishReason&&!t.hasPromptFeedback&&this.lastError)throw this.lastError.error;return!1}nextResumeToken(){const e=this.hop,t=this.reconnectsWithoutProgress;return void 0!==e.finishReason||e.hasPromptFeedback?e.finishReason===Ie.CONTINUATION&&!e.hasPromptFeedback&&e.token&&e.token!==e.startToken?[e.token,0]:[void 0,0]:e.token&&e.token!==e.startToken?[e.token,0]:e.hasYieldedContent||t>=3?[void 0,t]:[e.startToken,t+1]}};function pl(e){return{startToken:e,hasPromptFeedback:!1,hasYieldedContent:!1,receivedAnyChunk:!1}}function ml(e){var t;const n=null===(t=null==e?void 0:e.candidates)||void 0===t?void 0:t[0];if(null==n?void 0:n.continuationToken)return ul(n.finishReason)?n.continuationToken:void 0}function hl(e,t,n=!1){const o=void 0!==(null==e?void 0:e.automaticContinuation)&&null!==(null==e?void 0:e.automaticContinuation),i=n&&o;if(!t&&!i)return e;if(!e)return t?{continuationToken:t}:void 0;const r=Object.assign({},e);return t&&(r.continuationToken=t),i&&delete r.automaticContinuation,r}function fl(e,t){var n,o;const i=/* @__PURE__ */new Map,r=[];for(const s of[...e,...t]){const e=s.modality;i.has(e)||(i.set(e,0),r.push(e)),i.set(e,(null!==(n=i.get(e))&&void 0!==n?n:0)+(null!==(o=s.tokenCount)&&void 0!==o?o:0))}return r.map(e=>{var t;return{modality:e,tokenCount:null!==(t=i.get(e))&&void 0!==t?t:0}})}function vl(e,t){const n=/* @__PURE__ */new Map,o=[];for(const i of[...e,...t]){const e=i.category;n.has(e)||o.push(e),n.set(e,i)}return o.map(e=>n.get(e))}function gl(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(e instanceof Ut)return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype||e instanceof Ht||e instanceof Lt||e instanceof qt}function _l(e,t){return!!e.endsWith("TokensDetails")||t.length>0&&"object"==typeof t[0]&&null!==t[0]&&"modality"in t[0]}function yl(e,t){if(0===e.length)return t;if(0===t.length)return e.map(e=>Il(e,{},!0,!1));const n=[],o=Math.min(e.length,t.length);for(let i=0;i<o;i++)n.push(Il(e[i],t[i],!0,!1));return e.length>o&&n.push(...e.slice(o)),t.length>o&&n.push(...t.slice(o)),n}function El(e){var t;if(e)return null!==(t=e._initialPromptTokenCount)&&void 0!==t?t:e.promptTokenCount}function Tl(e,t){const n=null!=t?t:El(e);return void 0!==n&&Object.defineProperty(e,"_initialPromptTokenCount",{value:n,enumerable:!1,configurable:!0,writable:!0}),e instanceof qt||Object.prototype.hasOwnProperty.call(e,"initialPromptTokenCount")||Object.defineProperty(e,"initialPromptTokenCount",{get(){return El(this)},enumerable:!1,configurable:!0}),e}function Al(e,t){var n;if(!t)return e?Tl(e):e;if(!e)return Tl(t);const o=null!==(n=El(e))&&void 0!==n?n:El(t);return Tl(Il(e,t,!1,!0),o)}function Il(e,t,n=!1,o=!1){n&&(t=function(e,t){const n=t.groundingMetadata,o=null==n?void 0:n.groundingSupports;if(!Array.isArray(o)||0===o.length)return t;const i=e.content,r=Array.isArray(null==i?void 0:i.parts)?i.parts.length:0,s=e.groundingMetadata,a=Array.isArray(null==s?void 0:s.groundingChunks)?s.groundingChunks.length:0;if(0===r&&0===a)return t;const l=o.map(e=>{var t;if(!e||"object"!=typeof e)return e;const n=Object.assign({},e);return a>0&&Array.isArray(e.groundingChunkIndices)&&e.groundingChunkIndices.length>0&&(n.groundingChunkIndices=e.groundingChunkIndices.map(e=>e+a)),r>0&&e.segment&&"object"==typeof e.segment&&(n.segment=Object.assign(Object.assign({},e.segment),{partIndex:(null!==(t=e.segment.partIndex)&&void 0!==t?t:0)+r})),n});return Object.assign(Object.assign({},t),{groundingMetadata:Object.assign(Object.assign({},n),{groundingSupports:l})})}(e,t));const i={},r=/* @__PURE__ */new Set([...Object.keys(e),...Object.keys(t)]);for(const s of r){const r=e[s],a=t[s];if(!n||"continuationToken"!==s&&"finishReason"!==s&&"finishMessage"!==s)if(n||o||"candidates"!==s||!Array.isArray(r)){if("usageMetadata"===s){const e=Al(r,a);void 0!==e&&(i[s]=e);continue}null==a?void 0!==r&&(i[s]=r):null==r?i[s]=a:"number"==typeof r&&"number"==typeof a&&(o||"tokenCount"===s||s.endsWith("TokenCount")||s.endsWith("Count")||s.endsWith("Sum"))?i[s]=r+a:Array.isArray(r)&&Array.isArray(a)?_l(s,r)||_l(s,a)?i[s]=fl(r,a):i[s]="safetyRatings"===s?vl(r,a):[...r,...a]:gl(r)&&gl(a)?i[s]=Il(r,a,!1,"usageMetadata"===s||o):i[s]=a}else i[s]=yl(r,Array.isArray(a)?a:[]);else void 0!==a&&(i[s]=a)}return i}var Cl=class e extends Rt{constructor(t){super(),this.apiClient=t,this.embedContent=async e=>{if(!this.apiClient.isVertexAI()){const t=Yn(e.model)?Rn(e.contents):e.contents;return await this.embedContentInternal({model:e.model,contents:t,config:e.config})}if(function(e){var t;const n=null!==(t=e.split("/").pop())&&void 0!==t?t:e;return n.includes("gemini")||n.includes("maas")}(e.model)){const t=function(e,t){if(Yn(e)||Wn(e))return Rn(t);if(null==t||Array.isArray(t)&&0===t.length)throw new Error("contents are required");return Array.isArray(t)?t.map(e=>On(e)):[On(t)]}(e.model,e.contents);if(t.length>1){if(Wn(e.model))throw new Error("The embedContent API for this model only supports one content at a time.");const n={model:e.model,batchContents:t,embeddingApiType:nt.BATCH_EMBED_CONTENTS,config:e.config};return await this.embedContentInternal(n)}const n={model:e.model,content:t[0],embeddingApiType:nt.EMBED_CONTENT,config:e.config};return await this.embedContentInternal(n)}{const t={model:e.model,contents:e.contents,embeddingApiType:nt.PREDICT,config:e.config};return await this.embedContentInternal(t)}},this.generateContent=async e=>{var t,n,o,i,r;const s=await this.processParamsMaybeAddMcpUsage(e);if(this.maybeMoveToResponseJsonSchema(e),!function(e){var t,n,o;return null!==(o=null===(n=null===(t=e.config)||void 0===t?void 0:t.tools)||void 0===n?void 0:n.some(e=>rl(e)))&&void 0!==o&&o}(e)||il(e.config))return ll(e.config,!0)?await this.generateContentWithContinuation(s):await this.generateContentInternal(s);const a=sl(e);if(a.length>0){const e=a.map(e=>`tools[${e}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${e}.`)}let l,u;const c=Rn(s.contents),d=null!==(o=null===(n=null===(t=s.config)||void 0===t?void 0:t.automaticFunctionCalling)||void 0===n?void 0:n.maximumRemoteCalls)&&void 0!==o?o:10;let p=0;for(;p<d&&(l=await this.generateContentWithContinuation(s),l.functionCalls&&0!==l.functionCalls.length);){const t=l.candidates[0].content,n=[];for(const o of null!==(r=null===(i=e.config)||void 0===i?void 0:i.tools)&&void 0!==r?r:[])if(rl(o)){const e=await o.callTool(l.functionCalls);n.push(...e)}p++,u={role:"user",parts:n},s.contents=Rn(s.contents),s.contents.push(t),s.contents.push(u),al(s.config)&&(c.push(t),c.push(u))}return al(s.config)&&(l.automaticFunctionCallingHistory=c),l},this.generateContentStream=async e=>{var t,n,o,i,r;if(this.maybeMoveToResponseJsonSchema(e),il(e.config)){const t=await this.processParamsMaybeAddMcpUsage(e);return ll(e.config,!0)?await this.generateContentStreamWithContinuation(t):await this.generateContentStreamInternal(t)}const s=sl(e);if(s.length>0){const e=s.map(e=>`tools[${e}]`).join(", ");throw new Error(`Incompatible tools found at ${e}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}const a=null===(o=null===(n=null===(t=null==e?void 0:e.config)||void 0===t?void 0:t.toolConfig)||void 0===n?void 0:n.functionCallingConfig)||void 0===o?void 0:o.streamFunctionCallArguments,l=null===(r=null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.automaticFunctionCalling)||void 0===r?void 0:r.disable;if(a&&!l)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(e)},this.generateImages=async t=>(e.loggedGenerateImagesWarning||(e.loggedGenerateImagesWarning=!0),await this.generateImagesInternal(t).then(e=>{var t;let n;const o=[];if(null==e?void 0:e.generatedImages)for(const r of e.generatedImages)r&&(null==r?void 0:r.safetyAttributes)&&"Positive Prompt"===(null===(t=null==r?void 0:r.safetyAttributes)||void 0===t?void 0:t.contentType)?n=null==r?void 0:r.safetyAttributes:o.push(r);let i;return i=n?{generatedImages:o,positivePromptSafetyAttributes:n,sdkHttpResponse:e.sdkHttpResponse}:{generatedImages:o,sdkHttpResponse:e.sdkHttpResponse},i})),this.list=async e=>{var t;const n={config:Object.assign(Object.assign({},{queryBase:!0}),null==e?void 0:e.config)};if(this.apiClient.isVertexAI()&&!n.config.queryBase){if(null===(t=n.config)||void 0===t?void 0:t.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");n.config.filter="labels.tune-type:*"}return new to(Gt.PAGED_ITEM_MODELS,e=>this.listInternal(e),await this.listInternal(n),n)},this.editImage=async t=>{e.loggedEditImageWarning||(e.loggedEditImageWarning=!0);const n={model:t.model,prompt:t.prompt,referenceImages:[],config:t.config};return t.referenceImages&&t.referenceImages&&(n.referenceImages=t.referenceImages.map(e=>e.toReferenceImageAPI())),await this.editImageInternal(n)},this.upscaleImage=async e=>{let t={numberOfImages:1,mode:"upscale"};e.config&&(t=Object.assign(Object.assign({},t),e.config));const n={model:e.model,image:e.image,upscaleFactor:e.upscaleFactor,config:t};return await this.upscaleImageInternal(n)},this.generateVideos=async t=>{var n,o,i,r,s,a;if((t.prompt||t.image||t.video)&&t.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(t.prompt||t.image||t.video)&&(e.loggedGenerateVideosWarning||(e.loggedGenerateVideosWarning=!0)),this.apiClient.isVertexAI()||((null===(n=t.video)||void 0===n?void 0:n.uri)&&(null===(o=t.video)||void 0===o?void 0:o.videoBytes)?t.video={uri:t.video.uri,mimeType:t.video.mimeType}:(null===(r=null===(i=t.source)||void 0===i?void 0:i.video)||void 0===r?void 0:r.uri)&&(null===(a=null===(s=t.source)||void 0===s?void 0:s.video)||void 0===a?void 0:a.videoBytes)&&(t.source.video={uri:t.source.video.uri,mimeType:t.source.video.mimeType})),await this.generateVideosInternal(t)}}async generateContentWithContinuation(e){const t=ll(e.config,!0);let n;const o=[];for(;0===o.length||t&&Boolean(n);){const t=hl(e.config,n),i=t===e.config?e:Object.assign(Object.assign({},e),{config:t}),r=await this.generateContentInternal(i);o.push(r),n=ml(r)}return function(e){if(0===e.length)return new Ht;if(1===e.length)return e[0].usageMetadata&&Tl(e[0].usageMetadata),e[0];let t=e[0];for(let o=1;o<e.length;o++)t=Il(t,e[o],!1,!1);const n=new Ht;return Object.assign(n,t),n}(o)}async generateContentStreamWithContinuation(e){const t=new dl(e.config);return t.startHop(),function(e,n,o){return D(this,arguments,function*(){var i,r,s,a;let l=async()=>o;for(;;){let o;try{try{for(var u,c=!0,d=(r=void 0,M(yield k(l())));!(i=(u=yield k(d.next())).done);c=!0){a=u.value,c=!1;const e=a;yield yield k(t.observe(e))}}catch(p){r={error:p}}finally{try{c||i||!(s=d.return)||(yield k(s.call(d)))}finally{if(r)throw r.error}}}catch(m){o={error:m}}if(!t.endHop(o))return yield k(void 0);const h=Object.assign(Object.assign({},n),{config:t.startHop()});l=()=>e.generateContentStreamInternal(h)}})}(this,e,await this.generateContentStreamInternal(e))}maybeMoveToResponseJsonSchema(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 t,n,o;const i=null===(t=e.config)||void 0===t?void 0:t.tools;if(!i)return e;const r=await Promise.all(i.map(async e=>rl(e)?await e.tool():e)),s={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:r})};if(s.config.tools=r,e.config&&e.config.tools&&Wa(e.config.tools)){const t=null!==(o=null===(n=e.config.httpOptions)||void 0===n?void 0:n.headers)&&void 0!==o?o:{};let i=Object.assign({},t);0===Object.keys(i).length&&(i=this.apiClient.getDefaultHeaders()),Ya(i),s.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:i})}return s}async initAfcToolsMap(e){var t,n,o;const i=/* @__PURE__ */new Map;for(const r of null!==(n=null===(t=e.config)||void 0===t?void 0:t.tools)&&void 0!==n?n:[])if(rl(r)){const e=r,t=await e.tool();for(const n of null!==(o=t.functionDeclarations)&&void 0!==o?o:[]){if(!n.name)throw new Error("Function declaration name is required.");if(i.has(n.name))throw new Error(`Duplicate tool declaration name: ${n.name}`);i.set(n.name,e)}}return i}async processAfcStream(e){var t,n,o;const i=null!==(o=null===(n=null===(t=e.config)||void 0===t?void 0:t.automaticFunctionCalling)||void 0===n?void 0:n.maximumRemoteCalls)&&void 0!==o?o:10;let r=!1,s=0;return function(e,t,n){return D(this,arguments,function*(){for(var o,a,l,u,c,d;s<i;){r&&(s++,r=!1);const v=yield k(e.processParamsMaybeAddMcpUsage(n)),g=yield k(e.generateContentStreamWithContinuation(v)),_=[],y=[];try{for(var p,m=!0,h=(a=void 0,M(g));!(o=(p=yield k(h.next())).done);m=!0){u=p.value,m=!1;const e=u;if(yield yield k(e),e.candidates&&(null===(c=e.candidates[0])||void 0===c?void 0:c.content)){y.push(e.candidates[0].content);for(const n of null!==(d=e.candidates[0].content.parts)&&void 0!==d?d:[])if(s<i&&n.functionCall){if(!n.functionCall.name)throw new Error("Function call name was not returned by the model.");if(!t.has(n.functionCall.name))throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${t.keys()}, missing tool: ${n.functionCall.name}`);{const e=yield k(t.get(n.functionCall.name).callTool([n.functionCall]));_.push(...e)}}}}}catch(f){a={error:f}}finally{try{m||o||!(l=h.return)||(yield k(l.call(h)))}finally{if(a)throw a.error}}if(!(_.length>0))break;{r=!0;const e=new Ht;e.candidates=[{content:{role:"user",parts:_}}],yield yield k(e);const t=[];t.push(...y),t.push({role:"user",parts:_}),n.contents=Rn(n.contents).concat(t)}}})}(this,await this.initAfcToolsMap(e),e)}async generateContentInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=ba(this.apiClient,e);return s=Pt("{model}:generateContent",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=wa(e),n=new Ht;return Object.assign(n,t),n})}{const t=Sa(this.apiClient,e);return s=Pt("{model}:generateContent",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=Oa(e),n=new Ht;return Object.assign(n,t),n})}}async generateContentStreamInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=ba(this.apiClient,e);return s=Pt("{model}:streamGenerateContent?alt=sse",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.requestStream({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}),r.then(function(e){return D(this,arguments,function*(){var t,n,o,i;try{for(var r,s=!0,a=M(e);!(t=(r=yield k(a.next())).done);s=!0){i=r.value,s=!1;const e=i,t=wa(yield k(e.json()));t.sdkHttpResponse={headers:e.headers};const n=new Ht;Object.assign(n,t),yield yield k(n)}}catch(l){n={error:l}}finally{try{s||t||!(o=a.return)||(yield k(o.call(a)))}finally{if(n)throw n.error}}})})}{const t=Sa(this.apiClient,e);return s=Pt("{model}:streamGenerateContent?alt=sse",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.requestStream({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}),r.then(function(e){return D(this,arguments,function*(){var t,n,o,i;try{for(var r,s=!0,a=M(e);!(t=(r=yield k(a.next())).done);s=!0){i=r.value,s=!1;const e=i,t=Oa(yield k(e.json()));t.sdkHttpResponse={headers:e.headers};const n=new Ht;Object.assign(n,t),yield yield k(n)}}catch(l){n={error:l}}finally{try{s||t||!(o=a.return)||(yield k(o.call(a)))}finally{if(n)throw n.error}}})})}}async embedContentInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t,n){const o={},i=kt(t,["model"]);null!=i&&Nt(o,["_url","model"],vn(e,i));let r=kt(n,["embeddingApiType"]);if(void 0===r&&(r="PREDICT"),"PREDICT"===r){const n=kt(t,["contents"]);if(null!=n){let t=wn(e,n);Array.isArray(t)&&(t=t.map(e=>e)),Nt(o,["instances[]","content"],t)}}let s=kt(n,["embeddingApiType"]);if(void 0===s&&(s="PREDICT"),"EMBED_CONTENT"===s){const e=kt(t,["content"]);null!=e&&Nt(o,["content"],Ca(On(e)))}let a=kt(n,["embeddingApiType"]);if(void 0===a&&(a="PREDICT"),"BATCH_EMBED_CONTENTS"===a){const e=kt(t,["batchContents"]);if(null!=e){let t=Rn(e);Array.isArray(t)&&(t=t.map(e=>Ca(e))),Nt(o,["requests[]","content"],t)}}const l=kt(t,["config"]);return null!=l&&function(e,t,n){let o=kt(n,["embeddingApiType"]);if(void 0===o&&(o="PREDICT"),"PREDICT"===o){const n=kt(e,["taskType"]);void 0!==t&&null!=n&&Nt(t,["instances[]","task_type"],n)}else if("EMBED_CONTENT"===o){const n=kt(e,["taskType"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","taskType"],n)}else if("BATCH_EMBED_CONTENTS"===o){const n=kt(e,["taskType"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","taskType"],n)}let i=kt(n,["embeddingApiType"]);if(void 0===i&&(i="PREDICT"),"PREDICT"===i){const n=kt(e,["title"]);void 0!==t&&null!=n&&Nt(t,["instances[]","title"],n)}else if("EMBED_CONTENT"===i){const n=kt(e,["title"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","title"],n)}else if("BATCH_EMBED_CONTENTS"===i){const n=kt(e,["title"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","title"],n)}let r=kt(n,["embeddingApiType"]);if(void 0===r&&(r="PREDICT"),"PREDICT"===r){const n=kt(e,["outputDimensionality"]);void 0!==t&&null!=n&&Nt(t,["parameters","outputDimensionality"],n)}else if("EMBED_CONTENT"===r){const n=kt(e,["outputDimensionality"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","outputDimensionality"],n)}else if("BATCH_EMBED_CONTENTS"===r){const n=kt(e,["outputDimensionality"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","outputDimensionality"],n)}let s=kt(n,["embeddingApiType"]);if(void 0===s&&(s="PREDICT"),"PREDICT"===s){const n=kt(e,["mimeType"]);void 0!==t&&null!=n&&Nt(t,["instances[]","mimeType"],n)}let a=kt(n,["embeddingApiType"]);if(void 0===a&&(a="PREDICT"),"PREDICT"===a){const n=kt(e,["autoTruncate"]);void 0!==t&&null!=n&&Nt(t,["parameters","autoTruncate"],n)}else if("EMBED_CONTENT"===a){const n=kt(e,["autoTruncate"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","autoTruncate"],n)}else if("BATCH_EMBED_CONTENTS"===a){const n=kt(e,["autoTruncate"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","autoTruncate"],n)}let l=kt(n,["embeddingApiType"]);if(void 0===l&&(l="PREDICT"),"EMBED_CONTENT"===l){const n=kt(e,["documentOcr"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","documentOcr"],n)}else if("BATCH_EMBED_CONTENTS"===l){const n=kt(e,["documentOcr"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","documentOcr"],n)}let u=kt(n,["embeddingApiType"]);if(void 0===u&&(u="PREDICT"),"EMBED_CONTENT"===u){const n=kt(e,["audioTrackExtraction"]);void 0!==t&&null!=n&&Nt(t,["embedContentConfig","audioTrackExtraction"],n)}else if("BATCH_EMBED_CONTENTS"===u){const n=kt(e,["audioTrackExtraction"]);void 0!==t&&null!=n&&Nt(t,["requests[]","embedContentConfig","audioTrackExtraction"],n)}}(l,o,n),o}(this.apiClient,e,e);let i="{model}:predict";return e.embeddingApiType===nt.BATCH_EMBED_CONTENTS?i="{model}:batchEmbedContents":e.embeddingApiType===nt.EMBED_CONTENT&&(i="{model}:embedContent"),s=Pt(i,o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(t=>{const n=function(e,t){const n={},o=kt(e,["sdkHttpResponse"]);null!=o&&Nt(n,["sdkHttpResponse"],o);const i=kt(e,["predictions[]","embeddings"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>Aa(e))),Nt(n,["embeddings"],e)}const r=kt(e,["metadata"]);null!=r&&Nt(n,["metadata"],r);const s=kt(e,["truncated"]);null!=s&&Nt(n,["truncated"],s);const a=kt(e,["usageMetadata"]);if(null!=a&&Nt(n,["usageMetadata"],function(e){const t={},n=kt(e,["candidatesTokenCount"]);null!=n&&Nt(t,["responseTokenCount"],n);const o=kt(e,["candidatesTokensDetails"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["responseTokensDetails"],e)}const i=kt(e,["cacheTokensDetails"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["cacheTokensDetails"],e)}const r=kt(e,["cachedContentTokenCount"]);null!=r&&Nt(t,["cachedContentTokenCount"],r);const s=kt(e,["promptTokenCount"]);null!=s&&Nt(t,["promptTokenCount"],s);const a=kt(e,["promptTokensDetails"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["promptTokensDetails"],e)}const l=kt(e,["thoughtsTokenCount"]);null!=l&&Nt(t,["thoughtsTokenCount"],l);const u=kt(e,["toolUsePromptTokenCount"]);null!=u&&Nt(t,["toolUsePromptTokenCount"],u);const c=kt(e,["toolUsePromptTokensDetails"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["toolUsePromptTokensDetails"],e)}const d=kt(e,["totalTokenCount"]);null!=d&&Nt(t,["totalTokenCount"],d);const p=kt(e,["trafficType"]);return null!=p&&Nt(t,["trafficType"],p),t}(a)),t&&"EMBED_CONTENT"===kt(t,["embeddingApiType"])){const t=kt(e,["embedding"]),o=kt(e,["usageMetadata"]),i=kt(e,["truncated"]);if(t){const e={};o&&o.promptTokenCount&&(e.tokenCount=o.promptTokenCount),o&&o.promptTokensDetails&&(e.tokensDetails=o.promptTokensDetails),i&&(e.truncated=i),t.statistics=e,Nt(n,["embeddings"],[t])}}else if(t&&"BATCH_EMBED_CONTENTS"===kt(t,["embeddingApiType"])){const t=kt(e,["embeddings"]);Array.isArray(t)&&Nt(n,["embeddings"],t.map(e=>Aa(e)))}return n}(t,e),o=new jt;return Object.assign(o,n),o})}{const t=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["contents"]);if(null!=i){let t=wn(e,i);Array.isArray(t)&&(t=t.map(e=>e)),Nt(n,["requests[]","content"],t)}const r=kt(t,["content"]);if(null!=r&&Ia(On(r)),void 0!==kt(t,["batchContents"]))throw new Error("batchContents parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(t,["config"]);null!=s&&function(e,t){const n=kt(e,["taskType"]);void 0!==t&&null!=n&&Nt(t,["requests[]","taskType"],n);const o=kt(e,["title"]);void 0!==t&&null!=o&&Nt(t,["requests[]","title"],o);const i=kt(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&Nt(t,["requests[]","outputDimensionality"],i),void 0!==kt(e,["mimeType"]))throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["autoTruncate"]))throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["documentOcr"]))throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["audioTrackExtraction"]))throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(s,n);const a=kt(t,["model"]);return void 0!==a&&Nt(n,["requests[]","model"],vn(e,a)),n}(this.apiClient,e);return s=Pt("{model}:batchEmbedContents",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["embeddings"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["embeddings"],e)}const i=kt(e,["metadata"]);null!=i&&Nt(t,["metadata"],i);const r=kt(e,["usageMetadata"]);return null!=r&&Nt(t,["usageMetadata"],r),t}(e),n=new jt;return Object.assign(n,t),n})}}async generateImagesInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["prompt"]);null!=i&&Nt(n,["instances[0]","prompt"],i);const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["outputGcsUri"]);void 0!==t&&null!=n&&Nt(t,["parameters","storageUri"],n);const o=kt(e,["negativePrompt"]);void 0!==t&&null!=o&&Nt(t,["parameters","negativePrompt"],o);const i=kt(e,["numberOfImages"]);void 0!==t&&null!=i&&Nt(t,["parameters","sampleCount"],i);const r=kt(e,["aspectRatio"]);void 0!==t&&null!=r&&Nt(t,["parameters","aspectRatio"],r);const s=kt(e,["guidanceScale"]);void 0!==t&&null!=s&&Nt(t,["parameters","guidanceScale"],s);const a=kt(e,["seed"]);void 0!==t&&null!=a&&Nt(t,["parameters","seed"],a);const l=kt(e,["safetyFilterLevel"]);void 0!==t&&null!=l&&Nt(t,["parameters","safetySetting"],l);const u=kt(e,["personGeneration"]);void 0!==t&&null!=u&&Nt(t,["parameters","personGeneration"],u);const c=kt(e,["includeSafetyAttributes"]);void 0!==t&&null!=c&&Nt(t,["parameters","includeSafetyAttributes"],c);const d=kt(e,["includeRaiReason"]);void 0!==t&&null!=d&&Nt(t,["parameters","includeRaiReason"],d);const p=kt(e,["language"]);void 0!==t&&null!=p&&Nt(t,["parameters","language"],p);const m=kt(e,["outputMimeType"]);void 0!==t&&null!=m&&Nt(t,["parameters","outputOptions","mimeType"],m);const h=kt(e,["outputCompressionQuality"]);void 0!==t&&null!=h&&Nt(t,["parameters","outputOptions","compressionQuality"],h);const f=kt(e,["addWatermark"]);void 0!==t&&null!=f&&Nt(t,["parameters","addWatermark"],f);const v=kt(e,["labels"]);void 0!==t&&null!=v&&Nt(t,["labels"],v);const g=kt(e,["imageSize"]);void 0!==t&&null!=g&&Nt(t,["parameters","sampleImageSize"],g);const _=kt(e,["enhancePrompt"]);void 0!==t&&null!=_&&Nt(t,["parameters","enhancePrompt"],_)}(r,n),n}(this.apiClient,e);return i=Pt("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["predictions"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Pa(e))),Nt(t,["generatedImages"],e)}const i=kt(e,["positivePromptSafetyAttributes"]);return null!=i&&Nt(t,["positivePromptSafetyAttributes"],xa(i)),t}(e),n=new Ft;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["prompt"]);null!=i&&Nt(n,["instances[0]","prompt"],i);const r=kt(t,["referenceImages"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["referenceImage"]);null!=n&&Nt(t,["referenceImage"],ka(n));const o=kt(e,["referenceId"]);null!=o&&Nt(t,["referenceId"],o);const i=kt(e,["referenceType"]);null!=i&&Nt(t,["referenceType"],i);const r=kt(e,["maskImageConfig"]);null!=r&&Nt(t,["maskImageConfig"],function(e){const t={},n=kt(e,["maskMode"]);null!=n&&Nt(t,["maskMode"],n);const o=kt(e,["segmentationClasses"]);null!=o&&Nt(t,["maskClasses"],o);const i=kt(e,["maskDilation"]);return null!=i&&Nt(t,["dilation"],i),t}(r));const s=kt(e,["controlImageConfig"]);null!=s&&Nt(t,["controlImageConfig"],function(e){const t={},n=kt(e,["controlType"]);null!=n&&Nt(t,["controlType"],n);const o=kt(e,["enableControlImageComputation"]);return null!=o&&Nt(t,["computeControl"],o),t}(s));const a=kt(e,["styleImageConfig"]);null!=a&&Nt(t,["styleImageConfig"],a);const l=kt(e,["subjectImageConfig"]);return null!=l&&Nt(t,["subjectImageConfig"],l),t}(e))),Nt(n,["instances[0]","referenceImages"],e)}const s=kt(t,["config"]);return null!=s&&function(e,t){const n=kt(e,["outputGcsUri"]);void 0!==t&&null!=n&&Nt(t,["parameters","storageUri"],n);const o=kt(e,["negativePrompt"]);void 0!==t&&null!=o&&Nt(t,["parameters","negativePrompt"],o);const i=kt(e,["numberOfImages"]);void 0!==t&&null!=i&&Nt(t,["parameters","sampleCount"],i);const r=kt(e,["aspectRatio"]);void 0!==t&&null!=r&&Nt(t,["parameters","aspectRatio"],r);const s=kt(e,["guidanceScale"]);void 0!==t&&null!=s&&Nt(t,["parameters","guidanceScale"],s);const a=kt(e,["seed"]);void 0!==t&&null!=a&&Nt(t,["parameters","seed"],a);const l=kt(e,["safetyFilterLevel"]);void 0!==t&&null!=l&&Nt(t,["parameters","safetySetting"],l);const u=kt(e,["personGeneration"]);void 0!==t&&null!=u&&Nt(t,["parameters","personGeneration"],u);const c=kt(e,["includeSafetyAttributes"]);void 0!==t&&null!=c&&Nt(t,["parameters","includeSafetyAttributes"],c);const d=kt(e,["includeRaiReason"]);void 0!==t&&null!=d&&Nt(t,["parameters","includeRaiReason"],d);const p=kt(e,["language"]);void 0!==t&&null!=p&&Nt(t,["parameters","language"],p);const m=kt(e,["outputMimeType"]);void 0!==t&&null!=m&&Nt(t,["parameters","outputOptions","mimeType"],m);const h=kt(e,["outputCompressionQuality"]);void 0!==t&&null!=h&&Nt(t,["parameters","outputOptions","compressionQuality"],h);const f=kt(e,["addWatermark"]);void 0!==t&&null!=f&&Nt(t,["parameters","addWatermark"],f);const v=kt(e,["labels"]);void 0!==t&&null!=v&&Nt(t,["labels"],v);const g=kt(e,["editMode"]);void 0!==t&&null!=g&&Nt(t,["parameters","editMode"],g);const _=kt(e,["baseSteps"]);void 0!==t&&null!=_&&Nt(t,["parameters","editConfig","baseSteps"],_)}(s,n),n}(this.apiClient,e);return i=Pt("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["predictions"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Pa(e))),Nt(t,["generatedImages"],e)}return t}(e),n=new Xt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["image"]);null!=i&&Nt(n,["instances[0]","image"],ka(i));const r=kt(t,["upscaleFactor"]);null!=r&&Nt(n,["parameters","upscaleConfig","upscaleFactor"],r);const s=kt(t,["config"]);return null!=s&&function(e,t){const n=kt(e,["outputGcsUri"]);void 0!==t&&null!=n&&Nt(t,["parameters","storageUri"],n);const o=kt(e,["safetyFilterLevel"]);void 0!==t&&null!=o&&Nt(t,["parameters","safetySetting"],o);const i=kt(e,["personGeneration"]);void 0!==t&&null!=i&&Nt(t,["parameters","personGeneration"],i);const r=kt(e,["includeRaiReason"]);void 0!==t&&null!=r&&Nt(t,["parameters","includeRaiReason"],r);const s=kt(e,["outputMimeType"]);void 0!==t&&null!=s&&Nt(t,["parameters","outputOptions","mimeType"],s);const a=kt(e,["outputCompressionQuality"]);void 0!==t&&null!=a&&Nt(t,["parameters","outputOptions","compressionQuality"],a);const l=kt(e,["enhanceInputImage"]);void 0!==t&&null!=l&&Nt(t,["parameters","upscaleConfig","enhanceInputImage"],l);const u=kt(e,["imagePreservationFactor"]);void 0!==t&&null!=u&&Nt(t,["parameters","upscaleConfig","imagePreservationFactor"],u);const c=kt(e,["labels"]);void 0!==t&&null!=c&&Nt(t,["labels"],c);const d=kt(e,["numberOfImages"]);void 0!==t&&null!=d&&Nt(t,["parameters","sampleCount"],d);const p=kt(e,["mode"]);void 0!==t&&null!=p&&Nt(t,["parameters","mode"],p)}(s,n),n}(this.apiClient,e);return i=Pt("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["predictions"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Pa(e))),Nt(t,["generatedImages"],e)}return t}(e),n=new Bt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["source"]);null!=i&&function(e,t){const n=kt(e,["prompt"]);void 0!==t&&null!=n&&Nt(t,["instances[0]","prompt"],n);const o=kt(e,["personImage"]);void 0!==t&&null!=o&&Nt(t,["instances[0]","personImage","image"],ka(o));const i=kt(e,["productImages"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["productImage"]);return null!=n&&Nt(t,["image"],ka(n)),t}(e))),Nt(t,["instances[0]","productImages"],e)}}(i,n);const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["numberOfImages"]);void 0!==t&&null!=n&&Nt(t,["parameters","sampleCount"],n);const o=kt(e,["baseSteps"]);void 0!==t&&null!=o&&Nt(t,["parameters","baseSteps"],o);const i=kt(e,["outputGcsUri"]);void 0!==t&&null!=i&&Nt(t,["parameters","storageUri"],i);const r=kt(e,["seed"]);void 0!==t&&null!=r&&Nt(t,["parameters","seed"],r);const s=kt(e,["safetyFilterLevel"]);void 0!==t&&null!=s&&Nt(t,["parameters","safetySetting"],s);const a=kt(e,["personGeneration"]);void 0!==t&&null!=a&&Nt(t,["parameters","personGeneration"],a);const l=kt(e,["addWatermark"]);void 0!==t&&null!=l&&Nt(t,["parameters","addWatermark"],l);const u=kt(e,["outputMimeType"]);void 0!==t&&null!=u&&Nt(t,["parameters","outputOptions","mimeType"],u);const c=kt(e,["outputCompressionQuality"]);void 0!==t&&null!=c&&Nt(t,["parameters","outputOptions","compressionQuality"],c);const d=kt(e,["enhancePrompt"]);void 0!==t&&null!=d&&Nt(t,["parameters","enhancePrompt"],d);const p=kt(e,["labels"]);void 0!==t&&null!=p&&Nt(t,["labels"],p)}(r,n),n}(this.apiClient,e);return i=Pt("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>Pa(e))),Nt(t,["generatedImages"],e)}return t}(e),n=new Vt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["source"]);null!=i&&function(e,t){const n=kt(e,["prompt"]);void 0!==t&&null!=n&&Nt(t,["instances[0]","prompt"],n);const o=kt(e,["image"]);void 0!==t&&null!=o&&Nt(t,["instances[0]","image"],ka(o));const i=kt(e,["scribbleImage"]);void 0!==t&&null!=i&&Nt(t,["instances[0]","scribble"],function(e){const t={},n=kt(e,["image"]);return null!=n&&Nt(t,["image"],ka(n)),t}(i))}(i,n);const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["mode"]);void 0!==t&&null!=n&&Nt(t,["parameters","mode"],n);const o=kt(e,["maxPredictions"]);void 0!==t&&null!=o&&Nt(t,["parameters","maxPredictions"],o);const i=kt(e,["confidenceThreshold"]);void 0!==t&&null!=i&&Nt(t,["parameters","confidenceThreshold"],i);const r=kt(e,["maskDilation"]);void 0!==t&&null!=r&&Nt(t,["parameters","maskDilation"],r);const s=kt(e,["binaryColorThreshold"]);void 0!==t&&null!=s&&Nt(t,["parameters","binaryColorThreshold"],s);const a=kt(e,["labels"]);void 0!==t&&null!=a&&Nt(t,["labels"],a)}(r,n),n}(this.apiClient,e);return i=Pt("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["_self"]);null!=n&&Nt(t,["mask"],Na(n));const o=kt(e,["labels"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["labels"],e)}return t}(e))),Nt(t,["generatedMasks"],e)}return t}(e),n=new Jt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);return null!=o&&Nt(n,["_url","name"],vn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>Ma(e))}{const t=function(e,t){const n={},o=kt(t,["model"]);return null!=o&&Nt(n,["_url","name"],vn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Da(e))}}async listInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["config"]);return null!=o&&function(e,t,n){const o=kt(t,["pageSize"]);void 0!==n&&null!=o&&Nt(n,["_query","pageSize"],o);const i=kt(t,["pageToken"]);void 0!==n&&null!=i&&Nt(n,["_query","pageToken"],i);const r=kt(t,["filter"]);void 0!==n&&null!=r&&Nt(n,["_query","filter"],r);const s=kt(t,["queryBase"]);void 0!==n&&null!=s&&Nt(n,["_url","models_url"],Hn(e,s))}(e,o,n),n}(this.apiClient,e);return s=Pt("{models_url}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["_self"]);if(null!=i){let e=jn(i);Array.isArray(e)&&(e=e.map(e=>Ma(e))),Nt(t,["models"],e)}return t}(e),n=new $t;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=kt(t,["config"]);return null!=o&&function(e,t,n){const o=kt(t,["pageSize"]);void 0!==n&&null!=o&&Nt(n,["_query","pageSize"],o);const i=kt(t,["pageToken"]);void 0!==n&&null!=i&&Nt(n,["_query","pageToken"],i);const r=kt(t,["filter"]);void 0!==n&&null!=r&&Nt(n,["_query","filter"],r);const s=kt(t,["queryBase"]);void 0!==n&&null!=s&&Nt(n,["_url","models_url"],Hn(e,s))}(e,o,n),n}(this.apiClient,e);return s=Pt("{models_url}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["_self"]);if(null!=i){let e=jn(i);Array.isArray(e)&&(e=e.map(e=>Da(e))),Nt(t,["models"],e)}return t}(e),n=new $t;return Object.assign(n,t),n})}}async update(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["displayName"]);void 0!==t&&null!=n&&Nt(t,["displayName"],n);const o=kt(e,["description"]);void 0!==t&&null!=o&&Nt(t,["description"],o);const i=kt(e,["defaultCheckpointId"]);void 0!==t&&null!=i&&Nt(t,["defaultCheckpointId"],i)}(i,n),n}(this.apiClient,e);return s=Pt("{model}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"PATCH",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>Ma(e))}{const t=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","name"],vn(e,o));const i=kt(t,["config"]);return null!=i&&function(e,t){const n=kt(e,["displayName"]);void 0!==t&&null!=n&&Nt(t,["displayName"],n);const o=kt(e,["description"]);void 0!==t&&null!=o&&Nt(t,["description"],o);const i=kt(e,["defaultCheckpointId"]);void 0!==t&&null!=i&&Nt(t,["defaultCheckpointId"],i)}(i,n),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"PATCH",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Da(e))}}async delete(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);return null!=o&&Nt(n,["_url","name"],vn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new Wt;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=kt(t,["model"]);return null!=o&&Nt(n,["_url","name"],vn(e,o)),n}(this.apiClient,e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"DELETE",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new Wt;return Object.assign(n,t),n})}}async countTokens(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["contents"]);if(null!=i){let e=Rn(i);Array.isArray(e)&&(e=e.map(e=>Ca(e))),Nt(n,["contents"],e)}const r=kt(t,["config"]);return null!=r&&function(e,t){const n=kt(e,["systemInstruction"]);void 0!==t&&null!=n&&Nt(t,["systemInstruction"],Ca(On(n)));const o=kt(e,["tools"]);if(void 0!==t&&null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Ua(e))),Nt(t,["tools"],e)}const i=kt(e,["generationConfig"]);void 0!==t&&null!=i&&Nt(t,["generationConfig"],function(e){const t={},n=kt(e,["modelSelectionConfig"]);null!=n&&Nt(t,["modelConfig"],n);const o=kt(e,["responseJsonSchema"]);null!=o&&Nt(t,["responseJsonSchema"],o);const i=kt(e,["audioTranscriptionConfig"]);null!=i&&Nt(t,["audioTranscriptionConfig"],i);const r=kt(e,["audioTimestamp"]);null!=r&&Nt(t,["audioTimestamp"],r);const s=kt(e,["candidateCount"]);null!=s&&Nt(t,["candidateCount"],s);const a=kt(e,["enableAffectiveDialog"]);null!=a&&Nt(t,["enableAffectiveDialog"],a);const l=kt(e,["frequencyPenalty"]);null!=l&&Nt(t,["frequencyPenalty"],l);const u=kt(e,["logprobs"]);null!=u&&Nt(t,["logprobs"],u);const c=kt(e,["maxOutputTokens"]);null!=c&&Nt(t,["maxOutputTokens"],c);const d=kt(e,["mediaResolution"]);null!=d&&Nt(t,["mediaResolution"],d);const p=kt(e,["presencePenalty"]);null!=p&&Nt(t,["presencePenalty"],p);const m=kt(e,["responseFormat"]);if(null!=m){let e=m;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["responseFormat"],e)}const h=kt(e,["responseLogprobs"]);null!=h&&Nt(t,["responseLogprobs"],h);const f=kt(e,["responseMimeType"]);null!=f&&Nt(t,["responseMimeType"],f);const v=kt(e,["responseModalities"]);null!=v&&Nt(t,["responseModalities"],v);const g=kt(e,["responseSchema"]);null!=g&&Nt(t,["responseSchema"],g);const _=kt(e,["routingConfig"]);null!=_&&Nt(t,["routingConfig"],_);const y=kt(e,["seed"]);null!=y&&Nt(t,["seed"],y);const E=kt(e,["speechConfig"]);null!=E&&Nt(t,["speechConfig"],Ga(E));const T=kt(e,["stopSequences"]);null!=T&&Nt(t,["stopSequences"],T);const A=kt(e,["temperature"]);null!=A&&Nt(t,["temperature"],A);const I=kt(e,["thinkingConfig"]);null!=I&&Nt(t,["thinkingConfig"],I);const C=kt(e,["topK"]);null!=C&&Nt(t,["topK"],C);const S=kt(e,["topP"]);if(null!=S&&Nt(t,["topP"],S),void 0!==kt(e,["enableEnhancedCivicAnswers"]))throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const b=kt(e,["translationConfig"]);return null!=b&&Nt(t,["translationConfig"],b),t}(i))}(r,n),n}(this.apiClient,e);return s=Pt("{model}:countTokens",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["totalTokens"]);return null!=o&&Nt(t,["totalTokens"],o),t}(e),n=new Yt;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["contents"]);if(null!=i){let e=Rn(i);Array.isArray(e)&&(e=e.map(e=>Ia(e))),Nt(n,["contents"],e)}const r=kt(t,["config"]);return null!=r&&function(e){if(void 0!==kt(e,["systemInstruction"]))throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["tools"]))throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["generationConfig"]))throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(r),n}(this.apiClient,e);return s=Pt("{model}:countTokens",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["totalTokens"]);null!=o&&Nt(t,["totalTokens"],o);const i=kt(e,["cachedContentTokenCount"]);return null!=i&&Nt(t,["cachedContentTokenCount"],i),t}(e),n=new Yt;return Object.assign(n,t),n})}}async computeTokens(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["_url","model"],vn(e,o));const i=kt(t,["contents"]);if(null!=i){let e=Rn(i);Array.isArray(e)&&(e=e.map(e=>Ca(e))),Nt(n,["contents"],e)}return n}(this.apiClient,e);return i=Pt("{model}:computeTokens",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["tokensInfo"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["tokensInfo"],e)}return t}(e),n=new Kt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=Ra(this.apiClient,e);return i=Pt("{model}:predictLongRunning",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["videos"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["_self"]);return null!=n&&Nt(t,["video"],function(e){const t={},n=kt(e,["gcsUri"]);null!=n&&Nt(t,["uri"],n);const o=kt(e,["bytesBase64Encoded"]);null!=o&&Nt(t,["videoBytes"],Ln(o));const i=kt(e,["mimeType"]);return null!=i&&Nt(t,["mimeType"],i),t}(n)),t}(e))),Nt(t,["generatedVideos"],e)}const o=kt(e,["raiMediaFilteredCount"]);null!=o&&Nt(t,["raiMediaFilteredCount"],o);const i=kt(e,["raiMediaFilteredReasons"]);return null!=i&&Nt(t,["raiMediaFilteredReasons"],i),t}(s)),t}(e),n=new zt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};Cl.loggedGenerateImagesWarning=!1,Cl.loggedEditImageWarning=!1,Cl.loggedGenerateVideosWarning=!1;var Sl=class extends Rt{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){const t=e.operation,n=e.config;if(void 0===t.name||""===t.name)throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const e=t.name.split("/operations/")[0];let o;n&&"httpOptions"in n&&(o=n.httpOptions);const i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:e,config:{httpOptions:o}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{const e=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async get(e){const t=e.operation,n=e.config;if(void 0===t.name||""===t.name)throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const e=t.name.split("/operations/")[0];let o;n&&"httpOptions"in n&&(o=n.httpOptions);const i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:e,config:{httpOptions:o}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{const e=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=kt(e,["operationName"]);return null!=n&&Nt(t,["_url","operationName"],n),t}(e);return s=Pt("{operationName}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r}{const t=function(e){const t={},n=kt(e,["operationName"]);return null!=n&&Nt(t,["_url","operationName"],n),t}(e);return s=Pt("{operationName}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r}}async fetchPredictVideosOperationInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e){const t={},n=kt(e,["operationName"]);null!=n&&Nt(t,["operationName"],n);const o=kt(e,["resourceName"]);return null!=o&&Nt(t,["_url","resourceName"],o),t}(e);return i=Pt("{resourceName}:fetchPredictOperation",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function bl(e,t,n){const o=kt(t,["expireTime"]);void 0!==n&&null!=o&&Nt(n,["expireTime"],o);const i=kt(t,["newSessionExpireTime"]);void 0!==n&&null!=i&&Nt(n,["newSessionExpireTime"],i);const r=kt(t,["uses"]);void 0!==n&&null!=r&&Nt(n,["uses"],r);const s=kt(t,["liveConnectConstraints"]);void 0!==n&&null!=s&&Nt(n,["bidiGenerateContentSetup"],function(e,t){const n={},o=kt(t,["model"]);null!=o&&Nt(n,["setup","model"],vn(e,o));const i=kt(t,["config"]);return null!=i&&Nt(n,["config"],function(e,t){const n=kt(e,["generationConfig"]);void 0!==t&&null!=n&&Nt(t,["setup","generationConfig"],n);const o=kt(e,["responseModalities"]);void 0!==t&&null!=o&&Nt(t,["setup","generationConfig","responseModalities"],o);const i=kt(e,["temperature"]);void 0!==t&&null!=i&&Nt(t,["setup","generationConfig","temperature"],i);const r=kt(e,["topP"]);void 0!==t&&null!=r&&Nt(t,["setup","generationConfig","topP"],r);const s=kt(e,["topK"]);void 0!==t&&null!=s&&Nt(t,["setup","generationConfig","topK"],s);const a=kt(e,["maxOutputTokens"]);void 0!==t&&null!=a&&Nt(t,["setup","generationConfig","maxOutputTokens"],a);const l=kt(e,["mediaResolution"]);void 0!==t&&null!=l&&Nt(t,["setup","generationConfig","mediaResolution"],l);const u=kt(e,["seed"]);void 0!==t&&null!=u&&Nt(t,["setup","generationConfig","seed"],u);const c=kt(e,["speechConfig"]);void 0!==t&&null!=c&&Nt(t,["setup","generationConfig","speechConfig"],Dn(c));const d=kt(e,["thinkingConfig"]);void 0!==t&&null!=d&&Nt(t,["setup","generationConfig","thinkingConfig"],d);const p=kt(e,["enableAffectiveDialog"]);void 0!==t&&null!=p&&Nt(t,["setup","generationConfig","enableAffectiveDialog"],p);const m=kt(e,["systemInstruction"]);void 0!==t&&null!=m&&Nt(t,["setup","systemInstruction"],function(e){const t={},n=kt(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);null!=n&&Nt(t,["mediaResolution"],n);const o=kt(e,["toolCall"]);null!=o&&Nt(t,["toolCall"],o);const i=kt(e,["toolResponse"]);null!=i&&Nt(t,["toolResponse"],i);const r=kt(e,["audioTranscription"]);null!=r&&Nt(t,["audioTranscription"],r);const s=kt(e,["codeExecutionResult"]);null!=s&&Nt(t,["codeExecutionResult"],s);const a=kt(e,["executableCode"]);null!=a&&Nt(t,["executableCode"],a);const l=kt(e,["fileData"]);null!=l&&Nt(t,["fileData"],l);const u=kt(e,["functionCall"]);null!=u&&Nt(t,["functionCall"],function(e){const t={},n=kt(e,["args"]);null!=n&&Nt(t,["args"],n);const o=kt(e,["id"]);null!=o&&Nt(t,["id"],o);const i=kt(e,["name"]);if(null!=i&&Nt(t,["name"],i),void 0!==kt(e,["partialArgs"]))throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(u));const c=kt(e,["functionResponse"]);null!=c&&Nt(t,["functionResponse"],c);const d=kt(e,["inlineData"]);null!=d&&Nt(t,["inlineData"],d);const p=kt(e,["text"]);null!=p&&Nt(t,["text"],p);const m=kt(e,["thought"]);null!=m&&Nt(t,["thought"],m);const h=kt(e,["thoughtSignature"]);null!=h&&Nt(t,["thoughtSignature"],h);const f=kt(e,["videoMetadata"]);null!=f&&Nt(t,["videoMetadata"],f);const v=kt(e,["partMetadata"]);null!=v&&Nt(t,["partMetadata"],v);const g=kt(e,["mediaProcessing"]);null!=g&&Nt(t,["mediaProcessing"],g);const _=kt(e,["speechMetadata"]);null!=_&&Nt(t,["speechMetadata"],_);const y=kt(e,["documentMetadata"]);null!=y&&Nt(t,["documentMetadata"],y);const E=kt(e,["spreadsheetMetadata"]);null!=E&&Nt(t,["spreadsheetMetadata"],E);const T=kt(e,["audioMetadata"]);return null!=T&&Nt(t,["audioMetadata"],T),t}(e))),Nt(t,["parts"],e)}const o=kt(e,["role"]);return null!=o&&Nt(t,["role"],o),t}(On(m)));const h=kt(e,["tools"]);if(void 0!==t&&null!=h){let e=xn(h);Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==kt(e,["retrieval"]))throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["googleMaps"]);null!=n&&Nt(t,["googleMaps"],function(e){const t={},n=kt(e,["authConfig"]);null!=n&&Nt(t,["authConfig"],function(e){const t={},n=kt(e,["apiKey"]);if(null!=n&&Nt(t,["apiKey"],n),void 0!==kt(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["authType"]))throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oauthConfig"]))throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["oidcConfig"]))throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["enableWidget"]);if(null!=o&&Nt(t,["enableWidget"],o),void 0!==kt(e,["groundingTypes"]))throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(n));const o=kt(e,["mcpServers"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["mcpServers"],e)}const i=kt(e,["codeExecution"]);null!=i&&Nt(t,["codeExecution"],i);const r=kt(e,["computerUse"]);if(null!=r&&Nt(t,["computerUse"],r),void 0!==kt(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["exaAiSearch"]))throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const s=kt(e,["functionDeclarations"]);if(null!=s){let e=s;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const a=kt(e,["googleSearch"]);null!=a&&Nt(t,["googleSearch"],function(e){const t={};if(void 0!==kt(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["excludeDomains"]))throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["searchTypes"]);null!=n&&Nt(t,["searchTypes"],n);const o=kt(e,["timeRangeFilter"]);return null!=o&&Nt(t,["timeRangeFilter"],o),t}(a));const l=kt(e,["googleSearchRetrieval"]);if(null!=l&&Nt(t,["googleSearchRetrieval"],l),void 0!==kt(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const u=kt(e,["urlContext"]);null!=u&&Nt(t,["urlContext"],u);const c=kt(e,["fileSearch"]);return null!=c&&Nt(t,["fileSearch"],c),t}(Mn(e)))),Nt(t,["setup","tools"],e)}const f=kt(e,["sessionResumption"]);void 0!==t&&null!=f&&Nt(t,["setup","sessionResumption"],function(e){const t={},n=kt(e,["handle"]);if(null!=n&&Nt(t,["handle"],n),void 0!==kt(e,["transparent"]))throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return t}(f));const v=kt(e,["inputAudioTranscription"]);void 0!==t&&null!=v&&Nt(t,["setup","inputAudioTranscription"],v);const g=kt(e,["outputAudioTranscription"]);void 0!==t&&null!=g&&Nt(t,["setup","outputAudioTranscription"],g);const _=kt(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&Nt(t,["setup","realtimeInputConfig"],_);const y=kt(e,["contextWindowCompression"]);void 0!==t&&null!=y&&Nt(t,["setup","contextWindowCompression"],y);const E=kt(e,["proactivity"]);if(void 0!==t&&null!=E&&Nt(t,["setup","proactivity"],E),void 0!==kt(e,["explicitVadSignal"]))throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const T=kt(e,["avatarConfig"]);void 0!==t&&null!=T&&Nt(t,["setup","avatarConfig"],T);const A=kt(e,["safetySettings"]);if(void 0!==t&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["category"]);if(null!=n&&Nt(t,["category"],n),void 0!==kt(e,["method"]))throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["threshold"]);return null!=o&&Nt(t,["threshold"],o),t}(e))),Nt(t,["setup","safetySettings"],e)}const I=kt(e,["translationConfig"]);void 0!==t&&null!=I&&Nt(t,["setup","generationConfig","translationConfig"],I);const C=kt(e,["labels"]);return void 0!==t&&null!=C&&Nt(t,["setup","labels"],C),{}}(i,n)),n}(e,s));const a=kt(t,["lockAdditionalFields"]);return void 0!==n&&null!=a&&Nt(n,["fieldMask"],a),{}}var Ol=class extends Rt{constructor(e){super(),this.apiClient=e}async create(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{const s=function(e,t){const n={},o=kt(t,["config"]);return null!=o&&Nt(n,["config"],bl(e,o,n)),n}(this.apiClient,e);i=Pt("auth_tokens",s._url),r=s._query,delete s.config,delete s._url,delete s._query;const a=function(e,t){let n=null;const o=e.bidiGenerateContentSetup;if("object"==typeof o&&null!==o&&"setup"in o){const t=o.setup;"object"==typeof t&&null!==t?(e.bidiGenerateContentSetup=t,n=t):delete e.bidiGenerateContentSetup}else void 0!==o&&delete e.bidiGenerateContentSetup;const i=e.fieldMask;if(n){const o=function(e){const t=[];for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const o=e[n];if("object"==typeof o&&null!=o&&!Array.isArray(o)&&Object.keys(o).length>0){const e=Object.keys(o).map(e=>`${n}.${e}`);t.push(...e)}else t.push(n)}return t.join(",")}(n);if(Array.isArray(null==t?void 0:t.lockAdditionalFields)&&0===(null==t?void 0:t.lockAdditionalFields.length))o?e.fieldMask=o:delete e.fieldMask;else if((null==t?void 0:t.lockAdditionalFields)&&t.lockAdditionalFields.length>0&&null!==i&&Array.isArray(i)&&i.length>0){const t=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let n=[];i.length>0&&(n=i.map(e=>t.includes(e)?`generationConfig.${e}`:e));const r=[];o&&r.push(o),n.length>0&&r.push(...n),r.length>0?e.fieldMask=r.join(","):delete e.fieldMask}else delete e.fieldMask}else null!==i&&Array.isArray(i)&&i.length>0?e.fieldMask=i.join(","):delete e.fieldMask;return e}(s,e.config);return o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}};var wl=class extends Rt{constructor(e){super(),this.apiClient=e,this.list=async e=>new to(Gt.PAGED_ITEM_DOCUMENTS,t=>this.listInternal({parent:e.parent,config:t.config}),await this.listInternal(e),e)}async get(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return i=Pt("{name}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async delete(e){var t,n;let o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const r=function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["_url","name"],n);const o=kt(e,["config"]);return null!=o&&function(e,t){const n=kt(e,["force"]);void 0!==t&&null!=n&&Nt(t,["_query","force"],n)}(o,t),t}(e);o=Pt("{name}",r._url),i=r._query,delete r._url,delete r._query,await this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(r),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal})}}async listInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["parent"]);null!=n&&Nt(t,["_url","parent"],n);const o=kt(e,["config"]);return null!=o&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o)}(o,t),t}(e);return i=Pt("{parent}/documents",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["documents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["documents"],e)}return t}(e),n=new on;return Object.assign(n,t),n})}}},Rl=class extends Rt{constructor(e,t=new wl(e)){super(),this.apiClient=e,this.documents=t,this.list=async(e={})=>new to(Gt.PAGED_ITEM_FILE_SEARCH_STORES,e=>this.listInternal(e),await this.listInternal(e),e)}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,t){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");const n=new URL(e,"http://dummy.com");let o=n.pathname;if(o.startsWith("/")&&(o=o.slice(1)),!o.includes("/media/"))throw new Error(`Invalid uri format: ${e}. Expected to contain /media/`);const i={};n.searchParams.forEach((e,t)=>{i[t]=e}),i.alt="media";const r=Object.assign({},null==t?void 0:t.httpOptions),s=await this.apiClient.request({path:o,httpMethod:"GET",queryParams:i,httpOptions:r});if(s instanceof Ut){const e=await s.responseInternal.arrayBuffer();return new Uint8Array(e)}throw new Error("Unexpected response type from downloadMedia")}async create(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e,t){const n={},o=kt(t,["config"]);return null!=o&&function(e,t,n){const o=kt(t,["displayName"]);void 0!==n&&null!=o&&Nt(n,["displayName"],o);const i=kt(t,["embeddingModel"]);void 0!==n&&null!=i&&Nt(n,["embeddingModel"],vn(e,i))}(e,o,n),n}(this.apiClient,e);return i=Pt("fileSearchStores",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async get(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return i=Pt("{name}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async delete(e){var t,n;let o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const r=function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["_url","name"],n);const o=kt(e,["config"]);return null!=o&&function(e,t){const n=kt(e,["force"]);void 0!==t&&null!=n&&Nt(t,["_query","force"],n)}(o,t),t}(e);o=Pt("{name}",r._url),i=r._query,delete r._url,delete r._query,await this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(r),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal})}}async listInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o)}(n,t),t}(e);return i=Pt("fileSearchStores",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["fileSearchStores"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["fileSearchStores"],e)}return t}(e),n=new rn;return Object.assign(n,t),n})}}async uploadToFileSearchStoreInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["fileSearchStoreName"]);null!=n&&Nt(t,["_url","file_search_store_name"],n);const o=kt(e,["config"]);return null!=o&&Ha(o,t),t}(e);return i=Pt("upload/{api_version}/{file_search_store_name}:uploadToFileSearchStore",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new sn;return Object.assign(n,t),n})}}async importFile(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["fileSearchStoreName"]);null!=n&&Nt(t,["_url","file_search_store_name"],n);const o=kt(e,["fileName"]);null!=o&&Nt(t,["fileName"],o);const i=kt(e,["config"]);return null!=i&&function(e,t){const n=kt(e,["customMetadata"]);if(void 0!==t&&null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["customMetadata"],e)}const o=kt(e,["chunkingConfig"]);void 0!==t&&null!=o&&Nt(t,["chunkingConfig"],o)}(i,t),t}(e);return i=Pt("{file_search_store_name}:importFile",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["name"],n);const o=kt(e,["metadata"]);null!=o&&Nt(t,["metadata"],o);const i=kt(e,["done"]);null!=i&&Nt(t,["done"],i);const r=kt(e,["error"]);null!=r&&Nt(t,["error"],r);const s=kt(e,["response"]);return null!=s&&Nt(t,["response"],function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["parent"]);null!=o&&Nt(t,["parent"],o);const i=kt(e,["documentName"]);return null!=i&&Nt(t,["documentName"],i),t}(s)),t}(e),n=new an;return Object.assign(n,t),n})}}};function Pl(e,t){const n={},o=kt(e,["parts"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["mediaResolution"]);if(null!=n&&Nt(t,["mediaResolution"],n),void 0!==kt(e,["toolCall"]))throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["toolResponse"]))throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const o=kt(e,["audioTranscription"]);null!=o&&Nt(t,["audioTranscription"],o);const i=kt(e,["codeExecutionResult"]);null!=i&&Nt(t,["codeExecutionResult"],i);const r=kt(e,["executableCode"]);null!=r&&Nt(t,["executableCode"],r);const s=kt(e,["fileData"]);null!=s&&Nt(t,["fileData"],s);const a=kt(e,["functionCall"]);null!=a&&Nt(t,["functionCall"],a);const l=kt(e,["functionResponse"]);null!=l&&Nt(t,["functionResponse"],function(e){const t={},n=kt(e,["id"]);null!=n&&Nt(t,["id"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["parts"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["fileData"]);null!=n&&Nt(t,["fileData"],n);const o=kt(e,["inlineData"]);if(null!=o&&Nt(t,["inlineData"],o),void 0!==kt(e,["mediaProcessing"]))throw new Error("mediaProcessing parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const i=kt(e,["mediaResolution"]);null!=i&&Nt(t,["mediaResolution"],i);const r=kt(e,["videoMetadata"]);null!=r&&Nt(t,["videoMetadata"],r);const s=kt(e,["documentMetadata"]);null!=s&&Nt(t,["documentMetadata"],s);const a=kt(e,["spreadsheetMetadata"]);null!=a&&Nt(t,["spreadsheetMetadata"],a);const l=kt(e,["audioMetadata"]);return null!=l&&Nt(t,["audioMetadata"],l),t}(e))),Nt(t,["parts"],e)}const r=kt(e,["response"]);null!=r&&Nt(t,["response"],r);const s=kt(e,["scheduling"]);if(null!=s&&Nt(t,["scheduling"],s),void 0!==kt(e,["willContinue"]))throw new Error("willContinue parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(l));const u=kt(e,["inlineData"]);null!=u&&Nt(t,["inlineData"],u);const c=kt(e,["text"]);null!=c&&Nt(t,["text"],c);const d=kt(e,["thought"]);null!=d&&Nt(t,["thought"],d);const p=kt(e,["thoughtSignature"]);null!=p&&Nt(t,["thoughtSignature"],p);const m=kt(e,["videoMetadata"]);if(null!=m&&Nt(t,["videoMetadata"],m),void 0!==kt(e,["partMetadata"]))throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");const h=kt(e,["mediaProcessing"]);null!=h&&Nt(t,["mediaProcessing"],h);const f=kt(e,["speechMetadata"]);null!=f&&Nt(t,["speechMetadata"],f);const v=kt(e,["documentMetadata"]);null!=v&&Nt(t,["documentMetadata"],v);const g=kt(e,["spreadsheetMetadata"]);null!=g&&Nt(t,["spreadsheetMetadata"],g);const _=kt(e,["audioMetadata"]);return null!=_&&Nt(t,["audioMetadata"],_),t}(e))),Nt(n,["parts"],e)}const i=kt(e,["role"]);return null!=i&&Nt(n,["role"],i),n}function Nl(e,t){const n={},o=kt(e,["epochCount"]);null!=o&&Nt(n,["epochCount"],o);const i=kt(e,["learningRateMultiplier"]);null!=i&&Nt(n,["learningRateMultiplier"],i);const r=kt(e,["adapterSize"]);null!=r&&Nt(n,["adapterSize"],r);const s=kt(e,["batchSize"]);null!=s&&Nt(n,["batchSize"],s);const a=kt(e,["learningRate"]);null!=a&&Nt(n,["learningRate"],a);const l=kt(e,["generationConfig"]);return null!=l&&Nt(n,["generationConfig"],function(e){const t={},n=kt(e,["modelConfig"]);null!=n&&Nt(t,["modelSelectionConfig"],n);const o=kt(e,["responseJsonSchema"]);null!=o&&Nt(t,["responseJsonSchema"],o);const i=kt(e,["audioTranscriptionConfig"]);null!=i&&Nt(t,["audioTranscriptionConfig"],i);const r=kt(e,["audioTimestamp"]);null!=r&&Nt(t,["audioTimestamp"],r);const s=kt(e,["candidateCount"]);null!=s&&Nt(t,["candidateCount"],s);const a=kt(e,["enableAffectiveDialog"]);null!=a&&Nt(t,["enableAffectiveDialog"],a);const l=kt(e,["frequencyPenalty"]);null!=l&&Nt(t,["frequencyPenalty"],l);const u=kt(e,["logprobs"]);null!=u&&Nt(t,["logprobs"],u);const c=kt(e,["maxOutputTokens"]);null!=c&&Nt(t,["maxOutputTokens"],c);const d=kt(e,["mediaResolution"]);null!=d&&Nt(t,["mediaResolution"],d);const p=kt(e,["presencePenalty"]);null!=p&&Nt(t,["presencePenalty"],p);const m=kt(e,["responseFormat"]);if(null!=m){let e=m;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["responseFormat"],e)}const h=kt(e,["responseLogprobs"]);null!=h&&Nt(t,["responseLogprobs"],h);const f=kt(e,["responseMimeType"]);null!=f&&Nt(t,["responseMimeType"],f);const v=kt(e,["responseModalities"]);null!=v&&Nt(t,["responseModalities"],v);const g=kt(e,["responseSchema"]);null!=g&&Nt(t,["responseSchema"],g);const _=kt(e,["routingConfig"]);null!=_&&Nt(t,["routingConfig"],_);const y=kt(e,["seed"]);null!=y&&Nt(t,["seed"],y);const E=kt(e,["speechConfig"]);null!=E&&Nt(t,["speechConfig"],E);const T=kt(e,["stopSequences"]);null!=T&&Nt(t,["stopSequences"],T);const A=kt(e,["temperature"]);null!=A&&Nt(t,["temperature"],A);const I=kt(e,["thinkingConfig"]);null!=I&&Nt(t,["thinkingConfig"],I);const C=kt(e,["topK"]);null!=C&&Nt(t,["topK"],C);const S=kt(e,["topP"]);null!=S&&Nt(t,["topP"],S);const b=kt(e,["translationConfig"]);return null!=b&&Nt(t,["translationConfig"],b),t}(l)),n}function kl(e,t){const n={},o=kt(e,["sdkHttpResponse"]);null!=o&&Nt(n,["sdkHttpResponse"],o);const i=kt(e,["name"]);null!=i&&Nt(n,["name"],i);const r=kt(e,["state"]);null!=r&&Nt(n,["state"],Un(r));const s=kt(e,["createTime"]);null!=s&&Nt(n,["createTime"],s);const a=kt(e,["startTime"]);null!=a&&Nt(n,["startTime"],a);const l=kt(e,["endTime"]);null!=l&&Nt(n,["endTime"],l);const u=kt(e,["updateTime"]);null!=u&&Nt(n,["updateTime"],u);const c=kt(e,["error"]);null!=c&&Nt(n,["error"],c);const d=kt(e,["description"]);null!=d&&Nt(n,["description"],d);const p=kt(e,["baseModel"]);null!=p&&Nt(n,["baseModel"],p);const m=kt(e,["tunedModel"]);null!=m&&Nt(n,["tunedModel"],m);const h=kt(e,["preTunedModel"]);null!=h&&Nt(n,["preTunedModel"],h);const f=kt(e,["supervisedTuningSpec"]);null!=f&&Nt(n,["supervisedTuningSpec"],f);const v=kt(e,["preferenceOptimizationSpec"]);null!=v&&Nt(n,["preferenceOptimizationSpec"],v);const g=kt(e,["distillationSamplingSpec"]);null!=g&&Nt(n,["distillationSamplingSpec"],function(e){const t={},n=kt(e,["promptDatasetUri"]);null!=n&&Nt(t,["promptDatasetUri"],n);const o=kt(e,["validationDatasetUri"]);null!=o&&Nt(t,["validationDatasetUri"],o);const i=kt(e,["baseTeacherModel"]);null!=i&&Nt(t,["baseTeacherModel"],i);const r=kt(e,["tunedTeacherModelSource"]);null!=r&&Nt(t,["tunedTeacherModelSource"],r);const s=kt(e,["hyperparameters"]);return null!=s&&Nt(t,["hyperparameters"],Nl(s)),t}(g));const _=kt(e,["distillationSpec"]);null!=_&&Nt(n,["distillationSpec"],function(e){const t={},n=kt(e,["baseTeacherModel"]);null!=n&&Nt(t,["baseTeacherModel"],n);const o=kt(e,["hyperParameters"]);null!=o&&Nt(t,["hyperParameters"],Nl(o));const i=kt(e,["pipelineRootDirectory"]);null!=i&&Nt(t,["pipelineRootDirectory"],i);const r=kt(e,["promptDatasetUri"]);null!=r&&Nt(t,["promptDatasetUri"],r);const s=kt(e,["studentModel"]);null!=s&&Nt(t,["studentModel"],s);const a=kt(e,["trainingDatasetUri"]);null!=a&&Nt(t,["trainingDatasetUri"],a);const l=kt(e,["tunedTeacherModelSource"]);null!=l&&Nt(t,["tunedTeacherModelSource"],l);const u=kt(e,["tuningMode"]);null!=u&&Nt(t,["tuningMode"],u);const c=kt(e,["validationDatasetUri"]);return null!=c&&Nt(t,["validationDatasetUri"],c),t}(_));const y=kt(e,["reinforcementTuningSpec"]);null!=y&&Nt(n,["reinforcementTuningSpec"],y);const E=kt(e,["tuningDataStats"]);null!=E&&Nt(n,["tuningDataStats"],E);const T=kt(e,["encryptionSpec"]);null!=T&&Nt(n,["encryptionSpec"],T);const A=kt(e,["partnerModelTuningSpec"]);null!=A&&Nt(n,["partnerModelTuningSpec"],A);const I=kt(e,["customBaseModel"]);null!=I&&Nt(n,["customBaseModel"],I);const C=kt(e,["evaluateDatasetRuns"]);if(null!=C){let e=C;Array.isArray(e)&&(e=e.map(e=>e)),Nt(n,["evaluateDatasetRuns"],e)}const S=kt(e,["experiment"]);null!=S&&Nt(n,["experiment"],S);const b=kt(e,["fullFineTuningSpec"]);null!=b&&Nt(n,["fullFineTuningSpec"],b);const O=kt(e,["labels"]);null!=O&&Nt(n,["labels"],O);const w=kt(e,["outputUri"]);null!=w&&Nt(n,["outputUri"],w);const R=kt(e,["pipelineJob"]);null!=R&&Nt(n,["pipelineJob"],R);const P=kt(e,["serviceAccount"]);null!=P&&Nt(n,["serviceAccount"],P);const N=kt(e,["tunedModelDisplayName"]);null!=N&&Nt(n,["tunedModelDisplayName"],N);const k=kt(e,["tuningJobMetadata"]);null!=k&&Nt(n,["tuningJobMetadata"],k);const D=kt(e,["tuningJobState"]);null!=D&&Nt(n,["tuningJobState"],D);const M=kt(e,["veoLoraTuningSpec"]);null!=M&&Nt(n,["veoLoraTuningSpec"],M);const x=kt(e,["veoTuningSpec"]);null!=x&&Nt(n,["veoTuningSpec"],x);const G=kt(e,["gcsMetricsUri"]);return null!=G&&Nt(n,["gcsMetricsUri"],G),n}function Dl(e,t){const n={},o=kt(e,["gcsUri"]);null!=o&&Nt(n,["validationDatasetUri"],o);const i=kt(e,["vertexDatasetResource"]);return null!=i&&Nt(n,["validationDatasetUri"],i),n}var Ml=class extends Rt{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new to(Gt.PAGED_ITEM_TUNING_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.get=async e=>await this.getInternal(e),this.tune=async e=>{var t;if(this.apiClient.isVertexAI()){if(e.baseModel.startsWith("projects/")){const n={tunedModelName:e.baseModel};(null===(t=e.config)||void 0===t?void 0:t.preTunedModelCheckpointId)&&(n.checkpointId=e.config.preTunedModelCheckpointId);const o=Object.assign(Object.assign({},e),{preTunedModel:n});return o.baseModel=void 0,await this.tuneInternal(o)}{const t=Object.assign({},e);return await this.tuneInternal(t)}}{const t=Object.assign({},e),n=await this.tuneMldevInternal(t);let o="";return void 0!==n.metadata&&void 0!==n.metadata.tunedModel?o=n.metadata.tunedModel:void 0!==n.name&&n.name.includes("/operations/")&&(o=n.name.split("/operations/")[0]),{name:o,state:Fe.JOB_STATE_QUEUED}}}}async getInternal(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return s=Pt("{name}",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>kl(e))}{const t=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return s=Pt("{name}",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["state"]);null!=i&&Nt(t,["state"],Un(i));const r=kt(e,["createTime"]);null!=r&&Nt(t,["createTime"],r);const s=kt(e,["tuningTask","startTime"]);null!=s&&Nt(t,["startTime"],s);const a=kt(e,["tuningTask","completeTime"]);null!=a&&Nt(t,["endTime"],a);const l=kt(e,["updateTime"]);null!=l&&Nt(t,["updateTime"],l);const u=kt(e,["description"]);null!=u&&Nt(t,["description"],u);const c=kt(e,["baseModel"]);null!=c&&Nt(t,["baseModel"],c);const d=kt(e,["_self"]);return null!=d&&Nt(t,["tunedModel"],function(e){const t={},n=kt(e,["name"]);null!=n&&Nt(t,["model"],n);const o=kt(e,["name"]);return null!=o&&Nt(t,["endpoint"],o),t}(d)),t}(e))}}async listInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e){const t={},n=kt(e,["config"]);return null!=n&&function(e,t){const n=kt(e,["pageSize"]);void 0!==t&&null!=n&&Nt(t,["_query","pageSize"],n);const o=kt(e,["pageToken"]);void 0!==t&&null!=o&&Nt(t,["_query","pageToken"],o);const i=kt(e,["filter"]);void 0!==t&&null!=i&&Nt(t,["_query","filter"],i)}(n,t),t}(e);return i=Pt("tuningJobs",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["nextPageToken"]);null!=o&&Nt(t,["nextPageToken"],o);const i=kt(e,["tuningJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>kl(e))),Nt(t,["tuningJobs"],e)}return t}(e),n=new Zt;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var t,n,o,i;let r,s="",a={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return s=Pt("{name}:cancel",o._url),a=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new Qt;return Object.assign(n,t),n})}{const t=function(e){const t={},n=kt(e,["name"]);return null!=n&&Nt(t,["_url","name"],n),t}(e);return s=Pt("{name}:cancel",t._url),a=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);return null!=n&&Nt(t,["sdkHttpResponse"],n),t}(e),n=new Qt;return Object.assign(n,t),n})}}async tuneInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=kt(e,["baseModel"]);null!=o&&Nt(n,["baseModel"],o);const i=kt(e,["preTunedModel"]);null!=i&&Nt(n,["preTunedModel"],i);const r=kt(e,["trainingDataset"]);null!=r&&function(e,t,n){let o=kt(n,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){const n=kt(e,["gcsUri"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","trainingDatasetUri"],n)}else if("PREFERENCE_TUNING"===o){const n=kt(e,["gcsUri"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","trainingDatasetUri"],n)}else if("DISTILLATION"===o){const n=kt(e,["gcsUri"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","promptDatasetUri"],n)}else if("REINFORCEMENT_TUNING"===o){const n=kt(e,["gcsUri"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","trainingDatasetUri"],n)}let i=kt(n,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){const n=kt(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","trainingDatasetUri"],n)}else if("PREFERENCE_TUNING"===i){const n=kt(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","trainingDatasetUri"],n)}else if("DISTILLATION"===i){const n=kt(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","promptDatasetUri"],n)}else if("REINFORCEMENT_TUNING"===i){const n=kt(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","trainingDatasetUri"],n)}if(void 0!==kt(e,["examples"]))throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.")}(r,n,t);const s=kt(e,["config"]);return null!=s&&function(e,t,n){let o=kt(n,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){const n=kt(e,["validationDataset"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec"],Dl(n))}else if("PREFERENCE_TUNING"===o){const n=kt(e,["validationDataset"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec"],Dl(n))}else if("DISTILLATION"===o){const n=kt(e,["validationDataset"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec"],Dl(n))}else if("REINFORCEMENT_TUNING"===o){const n=kt(e,["validationDataset"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec"],Dl(n))}const i=kt(e,["tunedModelDisplayName"]);void 0!==t&&null!=i&&Nt(t,["tunedModelDisplayName"],i);const r=kt(e,["description"]);void 0!==t&&null!=r&&Nt(t,["description"],r);let s=kt(n,["config","method"]);if(void 0===s&&(s="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===s){const n=kt(e,["epochCount"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","hyperParameters","epochCount"],n)}else if("PREFERENCE_TUNING"===s){const n=kt(e,["epochCount"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],n)}else if("DISTILLATION"===s){const n=kt(e,["epochCount"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","hyperParameters","epochCount"],n)}else if("REINFORCEMENT_TUNING"===s){const n=kt(e,["epochCount"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","hyperParameters","epochCount"],n)}let a=kt(n,["config","method"]);if(void 0===a&&(a="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===a){const n=kt(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],n)}else if("PREFERENCE_TUNING"===a){const n=kt(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],n)}else if("DISTILLATION"===a){const n=kt(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","hyperParameters","learningRateMultiplier"],n)}else if("REINFORCEMENT_TUNING"===a){const n=kt(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],n)}let l=kt(n,["config","method"]);if(void 0===l&&(l="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===l){const n=kt(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","exportLastCheckpointOnly"],n)}else if("PREFERENCE_TUNING"===l){const n=kt(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],n)}else if("DISTILLATION"===l){const n=kt(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","exportLastCheckpointOnly"],n)}let u=kt(n,["config","method"]);if(void 0===u&&(u="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===u){const n=kt(e,["adapterSize"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","hyperParameters","adapterSize"],n)}else if("PREFERENCE_TUNING"===u){const n=kt(e,["adapterSize"]);void 0!==t&&null!=n&&Nt(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],n)}else if("DISTILLATION"===u){const n=kt(e,["adapterSize"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","hyperParameters","adapterSize"],n)}else if("REINFORCEMENT_TUNING"===u){const n=kt(e,["adapterSize"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","hyperParameters","adapterSize"],n)}let c=kt(n,["config","method"]);if(void 0===c&&(c="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===c){const n=kt(e,["tuningMode"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","tuningMode"],n)}else if("DISTILLATION"===c){const n=kt(e,["tuningMode"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","tuningMode"],n)}const d=kt(e,["customBaseModel"]);void 0!==t&&null!=d&&Nt(t,["customBaseModel"],d);let p=kt(n,["config","method"]);if(void 0===p&&(p="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===p){const n=kt(e,["batchSize"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","hyperParameters","batchSize"],n)}else if("DISTILLATION"===p){const n=kt(e,["batchSize"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","hyperParameters","batchSize"],n)}else if("REINFORCEMENT_TUNING"===p){const n=kt(e,["batchSize"]);void 0!==t&&null!=n&&Nt(t,["reinforcementTuningSpec","hyperParameters","batchSize"],n)}let m=kt(n,["config","method"]);if(void 0===m&&(m="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===m){const n=kt(e,["learningRate"]);void 0!==t&&null!=n&&Nt(t,["supervisedTuningSpec","hyperParameters","learningRate"],n)}else if("DISTILLATION"===m){const n=kt(e,["learningRate"]);void 0!==t&&null!=n&&Nt(t,["distillationSpec","hyperParameters","learningRate"],n)}const h=kt(e,["labels"]);void 0!==t&&null!=h&&Nt(t,["labels"],h);const f=kt(e,["beta"]);void 0!==t&&null!=f&&Nt(t,["preferenceOptimizationSpec","hyperParameters","beta"],f);const v=kt(e,["baseTeacherModel"]);void 0!==t&&null!=v&&Nt(t,["distillationSpec","baseTeacherModel"],v);const g=kt(e,["tunedTeacherModelSource"]);void 0!==t&&null!=g&&Nt(t,["distillationSpec","tunedTeacherModelSource"],g);const _=kt(e,["sftLossWeightMultiplier"]);void 0!==t&&null!=_&&Nt(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],_);const y=kt(e,["outputUri"]);void 0!==t&&null!=y&&Nt(t,["outputUri"],y);const E=kt(e,["rewardConfig"]);void 0!==t&&null!=E&&Nt(t,["reinforcementTuningSpec","singleRewardConfig"],E);const T=kt(e,["compositeRewardConfig"]);void 0!==t&&null!=T&&Nt(t,["reinforcementTuningSpec","compositeRewardConfig"],T);const A=kt(e,["samplesPerPrompt"]);void 0!==t&&null!=A&&Nt(t,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],A);const I=kt(e,["evaluateInterval"]);void 0!==t&&null!=I&&Nt(t,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],I);const C=kt(e,["checkpointInterval"]);void 0!==t&&null!=C&&Nt(t,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],C);const S=kt(e,["maxOutputTokens"]);void 0!==t&&null!=S&&Nt(t,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],S);const b=kt(e,["thinkingLevel"]);void 0!==t&&null!=b&&Nt(t,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],b);const O=kt(e,["validationDatasetUri"]);void 0!==t&&null!=O&&Nt(t,["reinforcementTuningSpec","validationDatasetUri"],O);const w=kt(e,["encryptionSpec"]);void 0!==t&&null!=w&&Nt(t,["encryptionSpec"],w)}(s,n,t),n}(e,e);return i=Pt("tuningJobs",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>kl(e))}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=kt(e,["baseModel"]);null!=n&&Nt(t,["baseModel"],n);const o=kt(e,["preTunedModel"]);null!=o&&Nt(t,["preTunedModel"],o);const i=kt(e,["trainingDataset"]);null!=i&&function(e){const t={};if(void 0!==kt(e,["gcsUri"]))throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["vertexDatasetResource"]))throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["examples"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["examples","examples"],e)}}(i);const r=kt(e,["config"]);return null!=r&&function(e,t){if(void 0!==kt(e,["validationDataset"]))throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const n=kt(e,["tunedModelDisplayName"]);if(void 0!==t&&null!=n&&Nt(t,["displayName"],n),void 0!==kt(e,["description"]))throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const o=kt(e,["epochCount"]);void 0!==t&&null!=o&&Nt(t,["tuningTask","hyperparameters","epochCount"],o);const i=kt(e,["learningRateMultiplier"]);if(null!=i&&Nt({},["tuningTask","hyperparameters","learningRateMultiplier"],i),void 0!==kt(e,["exportLastCheckpointOnly"]))throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["preTunedModelCheckpointId"]))throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["adapterSize"]))throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["tuningMode"]))throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["customBaseModel"]))throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");const r=kt(e,["batchSize"]);void 0!==t&&null!=r&&Nt(t,["tuningTask","hyperparameters","batchSize"],r);const s=kt(e,["learningRate"]);if(void 0!==t&&null!=s&&Nt(t,["tuningTask","hyperparameters","learningRate"],s),void 0!==kt(e,["labels"]))throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["beta"]))throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["baseTeacherModel"]))throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["tunedTeacherModelSource"]))throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["sftLossWeightMultiplier"]))throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["outputUri"]))throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["rewardConfig"]))throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["compositeRewardConfig"]))throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["samplesPerPrompt"]))throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["evaluateInterval"]))throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["checkpointInterval"]))throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["maxOutputTokens"]))throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["thinkingLevel"]))throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["validationDatasetUri"]))throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(void 0!==kt(e,["encryptionSpec"]))throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.")}(r,t),t}(e);return i=Pt("tunedModels",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["name"]);null!=o&&Nt(t,["name"],o);const i=kt(e,["metadata"]);null!=i&&Nt(t,["metadata"],i);const r=kt(e,["done"]);null!=r&&Nt(t,["done"],r);const s=kt(e,["error"]);return null!=s&&Nt(t,["error"],s),t}(e))}}async validateReward(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e){const t={},n=kt(e,["parent"]);null!=n&&Nt(t,["_url","parent"],n);const o=kt(e,["sampleResponse"]);null!=o&&Nt(t,["sampleResponse"],Pl(o));const i=kt(e,["example"]);null!=i&&Nt(t,["example"],function(e){const t={},n=kt(e,["references"]);null!=n&&Nt(t,["references"],n);const o=kt(e,["contents"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Pl(e))),Nt(t,["contents"],e)}const i=kt(e,["systemInstruction"]);null!=i&&Nt(t,["systemInstruction"],Pl(i));const r=kt(e,["tools"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=kt(e,["retrieval"]);null!=n&&Nt(t,["retrieval"],n);const o=kt(e,["googleMaps"]);null!=o&&Nt(t,["googleMaps"],o);const i=kt(e,["mcpServers"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){if(void 0!==kt(e,["name"]))throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(void 0!==kt(e,["streamableHttpTransport"]))throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return{}}(e))),Nt(t,["mcpServers"],e)}const r=kt(e,["codeExecution"]);null!=r&&Nt(t,["codeExecution"],r);const s=kt(e,["computerUse"]);null!=s&&Nt(t,["computerUse"],s);const a=kt(e,["enterpriseWebSearch"]);null!=a&&Nt(t,["enterpriseWebSearch"],a);const l=kt(e,["exaAiSearch"]);null!=l&&Nt(t,["exaAiSearch"],l);const u=kt(e,["functionDeclarations"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),Nt(t,["functionDeclarations"],e)}const c=kt(e,["googleSearch"]);null!=c&&Nt(t,["googleSearch"],c);const d=kt(e,["googleSearchRetrieval"]);null!=d&&Nt(t,["googleSearchRetrieval"],d);const p=kt(e,["parallelAiSearch"]);null!=p&&Nt(t,["parallelAiSearch"],p);const m=kt(e,["urlContext"]);if(null!=m&&Nt(t,["urlContext"],m),void 0!==kt(e,["fileSearch"]))throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return t}(e))),Nt(t,["tools"],e)}return t}(i));const r=kt(e,["singleRewardConfig"]);null!=r&&Nt(t,["singleRewardConfig"],r);const s=kt(e,["compositeRewardConfig"]);return null!=s&&Nt(t,["compositeRewardConfig"],s),t}(e);return i=Pt("{parent}/tuningJobs:validateReinforcementTuningReward",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=kt(e,["sdkHttpResponse"]);null!=n&&Nt(t,["sdkHttpResponse"],n);const o=kt(e,["overallReward"]);null!=o&&Nt(t,["overallReward"],o);const i=kt(e,["error"]);null!=i&&Nt(t,["error"],i);const r=kt(e,["rewardInfoDetails"]);return null!=r&&Nt(t,["rewardInfoDetails"],r),t}(e),n=new en;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},xl=class{async download(e,t){throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.")}},Gl="x-goog-upload-status";async function Ul(e,t,n,o){var i,r,s;let a=t;const l=(null==o?void 0:o.baseUrl)||(null===(i=n.clientOptions.httpOptions)||void 0===i?void 0:i.baseUrl);if(l){const e=new URL(l),n=new URL(t);n.protocol=e.protocol,n.host=e.host,n.port=e.port,a=n.toString()}let u=0,c=0,d=new Ut(new Response),p="upload";for(u=e.size;c<u;){const t=Math.min(8388608,u-c),i=e.slice(c,c+t);c+t>=u&&(p+=", finalize");let l=0,m=1e3;for(;l<3;){const e=Object.assign(Object.assign({},(null==o?void 0:o.headers)||{}),{"X-Goog-Upload-Command":p,"X-Goog-Upload-Offset":String(c)});if(d=await n.request({path:"",body:i,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},o),{apiVersion:"",baseUrl:a,headers:e})}),null===(r=null==d?void 0:d.headers)||void 0===r?void 0:r[Gl])break;l++,await Ll(m),m*=2}if(c+=t,"active"!==(null===(s=null==d?void 0:d.headers)||void 0===s?void 0:s[Gl]))break;if(u<=c)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return d}function Ll(e){return new Promise(t=>setTimeout(t,e))}var ql=class{async upload(e,t,n,o){if("string"==typeof e)throw new Error("File path is not supported in browser uploader.");return await async function(e,t,n,o){var i;const r=await Ul(e,t,n,o),s=await(null==r?void 0:r.json());if("final"!==(null===(i=null==r?void 0:r.headers)||void 0===i?void 0:i[Gl]))throw new Error("Failed to upload file: Upload status is not finalized.");return s.file}(e,t,n,o)}async uploadToFileSearchStore(e,t,n,o){if("string"==typeof e)throw new Error("File path is not supported in browser uploader.");return await async function(e,t,n,o){var i;const r=await Ul(e,t,n,o),s=await(null==r?void 0:r.json());if("final"!==(null===(i=null==r?void 0:r.headers)||void 0===i?void 0:i[Gl]))throw new Error("Failed to upload file: Upload status is not finalized.");const a=xt(s),l=new fn;return Object.assign(l,a),l}(e,t,n,o)}async stat(e){if("string"==typeof e)throw new Error("File path is not supported in browser uploader.");return await async function(e){return{size:e.size,type:e.type}}(e)}},Hl=class{constructor(){this.supportsHeaders=!1}create(e,t,n){return new jl(e,t,n)}},jl=class{constructor(e,t,n){this.url=e,this.headers=t,this.callbacks=n}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(void 0===this.ws)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(void 0===this.ws)throw new Error("WebSocket is not connected");this.ws.close()}},Fl="x-goog-api-key",Xl=class{constructor(e){this.apiKey=e}async addAuthHeaders(e,t){if(null===e.get(Fl)){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(Fl,this.apiKey)}}},Bl=class{getNextGenClient(){const e=this.httpOptions;return void 0===this._nextGenClient&&(this._nextGenClient=Xs(this.apiClient,{timeout_ms:null==e?void 0:e.timeout})),null==e||e.extraBody,this._nextGenClient}get interactions(){return void 0!==this._interactions||(this._interactions=new Vs(this.apiClient,new Hl)),this._interactions}get webhooks(){return void 0!==this._webhooks||(this._webhooks=new $s(this.apiClient)),this._webhooks}get agents(){return void 0!==this._agents||(this._agents=new Js(this.apiClient)),this._agents}get triggers(){return void 0!==this._triggers||(this._triggers=new Ws(this.apiClient)),this._triggers}get environments(){return void 0!==this._environments||(this._environments=new la(this.apiClient)),this._environments}get credentials(){return void 0!==this._credentials||(this._credentials=new ua(this.apiClient)),this._credentials}get voices(){return void 0!==this._voices||(this._voices=new ca(this.apiClient)),this._voices}get decisions(){return void 0!==this._decisions||(this._decisions=new da(this.apiClient)),this._decisions}constructor(e={}){var t;if(null==e.apiKey)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=null!==(t=e.vertexai)&&void 0!==t&&t,this.apiKey=e.apiKey;const n=function(e,t){var n,o;if(!(null==e?void 0:e.baseUrl)){const e={geminiUrl:void 0,vertexUrl:void 0};return t?null!==(n=e.vertexUrl)&&void 0!==n?n:void 0:null!==(o=e.geminiUrl)&&void 0!==o?o:void 0}return e.baseUrl}(e.httpOptions,e.vertexai);n&&(e.httpOptions?e.httpOptions.baseUrl=n:e.httpOptions={baseUrl:n}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;const o=new Xl(this.apiKey);this.apiClient=new Va({auth:o,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:"gl-node/web",uploader:new ql,downloader:new xl}),this.models=new Cl(this.apiClient),this.live=new tl(this.apiClient,o,new Hl),this.batches=new no(this.apiClient),this.chats=new uo(this.models,this.apiClient),this.caches=new ro(this.apiClient),this.files=new ho(this.apiClient),this.operations=new Sl(this.apiClient),this.authTokens=new Ol(this.apiClient),this.tunings=new Ml(this.apiClient),this.fileSearchStores=new Rl(this.apiClient)}},Vl={THINKING_LEVEL_UNSPECIFIED:fe.THINKING_LEVEL_UNSPECIFIED,MINIMAL:fe.MINIMAL,LOW:fe.LOW,MEDIUM:fe.MEDIUM,HIGH:fe.HIGH,XHIGH:fe.XHIGH};function Jl(e,t){const n=e.thinkingLevelMap?.[t],o="string"==typeof n?n.toLowerCase():t;switch(o){case"minimal":case"low":case"medium":case"high":case"xhigh":return o;default:throw new Error(`Unsupported Google thinking level mapping for ${e.provider}/${e.id}: ${t} -> ${String(n)}`)}}function $l(e){const t=e.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(t)||(nu(t)??0)>=4||"gemini-flash-latest"===t||"gemini-flash-lite-latest"===t||/gemma-?4/.test(t)}function Wl(e){switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH";case"xhigh":return"XHIGH"}}function Yl(e,t,n){const o="xhigh"===t?"high":t,i=n?.[o];return void 0!==i?i:e.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[o]:e.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[o]:e.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[o]:-1}function Kl(e){return Vl[e]}function zl(e){return!0===e.thought}function Zl(e,t){return"string"==typeof t&&t.length>0?t:e}var Ql=/^[A-Za-z0-9+/]+={0,2}$/;function eu(e,t){return e&&function(e){return!!e&&e.length%4==0&&Ql.test(e)}(t)?t:void 0}function tu(e){const t=nu(e);return e.startsWith("claude-")||e.startsWith("gpt-oss-")||void 0!==t&&t>=3}function nu(e){const t=e.toLowerCase().match(/gemini(?:-live)?-(\d+)/);if(t)return Number.parseInt(t[1],10)}function ou(e){const t=nu(e);return void 0===t||t>=3}var iu=/* @__PURE__ */new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function ru(e){if("object"!=typeof e||null===e||Array.isArray(e))return e;const t={};for(const[n,o]of Object.entries(e))iu.has(n)||(t[n]=ru(o));return t}var su=/* @__PURE__ */new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]),au=/* @__PURE__ */new Set(["additionalProperties","unevaluatedProperties","propertyNames","items","prefixItems","additionalItems","unevaluatedItems","contains","allOf","anyOf","oneOf","not","if","then","else","contentSchema"]);function lu(e,t=!1){if(Array.isArray(e))return e.map(e=>lu(e));if("object"!=typeof e||null===e)return e;const n=Object.fromEntries(Object.entries(e).map(([e,n])=>t||au.has(e)?[e,lu(n)]:su.has(e)?[e,lu(n,!0)]:[e,n]));if(!t&&"const"in n&&void 0===n.enum){const e=n.const;"string"!=typeof e&&"number"!=typeof e||(delete n.const,n.enum=[e])}return n}function uu(e,t=!1,n=!0){if(0!==e.length)return[{functionDeclarations:e.map(e=>{const o=v(e,n),i=y(e,o);return{name:e.name,description:e.description,...t?{parameters:ru(i)}:{parametersJsonSchema:lu(i)}}})}]}function cu(e){switch(e){case"auto":default:return Te.AUTO;case"none":return Te.NONE;case"any":return Te.ANY}}function du(e,t){const n=[`${e} prompt blocked: ${t.blockReason??"unknown reason"}`];if(t.blockReasonMessage&&n.push(t.blockReasonMessage),t.safetyRatings?.length){const e=t.safetyRatings.flatMap(e=>e.category?[`${e.category}${e.probability?` (${e.probability})`:""}`]:[]);e.length>0&&n.push(`Safety rating${1===e.length?"":"s"}: ${e.join(", ")}`)}return n.join(". ")}function pu(e){switch(e){case Ie.STOP:return"stop";case Ie.MAX_TOKENS:case Ie.CONTINUATION:return"length";case Ie.BLOCKLIST:case Ie.PROHIBITED_CONTENT:case Ie.SPII:case Ie.SAFETY:case Ie.IMAGE_SAFETY:case Ie.IMAGE_PROHIBITED_CONTENT:case Ie.IMAGE_RECITATION:case Ie.IMAGE_OTHER:case Ie.RECITATION:case Ie.FINISH_REASON_UNSPECIFIED:case Ie.OTHER:case Ie.LANGUAGE:case Ie.MALFORMED_FUNCTION_CALL:case Ie.UNEXPECTED_TOOL_CALL:case Ie.TOO_MANY_TOOL_CALLS:case Ie.NO_IMAGE:case Ie.MISSING_THOUGHT_SIGNATURE:case Ie.MALFORMED_RESPONSE:case Ie.ESCALATION:case Ie.PUP_LIMITED_DISABLED:case Ie.MODEL_ARMOR:return"error";default:throw new Error(`Unhandled stop reason: ${e}`)}}var mu=0,hu=(e,t,g)=>{const y=new c,E=r(t);return(async()=>{const t={role:"assistant",content:[],api:"google-generative-ai",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{const c=g?.apiKey;if(!c)throw new Error(`No API key for provider: ${e.provider}`);const d=function(e,t,n,o,i){const r={fetch:i??globalThis.fetch};e.baseUrl&&(r.baseUrl=e.baseUrl,r.apiVersion="");const s=m(u(e,o),e.headers,n);return s&&(r.headers=s),new Bl({apiKey:t,httpOptions:r})}(e,c,g?.headers,g?.identity,g?.fetch);let p=function(e,t,o={}){const u=function(e,t){const n=l(r(t).messages),o=[],i=_(n,e,t=>tu(e.id)?t.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):t);for(const r of i)if("user"===r.role)if("string"==typeof r.content)o.push({role:"user",parts:[{text:f(r.content)}]});else{const e=r.content.map(e=>"text"===e.type?{text:f(e.text)}:{inlineData:{mimeType:e.mimeType,data:e.data}});if(0===e.length)continue;o.push({role:"user",parts:e})}else if("assistant"===r.role){const t=[],n=r.provider===e.provider&&r.model===e.id;for(const o of r.content)if("text"===o.type){const e=eu(n,o.textSignature);if(!(o.text&&""!==o.text.trim()||e))continue;t.push({text:f(o.text),...e&&{thoughtSignature:e}})}else if("thinking"===o.type)if(n){const e=eu(n,o.thinkingSignature);if(!(o.thinking&&""!==o.thinking.trim()||e))continue;t.push({thought:!0,text:f(o.thinking),...e&&{thoughtSignature:e}})}else{if(!o.thinking||""===o.thinking.trim())continue;t.push({text:f(o.thinking)})}else if("toolCall"===o.type){const i=eu(n,o.thoughtSignature),r={functionCall:{name:o.name,args:o.arguments??{},...tu(e.id)?{id:o.id}:{}},...i&&{thoughtSignature:i}};t.push(r)}if(0===t.length)continue;o.push({role:"model",parts:t})}else if("toolResult"===r.role){const t=r.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n=e.input.includes("image")?r.content.filter(e=>"image"===e.type):[],i=t.trim().length>0,s=n.length>0,a=ou(e.id),l=i?f(t):s?"(see attached image)":"",u=n.map(e=>({inlineData:{mimeType:e.mimeType,data:e.data}})),c=tu(e.id),d={functionResponse:{name:r.toolName,response:r.isError?{error:l}:{output:l},...s&&a&&{parts:u},...c?{id:r.toolCallId}:{}}},p=o[o.length-1];"user"===p?.role&&p.parts?.some(e=>e.functionResponse)?p.parts.push(d):o.push({role:"user",parts:[d]}),s&&!a&&o.push({role:"user",parts:[{text:"Tool result image:"},...u]})}return o}(e,t),c=s(t.messages),d=a(t.messages),p={};void 0!==o.temperature&&(p.temperature=o.temperature),void 0!==o.maxTokens&&(p.maxOutputTokens=o.maxTokens);const m=function(e){const t=nu(e.id);return e.compat?.supportsStrictMode??(void 0!==t&&t>=3)}(e),h=d.length>0?function(e,t,n){const o=e.some(e=>!0===v(e,n));return"none"===t||"any"===t?cu(t):o?Te.VALIDATED:t?cu(t):void 0}(d,o.toolChoice,m):void 0,g=c?n(c):"",y={...Object.keys(p).length>0&&p,...g&&{systemInstruction:f(g)},...d.length>0&&{tools:uu(d,!1,m)},...void 0!==h&&{toolConfig:{functionCallingConfig:{mode:h}}},automaticContinuation:!1};if(o.thinking?.enabled&&e.reasoning){const e={includeThoughts:!0};void 0!==o.thinking.level?e.thinkingLevel=Kl(o.thinking.level):void 0!==o.thinking.budgetTokens&&(e.thinkingBudget=o.thinking.budgetTokens),y.thinkingConfig=e}else e.reasoning&&o.thinking&&!o.thinking.enabled&&(y.thinkingConfig=function(e){if(!$l(e))return{thinkingBudget:0};const t=i(e,"off");return"off"===t?{thinkingBudget:0}:{thinkingLevel:Kl(Wl(Jl(e,t)))}}(e));if(o.signal){if(o.signal.aborted)throw new Error("Request aborted");y.abortSignal=o.signal}return{model:e.id,contents:u,config:y}}(e,E,g);const T=await(g?.onPayload?.(p,e));void 0!==T&&(p=T);const A=await function(e,t,n){return h(async()=>{try{return await d.models.generateContentStream(p)}catch(e){throw e instanceof Error&&"status"in e&&!("headers"in e)&&(e.headers=void 0),e}},{maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,signal:n?.signal,onErrorResponse:e=>n?.onResponse?.(e,t)})}(0,e,g);y.push({type:"start",partial:t});let I,C=null,S=0;const b=t.content,O=()=>b.length-1;for await(const n of A){await(g?.onProviderStreamEvent?.(n,e)),S++,n.promptFeedback?.blockReason&&(I??=du("Google",n.promptFeedback)),t.responseId||=n.responseId;const i=n.candidates?.[0];if(i?.content?.parts)for(const e of i.content.parts){if(void 0!==e.text){const n=zl(e);(!C||n&&"thinking"!==C.type||!n&&"text"!==C.type)&&(C&&("text"===C.type?y.push({type:"text_end",contentIndex:b.length-1,content:C.text,partial:t}):y.push({type:"thinking_end",contentIndex:O(),content:C.thinking,partial:t})),n?(C={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(C),y.push({type:"thinking_start",contentIndex:O(),partial:t})):(C={type:"text",text:""},t.content.push(C),y.push({type:"text_start",contentIndex:O(),partial:t}))),"thinking"===C.type?(C.thinking+=e.text,C.thinkingSignature=Zl(C.thinkingSignature,e.thoughtSignature),y.push({type:"thinking_delta",contentIndex:O(),delta:e.text,partial:t})):(C.text+=e.text,C.textSignature=Zl(C.textSignature,e.thoughtSignature),y.push({type:"text_delta",contentIndex:O(),delta:e.text,partial:t}))}if(e.functionCall){C&&("text"===C.type?y.push({type:"text_end",contentIndex:O(),content:C.text,partial:t}):y.push({type:"thinking_end",contentIndex:O(),content:C.thinking,partial:t}),C=null);const n=e.functionCall.id,o={type:"toolCall",id:!n||t.content.some(e=>"toolCall"===e.type&&e.id===n)?`${e.functionCall.name}_${Date.now()}_${++mu}`:n,name:e.functionCall.name||"",arguments:e.functionCall.args??{},...e.thoughtSignature&&{thoughtSignature:e.thoughtSignature}};t.content.push(o),y.push({type:"toolcall_start",contentIndex:O(),partial:t}),y.push({type:"toolcall_delta",contentIndex:O(),delta:JSON.stringify(o.arguments),partial:t}),y.push({type:"toolcall_end",contentIndex:O(),toolCall:o,partial:t})}}i?.finishReason&&(t.rawStopReason=i.finishReason,t.stopReason=pu(i.finishReason),t.content.some(e=>"toolCall"===e.type)&&"stop"===t.stopReason&&(t.stopReason="toolUse")),n.usageMetadata&&(t.usage={input:(n.usageMetadata.promptTokenCount||0)-(n.usageMetadata.cachedContentTokenCount||0),output:(n.usageMetadata.candidatesTokenCount||0)+(n.usageMetadata.thoughtsTokenCount||0),cacheRead:n.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:n.usageMetadata.thoughtsTokenCount||0,totalTokens:n.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},o(e,t.usage))}if(C&&("text"===C.type?y.push({type:"text_end",contentIndex:O(),content:C.text,partial:t}):y.push({type:"thinking_end",contentIndex:O(),content:C.thinking,partial:t})),g?.signal?.aborted)throw new Error("Request was aborted");if("pending"===t.stopReason){if(I)throw new Error(I);throw new Error(`Google stream ended without a finish reason after receiving ${S} ${1===S?"chunk":"chunks"}`)}if("aborted"===t.stopReason||"error"===t.stopReason){const e=t.rawStopReason?`Provider stopped with: ${t.rawStopReason}`:"An unknown error occurred";throw new Error(e)}y.push({type:"done",reason:t.stopReason,message:t}),y.end()}catch(c){t.stopReason=g?.signal?.aborted?"aborted":"error",t.errorMessage=p(d(c)),y.push({type:"error",reason:t.stopReason,error:t}),y.end()}})(),y},fu=(e,t,n)=>{const o=n?.apiKey;if(!o)throw new Error(`No API key for provider: ${e.provider}`);const r={...g(e,t,n,o),toolChoice:n?.toolChoice};if(!n?.reasoning)return hu(e,t,{...r,thinking:{enabled:!1}});const s=i(e,n.reasoning);if("off"===s)return hu(e,t,{...r,thinking:{enabled:!1}});const a=Jl(e,s);return $l(e)?hu(e,t,{...r,thinking:{enabled:!0,level:Wl(a)}}):hu(e,t,{...r,thinking:{enabled:!0,budgetTokens:Yl(e,a,n.thinkingBudgets)}})};export{hu as stream,fu as streamSimple};