@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
19 lines • 743 kB
JavaScript
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
import{require_src}from"./chunk-QPGJHUIK.js";import{normalizeToolCallId}from"./chunk-W7O55C7F.js";import{retryProviderRequest}from"./chunk-GIT63LXN.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-QD45L5SP.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{clampThinkingLevel,collapseSystemMessages,isGoogleGeneration4OrLaterModelId,withoutInitialSystemMessage}from"./chunk-AFDUWYAX.js";import{__commonJS,__require,__toESM}from"./chunk-IKOFCODM.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.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))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self=this;return this._timer=setTimeout(function(){self._attempts++,self._operationTimeoutCb&&(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref&&self._timeout.unref()),self._fn(self._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_constants=__commonJS({"node_modules/ws/lib/constants.js"(exports,module){"use strict";var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"],hasBlob=typeof Blob<"u";hasBlob&&BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports,module){"use strict";var{EMPTY_BUFFER}=require_constants(),FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];let target=Buffer.allocUnsafe(totalLength),offset=0;for(let i=0;i<list.length;i++){let buf=list[i];target.set(buf,offset),offset+=buf.length}return offset<totalLength?new FastBuffer(target.buffer,target.byteOffset,offset):target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++)output[offset+i]=source[i]^mask[i&3]}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++)buffer[i]^=mask[i&3]}function toArrayBuffer(buf){return buf.length===buf.buffer.byteLength?buf.buffer:buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){if(toBuffer.readOnly=!0,Buffer.isBuffer(data))return data;let buf;return data instanceof ArrayBuffer?buf=new FastBuffer(data):ArrayBuffer.isView(data)?buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength):(buf=Buffer.from(data),toBuffer.readOnly=!1),buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL)try{let bufferUtil=__require("bufferutil");module.exports.mask=function(source,mask,output,offset,length){length<48?_mask(source,mask,output,offset,length):bufferUtil.mask(source,mask,output,offset,length)},module.exports.unmask=function(buffer,mask){buffer.length<32?_unmask(buffer,mask):bufferUtil.unmask(buffer,mask)}}catch{}}});var require_limiter=__commonJS({"node_modules/ws/lib/limiter.js"(exports,module){"use strict";var kDone=Symbol("kDone"),kRun=Symbol("kRun"),Limiter=class{constructor(concurrency){this[kDone]=()=>{this.pending--,this[kRun]()},this.concurrency=concurrency||1/0,this.jobs=[],this.pending=0}add(job){this.jobs.push(job),this[kRun]()}[kRun](){if(this.pending!==this.concurrency&&this.jobs.length){let job=this.jobs.shift();this.pending++,job(this[kDone])}}};module.exports=Limiter}});var require_permessage_deflate=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports,module){"use strict";var zlib=__require("zlib"),bufferUtil=require_buffer_util(),Limiter=require_limiter(),{kStatusCode}=require_constants(),FastBuffer=Buffer[Symbol.species],TRAILER=Buffer.from([0,0,255,255]),kPerMessageDeflate=Symbol("permessage-deflate"),kTotalLength=Symbol("total-length"),kCallback=Symbol("callback"),kBuffers=Symbol("buffers"),kError=Symbol("error"),zlibLimiter,PerMessageDeflate2=class{constructor(options){if(this._options=options||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!zlibLimiter){let concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){let params={};return this._options.serverNoContextTakeover&&(params.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(params.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(params.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?params.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(params.client_max_window_bits=!0),params}accept(configurations){return configurations=this.normalizeParams(configurations),this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let callback=this._deflate[kCallback];this._deflate.close(),this._deflate=null,callback&&callback(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(offers){let opts=this._options,accepted=offers.find(params=>!(opts.serverNoContextTakeover===!1&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===!1||typeof opts.serverMaxWindowBits=="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits=="number"&&(typeof params.client_max_window_bits=="number"?opts.clientMaxWindowBits>params.client_max_window_bits:!params.client_max_window_bits)));if(!accepted)throw new Error("None of the extension offers can be accepted");return opts.serverNoContextTakeover&&(accepted.server_no_context_takeover=!0),opts.clientNoContextTakeover&&(accepted.client_no_context_takeover=!0),typeof opts.serverMaxWindowBits=="number"&&(accepted.server_max_window_bits=opts.serverMaxWindowBits),typeof opts.clientMaxWindowBits=="number"?accepted.client_max_window_bits=opts.clientMaxWindowBits:(accepted.client_max_window_bits===!0||opts.clientMaxWindowBits===!1)&&delete accepted.client_max_window_bits,accepted}acceptAsClient(response){let params=response[0];if(this._options.clientNoContextTakeover===!1&¶ms.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!params.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(params.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return params}normalizeParams(configurations){return configurations.forEach(params=>{Object.keys(params).forEach(key=>{let value=params[key];if(value.length>1)throw new Error(`Parameter "${key}" must have only a single value`);if(value=value[0],key==="client_max_window_bits"){if(value!==!0){let num=+value;if(!Number.isInteger(num)||num<8||num>15)throw new TypeError(`Invalid value for parameter "${key}": ${value}`);value=num}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}else if(key==="server_max_window_bits"){let num=+value;if(!Number.isInteger(num)||num<8||num>15)throw new TypeError(`Invalid value for parameter "${key}": ${value}`);value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==!0)throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}else throw new Error(`Unknown parameter "${key}"`);params[key]=value})}),configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err,result)=>{done(),callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err,result)=>{done(),callback(err,result)})})}_decompress(data,fin,callback){let endpoint=this._isServer?"client":"server";if(!this._inflate){let key=`${endpoint}_max_window_bits`,windowBits=typeof this.params[key]!="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits}),this._inflate[kPerMessageDeflate]=this,this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],this._inflate.on("error",inflateOnError),this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback,this._inflate.write(data),fin&&this._inflate.write(TRAILER),this._inflate.flush(()=>{let err=this._inflate[kError];if(err){this._inflate.close(),this._inflate=null,callback(err);return}let data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],fin&&this.params[`${endpoint}_no_context_takeover`]&&this._inflate.reset()),callback(null,data2)})}_compress(data,fin,callback){let endpoint=this._isServer?"server":"client";if(!this._deflate){let key=`${endpoint}_max_window_bits`,windowBits=typeof this.params[key]!="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits}),this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback,this._deflate.write(data),this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);fin&&(data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)),this._deflate[kCallback]=null,this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],fin&&this.params[`${endpoint}_no_context_takeover`]&&this._deflate.reset(),callback(null,data2)})}};module.exports=PerMessageDeflate2;function deflateOnData(chunk){this[kBuffers].push(chunk),this[kTotalLength]+=chunk.length}function inflateOnData(chunk){if(this[kTotalLength]+=chunk.length,this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded"),this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[kError][kStatusCode]=1009,this.removeListener("data",inflateOnData),this.reset()}function inflateOnError(err){if(this[kPerMessageDeflate]._inflate=null,this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007,this[kCallback](err)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports,module){"use strict";var{isUtf8}=__require("buffer"),{hasBlob}=require_constants(),tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){let len=buf.length,i=0;for(;i<len;)if((buf[i]&128)===0)i++;else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192)return!1;i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160)return!1;i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244)return!1;i+=4}else return!1;return!0}function isBlob(value){return hasBlob&&typeof value=="object"&&typeof value.arrayBuffer=="function"&&typeof value.type=="string"&&typeof value.stream=="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8)module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let isValidUTF8=__require("utf-8-validate");module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch{}}});var require_receiver=__commonJS({"node_modules/ws/lib/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream"),PerMessageDeflate2=require_permessage_deflate(),{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants(),{concat,toArrayBuffer,unmask}=require_buffer_util(),{isValidStatusCode,isValidUTF8}=require_validation(),FastBuffer=Buffer[Symbol.species],GET_INFO=0,GET_PAYLOAD_LENGTH_16=1,GET_PAYLOAD_LENGTH_64=2,GET_MASK=3,GET_DATA=4,INFLATING=5,DEFER_EVENT=6,Receiver2=class extends Writable{constructor(options={}){super(),this._allowSynchronousEvents=options.allowSynchronousEvents!==void 0?options.allowSynchronousEvents:!0,this._binaryType=options.binaryType||BINARY_TYPES[0],this._extensions=options.extensions||{},this._isServer=!!options.isServer,this._maxBufferedChunks=options.maxBufferedChunks|0,this._maxFragments=options.maxFragments|0,this._maxPayload=options.maxPayload|0,this._skipUTF8Validation=!!options.skipUTF8Validation,this[kWebSocket]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length,this._buffers.push(chunk),this.startLoop(cb)}consume(n){if(this._bufferedBytes-=n,n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){let buf=this._buffers[0];return this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n),new FastBuffer(buf.buffer,buf.byteOffset,n)}let dst=Buffer.allocUnsafe(n);do{let buf=this._buffers[0],offset=dst.length-n;n>=buf.length?dst.set(this._buffers.shift(),offset):(dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset),this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)),n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=!0;do switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=!1;return}while(this._loop);this._errored||cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=!1;return}let buf=this.consume(2);if((buf[0]&48)!==0){let error=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}let compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate2.extensionName]){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._fin=(buf[0]&128)===128,this._opcode=buf[0]&15,this._payloadLength=buf[1]&127,this._opcode===0){if(compressed){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){let error=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let error=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let error=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{let error=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(buf[1]&128)===128,this._isServer){if(!this._masked){let error=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){let error=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}this._payloadLength===126?this._state=GET_PAYLOAD_LENGTH_16:this._payloadLength===127?this._state=GET_PAYLOAD_LENGTH_64:this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=!1;return}let buf=this.consume(8),num=buf.readUInt32BE(0);if(num>Math.pow(2,21)-1){let error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4),this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let error=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._masked?this._state=GET_MASK:this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}data=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&unmask(data,this._mask)}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let error=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}if(this._compressed){this._state=INFLATING,this.decompress(data,cb);return}data.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(data)),this.dataMessage(cb)}decompress(data,cb){this._extensions[PerMessageDeflate2.extensionName].decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){if(this._messageLength+=buf.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let error=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb),this._state===GET_INFO&&this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}let messageLength=this._messageLength,fragments=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let data;this._binaryType==="nodebuffer"?data=concat(fragments,messageLength):this._binaryType==="arraybuffer"?data=toArrayBuffer(concat(fragments,messageLength)):this._binaryType==="blob"?data=new Blob(fragments):data=fragments,this._allowSynchronousEvents?(this.emit("message",data,!0),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit("message",data,!0),this._state=GET_INFO,this.startLoop(cb)}))}else{let buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){let error=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._state===INFLATING||this._allowSynchronousEvents?(this.emit("message",buf,!1),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit("message",buf,!1),this._state=GET_INFO,this.startLoop(cb)}))}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0)this._loop=!1,this.emit("conclude",1005,EMPTY_BUFFER),this.end();else{let code=data.readUInt16BE(0);if(!isValidStatusCode(code)){let error=this.createError(RangeError,`invalid status code ${code}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}let buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){let error=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=!1,this.emit("conclude",code,buf),this.end()}this._state=GET_INFO;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",data),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data),this._state=GET_INFO,this.startLoop(cb)}))}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=!1,this._errored=!0;let err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);return Error.captureStackTrace(err,this.createError),err.code=errorCode,err[kStatusCode]=statusCode,err}};module.exports=Receiver2}});var require_sender=__commonJS({"node_modules/ws/lib/sender.js"(exports,module){"use strict";var{Duplex}=__require("stream"),{randomFillSync}=__require("crypto"),{types:{isUint8Array}}=__require("util"),PerMessageDeflate2=require_permessage_deflate(),{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants(),{isBlob,isValidStatusCode}=require_validation(),{mask:applyMask,toBuffer}=require_buffer_util(),kByteLength=Symbol("kByteLength"),maskBuffer=Buffer.alloc(4),RANDOM_POOL_SIZE=8*1024,randomPool,randomPoolPointer=RANDOM_POOL_SIZE,DEFAULT=0,DEFLATING=1,GET_BLOB_DATA=2,Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{},generateMask&&(this._generateMask=generateMask,this._maskBuffer=Buffer.alloc(4)),this._socket=socket,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=DEFAULT,this.onerror=NOOP,this[kWebSocket]=void 0}static frame(data,options){let mask,merge=!1,offset=2,skipMasking=!1;options.mask&&(mask=options.maskBuffer||maskBuffer,options.generateMask?options.generateMask(mask):(randomPoolPointer===RANDOM_POOL_SIZE&&(randomPool===void 0&&(randomPool=Buffer.alloc(RANDOM_POOL_SIZE)),randomFillSync(randomPool,0,RANDOM_POOL_SIZE),randomPoolPointer=0),mask[0]=randomPool[randomPoolPointer++],mask[1]=randomPool[randomPoolPointer++],mask[2]=randomPool[randomPoolPointer++],mask[3]=randomPool[randomPoolPointer++]),skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0,offset=6);let dataLength;typeof data=="string"?(!options.mask||skipMasking)&&options[kByteLength]!==void 0?dataLength=options[kByteLength]:(data=Buffer.from(data),dataLength=data.length):(dataLength=data.length,merge=options.mask&&options.readOnly&&!skipMasking);let payloadLength=dataLength;dataLength>=65536?(offset+=8,payloadLength=127):dataLength>125&&(offset+=2,payloadLength=126);let target=Buffer.allocUnsafe(merge?dataLength+offset:offset);return target[0]=options.fin?options.opcode|128:options.opcode,options.rsv1&&(target[0]|=64),target[1]=payloadLength,payloadLength===126?target.writeUInt16BE(dataLength,2):payloadLength===127&&(target[2]=target[3]=0,target.writeUIntBE(dataLength,4,6)),options.mask?(target[1]|=128,target[offset-4]=mask[0],target[offset-3]=mask[1],target[offset-2]=mask[2],target[offset-1]=mask[3],skipMasking?[target,data]:merge?(applyMask(data,mask,target,offset,dataLength),[target]):(applyMask(data,mask,data,0,dataLength),[target,data])):[target,data]}close(code,data,mask,cb){let buf;if(code===void 0)buf=EMPTY_BUFFER;else{if(typeof code!="number"||!isValidStatusCode(code))throw new TypeError("First argument must be a valid error code number");if(data===void 0||!data.length)buf=Buffer.allocUnsafe(2),buf.writeUInt16BE(code,0);else{let length=Buffer.byteLength(data);if(length>123)throw new RangeError("The message must not be greater than 123 bytes");if(buf=Buffer.allocUnsafe(2+length),buf.writeUInt16BE(code,0),typeof data=="string")buf.write(data,2);else if(isUint8Array(data))buf.set(data,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let options={[kByteLength]:buf.length,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==DEFAULT?this.enqueue([this.dispatch,buf,!1,options,cb]):this.sendFrame(_Sender.frame(buf,options),cb)}ping(data,mask,cb){let byteLength,readOnly;if(typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),byteLength>125)throw new RangeError("The data size must not be greater than 125 bytes");let options={[kByteLength]:byteLength,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:!1};isBlob(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,!1,options,cb]):this.getBlobData(data,!1,options,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,!1,options,cb]):this.sendFrame(_Sender.frame(data,options),cb)}pong(data,mask,cb){let byteLength,readOnly;if(typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),byteLength>125)throw new RangeError("The data size must not be greater than 125 bytes");let options={[kByteLength]:byteLength,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:!1};isBlob(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,!1,options,cb]):this.getBlobData(data,!1,options,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,!1,options,cb]):this.sendFrame(_Sender.frame(data,options),cb)}send(data,options,cb){let perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName],opcode=options.binary?2:1,rsv1=options.compress,byteLength,readOnly;typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),this._firstFragment?(this._firstFragment=!1,rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(rsv1=byteLength>=perMessageDeflate._threshold),this._compress=rsv1):(rsv1=!1,opcode=0),options.fin&&(this._firstFragment=!0);let opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};isBlob(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,this._compress,opts,cb]):this.getBlobData(data,this._compress,opts,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,this._compress,opts,cb]):this.dispatch(data,this._compress,opts,cb)}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength],this._state=GET_BLOB_DATA,blob.arrayBuffer().then(arrayBuffer=>{if(this._socket.destroyed){let err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];let data=toBuffer(arrayBuffer);compress?this.dispatch(data,compress,options,cb):(this._state=DEFAULT,this.sendFrame(_Sender.frame(data,options),cb),this.dequeue())}).catch(err=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}let perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];this._bufferedBytes+=options[kByteLength],this._state=DEFLATING,perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){let err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength],this._state=DEFAULT,options.readOnly=!1,this.sendFrame(_Sender.frame(buf,options),cb),this.dequeue()})}dequeue(){for(;this._state===DEFAULT&&this._queue.length;){let params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength],Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength],this._queue.push(params)}sendFrame(list,cb){list.length===2?(this._socket.cork(),this._socket.write(list[0]),this._socket.write(list[1],cb),this._socket.uncork()):this._socket.write(list[0],cb)}};module.exports=Sender2;function callCallbacks(sender,err,cb){typeof cb=="function"&&cb(err);for(let i=0;i<sender._queue.length;i++){let params=sender._queue[i],callback=params[params.length-1];typeof callback=="function"&&callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb),sender.onerror(err)}}});var require_event_target=__commonJS({"node_modules/ws/lib/event-target.js"(exports,module){"use strict";var{kForOnEventAttribute,kListener}=require_constants(),kCode=Symbol("kCode"),kData=Symbol("kData"),kError=Symbol("kError"),kMessage=Symbol("kMessage"),kReason=Symbol("kReason"),kTarget=Symbol("kTarget"),kType=Symbol("kType"),kWasClean=Symbol("kWasClean"),Event=class{constructor(type){this[kTarget]=null,this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}};Object.defineProperty(Event.prototype,"target",{enumerable:!0});Object.defineProperty(Event.prototype,"type",{enumerable:!0});var CloseEvent=class extends Event{constructor(type,options={}){super(type),this[kCode]=options.code===void 0?0:options.code,this[kReason]=options.reason===void 0?"":options.reason,this[kWasClean]=options.wasClean===void 0?!1:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}};Object.defineProperty(CloseEvent.prototype,"code",{enumerable:!0});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:!0});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:!0});var ErrorEvent=class extends Event{constructor(type,options={}){super(type),this[kError]=options.error===void 0?null:options.error,this[kMessage]=options.message===void 0?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}};Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:!0});var MessageEvent=class extends Event{constructor(type,options={}){super(type),this[kData]=options.data===void 0?null:options.data}get data(){return this[kData]}};Object.defineProperty(MessageEvent.prototype,"data",{enumerable:!0});var EventTarget={addEventListener(type,handler,options={}){for(let listener of this.listeners(type))if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute])return;let wrapper;if(type==="message")wrapper=function(data,isBinary){let event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this,callListener(handler,this,event)};else if(type==="close")wrapper=function(code,message){let event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this,callListener(handler,this,event)};else if(type==="error")wrapper=function(error){let event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this,callListener(handler,this,event)};else if(type==="open")wrapper=function(){let event=new Event("open");event[kTarget]=this,callListener(handler,this,event)};else return;wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute],wrapper[kListener]=handler,options.once?this.once(type,wrapper):this.on(type,wrapper)},removeEventListener(type,handler){for(let listener of this.listeners(type))if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){typeof listener=="object"&&listener.handleEvent?listener.handleEvent.call(listener,event):listener.call(thisArg,event)}}});var require_extension=__commonJS({"node_modules/ws/lib/extension.js"(exports,module){"use strict";var{tokenChars}=require_validation();function push(dest,name,elem){dest[name]===void 0?dest[name]=[elem]:dest[name].push(elem)}function parse(header){let offers=Object.create(null),params=Object.create(null),mustUnescape=!1,isEscaping=!1,inQuotes=!1,extensionName,paramName,start=-1,code=-1,end=-1,i=0;for(;i<header.length;i++)if(code=header.charCodeAt(i),extensionName===void 0)if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(i!==0&&(code===32||code===9))end===-1&&start!==-1&&(end=i);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i}`);end===-1&&(end=i);let name=header.slice(start,end);code===44?(push(offers,name,params),params=Object.create(null)):extensionName=name,start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i}`);else if(paramName===void 0)if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(code===32||code===9)end===-1&&start!==-1&&(end=i);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i}`);end===-1&&(end=i),push(params,header.slice(start,end),!0),code===44&&(push(offers,extensionName,params),params=Object.create(null),extensionName=void 0),start=end=-1}else if(code===61&&start!==-1&&end===-1)paramName=header.slice(start,i),start=end=-1;else throw new SyntaxError(`Unexpected character at index ${i}`);else if(isEscaping){if(tokenChars[code]!==1)throw new SyntaxError(`Unexpected character at index ${i}`);start===-1?start=i:mustUnescape||(mustUnescape=!0),isEscaping=!1}else if(inQuotes)if(tokenChars[code]===1)start===-1&&(start=i);else if(code===34&&start!==-1)inQuotes=!1,end=i;else if(code===92)isEscaping=!0;else throw new SyntaxError(`Unexpected character at index ${i}`);else if(code===34&&header.charCodeAt(i-1)===61)inQuotes=!0;else if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(start!==-1&&(code===32||code===9))end===-1&&(end=i);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i}`);end===-1&&(end=i);let value=header.slice(start,end);mustUnescape&&(value=value.replace(/\\/g,""),mustUnescape=!1),push(params,paramName,value),code===44&&(push(offers,extensionName,params),params=Object.create(null),extensionName=void 0),paramName=void 0,start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i}`);if(start===-1||inQuotes||code===32||code===9)throw new SyntaxError("Unexpected end of input");end===-1&&(end=i);let token=header.slice(start,end);return extensionName===void 0?push(offers,token,params):(paramName===void 0?push(params,token,!0):mustUnescape?push(params,paramName,token.replace(/\\/g,"")):push(params,paramName,token),push(offers,extensionName,params)),offers}function format(extensions){return Object.keys(extensions).map(extension2=>{let configurations=extensions[extension2];return Array.isArray(configurations)||(configurations=[configurations]),configurations.map(params=>[extension2].concat(Object.keys(params).map(k=>{let values=params[k];return Array.isArray(values)||(values=[values]),values.map(v=>v===!0?k:`${k}=${v}`).join("; ")})).join("; ")).join(", ")}).join(", ")}module.exports={format,parse}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter=__require("events"),https=__require("https"),http=__require("http"),net=__require("net"),tls=__require("tls"),{randomBytes,createHash}=__require("crypto"),{Duplex,Readable:Readable2}=__require("stream"),{URL:URL2}=__require("url"),PerMessageDeflate2=require_permessage_deflate(),Receiver2=require_receiver(),Sender2=require_sender(),{isBlob}=require_validation(),{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants(),{EventTarget:{addEventListener,removeEventListener}}=require_event_target(),{format,parse}=require_extension(),{toBuffer}=require_buffer_util(),kAborted=Symbol("kAborted"),protocolVersions=[8,13],readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"],subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,WebSocket2=class _WebSocket extends EventEmitter{constructor(address,protocols,options){super(),this._binaryType=BINARY_TYPES[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=EMPTY_BUFFER,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=_WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,address!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,protocols===void 0?protocols=[]:Array.isArray(protocols)||(typeof protocols=="object"&&protocols!==null?(options=protocols,protocols=[]):protocols=[protocols]),initAsClient(this,address,protocols,options)):(this._autoPong=options.autoPong,this._closeTimeout=options.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(type){BINARY_TYPES.includes(type)&&(this._binaryType=type,this._receiver&&(this._receiver._binaryType=type))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){let receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation}),sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver,this._sender=sender,this._socket=socket,receiver[kWebSocket]=this,sender[kWebSocket]=this,socket[kWebSocket]=this,receiver.on("conclude",receiverOnConclude),receiver.on("drain",receiverOnDrain),receiver.on("error",receiverOnError),receiver.on("message",receiverOnMessage),receiver.on("ping",receiverOnPing),receiver.on("pong",receiverOnPong),sender.onerror=senderOnError,socket.setTimeout&&socket.setTimeout(0),socket.setNoDelay&&socket.setNoDelay(),head.length>0&&socket.unshift(head),socket.on("close",socketOnClose),socket.on("data",socketOnData),socket.on("end",socketOnEnd),socket.on("error",socketOnError),this._readyState=_WebSocket.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[PerMessageDeflate2.extensionName]&&this._extensions[PerMessageDeflate2.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===_WebSocket.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=_WebSocket.CLOSING,this._sender.close(code,data,!this._isServer,err=>{err||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),setCloseTimer(this)}}pause(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!0,this._socket.pause())}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof options=="function"&&(cb=options,options={}),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}let opts={binary:typeof data!="string",mask:!this._isServer,compress:!0,fin:!0,...options};this._extensions[PerMessageDeflate2.extensionName]||(opts.compress=!1),this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=_WebSocket.CLOSING,this._socket.destroy())}}};Object.defineProperty(WebSocket2,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2.prototype,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2.prototype,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2.prototype,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket2.prototype,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket2.prototype,property,{enumerable:!0})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket2.prototype,`on${method}`,{enumerable:!0,get(){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute])return listener[kListener];return null},set(handler){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}typeof handler=="function"&&this.addEventListener(method,handler,{[kForOnEventAttribute]:!0})}})});WebSocket2.prototype.addEventListener=addEventListener;WebSocket2.prototype.removeEventListener=removeEventListener;module.exports=WebSocket2;function initAsClient(websocket,address,protocols,options){let opts={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(websocket._autoPong=opts.autoPong,websocket._closeTimeout=opts.closeTimeout,!protocolVersions.includes(opts.protocolVersion))throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);let parsedUrl;if(address instanceof URL2)parsedUrl=address;else try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}parsedUrl.protocol==="http:"?parsedUrl.protocol="ws:":parsedUrl.protocol==="https:"&&(parsedUrl.protocol="wss:"),websocket._url=parsedUrl.href;let isSecure=parsedUrl.protocol==="wss:",isIpcUrl=parsedUrl.protocol==="ws+unix:",invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl?invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:isIpcUrl&&!parsedUrl.pathname?invalidUrlMessage="The URL's pathname is empty":parsedUrl.hash&&(invalidUrlMessage="The URL contains a fragment identifier"),invalidUrlMessage){let err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0)throw err;emitErrorAndClose(websocket,err);return}let defaultPort=isSecure?443:80,key=randomBytes(16).toString("base64"),request=isSecure?https.request:http.request,protocolSet=new Set,perMessageDeflate;if(opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect),opts.defaultPort=opts.defaultPort||defaultPort,opts.port=parsedUrl.port||defaultPort,opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname,opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"},opts.path=parsedUrl.pathname+parsedUrl.search,opts.timeout=opts.handshakeTimeout,opts.perMessageDeflate&&(perMessageDeflate=new PerMessageDeflate2({...opts.perMessageDeflate,isServer:!1,maxPayload:opts.maxPayload}),opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})),protocols.length){for(let protocol of protocols){if(typeof protocol!="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol))throw new SyntaxError("An invalid or duplicated subprotocol was specified");protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin&&(opts.protocolVersion<13?opts.headers["Sec-WebSocket-Origin"]=opts.origin:opts.headers.Origin=opts.origin),(parsedUrl.username||parsedUrl.password)&&(opts.auth=`${parsedUrl.username}:${parsedUrl.password}`),isIpcUrl){let parts=opts.path.split(":");opts.socketPath=parts[0],opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl,websocket._originalSecure=isSecure,websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;let headers=options&&options.headers;if(options={...options,headers:{}},headers)for(let[key2,value]of Object.entries(headers))options.headers[key2.toLowerCase()]=value}else if(websocket.listenerCount("redirect")===0){let isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:!1:websocket._originalIpc?!1:parsedUrl.host===websocket._originalHostOrSocketPath;(!isSameHost||websocket._originalSecure&&!isSecure)&&(delete opts.headers.authorization,delete opts.headers.cookie,isSameHost||delete opts.headers.host,opts.auth=void 0)}opts.auth&&!options.headers.authorization&&(options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")),req=websocket._req=request(opts),websocket._redirects&&websocket.emit("redirect",websocket.url,req)}else req=websocket._req=request(opts);opts.timeout&&req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")}),req.on("error",err=>{req===null||req[kAborted]||(req=websocket._req=null,emitErrorAndClose(websocket,err))}),req.on("response",res=>{let location=res.headers.location,statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address)}catch{let err=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else websocket.emit("unexpected-response",req,res)||abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}),req.on("upgrade",(res,socket,head)=>{if(websocket.emit("upgrade",res),websocket.readyState!==WebSocket2.CONNECTING)return;req=websocket._req=null;let upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}let digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}let serverProt=res.headers["sec-websocket-protocol"],protError;if(serverProt!==void 0?protocolSet.size?protocolSet.has(serverProt)||(protError="Server sent an invalid subprotocol"):protError="Server sent a subprotocol but none was requested":protocolSet.size&&(protError="Server sent no subprotocol"),protError){abortHandshake(websocket,socket,protError);return}serverProt&&(websocket._protocol=serverProt);let secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){abortHandshake(websocket,socket,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}let extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){abortHandshake(websocket,socket,"Server indicated an extension that was not requested");return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})}),opts.finishRequest?opts.finishRequest(req,websocket):req.end()}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket2.CLOSING,websocket._errorEmitted=!0,websocket.emit("error",err),websocket.emitClose()}function netConnect(options){return options.path=options.socketPath,net.connect(options)}function tlsConnect(options){return options.path=void 0,!options.servername&&options.servername!==""&&(options.servername=net.isIP(options.host)?"":options.host),tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket2.CLOSING;let err=new Error(message);Error.captureStackTrace(err,abortHandshake),stream.setHeader?(stream[kAborted]=!0,stream.abort(),stream.socket&&!stream.socket.destroyed&&stream.socket.destroy(),process.nextTick(emitErrorAndClose,websocket,err)):(stream.destroy(err),stream.once("error",websocket.emit.bind(websocket,"error")),stream.once("close",websocket.emitClose.bind(websocket)))}function sendAfterClose(websocket,data,cb){if(data){let length=isBlob(data)?data.size:toBuffer(data).length;websocket._socket?websocket._sender._bufferedBytes+=length:websocket._bufferedAmount+=length}if(cb){let err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){let websocket=this[kWebSocket];websocket._closeFrameReceived=!0,websocket._closeMessage=reason,websocket._closeCode=code,websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),code===1005?websocket.close():websocket.close(code,reason))}function receiverOnDrain(){let websocket=this[kWebSocket];websocket.isPaused||websocket._socket.resume()}function receiverOnError(err){let websocket=this[kWebSocket];websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),websocket.close(err[kStatusCode])),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err))}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){let websocket=this[kWebSocket];websocket._autoPong&&websocket.pong(data,!this._isServer,NOOP),websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){let websocket=this[kWebSocket];websocket.readyState!==WebSocket2.CLOSED&&(websocket.readyState===WebSocket2.OPEN&&(websocket._readyState=WebSocket2.CLOSING,setCloseTimer(websocket)),this._socket.end(),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err)))}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){let websocket=this[kWebSocket];if(this.removeListener("close",socketOnClose),this.removeListener("data",socketOnData),this.removeListener("end",socketOnEnd),websocket._readyState=WebSocket2.CLOSING,!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){let chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end(),this[kWebSocket]=void 0,clearTimeout(websocket._closeTimer),websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted?websocket.emitClose():(websocket._receiver.on("error",receiverOnFinish),websocket._receiver.on("finish",receiverOnFinish))}function socketOnData(chunk){this[kWebSocket]._receiver.write(chunk)||this.pause()}function socketOnEnd(){let websocket=this[kWebSocket];websocket._readyState=WebSocket2.CLOSING,websocket._receiver.end(),this.end()}function socketOnError(){let websocket=this[kWebSocket];this.removeListener("error",socketOnError),this.on("error",NOOP),websocket&&(websocket._readyState=WebSocket2.CLOSING,this.destroy())}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket2=require_websocket(),{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function duplexOnError(err){this.removeListener("error",duplexOnError),this.destroy(),this.listenerCount("error")===0&&this.emit("error",err)}function createWebSocketStream2(ws,options){let terminateOnDestroy=!0,duplex=new Duplex({...options,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return ws.on("message",function(msg,isBinary){let data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;duplex.push(data)||ws.pause()}),ws.once("error",function(err){duplex.destroyed||(terminateOnDestroy=!1,duplex.destroy(err))}),ws.once("close",function(){duplex.destroyed||duplex.push(null)}),duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err),process.nextTick(emitClose,duplex);return}let called=!1;ws.once("error",function(err2){called=!0,callback(err2)}),ws.once("close",function(){called||callback(err),process.nextTick(emitClose,duplex)}),terminateOnDestroy&&ws.terminate()},duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._final(callback)});return}ws._socket!==null&&(ws._socket._writableState.finished?(callback(),duplex._readableState.endEmitted&&duplex.destroy()):(ws._socket.once("finish",function(){callback()}),ws.close()))},duplex._read=function(){ws.isPaused&&ws.resume()},duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)},duplex.on("end",duplexOnEnd),duplex.on("error",duplexOnError),duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse(header){let protocols=new Set,start=-1,end=-1,i=0;for(i;i<header.length;i++){let code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1)start===-1&&(start=i);else if(i!==0&&(code===32||code===9))end===-1&&start!==-1&&(end=i);else if(code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i}`);end===-1&&(end=i);let protocol2=header.slice(start,end);if(protocols.has(protocol2))throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);protocols.add(protocol2),start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1||end!==-1)throw new SyntaxError("Unexpected end of input");let protocol=header.slice(start,i);if(protocols.has(protocol))throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);return protocols.add(protocol),protocols}module.exports={parse}}});var require_websocket_server=__commonJS({"node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter=__require("events"),http=__require("http"),{Duplex}=__require("stream"),{createHash}=__require("crypto"),extension2=require_extension(),PerMessageDeflate2=require_permessage_deflate(),subprotocol2=require_subprotocol(),WebSocket2=require_websocket(),{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants(),keyRegex=/^[+/0-9A-Za-z]{22}==$/,RUNNING=0,CLOSING=1,CLOSED=2,WebSocketServer2=class extends EventEmitter{constructor(options,callback){if(super(),options={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:WebSocket2,...options},options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(options.port!=null?(this._server=http.createServer((req,res)=>{let body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"}),res.end(body)}),this._server.listen(options.port,options.host,options.backlog,callback)):options.server&&(this._server=options.server),this._server){let emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}options.perMessageDeflate===!0&&(options.perMessageDeflate={}),options.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=options,this._state=RUNNING}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(cb){if(this._state===CLOSED){cb&&this.once("close",()=>{cb(new Error("The server is not running"))}),process.nextTick(emitClose,this);return}if(cb&&this.once("close",cb),this._state!==CLOSING)if(this._state=CLOSING,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(emitClose,this):process.nextTick(emitClose,this);else{let server=this._server;this._removeListeners(),this._removeListeners=this._server=null,server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){let index=req.url.indexOf("?");if((index!==-1?req.url.slice(0,index):req.url)!==this.options.path)return!1}return!0}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);let key=req.headers["sec-websocket-key"],upgrade=req.headers.upgrade,version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){abortHandshakeOrEmitwsClientError(this,req,socket,405,"Invalid HTTP method");return}if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid Upgrade header");return}if(key===void 0||!keyRegex.test(key)){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Missing or invalid Sec-WebSocket-Key header");return}if(version!==13&&version!==8){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}let secWebSocketProtocol=req.headers["sec-websocket-protocol"],protocols=new Set;if(secWebSocketProtocol!==void 0)try{protocols=subprotocol2.parse(secWebSocketProtocol)}catch{abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid Sec-WebSocket-Protocol header");return}let secWebSocketExtensions=req.headers["sec-websocket-extensions"],extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){let perMessageDeflate=new PerMessageDeflate2({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let offers=extension2.parse(secWebSocketExtensions);offers[PerMessageDeflate2.extensionName]&&(perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]),extensions[PerMessageDeflate2.extensionName]=perMessageDeflate)}catch{abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified)return abortHandshake(socket,code||401,message,headers);this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>RUNNING)return abortHandshake(socket,503);let headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${createHash("sha1").update(key+GUID).digest("base64")}`],ws=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){let protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;protocol&&(headers.push(`Sec-WebSocket-Protocol: ${protocol}`),ws._protocol=protocol)}if(extensions[PerMessageDeflate2.extensionName]){let params=extensions[PerMessageDeflate2.extensionName].params,value=extension2.format({[PerMessageDeflate2.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`),ws._extensions=extensions}this.emit("headers",headers,req),socket.write(headers.concat(`\r
`).join(`\r
`)),socket.removeListener("error",socketOnError),ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(ws),ws.on("close",()=>{this.clients.delete(ws),this._shouldEmitClose&&!this.clients.size&&process.nextTick(emitClose,this)})),cb(ws,req)}};module.exports=WebSocketServer2;function addListeners(server,map){for(let event of Object.keys(map))server.on(event,map[event]);return function(){for(let event of Object.keys(map))server.removeListener(event,map[event])}}function emitClose(server){server._state=CLOSED,server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http.STATUS_CODES[code],headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers},socket.once("finish",socket.destroy),socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join(`\r
`)+`\r
\r
`+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message,headers){if(server.listenerCount("wsClientError")){let err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError),server.emit("wsClientError",err,socket,req)}else abortHandshake(socket,code,message,headers)}}});var import_p_retry=__toESM(require_p_retry(),1),import_google_auth_library=__toESM(require_src(),1);import{createWriteStream}from"fs";import*as fs from"fs/promises";import{writeFile}from"fs/promises";import{Readable}from"node:stream";import{finished}from"node:stream/promises";var import_stream=__toESM(require_stream(),1),import_extension=__toESM(require_extension(),1),import_permessage_deflate=__toESM(require_permessage_deflate(),1),import_receiver=__toESM(require_receiver(),1),import_sender=__toESM(require_sender(),1),import_subprotocol=__toESM(require_subprotocol(),1),import_websocket=__toESM(require_websocket(),1),import_websocket_server=__toESM(require_websocket_server(),1);import*as path from"path";var _defaultBaseGeminiUrl,_defaultBaseVertexUrl;function getDefaultBaseUrls(){return{geminiUrl:_defaultBaseGeminiUrl,vertexUrl:_defaultBaseVertexUrl}}function getBaseUrl(httpOptions,vertexai,vertexBaseUrlFromEnv,geminiBaseUrlFromEnv){var _a2,_b;if(!httpOptions?.baseUrl){let defaultBaseUrls=getDefaultBaseUrls();return vertexai?(_a2=defaultBaseUrls.vertexUrl)!==null&&_a2!==void 0?_a2:vertexBaseUrlFromEnv:(_b=defaultBaseUrls.geminiUrl)!==null&&_b!==void 0?_b:geminiBaseUrlFromEnv}return httpOptions.baseUrl}var BaseModule=class{};function formatMap(templateString,valueMap){let regex=/\{([^}]+)\}/g;return templateString.replace(regex,(match2,key)=>{if(Object.prototype.hasOwnProperty.call(valueMap,key)){let value=valueMap[key];return value!=null?String(value):""}else throw new Error(`Key '${key}' not found in valueMap.`)})}function setValueByPath(data,keys,value){for(let i=0;i<keys.length-1;i++){let key=keys[i];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(!(keyName in data))if(Array.isArray(value))data[keyName]=Array.from({length:value.length},()=>({}));else throw new Error(`Value must be a list given an array path ${key}`);if(Array.isArray(data[keyName])){let arrayData=data[keyName];if(Array.isArray(value))for(let j=0;j<arrayData.length;j++){let entry=arrayData[j];setValueByPath(entry,keys.slice(i+1),value[j])}else for(let d of arrayData)setValueByPath(d,keys.slice(i+1),value)}return}else if(key.endsWith("[0]")){let keyName=key.slice(0,-3);keyName in data||(data[keyName]=[{}]);let arrayData=data[keyName];setValueByPath(arrayData[0],keys.slice(i+1),value);return}(!data[key]||typeof data[key]!="object")&&(data[key]={}),data=data[key]}let keyToSet=keys[keys.length-1],existingData=data[keyToSet];if(existingData!==void 0){if(!value||typeof value=="object"&&Object.keys(value).length===0||value===existingData)return;if(typeof existingData=="object"&&typeof value=="object"&&existingData!==null&&value!==null)Object.assign(existingData,value);else throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`)}else keyToSet==="_self"&&typeof value=="object"&&value!==null&&!Array.isArray(value)?Object.assign(data,value):data[keyToSet]=value}function getValueByPath(data,keys,defaultValue=void 0){try{if(keys.length===1&&keys[0]==="_self")return data;for(let i=0;i<keys.length;i++){if(typeof data!="object"||data===null)return defaultValue;let key=keys[i];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(keyName in data){let arrayData=data[keyName];return Array.isArray(arrayData)?arrayData.map(d=>getValueByPath(d,keys.slice(i+1),defaultValue)):defaultValue}else return defaultValue}else data=data[key]}return data}catch(error){if(error instanceof TypeError)return defaultValue;throw error}}function moveValueByPath(data,paths){for(let[sourcePath,destPath]of Object.entries(paths)){let sourceKeys=sourcePath.split("."),destKeys=destPath.split("."),excludeKeys=new Set,wildcardIdx=-1;for(let i=0;i<sourceKeys.length;i++)if(sourceKeys[i]==="*"){wildcardIdx=i;break}if(wildcardIdx!==-1&&destKeys.length>wildcardIdx)for(let i=wildcardIdx;i<destKeys.length;i++){let key=destKeys[i];key!=="*"&&!key.endsWith("[]")&&!key.endsWith("[0]")&&excludeKeys.add(key)}_moveValueRecursive(data,sourceKeys,destKeys,0,excludeKeys)}}function _moveValueRecursive(data,sourceKeys,destKeys,keyIdx,excludeKeys){if(keyIdx>=sourceKeys.length||typeof data!="object"||data===null)return;let key=sourceKeys[keyIdx];if(key.endsWith("[]")){let keyName=key.slice(0,-2),dataRecord=data;if(keyName in dataRecord&&Array.isArray(dataRecord[keyName]))for(let item of dataRecord[keyName])_moveValueRecursive(item,sourceKeys,destKeys,keyIdx+1,excludeKeys)}else if(key==="*"){if(typeof data=="object"&&data!==null&&!Array.isArray(data)){let dataRecord=data,keysToMove=Object.keys(dataRecord).filter(k=>!k.startsWith("_")&&!excludeKeys.has(k)),valuesToMove={};for(let k of keysToMove)valuesToMove[k]=dataRecord[k];for(let[k,v]of Object.entries(valuesToMove)){let newDestKeys=[];for(let dk of destKeys.slice(keyIdx))dk==="*"?newDestKeys.push(k):newDestKeys.push(dk);setValueByPath(dataRecord,newDestKeys,v)}for(let k of keysToMove)delete dataRecord[k]}}else{let dataRecord=data;key in dataRecord&&_moveValueRecursive(dataRecord[key],sourceKeys,destKeys,keyIdx+1,excludeKeys)}}function tBytes$1(fromBytes){if(typeof fromBytes!="string")throw new Error("fromImageBytes must be a string");return fromBytes}function fetchPredictOperationParametersToVertex(fromObject){let toObject={},fromOperationName=getValueByPath(fromObject,["operationName"]);fromOperationName!=null&&setValueByPath(toObject,["operationName"],fromOperationName);let fromResourceName=getValueByPath(fromObject,["resourceName"]);return fromResourceName!=null&&setValueByPath(toObject,["_url","resourceName"],fromResourceName),toObject}function generateVideosOperationFromMldev$1(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev$1(fromResponse)),toObject}function generateVideosOperationFromVertex$1(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex$1(fromResponse)),toObject}function generateVideosResponseFromMldev$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev$1(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex$1(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generatedVideoFromMldev$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev$1(fromVideo)),toObject}function generatedVideoFromVertex$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex$1(fromVideo)),toObject}function getOperationParametersToMldev(fromObject){let toObject={},fromOperationName=getValueByPath(fromObject,["operationName"]);return fromOperationName!=null&&setValueByPath(toObject,["_url","operationName"],fromOperationName),toObject}function getOperationParametersToVertex(fromObject){let toObject={},fromOperationName=getValueByPath(fromObject,["operationName"]);return fromOperationName!=null&&setValueByPath(toObject,["_url","operationName"],fromOperationName),toObject}function importFileOperationFromMldev$1(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],importFileResponseFromMldev$1(fromResponse)),toObject}function importFileResponseFromMldev$1(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["parent"],fromParent);let fromDocumentName=getValueByPath(fromObject,["documentName"]);return fromDocumentName!=null&&setValueByPath(toObject,["documentName"],fromDocumentName),toObject}function uploadToFileSearchStoreOperationFromMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],uploadToFileSearchStoreResponseFromMldev(fromResponse)),toObject}function uploadToFileSearchStoreResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["parent"],fromParent);let fromDocumentName=getValueByPath(fromObject,["documentName"]);return fromDocumentName!=null&&setValueByPath(toObject,["documentName"],fromDocumentName),toObject}function videoFromMldev$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}var Outcome;(function(Outcome2){Outcome2.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",Outcome2.OUTCOME_OK="OUTCOME_OK",Outcome2.OUTCOME_FAILED="OUTCOME_FAILED",Outcome2.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(Outcome||(Outcome={}));var Language;(function(Language2){Language2.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",Language2.PYTHON="PYTHON"})(Language||(Language={}));var FunctionResponseScheduling;(function(FunctionResponseScheduling2){FunctionResponseScheduling2.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",FunctionResponseScheduling2.SILENT="SILENT",FunctionResponseScheduling2.WHEN_IDLE="WHEN_IDLE",FunctionResponseScheduling2.INTERRUPT="INTERRUPT"})(FunctionResponseScheduling||(FunctionResponseScheduling={}));var Type;(function(Type2){Type2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",Type2.STRING="STRING",Type2.NUMBER="NUMBER",Type2.INTEGER="INTEGER",Type2.BOOLEAN="BOOLEAN",Type2.ARRAY="ARRAY",Type2.OBJECT="OBJECT",Type2.NULL="NULL"})(Type||(Type={}));var AuthType;(function(AuthType2){AuthType2.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",AuthType2.NO_AUTH="NO_AUTH",AuthType2.API_KEY_AUTH="API_KEY_AUTH",AuthType2.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",AuthType2.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",AuthType2.OAUTH="OAUTH",AuthType2.OIDC_AUTH="OIDC_AUTH"})(AuthType||(AuthType={}));var HttpElementLocation;(function(HttpElementLocation2){HttpElementLocation2.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",HttpElementLocation2.HTTP_IN_QUERY="HTTP_IN_QUERY",HttpElementLocation2.HTTP_IN_HEADER="HTTP_IN_HEADER",HttpElementLocation2.HTTP_IN_PATH="HTTP_IN_PATH",HttpElementLocation2.HTTP_IN_BODY="HTTP_IN_BODY",HttpElementLocation2.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(HttpElementLocation||(HttpElementLocation={}));var ApiSpec;(function(ApiSpec2){ApiSpec2.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",ApiSpec2.SIMPLE_SEARCH="SIMPLE_SEARCH",ApiSpec2.ELASTIC_SEARCH="ELASTIC_SEARCH"})(ApiSpec||(ApiSpec={}));var Environment;(function(Environment2){Environment2.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",Environment2.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",Environment2.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",Environment2.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(Environment||(Environment={}));var SafetyPolicy;(function(SafetyPolicy2){SafetyPolicy2.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",SafetyPolicy2.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",SafetyPolicy2.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",SafetyPolicy2.COMMUNICATION_TOOL="COMMUNICATION_TOOL",SafetyPolicy2.ACCOUNT_CREATION="ACCOUNT_CREATION",SafetyPolicy2.DATA_MODIFICATION="DATA_MODIFICATION",SafetyPolicy2.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",SafetyPolicy2.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(SafetyPolicy||(SafetyPolicy={}));var PhishBlockThreshold;(function(PhishBlockThreshold2){PhishBlockThreshold2.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",PhishBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",PhishBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",PhishBlockThreshold2.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",PhishBlockThreshold2.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",PhishBlockThreshold2.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",PhishBlockThreshold2.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(PhishBlockThreshold||(PhishBlockThreshold={}));var Behavior;(function(Behavior2){Behavior2.UNSPECIFIED="UNSPECIFIED",Behavior2.BLOCKING="BLOCKING",Behavior2.NON_BLOCKING="NON_BLOCKING"})(Behavior||(Behavior={}));var DynamicRetrievalConfigMode;(function(DynamicRetrievalConfigMode2){DynamicRetrievalConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",DynamicRetrievalConfigMode2.MODE_DYNAMIC="MODE_DYNAMIC"})(DynamicRetrievalConfigMode||(DynamicRetrievalConfigMode={}));var ThinkingLevel;(function(ThinkingLevel2){ThinkingLevel2.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",ThinkingLevel2.MINIMAL="MINIMAL",ThinkingLevel2.LOW="LOW",ThinkingLevel2.MEDIUM="MEDIUM",ThinkingLevel2.HIGH="HIGH"})(ThinkingLevel||(ThinkingLevel={}));var PersonGeneration;(function(PersonGeneration2){PersonGeneration2.DONT_ALLOW="DONT_ALLOW",PersonGeneration2.ALLOW_ADULT="ALLOW_ADULT",PersonGeneration2.ALLOW_ALL="ALLOW_ALL"})(PersonGeneration||(PersonGeneration={}));var ProminentPeople;(function(ProminentPeople2){ProminentPeople2.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",ProminentPeople2.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",ProminentPeople2.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(ProminentPeople||(ProminentPeople={}));var HarmCategory;(function(HarmCategory2){HarmCategory2.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",HarmCategory2.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",HarmCategory2.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",HarmCategory2.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",HarmCategory2.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",HarmCategory2.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",HarmCategory2.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",HarmCategory2.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",HarmCategory2.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(HarmCategory||(HarmCategory={}));var HarmBlockMethod;(function(HarmBlockMethod2){HarmBlockMethod2.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",HarmBlockMethod2.SEVERITY="SEVERITY",HarmBlockMethod2.PROBABILITY="PROBABILITY"})(HarmBlockMethod||(HarmBlockMethod={}));var HarmBlockThreshold;(function(HarmBlockThreshold2){HarmBlockThreshold2.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",HarmBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",HarmBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",HarmBlockThreshold2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",HarmBlockThreshold2.BLOCK_NONE="BLOCK_NONE",HarmBlockThreshold2.OFF="OFF"})(HarmBlockThreshold||(HarmBlockThreshold={}));var FunctionCallingConfigMode;(function(FunctionCallingConfigMode2){FunctionCallingConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",FunctionCallingConfigMode2.AUTO="AUTO",FunctionCallingConfigMode2.ANY="ANY",FunctionCallingConfigMode2.NONE="NONE",FunctionCallingConfigMode2.VALIDATED="VALIDATED"})(FunctionCallingConfigMode||(FunctionCallingConfigMode={}));var FinishReason;(function(FinishReason2){FinishReason2.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",FinishReason2.STOP="STOP",FinishReason2.MAX_TOKENS="MAX_TOKENS",FinishReason2.SAFETY="SAFETY",FinishReason2.RECITATION="RECITATION",FinishReason2.LANGUAGE="LANGUAGE",FinishReason2.OTHER="OTHER",FinishReason2.BLOCKLIST="BLOCKLIST",FinishReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",FinishReason2.SPII="SPII",FinishReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",FinishReason2.IMAGE_SAFETY="IMAGE_SAFETY",FinishReason2.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",FinishReason2.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",FinishReason2.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",FinishReason2.NO_IMAGE="NO_IMAGE",FinishReason2.IMAGE_RECITATION="IMAGE_RECITATION",FinishReason2.IMAGE_OTHER="IMAGE_OTHER"})(FinishReason||(FinishReason={}));var HarmProbability;(function(HarmProbability2){HarmProbability2.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",HarmProbability2.NEGLIGIBLE="NEGLIGIBLE",HarmProbability2.LOW="LOW",HarmProbability2.MEDIUM="MEDIUM",HarmProbability2.HIGH="HIGH"})(HarmProbability||(HarmProbability={}));var HarmSeverity;(function(HarmSeverity2){HarmSeverity2.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",HarmSeverity2.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",HarmSeverity2.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",HarmSeverity2.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",HarmSeverity2.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(HarmSeverity||(HarmSeverity={}));var UrlRetrievalStatus;(function(UrlRetrievalStatus2){UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(UrlRetrievalStatus||(UrlRetrievalStatus={}));var BlockedReason;(function(BlockedReason2){BlockedReason2.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",BlockedReason2.SAFETY="SAFETY",BlockedReason2.OTHER="OTHER",BlockedReason2.BLOCKLIST="BLOCKLIST",BlockedReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",BlockedReason2.IMAGE_SAFETY="IMAGE_SAFETY",BlockedReason2.MODEL_ARMOR="MODEL_ARMOR",BlockedReason2.JAILBREAK="JAILBREAK"})(BlockedReason||(BlockedReason={}));var TrafficType;(function(TrafficType2){TrafficType2.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",TrafficType2.ON_DEMAND="ON_DEMAND",TrafficType2.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",TrafficType2.ON_DEMAND_FLEX="ON_DEMAND_FLEX",TrafficType2.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(TrafficType||(TrafficType={}));var MediaModality;(function(MediaModality2){MediaModality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",MediaModality2.TEXT="TEXT",MediaModality2.IMAGE="IMAGE",MediaModality2.VIDEO="VIDEO",MediaModality2.AUDIO="AUDIO",MediaModality2.DOCUMENT="DOCUMENT"})(MediaModality||(MediaModality={}));var ModelStage;(function(ModelStage2){ModelStage2.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",ModelStage2.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",ModelStage2.EXPERIMENTAL="EXPERIMENTAL",ModelStage2.PREVIEW="PREVIEW",ModelStage2.STABLE="STABLE",ModelStage2.LEGACY="LEGACY",ModelStage2.DEPRECATED="DEPRECATED",ModelStage2.RETIRED="RETIRED"})(ModelStage||(ModelStage={}));var MediaResolution;(function(MediaResolution2){MediaResolution2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",MediaResolution2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",MediaResolution2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",MediaResolution2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(MediaResolution||(MediaResolution={}));var Modality;(function(Modality2){Modality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",Modality2.TEXT="TEXT",Modality2.IMAGE="IMAGE",Modality2.AUDIO="AUDIO",Modality2.VIDEO="VIDEO"})(Modality||(Modality={}));var Delivery;(function(Delivery2){Delivery2.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",Delivery2.INLINE="INLINE",Delivery2.URI="URI"})(Delivery||(Delivery={}));var AspectRatio;(function(AspectRatio2){AspectRatio2.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",AspectRatio2.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",AspectRatio2.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",AspectRatio2.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",AspectRatio2.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",AspectRatio2.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",AspectRatio2.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",AspectRatio2.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",AspectRatio2.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",AspectRatio2.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",AspectRatio2.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",AspectRatio2.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",AspectRatio2.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(AspectRatio||(AspectRatio={}));var ImageSize;(function(ImageSize2){ImageSize2.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",ImageSize2.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",ImageSize2.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",ImageSize2.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",ImageSize2.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(ImageSize||(ImageSize={}));var TuningMode;(function(TuningMode2){TuningMode2.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",TuningMode2.TUNING_MODE_FULL="TUNING_MODE_FULL",TuningMode2.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(TuningMode||(TuningMode={}));var AdapterSize;(function(AdapterSize2){AdapterSize2.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",AdapterSize2.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",AdapterSize2.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",AdapterSize2.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",AdapterSize2.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",AdapterSize2.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",AdapterSize2.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(AdapterSize||(AdapterSize={}));var ResponseParseType;(function(ResponseParseType2){ResponseParseType2.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",ResponseParseType2.IDENTITY="IDENTITY",ResponseParseType2.REGEX_EXTRACT="REGEX_EXTRACT"})(ResponseParseType||(ResponseParseType={}));var MatchOperation;(function(MatchOperation2){MatchOperation2.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",MatchOperation2.REGEX_CONTAINS="REGEX_CONTAINS",MatchOperation2.PARTIAL_MATCH="PARTIAL_MATCH",MatchOperation2.EXACT_MATCH="EXACT_MATCH"})(MatchOperation||(MatchOperation={}));var ReinforcementTuningThinkingLevel;(function(ReinforcementTuningThinkingLevel2){ReinforcementTuningThinkingLevel2.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",ReinforcementTuningThinkingLevel2.MINIMAL="MINIMAL",ReinforcementTuningThinkingLevel2.HIGH="HIGH"})(ReinforcementTuningThinkingLevel||(ReinforcementTuningThinkingLevel={}));var JobState;(function(JobState2){JobState2.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",JobState2.JOB_STATE_QUEUED="JOB_STATE_QUEUED",JobState2.JOB_STATE_PENDING="JOB_STATE_PENDING",JobState2.JOB_STATE_RUNNING="JOB_STATE_RUNNING",JobState2.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",JobState2.JOB_STATE_FAILED="JOB_STATE_FAILED",JobState2.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",JobState2.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",JobState2.JOB_STATE_PAUSED="JOB_STATE_PAUSED",JobState2.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",JobState2.JOB_STATE_UPDATING="JOB_STATE_UPDATING",JobState2.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(JobState||(JobState={}));var TuningJobState;(function(TuningJobState2){TuningJobState2.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",TuningJobState2.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",TuningJobState2.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",TuningJobState2.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(TuningJobState||(TuningJobState={}));var AggregationMetric;(function(AggregationMetric2){AggregationMetric2.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",AggregationMetric2.AVERAGE="AVERAGE",AggregationMetric2.MODE="MODE",AggregationMetric2.STANDARD_DEVIATION="STANDARD_DEVIATION",AggregationMetric2.VARIANCE="VARIANCE",AggregationMetric2.MINIMUM="MINIMUM",AggregationMetric2.MAXIMUM="MAXIMUM",AggregationMetric2.MEDIAN="MEDIAN",AggregationMetric2.PERCENTILE_P90="PERCENTILE_P90",AggregationMetric2.PERCENTILE_P95="PERCENTILE_P95",AggregationMetric2.PERCENTILE_P99="PERCENTILE_P99"})(AggregationMetric||(AggregationMetric={}));var PairwiseChoice;(function(PairwiseChoice2){PairwiseChoice2.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",PairwiseChoice2.BASELINE="BASELINE",PairwiseChoice2.CANDIDATE="CANDIDATE",PairwiseChoice2.TIE="TIE"})(PairwiseChoice||(PairwiseChoice={}));var VideoOrientation;(function(VideoOrientation2){VideoOrientation2.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",VideoOrientation2.LANDSCAPE="LANDSCAPE",VideoOrientation2.PORTRAIT="PORTRAIT"})(VideoOrientation||(VideoOrientation={}));var TuningSpeed;(function(TuningSpeed2){TuningSpeed2.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",TuningSpeed2.REGULAR="REGULAR",TuningSpeed2.FAST="FAST"})(TuningSpeed||(TuningSpeed={}));var TuningTask;(function(TuningTask2){TuningTask2.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",TuningTask2.TUNING_TASK_I2V="TUNING_TASK_I2V",TuningTask2.TUNING_TASK_T2V="TUNING_TASK_T2V",TuningTask2.TUNING_TASK_R2V="TUNING_TASK_R2V"})(TuningTask||(TuningTask={}));var DocumentState;(function(DocumentState2){DocumentState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",DocumentState2.STATE_PENDING="STATE_PENDING",DocumentState2.STATE_ACTIVE="STATE_ACTIVE",DocumentState2.STATE_FAILED="STATE_FAILED"})(DocumentState||(DocumentState={}));var ServiceTier;(function(ServiceTier2){ServiceTier2.UNSPECIFIED="unspecified",ServiceTier2.FLEX="flex",ServiceTier2.STANDARD="standard",ServiceTier2.PRIORITY="priority"})(ServiceTier||(ServiceTier={}));var MediaProcessing;(function(MediaProcessing2){MediaProcessing2.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",MediaProcessing2.STATIC="STATIC",MediaProcessing2.AGENTIC="AGENTIC"})(MediaProcessing||(MediaProcessing={}));var PartMediaResolutionLevel;(function(PartMediaResolutionLevel2){PartMediaResolutionLevel2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",PartMediaResolutionLevel2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",PartMediaResolutionLevel2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",PartMediaResolutionLevel2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",PartMediaResolutionLevel2.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(PartMediaResolutionLevel||(PartMediaResolutionLevel={}));var ToolType;(function(ToolType2){ToolType2.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",ToolType2.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",ToolType2.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",ToolType2.URL_CONTEXT="URL_CONTEXT",ToolType2.GOOGLE_MAPS="GOOGLE_MAPS",ToolType2.FILE_SEARCH="FILE_SEARCH",ToolType2.MEDIA_PROCESSING="MEDIA_PROCESSING"})(ToolType||(ToolType={}));var ResourceScope;(function(ResourceScope2){ResourceScope2.COLLECTION="COLLECTION"})(ResourceScope||(ResourceScope={}));var FeatureSelectionPreference;(function(FeatureSelectionPreference2){FeatureSelectionPreference2.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",FeatureSelectionPreference2.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",FeatureSelectionPreference2.BALANCED="BALANCED",FeatureSelectionPreference2.PRIORITIZE_COST="PRIORITIZE_COST"})(FeatureSelectionPreference||(FeatureSelectionPreference={}));var EmbeddingApiType;(function(EmbeddingApiType2){EmbeddingApiType2.PREDICT="PREDICT",EmbeddingApiType2.EMBED_CONTENT="EMBED_CONTENT"})(EmbeddingApiType||(EmbeddingApiType={}));var SafetyFilterLevel;(function(SafetyFilterLevel2){SafetyFilterLevel2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",SafetyFilterLevel2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",SafetyFilterLevel2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",SafetyFilterLevel2.BLOCK_NONE="BLOCK_NONE"})(SafetyFilterLevel||(SafetyFilterLevel={}));var ImagePromptLanguage;(function(ImagePromptLanguage2){ImagePromptLanguage2.auto="auto",ImagePromptLanguage2.en="en",ImagePromptLanguage2.ja="ja",ImagePromptLanguage2.ko="ko",ImagePromptLanguage2.hi="hi",ImagePromptLanguage2.zh="zh",ImagePromptLanguage2.pt="pt",ImagePromptLanguage2.es="es"})(ImagePromptLanguage||(ImagePromptLanguage={}));var MaskReferenceMode;(function(MaskReferenceMode2){MaskReferenceMode2.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",MaskReferenceMode2.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",MaskReferenceMode2.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",MaskReferenceMode2.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",MaskReferenceMode2.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(MaskReferenceMode||(MaskReferenceMode={}));var ControlReferenceType;(function(ControlReferenceType2){ControlReferenceType2.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",ControlReferenceType2.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",ControlReferenceType2.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",ControlReferenceType2.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(ControlReferenceType||(ControlReferenceType={}));var SubjectReferenceType;(function(SubjectReferenceType2){SubjectReferenceType2.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",SubjectReferenceType2.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",SubjectReferenceType2.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",SubjectReferenceType2.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(SubjectReferenceType||(SubjectReferenceType={}));var EditMode;(function(EditMode2){EditMode2.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",EditMode2.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",EditMode2.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",EditMode2.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",EditMode2.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",EditMode2.EDIT_MODE_STYLE="EDIT_MODE_STYLE",EditMode2.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",EditMode2.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(EditMode||(EditMode={}));var SegmentMode;(function(SegmentMode2){SegmentMode2.FOREGROUND="FOREGROUND",SegmentMode2.BACKGROUND="BACKGROUND",SegmentMode2.PROMPT="PROMPT",SegmentMode2.SEMANTIC="SEMANTIC",SegmentMode2.INTERACTIVE="INTERACTIVE"})(SegmentMode||(SegmentMode={}));var VideoGenerationReferenceType;(function(VideoGenerationReferenceType2){VideoGenerationReferenceType2.ASSET="ASSET",VideoGenerationReferenceType2.STYLE="STYLE"})(VideoGenerationReferenceType||(VideoGenerationReferenceType={}));var VideoGenerationMaskMode;(function(VideoGenerationMaskMode2){VideoGenerationMaskMode2.INSERT="INSERT",VideoGenerationMaskMode2.REMOVE="REMOVE",VideoGenerationMaskMode2.REMOVE_STATIC="REMOVE_STATIC",VideoGenerationMaskMode2.OUTPAINT="OUTPAINT"})(VideoGenerationMaskMode||(VideoGenerationMaskMode={}));var VideoCompressionQuality;(function(VideoCompressionQuality2){VideoCompressionQuality2.OPTIMIZED="OPTIMIZED",VideoCompressionQuality2.LOSSLESS="LOSSLESS"})(VideoCompressionQuality||(VideoCompressionQuality={}));var ImageResizeMode;(function(ImageResizeMode2){ImageResizeMode2.CROP="CROP",ImageResizeMode2.PAD="PAD"})(ImageResizeMode||(ImageResizeMode={}));var TuningMethod;(function(TuningMethod2){TuningMethod2.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",TuningMethod2.PREFERENCE_TUNING="PREFERENCE_TUNING",TuningMethod2.DISTILLATION="DISTILLATION",TuningMethod2.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(TuningMethod||(TuningMethod={}));var FileState;(function(FileState2){FileState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",FileState2.PROCESSING="PROCESSING",FileState2.ACTIVE="ACTIVE",FileState2.FAILED="FAILED"})(FileState||(FileState={}));var FileSource;(function(FileSource2){FileSource2.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",FileSource2.UPLOADED="UPLOADED",FileSource2.GENERATED="GENERATED",FileSource2.REGISTERED="REGISTERED"})(FileSource||(FileSource={}));var TurnCompleteReason;(function(TurnCompleteReason2){TurnCompleteReason2.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",TurnCompleteReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",TurnCompleteReason2.RESPONSE_REJECTED="RESPONSE_REJECTED",TurnCompleteReason2.NEED_MORE_INPUT="NEED_MORE_INPUT",TurnCompleteReason2.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",TurnCompleteReason2.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",TurnCompleteReason2.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",TurnCompleteReason2.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",TurnCompleteReason2.INPUT_OTHER="INPUT_OTHER",TurnCompleteReason2.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",TurnCompleteReason2.BLOCKLIST="BLOCKLIST",TurnCompleteReason2.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",TurnCompleteReason2.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",TurnCompleteReason2.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",TurnCompleteReason2.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",TurnCompleteReason2.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",TurnCompleteReason2.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",TurnCompleteReason2.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",TurnCompleteReason2.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",TurnCompleteReason2.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",TurnCompleteReason2.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",TurnCompleteReason2.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",TurnCompleteReason2.GENERATED_OTHER="GENERATED_OTHER",TurnCompleteReason2.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(TurnCompleteReason||(TurnCompleteReason={}));var InteractionStatus;(function(InteractionStatus2){InteractionStatus2.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",InteractionStatus2.IN_PROGRESS="IN_PROGRESS",InteractionStatus2.REQUIRES_ACTION="REQUIRES_ACTION",InteractionStatus2.IDLE="IDLE"})(InteractionStatus||(InteractionStatus={}));var VadSignalType;(function(VadSignalType2){VadSignalType2.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",VadSignalType2.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",VadSignalType2.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(VadSignalType||(VadSignalType={}));var VoiceActivityType;(function(VoiceActivityType2){VoiceActivityType2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",VoiceActivityType2.ACTIVITY_START="ACTIVITY_START",VoiceActivityType2.ACTIVITY_END="ACTIVITY_END"})(VoiceActivityType||(VoiceActivityType={}));var StartSensitivity;(function(StartSensitivity2){StartSensitivity2.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",StartSensitivity2.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",StartSensitivity2.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(StartSensitivity||(StartSensitivity={}));var EndSensitivity;(function(EndSensitivity2){EndSensitivity2.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",EndSensitivity2.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",EndSensitivity2.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(EndSensitivity||(EndSensitivity={}));var ActivityHandling;(function(ActivityHandling2){ActivityHandling2.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",ActivityHandling2.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",ActivityHandling2.NO_INTERRUPTION="NO_INTERRUPTION"})(ActivityHandling||(ActivityHandling={}));var TurnCoverage;(function(TurnCoverage2){TurnCoverage2.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",TurnCoverage2.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",TurnCoverage2.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",TurnCoverage2.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(TurnCoverage||(TurnCoverage={}));var AudioTranscriptionConfigMode;(function(AudioTranscriptionConfigMode2){AudioTranscriptionConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",AudioTranscriptionConfigMode2.VERBATIM="VERBATIM",AudioTranscriptionConfigMode2.SMART="SMART"})(AudioTranscriptionConfigMode||(AudioTranscriptionConfigMode={}));var Scale;(function(Scale2){Scale2.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",Scale2.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",Scale2.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",Scale2.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",Scale2.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",Scale2.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",Scale2.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",Scale2.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",Scale2.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",Scale2.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",Scale2.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",Scale2.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",Scale2.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(Scale||(Scale={}));var MusicGenerationMode;(function(MusicGenerationMode2){MusicGenerationMode2.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",MusicGenerationMode2.QUALITY="QUALITY",MusicGenerationMode2.DIVERSITY="DIVERSITY",MusicGenerationMode2.VOCALIZATION="VOCALIZATION"})(MusicGenerationMode||(MusicGenerationMode={}));var LiveMusicPlaybackControl;(function(LiveMusicPlaybackControl2){LiveMusicPlaybackControl2.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",LiveMusicPlaybackControl2.PLAY="PLAY",LiveMusicPlaybackControl2.PAUSE="PAUSE",LiveMusicPlaybackControl2.STOP="STOP",LiveMusicPlaybackControl2.RESET_CONTEXT="RESET_CONTEXT"})(LiveMusicPlaybackControl||(LiveMusicPlaybackControl={}));var HttpResponse=class{constructor(response){let headers={};for(let pair of response.headers.entries())headers[pair[0]]=pair[1];this.headers=headers,this.responseInternal=response}json(){return this.responseInternal.json()}};var GenerateContentResponse=class{get text(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let text="",anyTextPartText=!1,nonTextParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="text"&&fieldName!=="thought"&&fieldName!=="thoughtSignature"&&(fieldValue!==null||fieldValue!==void 0)&&nonTextParts.push(fieldName);if(typeof part.text=="string"){if(typeof part.thought=="boolean"&&part.thought)continue;anyTextPartText=!0,text+=part.text}}return nonTextParts.length>0&&console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),anyTextPartText?text:void 0}get data(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let data="",nonDataParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="inlineData"&&(fieldValue!==null||fieldValue!==void 0)&&nonDataParts.push(fieldName);part.inlineData&&typeof part.inlineData.data=="string"&&(data+=atob(part.inlineData.data))}return nonDataParts.length>0&&console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),data.length>0?btoa(data):void 0}get functionCalls(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let functionCalls=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.functionCall).map(part=>part.functionCall).filter(functionCall=>functionCall!==void 0);if(functionCalls?.length!==0)return functionCalls}get executableCode(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let executableCode=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.executableCode).map(part=>part.executableCode).filter(executableCode2=>executableCode2!==void 0);if(executableCode?.length!==0)return(_j=executableCode?.[0])===null||_j===void 0?void 0:_j.code}get codeExecutionResult(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let codeExecutionResult=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.codeExecutionResult).map(part=>part.codeExecutionResult).filter(codeExecutionResult2=>codeExecutionResult2!==void 0);if(codeExecutionResult?.length!==0)return(_j=codeExecutionResult?.[0])===null||_j===void 0?void 0:_j.output}},EmbedContentResponse=class{},GenerateImagesResponse=class{},EditImageResponse=class{},UpscaleImageResponse=class{},RecontextImageResponse=class{},SegmentImageResponse=class{},ListModelsResponse=class{},DeleteModelResponse=class{};var CountTokensResponse=class{},ComputeTokensResponse=class{};var GenerateVideosOperation=class _GenerateVideosOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _GenerateVideosOperation,response,op=apiResponse;return _isVertexAI?response=generateVideosOperationFromVertex$1(op):response=generateVideosOperationFromMldev$1(op),Object.assign(operation,response),operation}};var ListTuningJobsResponse=class{},CancelTuningJobResponse=class{},ValidateRewardResponse=class{},DeleteCachedContentResponse=class{},ListCachedContentsResponse=class{},ListDocumentsResponse=class{},ListFileSearchStoresResponse=class{},UploadToFileSearchStoreResumableResponse=class{};var ImportFileOperation=class _ImportFileOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _ImportFileOperation,response=importFileOperationFromMldev$1(apiResponse);return Object.assign(operation,response),operation}},ListFilesResponse=class{},CreateFileResponse=class{},DeleteFileResponse=class{},RegisterFilesResponse=class{};var ListBatchJobsResponse=class{};var LiveServerMessage=class{get text(){var _a2,_b,_c;let text="",anyTextPartFound=!1,nonTextParts=[];for(let part of(_c=(_b=(_a2=this.serverContent)===null||_a2===void 0?void 0:_a2.modelTurn)===null||_b===void 0?void 0:_b.parts)!==null&&_c!==void 0?_c:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="text"&&fieldName!=="thought"&&fieldValue!==null&&nonTextParts.push(fieldName);if(typeof part.text=="string"){if(typeof part.thought=="boolean"&&part.thought)continue;anyTextPartFound=!0,text+=part.text}}return nonTextParts.length>0&&console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),anyTextPartFound?text:void 0}get data(){var _a2,_b,_c;let data="",nonDataParts=[];for(let part of(_c=(_b=(_a2=this.serverContent)===null||_a2===void 0?void 0:_a2.modelTurn)===null||_b===void 0?void 0:_b.parts)!==null&&_c!==void 0?_c:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="inlineData"&&fieldValue!==null&&nonDataParts.push(fieldName);part.inlineData&&typeof part.inlineData.data=="string"&&(data+=atob(part.inlineData.data))}return nonDataParts.length>0&&console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),data.length>0?btoa(data):void 0}};var LiveMusicServerMessage=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var UploadToFileSearchStoreOperation=class _UploadToFileSearchStoreOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _UploadToFileSearchStoreOperation,response=uploadToFileSearchStoreOperationFromMldev(apiResponse);return Object.assign(operation,response),operation}};function tModel(apiClient,model){if(!model||typeof model!="string")throw new Error("model is required and must be a string");if(model.includes("..")||model.includes("?")||model.includes("&"))throw new Error("invalid model parameter");if(apiClient.isVertexAI()){if(model.startsWith("publishers/")||model.startsWith("projects/")||model.startsWith("models/"))return model;if(model.indexOf("/")>=0){let parts=model.split("/",2);return`publishers/${parts[0]}/models/${parts[1]}`}else return`publishers/google/models/${model}`}else return model.startsWith("models/")||model.startsWith("tunedModels/")?model:`models/${model}`}function tCachesModel(apiClient,model){let transformedModel=tModel(apiClient,model);return transformedModel?transformedModel.startsWith("publishers/")&&apiClient.isVertexAI()?`projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`:transformedModel.startsWith("models/")&&apiClient.isVertexAI()?`projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`:transformedModel:""}function tBlobs(blobs){return Array.isArray(blobs)?blobs.map(blob=>tBlob(blob)):[tBlob(blobs)]}function tBlob(blob){if(typeof blob=="object"&&blob!==null)return blob;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`)}function tImageBlob(blob){let transformedBlob=tBlob(blob);if(transformedBlob.mimeType&&transformedBlob.mimeType.startsWith("image/"))return transformedBlob;throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`)}function tAudioBlob(blob){let transformedBlob=tBlob(blob);if(transformedBlob.mimeType&&transformedBlob.mimeType.startsWith("audio/"))return transformedBlob;throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`)}function tPart(origin){if(origin==null)throw new Error("PartUnion is required");if(typeof origin=="object")return origin;if(typeof origin=="string")return{text:origin};throw new Error(`Unsupported part type: ${typeof origin}`)}function tParts(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("PartListUnion is required");return Array.isArray(origin)?origin.map(item=>tPart(item)):[tPart(origin)]}function _isContent(origin){return origin!=null&&typeof origin=="object"&&"parts"in origin&&Array.isArray(origin.parts)}function _isFunctionCallPart(origin){return origin!=null&&typeof origin=="object"&&"functionCall"in origin}function _isFunctionResponsePart(origin){return origin!=null&&typeof origin=="object"&&"functionResponse"in origin}function tContent(origin){if(origin==null)throw new Error("ContentUnion is required");return _isContent(origin)?origin:{role:"user",parts:tParts(origin)}}function tContentsForEmbed(apiClient,origin){if(!origin)return[];if(apiClient.isVertexAI()&&Array.isArray(origin))return origin.flatMap(item=>{let content=tContent(item);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]});if(apiClient.isVertexAI()){let content=tContent(origin);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]}return Array.isArray(origin)?origin.map(item=>tContent(item)):[tContent(origin)]}function tContents(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("contents are required");if(!Array.isArray(origin)){if(_isFunctionCallPart(origin)||_isFunctionResponsePart(origin))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[tContent(origin)]}let result=[],accumulatedParts=[],isContentArray=_isContent(origin[0]);for(let item of origin){let isContent=_isContent(item);if(isContent!=isContentArray)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(isContent)result.push(item);else{if(_isFunctionCallPart(item)||_isFunctionResponsePart(item))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");accumulatedParts.push(item)}}return isContentArray||result.push({role:"user",parts:tParts(accumulatedParts)}),result}function flattenTypeArrayToAnyOf(typeList,resultingSchema){typeList.includes("null")&&(resultingSchema.nullable=!0);let listWithoutNull=typeList.filter(type=>type!=="null");if(listWithoutNull.length===1)resultingSchema.type=Object.values(Type).includes(listWithoutNull[0].toUpperCase())?listWithoutNull[0].toUpperCase():Type.TYPE_UNSPECIFIED;else{resultingSchema.anyOf=[];for(let i of listWithoutNull)resultingSchema.anyOf.push({type:Object.values(Type).includes(i.toUpperCase())?i.toUpperCase():Type.TYPE_UNSPECIFIED})}}function processJsonSchema(_jsonSchema){let genAISchema={},schemaFieldNames=["items"],listSchemaFieldNames=["anyOf"],dictSchemaFieldNames=["properties"];if(_jsonSchema.type&&_jsonSchema.anyOf)throw new Error("type and anyOf cannot be both populated.");let incomingAnyOf=_jsonSchema.anyOf;incomingAnyOf!=null&&incomingAnyOf.length==2&&(incomingAnyOf[0].type==="null"?(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[1]):incomingAnyOf[1].type==="null"&&(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[0])),_jsonSchema.type instanceof Array&&flattenTypeArrayToAnyOf(_jsonSchema.type,genAISchema);for(let[fieldName,fieldValue]of Object.entries(_jsonSchema))if(fieldValue!=null)if(fieldName=="type"){if(fieldValue==="null")throw new Error("type: null can not be the only possible type for the field.");if(fieldValue instanceof Array)continue;genAISchema.type=Object.values(Type).includes(fieldValue.toUpperCase())?fieldValue.toUpperCase():Type.TYPE_UNSPECIFIED}else if(schemaFieldNames.includes(fieldName))genAISchema[fieldName]=processJsonSchema(fieldValue);else if(listSchemaFieldNames.includes(fieldName)){let listSchemaFieldValue=[];for(let item of fieldValue){if(item.type=="null"){genAISchema.nullable=!0;continue}listSchemaFieldValue.push(processJsonSchema(item))}genAISchema[fieldName]=listSchemaFieldValue}else if(dictSchemaFieldNames.includes(fieldName)){let dictSchemaFieldValue={};for(let[key,value]of Object.entries(fieldValue))dictSchemaFieldValue[key]=processJsonSchema(value);genAISchema[fieldName]=dictSchemaFieldValue}else{if(fieldName==="additionalProperties")continue;genAISchema[fieldName]=fieldValue}return genAISchema}function tSchema(schema){return processJsonSchema(schema)}function tSpeechConfig(speechConfig){if(typeof speechConfig=="object")return speechConfig;if(typeof speechConfig=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:speechConfig}}};throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`)}function tLiveSpeechConfig(speechConfig){if("multiSpeakerVoiceConfig"in speechConfig)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return speechConfig}function tTool(tool){if(tool.functionDeclarations)for(let functionDeclaration of tool.functionDeclarations)functionDeclaration.parameters&&(Object.keys(functionDeclaration.parameters).includes("$schema")?functionDeclaration.parametersJsonSchema||(functionDeclaration.parametersJsonSchema=functionDeclaration.parameters,delete functionDeclaration.parameters):functionDeclaration.parameters=processJsonSchema(functionDeclaration.parameters)),functionDeclaration.response&&(Object.keys(functionDeclaration.response).includes("$schema")?functionDeclaration.responseJsonSchema||(functionDeclaration.responseJsonSchema=functionDeclaration.response,delete functionDeclaration.response):functionDeclaration.response=processJsonSchema(functionDeclaration.response));return tool}function tTools(tools){if(tools==null)throw new Error("tools is required");if(!Array.isArray(tools))throw new Error("tools is required and must be an array of Tools");let result=[];for(let tool of tools)result.push(tool);return result}function resourceName(client,resourceName2,resourcePrefix,splitsAfterPrefix=1){let shouldAppendPrefix=!resourceName2.startsWith(`${resourcePrefix}/`)&&resourceName2.split("/").length===splitsAfterPrefix;return client.isVertexAI()?resourceName2.startsWith("projects/")?resourceName2:resourceName2.startsWith("locations/")?`projects/${client.getProject()}/${resourceName2}`:resourceName2.startsWith(`${resourcePrefix}/`)?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName2}`:shouldAppendPrefix?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName2}`:resourceName2:shouldAppendPrefix?`${resourcePrefix}/${resourceName2}`:resourceName2}function tCachedContentName(apiClient,name){if(typeof name!="string")throw new Error("name must be a string");return resourceName(apiClient,name,"cachedContents")}function tTuningJobStatus(status){switch(status){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 status}}function tBytes(fromImageBytes){return tBytes$1(fromImageBytes)}function _isFile(origin){return origin!=null&&typeof origin=="object"&&"name"in origin}function isGeneratedVideo(origin){return origin!=null&&typeof origin=="object"&&"video"in origin}function isVideo(origin){return origin!=null&&typeof origin=="object"&&"uri"in origin}function tFileName(fromName){var _a2;let name;if(_isFile(fromName)&&(name=fromName.name),!(isVideo(fromName)&&(name=fromName.uri,name===void 0))&&!(isGeneratedVideo(fromName)&&(name=(_a2=fromName.video)===null||_a2===void 0?void 0:_a2.uri,name===void 0))){if(typeof fromName=="string"&&(name=fromName),name===void 0)throw new Error("Could not extract file name from the provided input.");if(name.startsWith("https://")){let match2=name.split("files/")[1].match(/[a-z0-9]+/);if(match2===null)throw new Error(`Could not extract file name from URI ${name}`);name=match2[0]}else name.startsWith("files/")&&(name=name.split("files/")[1]);return name}}function tModelsUrl(apiClient,baseModels){let res;return apiClient.isVertexAI()?res=baseModels?"publishers/google/models":"models":res=baseModels?"models":"tunedModels",res}function tExtractModels(response){for(let key of["models","tunedModels","publisherModels"])if(hasField(response,key))return response[key];return[]}function hasField(data,fieldName){return data!==null&&typeof data=="object"&&fieldName in data}function mcpToGeminiTool(mcpTool,config={}){let mcpToolSchema=mcpTool,functionDeclaration={name:mcpToolSchema.name,description:mcpToolSchema.description,parametersJsonSchema:mcpToolSchema.inputSchema};return mcpToolSchema.outputSchema&&(functionDeclaration.responseJsonSchema=mcpToolSchema.outputSchema),config.behavior&&(functionDeclaration.behavior=config.behavior),{functionDeclarations:[functionDeclaration]}}function mcpToolsToGeminiTool(mcpTools,config={}){let functionDeclarations=[],toolNames=new Set;for(let mcpTool of mcpTools){let mcpToolName=mcpTool.name;if(toolNames.has(mcpToolName))throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);toolNames.add(mcpToolName);let geminiTool=mcpToGeminiTool(mcpTool,config);geminiTool.functionDeclarations&&functionDeclarations.push(...geminiTool.functionDeclarations)}return{functionDeclarations}}function tBatchJobSource(client,src){let sourceObj;if(typeof src=="string")if(client.isVertexAI())if(src.startsWith("gs://"))sourceObj={format:"jsonl",gcsUri:[src]};else if(src.startsWith("bq://"))sourceObj={format:"bigquery",bigqueryUri:src};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(src))sourceObj={format:"vertex-dataset",vertexDatasetName:src};else throw new Error(`Unsupported string source for Vertex AI: ${src}`);else if(src.startsWith("files/"))sourceObj={fileName:src};else throw new Error(`Unsupported string source for Gemini API: ${src}`);else if(Array.isArray(src)){if(client.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");sourceObj={inlinedRequests:src}}else sourceObj=src;let vertexSourcesCount=[sourceObj.gcsUri,sourceObj.bigqueryUri,sourceObj.vertexDatasetName].filter(Boolean).length,mldevSourcesCount=[sourceObj.inlinedRequests,sourceObj.fileName].filter(Boolean).length;if(client.isVertexAI()){if(mldevSourcesCount>0||vertexSourcesCount!==1)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(vertexSourcesCount>0||mldevSourcesCount!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return sourceObj}function tBatchJobDestination(dest){if(typeof dest!="string")return dest;let destString=dest;if(destString.startsWith("gs://"))return{format:"jsonl",gcsUri:destString};if(destString.startsWith("bq://"))return{format:"bigquery",bigqueryUri:destString};throw new Error(`Unsupported destination: ${destString}`)}function tRecvBatchJobDestination(dest){if(typeof dest!="object"||dest===null)return{};let obj=dest,inlineResponsesVal=obj.inlinedResponses;if(typeof inlineResponsesVal!="object"||inlineResponsesVal===null)return dest;let responsesArray=inlineResponsesVal.inlinedResponses;if(!Array.isArray(responsesArray)||responsesArray.length===0)return dest;let hasEmbedding=!1;for(let responseItem of responsesArray){if(typeof responseItem!="object"||responseItem===null)continue;let responseVal=responseItem.response;if(typeof responseVal!="object"||responseVal===null)continue;if(responseVal.embedding!==void 0){hasEmbedding=!0;break}}return hasEmbedding&&(obj.inlinedEmbedContentResponses=obj.inlinedResponses,delete obj.inlinedResponses),dest}function tBatchJobName(apiClient,name){let nameString=name;if(!apiClient.isVertexAI()){if(/batches\/[^/]+$/.test(nameString))return nameString.split("/").pop();throw new Error(`Invalid batch job name: ${nameString}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(nameString))return nameString.split("/").pop();if(/^\d+$/.test(nameString))return nameString;throw new Error(`Invalid batch job name: ${nameString}.`)}function tJobState(state){let stateString=state;return stateString==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":stateString==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":stateString==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":stateString==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":stateString==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":stateString==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":stateString==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":stateString}function tIsVertexEmbedContentModel(model){return model.includes("gemini")&&model!=="gemini-embedding-001"||model.includes("maas")}function authConfigToMldev$4(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function batchJobDestinationFromMldev(fromObject){let toObject={},fromFileName=getValueByPath(fromObject,["responsesFile"]);fromFileName!=null&&setValueByPath(toObject,["fileName"],fromFileName);let fromInlinedResponses=getValueByPath(fromObject,["inlinedResponses","inlinedResponses"]);if(fromInlinedResponses!=null){let transformedList=fromInlinedResponses;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>inlinedResponseFromMldev(item))),setValueByPath(toObject,["inlinedResponses"],transformedList)}let fromInlinedEmbedContentResponses=getValueByPath(fromObject,["inlinedEmbedContentResponses","inlinedResponses"]);if(fromInlinedEmbedContentResponses!=null){let transformedList=fromInlinedEmbedContentResponses;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["inlinedEmbedContentResponses"],transformedList)}return toObject}function batchJobDestinationFromVertex(fromObject){let toObject={},fromFormat=getValueByPath(fromObject,["predictionsFormat"]);fromFormat!=null&&setValueByPath(toObject,["format"],fromFormat);let fromGcsUri=getValueByPath(fromObject,["gcsDestination","outputUriPrefix"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromBigqueryUri=getValueByPath(fromObject,["bigqueryDestination","outputUri"]);fromBigqueryUri!=null&&setValueByPath(toObject,["bigqueryUri"],fromBigqueryUri);let fromVertexDataset=getValueByPath(fromObject,["vertexMultimodalDatasetDestination"]);return fromVertexDataset!=null&&setValueByPath(toObject,["vertexDataset"],vertexMultimodalDatasetDestinationFromVertex(fromVertexDataset)),toObject}function batchJobDestinationToVertex(fromObject){let toObject={},fromFormat=getValueByPath(fromObject,["format"]);fromFormat!=null&&setValueByPath(toObject,["predictionsFormat"],fromFormat);let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsDestination","outputUriPrefix"],fromGcsUri);let fromBigqueryUri=getValueByPath(fromObject,["bigqueryUri"]);fromBigqueryUri!=null&&setValueByPath(toObject,["bigqueryDestination","outputUri"],fromBigqueryUri);let fromVertexDataset=getValueByPath(fromObject,["vertexDataset"]);if(fromVertexDataset!=null&&setValueByPath(toObject,["vertexMultimodalDatasetDestination"],vertexMultimodalDatasetDestinationToVertex(fromVertexDataset)),getValueByPath(fromObject,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function batchJobFromMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["metadata","displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromState=getValueByPath(fromObject,["metadata","state"]);fromState!=null&&setValueByPath(toObject,["state"],tJobState(fromState));let fromCreateTime=getValueByPath(fromObject,["metadata","createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromEndTime=getValueByPath(fromObject,["metadata","endTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["metadata","updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromModel=getValueByPath(fromObject,["metadata","model"]);fromModel!=null&&setValueByPath(toObject,["model"],fromModel);let fromDest=getValueByPath(fromObject,["metadata","output"]);return fromDest!=null&&setValueByPath(toObject,["dest"],batchJobDestinationFromMldev(tRecvBatchJobDestination(fromDest))),toObject}function batchJobFromVertex(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tJobState(fromState));let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["endTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],fromModel);let fromSrc=getValueByPath(fromObject,["inputConfig"]);fromSrc!=null&&setValueByPath(toObject,["src"],batchJobSourceFromVertex(fromSrc));let fromDest=getValueByPath(fromObject,["outputConfig"]);fromDest!=null&&setValueByPath(toObject,["dest"],batchJobDestinationFromVertex(tRecvBatchJobDestination(fromDest)));let fromOutputInfo=getValueByPath(fromObject,["outputInfo"]);fromOutputInfo!=null&&setValueByPath(toObject,["outputInfo"],fromOutputInfo);let fromCompletionStats=getValueByPath(fromObject,["completionStats"]);return fromCompletionStats!=null&&setValueByPath(toObject,["completionStats"],fromCompletionStats),toObject}function batchJobSourceFromVertex(fromObject){let toObject={},fromFormat=getValueByPath(fromObject,["instancesFormat"]);fromFormat!=null&&setValueByPath(toObject,["format"],fromFormat);let fromGcsUri=getValueByPath(fromObject,["gcsSource","uris"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromBigqueryUri=getValueByPath(fromObject,["bigquerySource","inputUri"]);fromBigqueryUri!=null&&setValueByPath(toObject,["bigqueryUri"],fromBigqueryUri);let fromVertexDatasetName=getValueByPath(fromObject,["vertexMultimodalDatasetSource","datasetName"]);return fromVertexDatasetName!=null&&setValueByPath(toObject,["vertexDatasetName"],fromVertexDatasetName),toObject}function batchJobSourceToMldev(apiClient,fromObject){let toObject={};if(getValueByPath(fromObject,["format"])!==void 0)throw new Error("format parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["vertexDatasetName"])!==void 0)throw new Error("vertexDatasetName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileName=getValueByPath(fromObject,["fileName"]);fromFileName!=null&&setValueByPath(toObject,["fileName"],fromFileName);let fromInlinedRequests=getValueByPath(fromObject,["inlinedRequests"]);if(fromInlinedRequests!=null){let transformedList=fromInlinedRequests;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>inlinedRequestToMldev(apiClient,item))),setValueByPath(toObject,["requests","requests"],transformedList)}return toObject}function batchJobSourceToVertex(fromObject){let toObject={},fromFormat=getValueByPath(fromObject,["format"]);fromFormat!=null&&setValueByPath(toObject,["instancesFormat"],fromFormat);let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsSource","uris"],fromGcsUri);let fromBigqueryUri=getValueByPath(fromObject,["bigqueryUri"]);fromBigqueryUri!=null&&setValueByPath(toObject,["bigquerySource","inputUri"],fromBigqueryUri);let fromVertexDatasetName=getValueByPath(fromObject,["vertexDatasetName"]);if(fromVertexDatasetName!=null&&setValueByPath(toObject,["vertexMultimodalDatasetSource","datasetName"],fromVertexDatasetName),getValueByPath(fromObject,["fileName"])!==void 0)throw new Error("fileName parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function blobToMldev$4(fromObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function cancelBatchJobParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function cancelBatchJobParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function candidateFromMldev$1(fromObject){let toObject={},fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],fromContent);let fromCitationMetadata=getValueByPath(fromObject,["citationMetadata"]);fromCitationMetadata!=null&&setValueByPath(toObject,["citationMetadata"],citationMetadataFromMldev$1(fromCitationMetadata));let fromTokenCount=getValueByPath(fromObject,["tokenCount"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromFinishReason=getValueByPath(fromObject,["finishReason"]);fromFinishReason!=null&&setValueByPath(toObject,["finishReason"],fromFinishReason);let fromGroundingMetadata=getValueByPath(fromObject,["groundingMetadata"]);fromGroundingMetadata!=null&&setValueByPath(toObject,["groundingMetadata"],fromGroundingMetadata);let fromAvgLogprobs=getValueByPath(fromObject,["avgLogprobs"]);fromAvgLogprobs!=null&&setValueByPath(toObject,["avgLogprobs"],fromAvgLogprobs);let fromIndex=getValueByPath(fromObject,["index"]);fromIndex!=null&&setValueByPath(toObject,["index"],fromIndex);let fromLogprobsResult=getValueByPath(fromObject,["logprobsResult"]);fromLogprobsResult!=null&&setValueByPath(toObject,["logprobsResult"],fromLogprobsResult);let fromSafetyRatings=getValueByPath(fromObject,["safetyRatings"]);if(fromSafetyRatings!=null){let transformedList=fromSafetyRatings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["safetyRatings"],transformedList)}let fromUrlContextMetadata=getValueByPath(fromObject,["urlContextMetadata"]);return fromUrlContextMetadata!=null&&setValueByPath(toObject,["urlContextMetadata"],fromUrlContextMetadata),toObject}function citationMetadataFromMldev$1(fromObject){let toObject={},fromCitations=getValueByPath(fromObject,["citationSources"]);if(fromCitations!=null){let transformedList=fromCitations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["citations"],transformedList)}return toObject}function contentToMldev$4(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$4(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createBatchJobConfigToMldev(fromObject,parentObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);if(parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["batch","displayName"],fromDisplayName),getValueByPath(fromObject,["dest"])!==void 0)throw new Error("dest parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromWebhookConfig=getValueByPath(fromObject,["webhookConfig"]);return parentObject!==void 0&&fromWebhookConfig!=null&&setValueByPath(parentObject,["batch","webhookConfig"],fromWebhookConfig),toObject}function createBatchJobConfigToVertex(fromObject,parentObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDest=getValueByPath(fromObject,["dest"]);if(parentObject!==void 0&&fromDest!=null&&setValueByPath(parentObject,["outputConfig"],batchJobDestinationToVertex(tBatchJobDestination(fromDest))),getValueByPath(fromObject,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function createBatchJobParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSrc=getValueByPath(fromObject,["src"]);fromSrc!=null&&setValueByPath(toObject,["batch","inputConfig"],batchJobSourceToMldev(apiClient,tBatchJobSource(apiClient,fromSrc)));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createBatchJobConfigToMldev(fromConfig,toObject),toObject}function createBatchJobParametersToVertex(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],tModel(apiClient,fromModel));let fromSrc=getValueByPath(fromObject,["src"]);fromSrc!=null&&setValueByPath(toObject,["inputConfig"],batchJobSourceToVertex(tBatchJobSource(apiClient,fromSrc)));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createBatchJobConfigToVertex(fromConfig,toObject),toObject}function createEmbeddingsBatchJobConfigToMldev(fromObject,parentObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);return parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["batch","displayName"],fromDisplayName),toObject}function createEmbeddingsBatchJobParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSrc=getValueByPath(fromObject,["src"]);fromSrc!=null&&setValueByPath(toObject,["batch","inputConfig"],embeddingsBatchJobSourceToMldev(apiClient,fromSrc));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createEmbeddingsBatchJobConfigToMldev(fromConfig,toObject),toObject}function deleteBatchJobParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function deleteBatchJobParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function deleteResourceJobFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function deleteResourceJobFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function embedContentBatchToMldev(apiClient,fromObject){let toObject={},fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["requests[]","request","content"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&(setValueByPath(toObject,["_self"],embedContentConfigToMldev$1(fromConfig,toObject)),moveValueByPath(toObject,{"requests[].*":"requests[].request.*"})),toObject}function embedContentConfigToMldev$1(fromObject,parentObject){let toObject={},fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["requests[]","taskType"],fromTaskType);let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["requests[]","title"],fromTitle);let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);if(parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["requests[]","outputDimensionality"],fromOutputDimensionality),getValueByPath(fromObject,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function embeddingsBatchJobSourceToMldev(apiClient,fromObject){let toObject={},fromFileName=getValueByPath(fromObject,["fileName"]);fromFileName!=null&&setValueByPath(toObject,["file_name"],fromFileName);let fromInlinedRequests=getValueByPath(fromObject,["inlinedRequests"]);return fromInlinedRequests!=null&&setValueByPath(toObject,["requests"],embedContentBatchToMldev(apiClient,fromInlinedRequests)),toObject}function fileDataToMldev$4(fromObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev$4(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev$2(fromObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToMldev$1(apiClient,fromObject,parentObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$4(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);if(fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema),getValueByPath(fromObject,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$3(item))),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$4(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev$2(fromToolConfig)),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);if(fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],tSpeechConfig(fromSpeechConfig)),getValueByPath(fromObject,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToMldev$1(fromImageConfig));let fromEnableEnhancedCivicAnswers=getValueByPath(fromObject,["enableEnhancedCivicAnswers"]);if(fromEnableEnhancedCivicAnswers!=null&&setValueByPath(toObject,["enableEnhancedCivicAnswers"],fromEnableEnhancedCivicAnswers),getValueByPath(fromObject,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentResponseFromMldev$1(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>candidateFromMldev$1(item))),setValueByPath(toObject,["candidates"],transformedList)}let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata);let fromModelStatus=getValueByPath(fromObject,["modelStatus"]);return fromModelStatus!=null&&setValueByPath(toObject,["modelStatus"],fromModelStatus),toObject}function getBatchJobParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function getBatchJobParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tBatchJobName(apiClient,fromName)),toObject}function googleMapsToMldev$4(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$4(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$4(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function imageConfigToMldev$1(fromObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);if(fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize),getValueByPath(fromObject,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function inlinedRequestToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["request","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$4(item))),setValueByPath(toObject,["request","contents"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["request","generationConfig"],generateContentConfigToMldev$1(apiClient,fromConfig,getValueByPath(toObject,["request"],{}))),toObject}function inlinedResponseFromMldev(fromObject){let toObject={},fromResponse=getValueByPath(fromObject,["response"]);fromResponse!=null&&setValueByPath(toObject,["response"],generateContentResponseFromMldev$1(fromResponse));let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromError=getValueByPath(fromObject,["error"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function listBatchJobsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);if(parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),getValueByPath(fromObject,["filter"])!==void 0)throw new Error("filter parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function listBatchJobsConfigToVertex(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);return parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter),toObject}function listBatchJobsParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listBatchJobsConfigToMldev(fromConfig,toObject),toObject}function listBatchJobsParametersToVertex(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listBatchJobsConfigToVertex(fromConfig,toObject),toObject}function listBatchJobsResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromBatchJobs=getValueByPath(fromObject,["operations"]);if(fromBatchJobs!=null){let transformedList=fromBatchJobs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>batchJobFromMldev(item))),setValueByPath(toObject,["batchJobs"],transformedList)}return toObject}function listBatchJobsResponseFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromBatchJobs=getValueByPath(fromObject,["batchPredictionJobs"]);if(fromBatchJobs!=null){let transformedList=fromBatchJobs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>batchJobFromVertex(item))),setValueByPath(toObject,["batchJobs"],transformedList)}return toObject}function partToMldev$4(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$4(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$4(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$4(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function safetySettingToMldev$3(fromObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function toolConfigToMldev$2(fromObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev$2(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolToMldev$4(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$4(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$4(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function vertexMultimodalDatasetDestinationFromVertex(fromObject){let toObject={},fromBigqueryDestination=getValueByPath(fromObject,["bigqueryDestination","outputUri"]);fromBigqueryDestination!=null&&setValueByPath(toObject,["bigqueryDestination"],fromBigqueryDestination);let fromDisplayName=getValueByPath(fromObject,["displayName"]);return fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName),toObject}function vertexMultimodalDatasetDestinationToVertex(fromObject){let toObject={},fromBigqueryDestination=getValueByPath(fromObject,["bigqueryDestination"]);fromBigqueryDestination!=null&&setValueByPath(toObject,["bigqueryDestination","outputUri"],fromBigqueryDestination);let fromDisplayName=getValueByPath(fromObject,["displayName"]);return fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName),toObject}var PagedItem;(function(PagedItem2){PagedItem2.PAGED_ITEM_BATCH_JOBS="batchJobs",PagedItem2.PAGED_ITEM_MODELS="models",PagedItem2.PAGED_ITEM_TUNING_JOBS="tuningJobs",PagedItem2.PAGED_ITEM_FILES="files",PagedItem2.PAGED_ITEM_CACHED_CONTENTS="cachedContents",PagedItem2.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",PagedItem2.PAGED_ITEM_DOCUMENTS="documents",PagedItem2.PAGED_ITEM_SKILLS="skills"})(PagedItem||(PagedItem={}));var Pager=class{constructor(name,request,response,params){this.pageInternal=[],this.paramsInternal={},this.requestInternal=request,this.init(name,response,params)}init(name,response,params){var _a2,_b;this.nameInternal=name,this.pageInternal=response[this.nameInternal]||[],this.sdkHttpResponseInternal=response?.sdkHttpResponse,this.idxInternal=0;let requestParams={config:{}};!params||Object.keys(params).length===0?requestParams={config:{}}:typeof params=="object"?requestParams=Object.assign({},params):requestParams=params,requestParams.config&&(requestParams.config.pageToken=response.nextPageToken),this.paramsInternal=requestParams,this.pageInternalSize=(_b=(_a2=requestParams.config)===null||_a2===void 0?void 0:_a2.pageSize)!==null&&_b!==void 0?_b:this.pageInternal.length}initNextPage(response){this.init(this.nameInternal,response,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(index){return this.pageInternal[index]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let item=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:item,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let response=await this.requestInternal(this.params);return this.initNextPage(response),this.page}hasNextPage(){var _a2;return((_a2=this.params.config)===null||_a2===void 0?void 0:_a2.pageToken)!==void 0}};var Batches=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS,x=>this.listInternal(x),await this.listInternal(params),params),this.create=async params=>(this.apiClient.isVertexAI()&&(params.config=this.formatDestination(params.src,params.config)),this.createInternal(params)),this.createEmbeddings=async params=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(params)}}createInlinedGenerateContentRequest(params){let body=createBatchJobParametersToMldev(this.apiClient,params),urlParams=body._url,path2=formatMap("{model}:batchGenerateContent",urlParams),requestsWrapper=body.batch.inputConfig.requests,requests=requestsWrapper.requests,newRequests=[];for(let request of requests){let requestDict=Object.assign({},request);if(requestDict.systemInstruction){let systemInstructionValue=requestDict.systemInstruction;delete requestDict.systemInstruction;let requestContent=requestDict.request;requestContent.systemInstruction=systemInstructionValue,requestDict.request=requestContent}newRequests.push(requestDict)}return requestsWrapper.requests=newRequests,delete body.config,delete body._url,delete body._query,{path:path2,body}}getGcsUri(src){if(typeof src=="string")return src.startsWith("gs://")?src:void 0;if(!Array.isArray(src)&&src.gcsUri&&src.gcsUri.length>0)return src.gcsUri[0]}getBigqueryUri(src){if(typeof src=="string")return src.startsWith("bq://")?src:void 0;if(!Array.isArray(src))return src.bigqueryUri}formatDestination(src,config){let newConfig=config?Object.assign({},config):{},timestampStr=Date.now().toString();if(newConfig.displayName||(newConfig.displayName=`genaiBatchJob_${timestampStr}`),newConfig.dest===void 0){let gcsUri=this.getGcsUri(src),bigqueryUri=this.getBigqueryUri(src);if(gcsUri)gcsUri.endsWith(".jsonl")?newConfig.dest=`${gcsUri.slice(0,-6)}/dest`:newConfig.dest=`${gcsUri}_dest_${timestampStr}`;else if(bigqueryUri)newConfig.dest=`${bigqueryUri}_dest_${timestampStr}`;else throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return newConfig}async createInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createBatchJobParametersToVertex(this.apiClient,params);return path2=formatMap("batchPredictionJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>batchJobFromVertex(apiResponse))}else{let body=createBatchJobParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:batchGenerateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>batchJobFromMldev(apiResponse))}}async createEmbeddingsInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createEmbeddingsBatchJobParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:asyncBatchEmbedContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>batchJobFromMldev(apiResponse))}}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getBatchJobParametersToVertex(this.apiClient,params);return path2=formatMap("batchPredictionJobs/{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>batchJobFromVertex(apiResponse))}else{let body=getBatchJobParametersToMldev(this.apiClient,params);return path2=formatMap("batches/{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>batchJobFromMldev(apiResponse))}}async cancel(params){var _a2,_b,_c,_d;let path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=cancelBatchJobParametersToVertex(this.apiClient,params);path2=formatMap("batchPredictionJobs/{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}else{let body=cancelBatchJobParametersToMldev(this.apiClient,params);path2=formatMap("batches/{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal})}}async listInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listBatchJobsParametersToVertex(params);return path2=formatMap("batchPredictionJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listBatchJobsResponseFromVertex(apiResponse),typedResp=new ListBatchJobsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listBatchJobsParametersToMldev(params);return path2=formatMap("batches",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listBatchJobsResponseFromMldev(apiResponse),typedResp=new ListBatchJobsResponse;return Object.assign(typedResp,resp),typedResp})}}async delete(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteBatchJobParametersToVertex(this.apiClient,params);return path2=formatMap("batchPredictionJobs/{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>deleteResourceJobFromVertex(apiResponse))}else{let body=deleteBatchJobParametersToMldev(this.apiClient,params);return path2=formatMap("batches/{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>deleteResourceJobFromMldev(apiResponse))}}};function authConfigToMldev$3(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev$3(fromObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function computerUseToVertex$2(fromObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentToMldev$3(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$3(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$3(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$3(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createCachedContentConfigToMldev(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromContents=getValueByPath(fromObject,["contents"]);if(parentObject!==void 0&&fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$3(item))),setValueByPath(parentObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$3(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$3(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev$1(fromToolConfig)),getValueByPath(fromObject,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function createCachedContentConfigToVertex(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromContents=getValueByPath(fromObject,["contents"]);if(parentObject!==void 0&&fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$3(item))),setValueByPath(parentObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$3(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$2(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToVertex$1(fromToolConfig));let fromKmsKeyName=getValueByPath(fromObject,["kmsKeyName"]);return parentObject!==void 0&&fromKmsKeyName!=null&&setValueByPath(parentObject,["encryption_spec","kmsKeyName"],fromKmsKeyName),toObject}function createCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],tCachesModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createCachedContentConfigToMldev(fromConfig,toObject),toObject}function createCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["model"],tCachesModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createCachedContentConfigToVertex(fromConfig,toObject),toObject}function deleteCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function deleteCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function deleteCachedContentResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteCachedContentResponseFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function fileDataToMldev$3(fromObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev$3(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev$1(fromObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function getCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function getCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName)),toObject}function googleMapsToMldev$3(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$3(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$3(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function listCachedContentsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listCachedContentsConfigToVertex(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listCachedContentsParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listCachedContentsConfigToMldev(fromConfig,toObject),toObject}function listCachedContentsParametersToVertex(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listCachedContentsConfigToVertex(fromConfig,toObject),toObject}function listCachedContentsResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromCachedContents=getValueByPath(fromObject,["cachedContents"]);if(fromCachedContents!=null){let transformedList=fromCachedContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["cachedContents"],transformedList)}return toObject}function listCachedContentsResponseFromVertex(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromCachedContents=getValueByPath(fromObject,["cachedContents"]);if(fromCachedContents!=null){let transformedList=fromCachedContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["cachedContents"],transformedList)}return toObject}function mcpServerToVertex$2(fromObject){let toObject={};if(getValueByPath(fromObject,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function partToMldev$3(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$3(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$3(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$3(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function partToVertex$3(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function toolConfigToMldev$1(fromObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev$1(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolConfigToVertex$1(fromObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],fromFunctionCallingConfig);let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);if(fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig),getValueByPath(fromObject,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function toolToMldev$3(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$3(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$3(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex$2(fromObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex$2(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex$2(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function updateCachedContentConfigToMldev(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);return parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime),toObject}function updateCachedContentConfigToVertex(fromObject,parentObject){let toObject={},fromTtl=getValueByPath(fromObject,["ttl"]);parentObject!==void 0&&fromTtl!=null&&setValueByPath(parentObject,["ttl"],fromTtl);let fromExpireTime=getValueByPath(fromObject,["expireTime"]);return parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime),toObject}function updateCachedContentParametersToMldev(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateCachedContentConfigToMldev(fromConfig,toObject),toObject}function updateCachedContentParametersToVertex(apiClient,fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],tCachedContentName(apiClient,fromName));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateCachedContentConfigToVertex(fromConfig,toObject),toObject}var Caches=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS,x=>this.listInternal(x),await this.listInternal(params),params)}async create(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=createCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=getCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteCachedContentResponseFromVertex(apiResponse),typedResp=new DeleteCachedContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=deleteCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteCachedContentResponseFromMldev(apiResponse),typedResp=new DeleteCachedContentResponse;return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateCachedContentParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}else{let body=updateCachedContentParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async listInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listCachedContentsParametersToVertex(params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listCachedContentsResponseFromVertex(apiResponse),typedResp=new ListCachedContentsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listCachedContentsParametersToMldev(params);return path2=formatMap("cachedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listCachedContentsResponseFromMldev(apiResponse),typedResp=new ListCachedContentsResponse;return Object.assign(typedResp,resp),typedResp})}}};function __rest(s,e){var t={};for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++)e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i])&&(t[p[i]]=s[p[i]]);return t}function __values(o){var s=typeof Symbol=="function"&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}function __await(v){return this instanceof __await?(this.v=v,this):new __await(v)}function __asyncGenerator(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var g=generator.apply(thisArg,_arguments||[]),i,q=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i[Symbol.asyncIterator]=function(){return this},i;function awaitReturn(f){return function(v){return Promise.resolve(v).then(f,reject)}}function verb(n,f){g[n]&&(i[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})},f&&(i[n]=f(i[n])))}function resume(n,v){try{step(g[n](v))}catch(e){settle(q[0][3],e)}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f,v){f(v),q.shift(),q.length&&resume(q[0][0],q[0][1])}}function __asyncValues(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m=o[Symbol.asyncIterator],i;return m?m.call(o):(o=typeof __values=="function"?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this},i);function verb(n){i[n]=o[n]&&function(v){return new Promise(function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value)})}}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v2){resolve({value:v2,done:d})},reject)}}function isValidResponse(response){var _a2;if(response.candidates==null||response.candidates.length===0)return!1;let content=(_a2=response.candidates[0])===null||_a2===void 0?void 0:_a2.content;return content===void 0?!1:isValidContent(content)}function isValidContent(content){if(content.parts===void 0||content.parts.length===0)return!1;for(let part of content.parts)if(part===void 0||Object.keys(part).length===0)return!1;return!0}function validateHistory(history){if(history.length!==0){for(let content of history)if(content.role!=="user"&&content.role!=="model")throw new Error(`Role must be user or model, but got ${content.role}.`)}}function extractCuratedHistory(comprehensiveHistory){if(comprehensiveHistory===void 0||comprehensiveHistory.length===0)return[];let curatedHistory=[],length=comprehensiveHistory.length,i=0;for(;i<length;)if(comprehensiveHistory[i].role==="user")curatedHistory.push(comprehensiveHistory[i]),i++;else{let modelOutput=[],isValid=!0;for(;i<length&&comprehensiveHistory[i].role==="model";)modelOutput.push(comprehensiveHistory[i]),isValid&&!isValidContent(comprehensiveHistory[i])&&(isValid=!1),i++;isValid?curatedHistory.push(...modelOutput):curatedHistory.pop()}return curatedHistory}var Chats=class{constructor(modelsModule,apiClient){this.modelsModule=modelsModule,this.apiClient=apiClient}create(params){return new Chat(this.apiClient,this.modelsModule,params.model,params.config,structuredClone(params.history))}},Chat=class{constructor(apiClient,modelsModule,model,config={},history=[]){this.apiClient=apiClient,this.modelsModule=modelsModule,this.model=model,this.config=config,this.history=history,this.sendPromise=Promise.resolve(),validateHistory(history)}async sendMessage(params){var _a2;await this.sendPromise;let inputContent=tContent(params.message),responsePromise=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(inputContent),config:(_a2=params.config)!==null&&_a2!==void 0?_a2:this.config});return this.sendPromise=(async()=>{var _a3,_b,_c;let response=await responsePromise,outputContent=(_b=(_a3=response.candidates)===null||_a3===void 0?void 0:_a3[0])===null||_b===void 0?void 0:_b.content,fullAutomaticFunctionCallingHistory=response.automaticFunctionCallingHistory,index=this.getHistory(!0).length,automaticFunctionCallingHistory=[];fullAutomaticFunctionCallingHistory!=null&&(automaticFunctionCallingHistory=(_c=fullAutomaticFunctionCallingHistory.slice(index))!==null&&_c!==void 0?_c:[]);let modelOutput=outputContent?[outputContent]:[];this.recordHistory(inputContent,modelOutput,automaticFunctionCallingHistory)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),responsePromise}async sendMessageStream(params){var _a2;await this.sendPromise;let inputContent=tContent(params.message),streamResponse=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(inputContent),config:(_a2=params.config)!==null&&_a2!==void 0?_a2:this.config});this.sendPromise=streamResponse.then(()=>{}).catch(()=>{});let response=await streamResponse;return this.processStreamResponse(response,inputContent)}getHistory(curated=!1){let history=curated?extractCuratedHistory(this.history):this.history;return structuredClone(history)}processStreamResponse(streamResponse,inputContent){return __asyncGenerator(this,arguments,function*(){var _a2,e_1,_b,_c,_d,_e;let outputContent=[];try{for(var _f=!0,streamResponse_1=__asyncValues(streamResponse),streamResponse_1_1;streamResponse_1_1=yield __await(streamResponse_1.next()),_a2=streamResponse_1_1.done,!_a2;_f=!0){_c=streamResponse_1_1.value,_f=!1;let chunk=_c;if(isValidResponse(chunk)){let content=(_e=(_d=chunk.candidates)===null||_d===void 0?void 0:_d[0])===null||_e===void 0?void 0:_e.content;content!==void 0&&outputContent.push(content)}yield yield __await(chunk)}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_f&&!_a2&&(_b=streamResponse_1.return)&&(yield __await(_b.call(streamResponse_1)))}finally{if(e_1)throw e_1.error}}this.recordHistory(inputContent,outputContent)})}recordHistory(userInput,modelOutput,automaticFunctionCallingHistory){let outputContents=[];modelOutput.length>0&&modelOutput.every(content=>content.role!==void 0)?outputContents=modelOutput:outputContents.push({role:"model",parts:[]}),automaticFunctionCallingHistory&&automaticFunctionCallingHistory.length>0?this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)):this.history.push(userInput),this.history.push(...outputContents)}};var ApiError=class _ApiError extends Error{constructor(options){super(options.message),this.name="ApiError",this.status=options.status,Object.setPrototypeOf(this,_ApiError.prototype)}};function createFileParametersToMldev(fromObject){let toObject={},fromFile=getValueByPath(fromObject,["file"]);return fromFile!=null&&setValueByPath(toObject,["file"],fromFile),toObject}function createFileResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteFileParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","file"],tFileName(fromName)),toObject}function deleteFileResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function getFileParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","file"],tFileName(fromName)),toObject}function internalRegisterFilesParametersToMldev(fromObject){let toObject={},fromUris=getValueByPath(fromObject,["uris"]);return fromUris!=null&&setValueByPath(toObject,["uris"],fromUris),toObject}function listFilesConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listFilesParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listFilesConfigToMldev(fromConfig,toObject),toObject}function listFilesResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromFiles=getValueByPath(fromObject,["files"]);if(fromFiles!=null){let transformedList=fromFiles;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["files"],transformedList)}return toObject}function registerFilesResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromFiles=getValueByPath(fromObject,["files"]);if(fromFiles!=null){let transformedList=fromFiles;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["files"],transformedList)}return toObject}var Files$1=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_FILES,x=>this.listInternal(x),await this.listInternal(params),params)}async upload(params){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(params.file,params.config).then(resp=>resp)}async download(params){await this.apiClient.downloadFile(params)}async registerFiles(params){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(params){return this.registerFilesInternal(params)}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listFilesParametersToMldev(params);return path2=formatMap("files",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listFilesResponseFromMldev(apiResponse),typedResp=new ListFilesResponse;return Object.assign(typedResp,resp),typedResp})}}async createInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createFileParametersToMldev(params);return path2=formatMap("upload/v1beta/files",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=createFileResponseFromMldev(apiResponse),typedResp=new CreateFileResponse;return Object.assign(typedResp,resp),typedResp})}}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getFileParametersToMldev(params);return path2=formatMap("files/{file}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteFileParametersToMldev(params);return path2=formatMap("files/{file}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteFileResponseFromMldev(apiResponse),typedResp=new DeleteFileResponse;return Object.assign(typedResp,resp),typedResp})}}async registerFilesInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=internalRegisterFilesParametersToMldev(params);return path2=formatMap("files:register",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=registerFilesResponseFromMldev(apiResponse),typedResp=new RegisterFilesResponse;return Object.assign(typedResp,resp),typedResp})}}};function authConfigToMldev$2(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev$2(fromObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function computerUseToVertex$1(fromObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentToMldev$2(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$2(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$2(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$2(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function fileDataToMldev$2(fromObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev$2(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generationConfigToVertex$1(fromObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex$1(fromSpeechConfig));let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);if(fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function googleMapsToMldev$2(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$2(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$2(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function liveConnectConfigToMldev$1(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],fromGenerationConfig);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],tLiveSpeechConfig(fromSpeechConfig));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToMldev$2(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$2(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],sessionResumptionConfigToMldev$1(fromSessionResumption));let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);if(parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity),getValueByPath(fromObject,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$2(item))),setValueByPath(parentObject,["setup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectConfigToVertex(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],generationConfigToVertex$1(fromGenerationConfig));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToVertex$2(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex$1(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],fromSessionResumption);let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity);let fromExplicitVadSignal=getValueByPath(fromObject,["explicitVadSignal"]);parentObject!==void 0&&fromExplicitVadSignal!=null&&setValueByPath(parentObject,["setup","explicitVadSignal"],fromExplicitVadSignal);let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["setup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectParametersToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],liveConnectConfigToMldev$1(fromConfig,toObject)),toObject}function liveConnectParametersToVertex(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],liveConnectConfigToVertex(fromConfig,toObject)),toObject}function liveMusicSetConfigParametersToMldev(fromObject){let toObject={},fromMusicGenerationConfig=getValueByPath(fromObject,["musicGenerationConfig"]);return fromMusicGenerationConfig!=null&&setValueByPath(toObject,["musicGenerationConfig"],fromMusicGenerationConfig),toObject}function liveMusicSetWeightedPromptsParametersToMldev(fromObject){let toObject={},fromWeightedPrompts=getValueByPath(fromObject,["weightedPrompts"]);if(fromWeightedPrompts!=null){let transformedList=fromWeightedPrompts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["weightedPrompts"],transformedList)}return toObject}function liveSendRealtimeInputParametersToMldev(fromObject){let toObject={},fromMedia=getValueByPath(fromObject,["media"]);if(fromMedia!=null){let transformedList=tBlobs(fromMedia);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>blobToMldev$2(item))),setValueByPath(toObject,["mediaChunks"],transformedList)}let fromAudio=getValueByPath(fromObject,["audio"]);fromAudio!=null&&setValueByPath(toObject,["audio"],blobToMldev$2(tAudioBlob(fromAudio)));let fromAudioStreamEnd=getValueByPath(fromObject,["audioStreamEnd"]);fromAudioStreamEnd!=null&&setValueByPath(toObject,["audioStreamEnd"],fromAudioStreamEnd);let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["video"],blobToMldev$2(tImageBlob(fromVideo)));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromActivityStart=getValueByPath(fromObject,["activityStart"]);fromActivityStart!=null&&setValueByPath(toObject,["activityStart"],fromActivityStart);let fromActivityEnd=getValueByPath(fromObject,["activityEnd"]);return fromActivityEnd!=null&&setValueByPath(toObject,["activityEnd"],fromActivityEnd),toObject}function liveSendRealtimeInputParametersToVertex(fromObject){let toObject={},fromMedia=getValueByPath(fromObject,["media"]);if(fromMedia!=null){let transformedList=tBlobs(fromMedia);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mediaChunks"],transformedList)}let fromAudio=getValueByPath(fromObject,["audio"]);fromAudio!=null&&setValueByPath(toObject,["audio"],tAudioBlob(fromAudio));let fromAudioStreamEnd=getValueByPath(fromObject,["audioStreamEnd"]);fromAudioStreamEnd!=null&&setValueByPath(toObject,["audioStreamEnd"],fromAudioStreamEnd);let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["video"],tImageBlob(fromVideo));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromActivityStart=getValueByPath(fromObject,["activityStart"]);fromActivityStart!=null&&setValueByPath(toObject,["activityStart"],fromActivityStart);let fromActivityEnd=getValueByPath(fromObject,["activityEnd"]);return fromActivityEnd!=null&&setValueByPath(toObject,["activityEnd"],fromActivityEnd),toObject}function liveServerMessageFromVertex(fromObject){let toObject={},fromSetupComplete=getValueByPath(fromObject,["setupComplete"]);fromSetupComplete!=null&&setValueByPath(toObject,["setupComplete"],fromSetupComplete);let fromServerContent=getValueByPath(fromObject,["serverContent"]);fromServerContent!=null&&setValueByPath(toObject,["serverContent"],fromServerContent);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolCallCancellation=getValueByPath(fromObject,["toolCallCancellation"]);fromToolCallCancellation!=null&&setValueByPath(toObject,["toolCallCancellation"],fromToolCallCancellation);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],usageMetadataFromVertex(fromUsageMetadata));let fromGoAway=getValueByPath(fromObject,["goAway"]);fromGoAway!=null&&setValueByPath(toObject,["goAway"],fromGoAway);let fromSessionResumptionUpdate=getValueByPath(fromObject,["sessionResumptionUpdate"]);fromSessionResumptionUpdate!=null&&setValueByPath(toObject,["sessionResumptionUpdate"],fromSessionResumptionUpdate);let fromVoiceActivityDetectionSignal=getValueByPath(fromObject,["voiceActivityDetectionSignal"]);fromVoiceActivityDetectionSignal!=null&&setValueByPath(toObject,["voiceActivityDetectionSignal"],fromVoiceActivityDetectionSignal);let fromVoiceActivity=getValueByPath(fromObject,["voiceActivity"]);return fromVoiceActivity!=null&&setValueByPath(toObject,["voiceActivity"],voiceActivityFromVertex(fromVoiceActivity)),toObject}function mcpServerToVertex$1(fromObject){let toObject={};if(getValueByPath(fromObject,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function multiSpeakerVoiceConfigToVertex$1(fromObject){let toObject={},fromSpeakerVoiceConfigs=getValueByPath(fromObject,["speakerVoiceConfigs"]);if(fromSpeakerVoiceConfigs!=null){let transformedList=fromSpeakerVoiceConfigs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>speakerVoiceConfigToVertex$1(item))),setValueByPath(toObject,["speakerVoiceConfigs"],transformedList)}return toObject}function partToMldev$2(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$2(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$2(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$2(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function partToVertex$2(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function replicatedVoiceConfigToVertex$1(fromObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType);let fromVoiceSampleAudio=getValueByPath(fromObject,["voiceSampleAudio"]);if(fromVoiceSampleAudio!=null&&setValueByPath(toObject,["voiceSampleAudio"],fromVoiceSampleAudio),getValueByPath(fromObject,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function safetySettingToMldev$2(fromObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function sessionResumptionConfigToMldev$1(fromObject){let toObject={},fromHandle=getValueByPath(fromObject,["handle"]);if(fromHandle!=null&&setValueByPath(toObject,["handle"],fromHandle),getValueByPath(fromObject,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function speakerVoiceConfigToVertex$1(fromObject){let toObject={},fromSpeaker=getValueByPath(fromObject,["speaker"]);fromSpeaker!=null&&setValueByPath(toObject,["speaker"],fromSpeaker);let fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);return fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex$1(fromVoiceConfig)),toObject}function speechConfigToVertex$1(fromObject){let toObject={},fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex$1(fromVoiceConfig));let fromLanguageCode=getValueByPath(fromObject,["languageCode"]);fromLanguageCode!=null&&setValueByPath(toObject,["languageCode"],fromLanguageCode);let fromMultiSpeakerVoiceConfig=getValueByPath(fromObject,["multiSpeakerVoiceConfig"]);return fromMultiSpeakerVoiceConfig!=null&&setValueByPath(toObject,["multiSpeakerVoiceConfig"],multiSpeakerVoiceConfigToVertex$1(fromMultiSpeakerVoiceConfig)),toObject}function toolToMldev$2(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$2(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$2(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex$1(fromObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex$1(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex$1(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function usageMetadataFromVertex(fromObject){let toObject={},fromResponseTokenCount=getValueByPath(fromObject,["candidatesTokenCount"]);fromResponseTokenCount!=null&&setValueByPath(toObject,["responseTokenCount"],fromResponseTokenCount);let fromResponseTokensDetails=getValueByPath(fromObject,["candidatesTokensDetails"]);if(fromResponseTokensDetails!=null){let transformedList=fromResponseTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseTokensDetails"],transformedList)}let fromCacheTokensDetails=getValueByPath(fromObject,["cacheTokensDetails"]);if(fromCacheTokensDetails!=null){let transformedList=fromCacheTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["cacheTokensDetails"],transformedList)}let fromCachedContentTokenCount=getValueByPath(fromObject,["cachedContentTokenCount"]);fromCachedContentTokenCount!=null&&setValueByPath(toObject,["cachedContentTokenCount"],fromCachedContentTokenCount);let fromPromptTokenCount=getValueByPath(fromObject,["promptTokenCount"]);fromPromptTokenCount!=null&&setValueByPath(toObject,["promptTokenCount"],fromPromptTokenCount);let fromPromptTokensDetails=getValueByPath(fromObject,["promptTokensDetails"]);if(fromPromptTokensDetails!=null){let transformedList=fromPromptTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["promptTokensDetails"],transformedList)}let fromThoughtsTokenCount=getValueByPath(fromObject,["thoughtsTokenCount"]);fromThoughtsTokenCount!=null&&setValueByPath(toObject,["thoughtsTokenCount"],fromThoughtsTokenCount);let fromToolUsePromptTokenCount=getValueByPath(fromObject,["toolUsePromptTokenCount"]);fromToolUsePromptTokenCount!=null&&setValueByPath(toObject,["toolUsePromptTokenCount"],fromToolUsePromptTokenCount);let fromToolUsePromptTokensDetails=getValueByPath(fromObject,["toolUsePromptTokensDetails"]);if(fromToolUsePromptTokensDetails!=null){let transformedList=fromToolUsePromptTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["toolUsePromptTokensDetails"],transformedList)}let fromTotalTokenCount=getValueByPath(fromObject,["totalTokenCount"]);fromTotalTokenCount!=null&&setValueByPath(toObject,["totalTokenCount"],fromTotalTokenCount);let fromTrafficType=getValueByPath(fromObject,["trafficType"]);return fromTrafficType!=null&&setValueByPath(toObject,["trafficType"],fromTrafficType),toObject}function voiceActivityFromVertex(fromObject){let toObject={},fromVoiceActivityType=getValueByPath(fromObject,["type"]);fromVoiceActivityType!=null&&setValueByPath(toObject,["voiceActivityType"],fromVoiceActivityType);let fromAudioOffset=getValueByPath(fromObject,["audioOffset"]);return fromAudioOffset!=null&&setValueByPath(toObject,["audioOffset"],fromAudioOffset),toObject}function voiceConfigToVertex$1(fromObject){let toObject={},fromReplicatedVoiceConfig=getValueByPath(fromObject,["replicatedVoiceConfig"]);fromReplicatedVoiceConfig!=null&&setValueByPath(toObject,["replicatedVoiceConfig"],replicatedVoiceConfigToVertex$1(fromReplicatedVoiceConfig));let fromPrebuiltVoiceConfig=getValueByPath(fromObject,["prebuiltVoiceConfig"]);return fromPrebuiltVoiceConfig!=null&&setValueByPath(toObject,["prebuiltVoiceConfig"],fromPrebuiltVoiceConfig),toObject}function authConfigToMldev$1(fromObject,_rootObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev$1(fromObject,_rootObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function candidateFromMldev(fromObject,rootObject){let toObject={},fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],fromContent);let fromCitationMetadata=getValueByPath(fromObject,["citationMetadata"]);fromCitationMetadata!=null&&setValueByPath(toObject,["citationMetadata"],citationMetadataFromMldev(fromCitationMetadata));let fromTokenCount=getValueByPath(fromObject,["tokenCount"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromFinishReason=getValueByPath(fromObject,["finishReason"]);fromFinishReason!=null&&setValueByPath(toObject,["finishReason"],fromFinishReason);let fromGroundingMetadata=getValueByPath(fromObject,["groundingMetadata"]);fromGroundingMetadata!=null&&setValueByPath(toObject,["groundingMetadata"],fromGroundingMetadata);let fromAvgLogprobs=getValueByPath(fromObject,["avgLogprobs"]);fromAvgLogprobs!=null&&setValueByPath(toObject,["avgLogprobs"],fromAvgLogprobs);let fromIndex=getValueByPath(fromObject,["index"]);fromIndex!=null&&setValueByPath(toObject,["index"],fromIndex);let fromLogprobsResult=getValueByPath(fromObject,["logprobsResult"]);fromLogprobsResult!=null&&setValueByPath(toObject,["logprobsResult"],fromLogprobsResult);let fromSafetyRatings=getValueByPath(fromObject,["safetyRatings"]);if(fromSafetyRatings!=null){let transformedList=fromSafetyRatings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["safetyRatings"],transformedList)}let fromUrlContextMetadata=getValueByPath(fromObject,["urlContextMetadata"]);return fromUrlContextMetadata!=null&&setValueByPath(toObject,["urlContextMetadata"],fromUrlContextMetadata),toObject}function citationMetadataFromMldev(fromObject,_rootObject){let toObject={},fromCitations=getValueByPath(fromObject,["citationSources"]);if(fromCitations!=null){let transformedList=fromCitations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["citations"],transformedList)}return toObject}function computeTokensParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}return toObject}function computeTokensResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTokensInfo=getValueByPath(fromObject,["tokensInfo"]);if(fromTokensInfo!=null){let transformedList=fromTokensInfo;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensInfo"],transformedList)}return toObject}function computerUseToVertex(fromObject,_rootObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentEmbeddingFromVertex(fromObject,rootObject){let toObject={},fromValues=getValueByPath(fromObject,["values"]);fromValues!=null&&setValueByPath(toObject,["values"],fromValues);let fromStatistics=getValueByPath(fromObject,["statistics"]);return fromStatistics!=null&&setValueByPath(toObject,["statistics"],contentEmbeddingStatisticsFromVertex(fromStatistics)),toObject}function contentEmbeddingStatisticsFromVertex(fromObject,_rootObject){let toObject={},fromTruncated=getValueByPath(fromObject,["truncated"]);fromTruncated!=null&&setValueByPath(toObject,["truncated"],fromTruncated);let fromTokenCount=getValueByPath(fromObject,["token_count"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromTokensDetails=getValueByPath(fromObject,["tokensDetails"]);if(fromTokensDetails!=null){let transformedList=fromTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensDetails"],transformedList)}return toObject}function contentToMldev$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function controlReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromControlType=getValueByPath(fromObject,["controlType"]);fromControlType!=null&&setValueByPath(toObject,["controlType"],fromControlType);let fromEnableControlImageComputation=getValueByPath(fromObject,["enableControlImageComputation"]);return fromEnableControlImageComputation!=null&&setValueByPath(toObject,["computeControl"],fromEnableControlImageComputation),toObject}function countTokensConfigToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function countTokensConfigToVertex(fromObject,parentObject,rootObject){let toObject={},fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["generationConfig"],generationConfigToVertex(fromGenerationConfig)),toObject}function countTokensParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToMldev(fromConfig),toObject}function countTokensParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToVertex(fromConfig,toObject),toObject}function countTokensResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens);let fromCachedContentTokenCount=getValueByPath(fromObject,["cachedContentTokenCount"]);return fromCachedContentTokenCount!=null&&setValueByPath(toObject,["cachedContentTokenCount"],fromCachedContentTokenCount),toObject}function countTokensResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);return fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens),toObject}function deleteModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteModelResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function editImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromEditMode=getValueByPath(fromObject,["editMode"]);parentObject!==void 0&&fromEditMode!=null&&setValueByPath(parentObject,["parameters","editMode"],fromEditMode);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);return parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","editConfig","baseSteps"],fromBaseSteps),toObject}function editImageParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>referenceImageAPIInternalToVertex(item))),setValueByPath(toObject,["instances[0]","referenceImages"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&editImageConfigToVertex(fromConfig,toObject),toObject}function editImageResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function embedContentConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["requests[]","taskType"],fromTaskType);let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["requests[]","title"],fromTitle);let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);if(parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["requests[]","outputDimensionality"],fromOutputDimensionality),getValueByPath(fromObject,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function embedContentConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorTaskType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorTaskType===void 0&&(discriminatorTaskType="PREDICT"),discriminatorTaskType==="PREDICT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["instances[]","task_type"],fromTaskType)}else if(discriminatorTaskType==="EMBED_CONTENT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["embedContentConfig","taskType"],fromTaskType)}let discriminatorTitle=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorTitle===void 0&&(discriminatorTitle="PREDICT"),discriminatorTitle==="PREDICT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["instances[]","title"],fromTitle)}else if(discriminatorTitle==="EMBED_CONTENT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["embedContentConfig","title"],fromTitle)}let discriminatorOutputDimensionality=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorOutputDimensionality===void 0&&(discriminatorOutputDimensionality="PREDICT"),discriminatorOutputDimensionality==="PREDICT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["parameters","outputDimensionality"],fromOutputDimensionality)}else if(discriminatorOutputDimensionality==="EMBED_CONTENT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["embedContentConfig","outputDimensionality"],fromOutputDimensionality)}let discriminatorMimeType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorMimeType===void 0&&(discriminatorMimeType="PREDICT"),discriminatorMimeType==="PREDICT"){let fromMimeType=getValueByPath(fromObject,["mimeType"]);parentObject!==void 0&&fromMimeType!=null&&setValueByPath(parentObject,["instances[]","mimeType"],fromMimeType)}let discriminatorAutoTruncate=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAutoTruncate===void 0&&(discriminatorAutoTruncate="PREDICT"),discriminatorAutoTruncate==="PREDICT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["parameters","autoTruncate"],fromAutoTruncate)}else if(discriminatorAutoTruncate==="EMBED_CONTENT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["embedContentConfig","autoTruncate"],fromAutoTruncate)}let discriminatorDocumentOcr=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorDocumentOcr===void 0&&(discriminatorDocumentOcr="PREDICT"),discriminatorDocumentOcr==="EMBED_CONTENT"){let fromDocumentOcr=getValueByPath(fromObject,["documentOcr"]);parentObject!==void 0&&fromDocumentOcr!=null&&setValueByPath(parentObject,["embedContentConfig","documentOcr"],fromDocumentOcr)}let discriminatorAudioTrackExtraction=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAudioTrackExtraction===void 0&&(discriminatorAudioTrackExtraction="PREDICT"),discriminatorAudioTrackExtraction==="EMBED_CONTENT"){let fromAudioTrackExtraction=getValueByPath(fromObject,["audioTrackExtraction"]);parentObject!==void 0&&fromAudioTrackExtraction!=null&&setValueByPath(parentObject,["embedContentConfig","audioTrackExtraction"],fromAudioTrackExtraction)}return toObject}function embedContentParametersPrivateToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["requests[]","content"],transformedList)}let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&contentToMldev$1(tContent(fromContent));let fromConfig=getValueByPath(fromObject,["config"]);fromConfig!=null&&embedContentConfigToMldev(fromConfig,toObject);let fromModelForEmbedContent=getValueByPath(fromObject,["model"]);return fromModelForEmbedContent!==void 0&&setValueByPath(toObject,["requests[]","model"],tModel(apiClient,fromModelForEmbedContent)),toObject}function embedContentParametersPrivateToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let discriminatorContents=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContents===void 0&&(discriminatorContents="PREDICT"),discriminatorContents==="PREDICT"){let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["instances[]","content"],transformedList)}}let discriminatorContent=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContent===void 0&&(discriminatorContent="PREDICT"),discriminatorContent==="EMBED_CONTENT"){let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],contentToVertex$1(tContent(fromContent)))}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&embedContentConfigToVertex(fromConfig,toObject,rootObject),toObject}function embedContentResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(fromObject,["embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);return fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),toObject}function embedContentResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(fromObject,["predictions[]","embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentEmbeddingFromVertex(item))),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);if(fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),rootObject&&getValueByPath(rootObject,["embeddingApiType"])==="EMBED_CONTENT"){let embedding=getValueByPath(fromObject,["embedding"]),usageMetadata=getValueByPath(fromObject,["usageMetadata"]),truncated=getValueByPath(fromObject,["truncated"]);if(embedding){let stats={};usageMetadata&&usageMetadata.promptTokenCount&&(stats.tokenCount=usageMetadata.promptTokenCount),usageMetadata&&usageMetadata.promptTokensDetails&&(stats.tokensDetails=usageMetadata.promptTokensDetails),truncated&&(stats.truncated=truncated),embedding.statistics=stats,setValueByPath(toObject,["embeddings"],[embedding])}}return toObject}function endpointFromVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["endpoint"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDeployedModelId=getValueByPath(fromObject,["deployedModelId"]);return fromDeployedModelId!=null&&setValueByPath(toObject,["deployedModelId"],fromDeployedModelId),toObject}function fileDataToMldev$1(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev$1(fromObject,_rootObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev(fromObject,_rootObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToMldev(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);if(fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema),getValueByPath(fromObject,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$1(item))),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$1(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev(fromToolConfig)),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);if(fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],tSpeechConfig(fromSpeechConfig)),getValueByPath(fromObject,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToMldev(fromImageConfig));let fromEnableEnhancedCivicAnswers=getValueByPath(fromObject,["enableEnhancedCivicAnswers"]);if(fromEnableEnhancedCivicAnswers!=null&&setValueByPath(toObject,["enableEnhancedCivicAnswers"],fromEnableEnhancedCivicAnswers),getValueByPath(fromObject,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToVertex(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToVertex(fromToolConfig));let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);if(fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToVertex(fromImageConfig)),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromModelArmorConfig=getValueByPath(fromObject,["modelArmorConfig"]);return parentObject!==void 0&&fromModelArmorConfig!=null&&setValueByPath(parentObject,["modelArmorConfig"],fromModelArmorConfig),toObject}function generateContentParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToMldev(apiClient,fromConfig,toObject)),toObject}function generateContentParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToVertex(apiClient,fromConfig,toObject)),toObject}function generateContentResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>candidateFromMldev(item))),setValueByPath(toObject,["candidates"],transformedList)}let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata);let fromModelStatus=getValueByPath(fromObject,["modelStatus"]);return fromModelStatus!=null&&setValueByPath(toObject,["modelStatus"],fromModelStatus),toObject}function generateContentResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["candidates"],transformedList)}let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);return fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata),toObject}function generateImagesConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromImageSize=getValueByPath(fromObject,["imageSize"]);parentObject!==void 0&&fromImageSize!=null&&setValueByPath(parentObject,["parameters","sampleImageSize"],fromImageSize);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);return parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),toObject}function generateImagesParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateImagesConfigToVertex(fromConfig,toObject),toObject}function generateImagesResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}let fromPositivePromptSafetyAttributes=getValueByPath(fromObject,["positivePromptSafetyAttributes"]);return fromPositivePromptSafetyAttributes!=null&&setValueByPath(toObject,["positivePromptSafetyAttributes"],safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)),toObject}function generateVideosConfigToMldev(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);if(parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos),getValueByPath(fromObject,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);if(parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds),getValueByPath(fromObject,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);if(parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration),getValueByPath(fromObject,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);if(parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),getValueByPath(fromObject,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToMldev(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToMldev(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}if(getValueByPath(fromObject,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromWebhookConfig=getValueByPath(fromObject,["webhookConfig"]);if(parentObject!==void 0&&fromWebhookConfig!=null&&setValueByPath(parentObject,["webhookConfig"],fromWebhookConfig),getValueByPath(fromObject,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateVideosConfigToVertex(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromFps=getValueByPath(fromObject,["fps"]);parentObject!==void 0&&fromFps!=null&&setValueByPath(parentObject,["parameters","fps"],fromFps);let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromPubsubTopic=getValueByPath(fromObject,["pubsubTopic"]);parentObject!==void 0&&fromPubsubTopic!=null&&setValueByPath(parentObject,["parameters","pubsubTopic"],fromPubsubTopic);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromGenerateAudio=getValueByPath(fromObject,["generateAudio"]);parentObject!==void 0&&fromGenerateAudio!=null&&setValueByPath(parentObject,["parameters","generateAudio"],fromGenerateAudio);let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToVertex(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToVertex(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}let fromMask=getValueByPath(fromObject,["mask"]);parentObject!==void 0&&fromMask!=null&&setValueByPath(parentObject,["instances[0]","mask"],videoGenerationMaskToVertex(fromMask));let fromCompressionQuality=getValueByPath(fromObject,["compressionQuality"]);parentObject!==void 0&&fromCompressionQuality!=null&&setValueByPath(parentObject,["parameters","compressionQuality"],fromCompressionQuality);let fromLabels=getValueByPath(fromObject,["labels"]);if(parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),getValueByPath(fromObject,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromResizeMode=getValueByPath(fromObject,["resizeMode"]);return parentObject!==void 0&&fromResizeMode!=null&&setValueByPath(parentObject,["parameters","resizeMode"],fromResizeMode),toObject}function generateVideosOperationFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev(fromResponse)),toObject}function generateVideosOperationFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex(fromResponse)),toObject}function generateVideosParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["instances[0]","video"],videoToMldev(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToMldev(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToMldev(fromConfig,toObject),toObject}function generateVideosParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["instances[0]","video"],videoToVertex(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToVertex(fromConfig,toObject),toObject}function generateVideosResponseFromMldev(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosSourceToMldev(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToMldev(fromVideo)),toObject}function generateVideosSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToVertex(fromVideo)),toObject}function generatedImageFromVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["_self"]);fromImage!=null&&setValueByPath(toObject,["image"],imageFromVertex(fromImage));let fromRaiFilteredReason=getValueByPath(fromObject,["raiFilteredReason"]);fromRaiFilteredReason!=null&&setValueByPath(toObject,["raiFilteredReason"],fromRaiFilteredReason);let fromSafetyAttributes=getValueByPath(fromObject,["_self"]);fromSafetyAttributes!=null&&setValueByPath(toObject,["safetyAttributes"],safetyAttributesFromVertex(fromSafetyAttributes));let fromEnhancedPrompt=getValueByPath(fromObject,["prompt"]);return fromEnhancedPrompt!=null&&setValueByPath(toObject,["enhancedPrompt"],fromEnhancedPrompt),toObject}function generatedImageMaskFromVertex(fromObject,rootObject){let toObject={},fromMask=getValueByPath(fromObject,["_self"]);fromMask!=null&&setValueByPath(toObject,["mask"],imageFromVertex(fromMask));let fromLabels=getValueByPath(fromObject,["labels"]);if(fromLabels!=null){let transformedList=fromLabels;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["labels"],transformedList)}return toObject}function generatedVideoFromMldev(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev(fromVideo)),toObject}function generatedVideoFromVertex(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex(fromVideo)),toObject}function generationConfigToVertex(fromObject,rootObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex(fromSpeechConfig));let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);if(fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function getModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function getModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function googleMapsToMldev$1(fromObject,rootObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$1(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$1(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function imageConfigToMldev(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);if(fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize),getValueByPath(fromObject,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function imageConfigToVertex(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);fromPersonGeneration!=null&&setValueByPath(toObject,["personGeneration"],fromPersonGeneration);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);fromOutputMimeType!=null&&setValueByPath(toObject,["imageOutputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);fromOutputCompressionQuality!=null&&setValueByPath(toObject,["imageOutputOptions","compressionQuality"],fromOutputCompressionQuality);let fromImageOutputOptions=getValueByPath(fromObject,["imageOutputOptions"]);fromImageOutputOptions!=null&&setValueByPath(toObject,["imageOutputOptions"],fromImageOutputOptions);let fromProminentPeople=getValueByPath(fromObject,["prominentPeople"]);return fromProminentPeople!=null&&setValueByPath(toObject,["prominentPeople"],fromProminentPeople),toObject}function imageFromVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromImageBytes!=null&&setValueByPath(toObject,["imageBytes"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function listModelsConfigToMldev(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsConfigToVertex(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToMldev(apiClient,fromConfig,toObject),toObject}function listModelsParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToVertex(apiClient,fromConfig,toObject),toObject}function listModelsResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromMldev(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function listModelsResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromVertex(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function maskReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromMaskMode=getValueByPath(fromObject,["maskMode"]);fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode);let fromSegmentationClasses=getValueByPath(fromObject,["segmentationClasses"]);fromSegmentationClasses!=null&&setValueByPath(toObject,["maskClasses"],fromSegmentationClasses);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);return fromMaskDilation!=null&&setValueByPath(toObject,["dilation"],fromMaskDilation),toObject}function mcpServerToVertex(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function modelFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["version"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromMldev(fromTunedModelInfo));let fromInputTokenLimit=getValueByPath(fromObject,["inputTokenLimit"]);fromInputTokenLimit!=null&&setValueByPath(toObject,["inputTokenLimit"],fromInputTokenLimit);let fromOutputTokenLimit=getValueByPath(fromObject,["outputTokenLimit"]);fromOutputTokenLimit!=null&&setValueByPath(toObject,["outputTokenLimit"],fromOutputTokenLimit);let fromSupportedActions=getValueByPath(fromObject,["supportedGenerationMethods"]);fromSupportedActions!=null&&setValueByPath(toObject,["supportedActions"],fromSupportedActions);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromMaxTemperature=getValueByPath(fromObject,["maxTemperature"]);fromMaxTemperature!=null&&setValueByPath(toObject,["maxTemperature"],fromMaxTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromThinking=getValueByPath(fromObject,["thinking"]);return fromThinking!=null&&setValueByPath(toObject,["thinking"],fromThinking),toObject}function modelFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["versionId"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromEndpoints=getValueByPath(fromObject,["deployedModels"]);if(fromEndpoints!=null){let transformedList=fromEndpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>endpointFromVertex(item))),setValueByPath(toObject,["endpoints"],transformedList)}let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromVertex(fromTunedModelInfo));let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);fromDefaultCheckpointId!=null&&setValueByPath(toObject,["defaultCheckpointId"],fromDefaultCheckpointId);let fromCheckpoints=getValueByPath(fromObject,["checkpoints"]);if(fromCheckpoints!=null){let transformedList=fromCheckpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["checkpoints"],transformedList)}return toObject}function multiSpeakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeakerVoiceConfigs=getValueByPath(fromObject,["speakerVoiceConfigs"]);if(fromSpeakerVoiceConfigs!=null){let transformedList=fromSpeakerVoiceConfigs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>speakerVoiceConfigToVertex(item))),setValueByPath(toObject,["speakerVoiceConfigs"],transformedList)}return toObject}function partToMldev$1(fromObject,rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$1(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$1(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$1(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function partToVertex$1(fromObject,_rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function productImageToVertex(fromObject,rootObject){let toObject={},fromProductImage=getValueByPath(fromObject,["productImage"]);return fromProductImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromProductImage)),toObject}function recontextImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","baseSteps"],fromBaseSteps);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function recontextImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&recontextImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&recontextImageConfigToVertex(fromConfig,toObject),toObject}function recontextImageResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function recontextImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromPersonImage=getValueByPath(fromObject,["personImage"]);parentObject!==void 0&&fromPersonImage!=null&&setValueByPath(parentObject,["instances[0]","personImage","image"],imageToVertex(fromPersonImage));let fromProductImages=getValueByPath(fromObject,["productImages"]);if(parentObject!==void 0&&fromProductImages!=null){let transformedList=fromProductImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>productImageToVertex(item))),setValueByPath(parentObject,["instances[0]","productImages"],transformedList)}return toObject}function referenceImageAPIInternalToVertex(fromObject,rootObject){let toObject={},fromReferenceImage=getValueByPath(fromObject,["referenceImage"]);fromReferenceImage!=null&&setValueByPath(toObject,["referenceImage"],imageToVertex(fromReferenceImage));let fromReferenceId=getValueByPath(fromObject,["referenceId"]);fromReferenceId!=null&&setValueByPath(toObject,["referenceId"],fromReferenceId);let fromReferenceType=getValueByPath(fromObject,["referenceType"]);fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType);let fromMaskImageConfig=getValueByPath(fromObject,["maskImageConfig"]);fromMaskImageConfig!=null&&setValueByPath(toObject,["maskImageConfig"],maskReferenceConfigToVertex(fromMaskImageConfig));let fromControlImageConfig=getValueByPath(fromObject,["controlImageConfig"]);fromControlImageConfig!=null&&setValueByPath(toObject,["controlImageConfig"],controlReferenceConfigToVertex(fromControlImageConfig));let fromStyleImageConfig=getValueByPath(fromObject,["styleImageConfig"]);fromStyleImageConfig!=null&&setValueByPath(toObject,["styleImageConfig"],fromStyleImageConfig);let fromSubjectImageConfig=getValueByPath(fromObject,["subjectImageConfig"]);return fromSubjectImageConfig!=null&&setValueByPath(toObject,["subjectImageConfig"],fromSubjectImageConfig),toObject}function replicatedVoiceConfigToVertex(fromObject,_rootObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType);let fromVoiceSampleAudio=getValueByPath(fromObject,["voiceSampleAudio"]);if(fromVoiceSampleAudio!=null&&setValueByPath(toObject,["voiceSampleAudio"],fromVoiceSampleAudio),getValueByPath(fromObject,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function safetyAttributesFromVertex(fromObject,_rootObject){let toObject={},fromCategories=getValueByPath(fromObject,["safetyAttributes","categories"]);fromCategories!=null&&setValueByPath(toObject,["categories"],fromCategories);let fromScores=getValueByPath(fromObject,["safetyAttributes","scores"]);fromScores!=null&&setValueByPath(toObject,["scores"],fromScores);let fromContentType=getValueByPath(fromObject,["contentType"]);return fromContentType!=null&&setValueByPath(toObject,["contentType"],fromContentType),toObject}function safetySettingToMldev$1(fromObject,_rootObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function scribbleImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);return fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage)),toObject}function segmentImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromMode=getValueByPath(fromObject,["mode"]);parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode);let fromMaxPredictions=getValueByPath(fromObject,["maxPredictions"]);parentObject!==void 0&&fromMaxPredictions!=null&&setValueByPath(parentObject,["parameters","maxPredictions"],fromMaxPredictions);let fromConfidenceThreshold=getValueByPath(fromObject,["confidenceThreshold"]);parentObject!==void 0&&fromConfidenceThreshold!=null&&setValueByPath(parentObject,["parameters","confidenceThreshold"],fromConfidenceThreshold);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);parentObject!==void 0&&fromMaskDilation!=null&&setValueByPath(parentObject,["parameters","maskDilation"],fromMaskDilation);let fromBinaryColorThreshold=getValueByPath(fromObject,["binaryColorThreshold"]);parentObject!==void 0&&fromBinaryColorThreshold!=null&&setValueByPath(parentObject,["parameters","binaryColorThreshold"],fromBinaryColorThreshold);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function segmentImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&segmentImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&segmentImageConfigToVertex(fromConfig,toObject),toObject}function segmentImageResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedMasks=getValueByPath(fromObject,["predictions"]);if(fromGeneratedMasks!=null){let transformedList=fromGeneratedMasks;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageMaskFromVertex(item))),setValueByPath(toObject,["generatedMasks"],transformedList)}return toObject}function segmentImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromScribbleImage=getValueByPath(fromObject,["scribbleImage"]);return parentObject!==void 0&&fromScribbleImage!=null&&setValueByPath(parentObject,["instances[0]","scribble"],scribbleImageToVertex(fromScribbleImage)),toObject}function speakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeaker=getValueByPath(fromObject,["speaker"]);fromSpeaker!=null&&setValueByPath(toObject,["speaker"],fromSpeaker);let fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);return fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig)),toObject}function speechConfigToVertex(fromObject,rootObject){let toObject={},fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig));let fromLanguageCode=getValueByPath(fromObject,["languageCode"]);fromLanguageCode!=null&&setValueByPath(toObject,["languageCode"],fromLanguageCode);let fromMultiSpeakerVoiceConfig=getValueByPath(fromObject,["multiSpeakerVoiceConfig"]);return fromMultiSpeakerVoiceConfig!=null&&setValueByPath(toObject,["multiSpeakerVoiceConfig"],multiSpeakerVoiceConfigToVertex(fromMultiSpeakerVoiceConfig)),toObject}function toolConfigToMldev(fromObject,rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolConfigToVertex(fromObject,_rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],fromFunctionCallingConfig);let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);if(fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig),getValueByPath(fromObject,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function toolToMldev$1(fromObject,rootObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$1(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$1(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex(fromObject,rootObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tunedModelInfoFromMldev(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function tunedModelInfoFromVertex(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["labels","google-vertex-llm-tuning-base-model-id"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function updateModelConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);return parentObject!==void 0&&fromDefaultCheckpointId!=null&&setValueByPath(parentObject,["defaultCheckpointId"],fromDefaultCheckpointId),toObject}function updateModelConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);return parentObject!==void 0&&fromDefaultCheckpointId!=null&&setValueByPath(parentObject,["defaultCheckpointId"],fromDefaultCheckpointId),toObject}function updateModelParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToMldev(fromConfig,toObject),toObject}function updateModelParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToVertex(fromConfig,toObject),toObject}function upscaleImageAPIConfigInternalToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromEnhanceInputImage=getValueByPath(fromObject,["enhanceInputImage"]);parentObject!==void 0&&fromEnhanceInputImage!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","enhanceInputImage"],fromEnhanceInputImage);let fromImagePreservationFactor=getValueByPath(fromObject,["imagePreservationFactor"]);parentObject!==void 0&&fromImagePreservationFactor!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","imagePreservationFactor"],fromImagePreservationFactor);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromMode=getValueByPath(fromObject,["mode"]);return parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode),toObject}function upscaleImageAPIParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromUpscaleFactor=getValueByPath(fromObject,["upscaleFactor"]);fromUpscaleFactor!=null&&setValueByPath(toObject,["parameters","upscaleConfig","upscaleFactor"],fromUpscaleFactor);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&upscaleImageAPIConfigInternalToVertex(fromConfig,toObject),toObject}function upscaleImageResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function videoFromMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoGenerationMaskToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["_self"],imageToVertex(fromImage));let fromMaskMode=getValueByPath(fromObject,["maskMode"]);return fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode),toObject}function videoGenerationReferenceImageToMldev(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToMldev(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoGenerationReferenceImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoToMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["encodedVideo"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["encoding"],fromMimeType),toObject}function videoToVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["gcsUri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function voiceConfigToVertex(fromObject,rootObject){let toObject={},fromReplicatedVoiceConfig=getValueByPath(fromObject,["replicatedVoiceConfig"]);fromReplicatedVoiceConfig!=null&&setValueByPath(toObject,["replicatedVoiceConfig"],replicatedVoiceConfigToVertex(fromReplicatedVoiceConfig));let fromPrebuiltVoiceConfig=getValueByPath(fromObject,["prebuiltVoiceConfig"]);return fromPrebuiltVoiceConfig!=null&&setValueByPath(toObject,["prebuiltVoiceConfig"],fromPrebuiltVoiceConfig),toObject}function createFileSearchStoreConfigToMldev(apiClient,fromObject,parentObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromEmbeddingModel=getValueByPath(fromObject,["embeddingModel"]);return parentObject!==void 0&&fromEmbeddingModel!=null&&setValueByPath(parentObject,["embeddingModel"],tModel(apiClient,fromEmbeddingModel)),toObject}function createFileSearchStoreParametersToMldev(apiClient,fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createFileSearchStoreConfigToMldev(apiClient,fromConfig,toObject),toObject}function deleteFileSearchStoreConfigToMldev(fromObject,parentObject){let toObject={},fromForce=getValueByPath(fromObject,["force"]);return parentObject!==void 0&&fromForce!=null&&setValueByPath(parentObject,["_query","force"],fromForce),toObject}function deleteFileSearchStoreParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],fromName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&deleteFileSearchStoreConfigToMldev(fromConfig,toObject),toObject}function getFileSearchStoreParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function importFileConfigToMldev(fromObject,parentObject){let toObject={},fromCustomMetadata=getValueByPath(fromObject,["customMetadata"]);if(parentObject!==void 0&&fromCustomMetadata!=null){let transformedList=fromCustomMetadata;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["customMetadata"],transformedList)}let fromChunkingConfig=getValueByPath(fromObject,["chunkingConfig"]);return parentObject!==void 0&&fromChunkingConfig!=null&&setValueByPath(parentObject,["chunkingConfig"],fromChunkingConfig),toObject}function importFileOperationFromMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],importFileResponseFromMldev(fromResponse)),toObject}function importFileParametersToMldev(fromObject){let toObject={},fromFileSearchStoreName=getValueByPath(fromObject,["fileSearchStoreName"]);fromFileSearchStoreName!=null&&setValueByPath(toObject,["_url","file_search_store_name"],fromFileSearchStoreName);let fromFileName=getValueByPath(fromObject,["fileName"]);fromFileName!=null&&setValueByPath(toObject,["fileName"],fromFileName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&importFileConfigToMldev(fromConfig,toObject),toObject}function importFileResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["parent"],fromParent);let fromDocumentName=getValueByPath(fromObject,["documentName"]);return fromDocumentName!=null&&setValueByPath(toObject,["documentName"],fromDocumentName),toObject}function listFileSearchStoresConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listFileSearchStoresParametersToMldev(fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listFileSearchStoresConfigToMldev(fromConfig,toObject),toObject}function listFileSearchStoresResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromFileSearchStores=getValueByPath(fromObject,["fileSearchStores"]);if(fromFileSearchStores!=null){let transformedList=fromFileSearchStores;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["fileSearchStores"],transformedList)}return toObject}function uploadToFileSearchStoreConfigToMldev(fromObject,parentObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);parentObject!==void 0&&fromMimeType!=null&&setValueByPath(parentObject,["mimeType"],fromMimeType);let fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromCustomMetadata=getValueByPath(fromObject,["customMetadata"]);if(parentObject!==void 0&&fromCustomMetadata!=null){let transformedList=fromCustomMetadata;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["customMetadata"],transformedList)}let fromChunkingConfig=getValueByPath(fromObject,["chunkingConfig"]);return parentObject!==void 0&&fromChunkingConfig!=null&&setValueByPath(parentObject,["chunkingConfig"],fromChunkingConfig),toObject}function uploadToFileSearchStoreParametersToMldev(fromObject){let toObject={},fromFileSearchStoreName=getValueByPath(fromObject,["fileSearchStoreName"]);fromFileSearchStoreName!=null&&setValueByPath(toObject,["_url","file_search_store_name"],fromFileSearchStoreName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&uploadToFileSearchStoreConfigToMldev(fromConfig,toObject),toObject}function uploadToFileSearchStoreResumableResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}var CONTENT_TYPE_HEADER="Content-Type",SERVER_TIMEOUT_HEADER="X-Server-Timeout",USER_AGENT_HEADER="User-Agent",GOOGLE_API_CLIENT_HEADER="x-goog-api-client",SDK_VERSION="2.23.0",LIBRARY_LABEL=`google-genai-sdk/${SDK_VERSION}`,VERTEX_AI_API_DEFAULT_VERSION="v1beta1",GOOGLE_AI_API_DEFAULT_VERSION="v1beta",MULTI_REGIONAL_LOCATIONS=new Set(["us","eu"]);function raiseUndiciTimeouts(timeout){let globalDispatcher=globalThis[Symbol.for("undici.globalDispatcher.1")];if(globalDispatcher)for(let sym of Object.getOwnPropertySymbols(globalDispatcher)){let desc=sym.description;if(desc?.includes("headers timeout")||desc?.includes("body timeout")){let currentTimeout=globalDispatcher[sym];typeof currentTimeout=="number"&&(globalDispatcher[sym]=Math.max(currentTimeout,timeout))}}}function createAttemptSignal(timeout,callerSignal){let noop=()=>{};if(!(timeout&&timeout>0)&&!callerSignal)return{signal:void 0,dispose:noop};let controller=new AbortController,timeoutHandle;timeout&&timeout>0&&(timeoutHandle=setTimeout(()=>controller.abort(),timeout),timeoutHandle&&typeof timeoutHandle.unref=="function"&&timeoutHandle.unref());let onCallerAbort=()=>controller.abort();return callerSignal&&(callerSignal.aborted?controller.abort():callerSignal.addEventListener("abort",onCallerAbort)),{signal:controller.signal,dispose:()=>{timeoutHandle!==void 0&&clearTimeout(timeoutHandle),callerSignal?.removeEventListener("abort",onCallerAbort)}}}var DEFAULT_RETRY_ATTEMPTS=5,DEFAULT_RETRY_INITIAL_DELAY=1,DEFAULT_RETRY_MAX_DELAY=60,DEFAULT_RETRY_EXP_BASE=2,DEFAULT_RETRY_JITTER=1,DEFAULT_RETRY_HTTP_STATUS_CODES=[408,429,500,502,503,504],ApiClient=class{constructor(opts){var _a2,_b,_c;this.clientOptions=Object.assign({},opts),this.customBaseUrl=(_a2=opts.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl;let initHttpOptions={};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.");let hasConstructorAuth=opts.project&&opts.location||!!opts.apiKey;this.customBaseUrl&&!hasConstructorAuth?(initHttpOptions.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey&&!this.clientOptions.project||this.clientOptions.location==="global"?initHttpOptions.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&MULTI_REGIONAL_LOCATIONS.has(this.clientOptions.location)?initHttpOptions.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(initHttpOptions.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),initHttpOptions.apiVersion=(_b=this.clientOptions.apiVersion)!==null&&_b!==void 0?_b:VERTEX_AI_API_DEFAULT_VERSION}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),initHttpOptions.apiVersion=(_c=this.clientOptions.apiVersion)!==null&&_c!==void 0?_c:GOOGLE_AI_API_DEFAULT_VERSION,initHttpOptions.baseUrl="https://generativelanguage.googleapis.com/";initHttpOptions.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=initHttpOptions,opts.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(initHttpOptions,opts.httpOptions))}isVertexAI(){var _a2;return(_a2=this.clientOptions.vertexai)!==null&&_a2!==void 0?_a2:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let headers=new Headers;return await this.clientOptions.auth.addAuthHeaders(headers),headers}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getFetch(){var _a2;return(_a2=this.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.fetch}getRequestUrlInternal(httpOptions){if(!httpOptions||httpOptions.baseUrl===void 0||httpOptions.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");let urlElement=[httpOptions.baseUrl.endsWith("/")?httpOptions.baseUrl.slice(0,-1):httpOptions.baseUrl];return httpOptions.apiVersion&&httpOptions.apiVersion!==""&&urlElement.push(httpOptions.apiVersion),urlElement.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let baseUrl=this.getBaseUrl(),urlParts=new URL(baseUrl);return urlParts.protocol=urlParts.protocol=="http:"?"ws":"wss",urlParts.toString()}setBaseUrl(url){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=url;else throw new Error("HTTP options are not correctly set.")}constructUrl(path2,httpOptions,prependProjectLocation){let urlElement=[this.getRequestUrlInternal(httpOptions)];return prependProjectLocation&&urlElement.push(this.getBaseResourcePath()),path2!==""&&urlElement.push(path2),new URL(`${urlElement.join("/")}`)}shouldPrependVertexProjectPath(request,httpOptions){return!(httpOptions.baseUrl&&httpOptions.baseUrlResourceScope===ResourceScope.COLLECTION||!this.clientOptions.vertexai||!this.clientOptions.project||!this.clientOptions.location||request.path.startsWith("projects/")||request.httpMethod==="GET"&&request.path.startsWith("publishers/google/models"))}async request(request){let patchedHttpOptions=this.clientOptions.httpOptions;request.httpOptions&&(patchedHttpOptions=this.patchHttpOptions(this.clientOptions.httpOptions,request.httpOptions));let prependProjectLocation=this.shouldPrependVertexProjectPath(request,patchedHttpOptions),url=this.constructUrl(request.path,patchedHttpOptions,prependProjectLocation);if(request.queryParams)for(let[key,value]of Object.entries(request.queryParams))url.searchParams.append(key,String(value));let requestInit={};if(request.httpMethod==="GET"){if(request.body&&request.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else requestInit.body=request.body;return requestInit=await this.includeExtraHttpOptionsToRequestInit(requestInit,patchedHttpOptions,url.toString()),this.unaryApiCall(url,requestInit,request.httpMethod,patchedHttpOptions.retryOptions,patchedHttpOptions.timeout,request.abortSignal,patchedHttpOptions.fetch)}patchHttpOptions(baseHttpOptions,requestHttpOptions){let patchedHttpOptions=JSON.parse(JSON.stringify(baseHttpOptions));baseHttpOptions.fetch&&(patchedHttpOptions.fetch=baseHttpOptions.fetch);for(let[key,value]of Object.entries(requestHttpOptions))typeof value=="object"?patchedHttpOptions[key]=Object.assign(Object.assign({},patchedHttpOptions[key]),value):value!==void 0&&(patchedHttpOptions[key]=value);return patchedHttpOptions}async requestStream(request){let patchedHttpOptions=this.clientOptions.httpOptions;request.httpOptions&&(patchedHttpOptions=this.patchHttpOptions(this.clientOptions.httpOptions,request.httpOptions));let prependProjectLocation=this.shouldPrependVertexProjectPath(request,patchedHttpOptions),url=this.constructUrl(request.path,patchedHttpOptions,prependProjectLocation);(!url.searchParams.has("alt")||url.searchParams.get("alt")!=="sse")&&url.searchParams.set("alt","sse");let requestInit={};return requestInit.body=request.body,requestInit=await this.includeExtraHttpOptionsToRequestInit(requestInit,patchedHttpOptions,url.toString()),this.streamApiCall(url,requestInit,request.httpMethod,patchedHttpOptions.retryOptions,patchedHttpOptions.timeout,request.abortSignal,patchedHttpOptions.fetch)}async includeExtraHttpOptionsToRequestInit(requestInit,httpOptions,url){return httpOptions?.timeout&&httpOptions.timeout>0&&raiseUndiciTimeouts(httpOptions.timeout),httpOptions&&httpOptions.extraBody!==null&&includeExtraBodyToRequestInit(requestInit,httpOptions.extraBody),requestInit.headers=await this.getHeadersInternal(httpOptions,url),requestInit}async unaryApiCall(url,requestInit,httpMethod,retryOptions,timeout,abortSignal,fetchFn){return this.apiCall(url.toString(),Object.assign(Object.assign({},requestInit),{method:httpMethod}),retryOptions,timeout,abortSignal,fetchFn).then(async response=>(await throwErrorIfNotOK(response),new HttpResponse(response))).catch(e=>{throw e instanceof Error?e:new Error(`exception ${e} sending request`,{cause:e})})}async streamApiCall(url,requestInit,httpMethod,retryOptions,timeout,abortSignal,fetchFn){return this.apiCall(url.toString(),Object.assign(Object.assign({},requestInit),{method:httpMethod}),retryOptions,timeout,abortSignal,fetchFn).then(async response=>(await throwErrorIfNotOK(response),this.processStreamResponse(response))).catch(e=>{throw e instanceof Error?e:new Error(`exception ${e} sending request`,{cause:e})})}processStreamResponse(response){return __asyncGenerator(this,arguments,function*(){var _a2;let reader=(_a2=response?.body)===null||_a2===void 0?void 0:_a2.getReader(),decoder=new TextDecoder("utf-8");if(!reader)throw new Error("Response body is empty");try{let buffer="",dataPrefix="data:",delimiters=[`
`,"\r\r",`\r
\r
`];for(;;){let{done,value}=yield __await(reader.read());if(done){if(buffer.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let chunkString=decoder.decode(value,{stream:!0});try{let chunkJson=JSON.parse(chunkString);if("error"in chunkJson){let errorJson=JSON.parse(JSON.stringify(chunkJson.error)),status=errorJson.status,code=errorJson.code,errorMessage=`got status: ${status}. ${JSON.stringify(chunkJson)}`;if(code>=400&&code<600)throw new ApiError({message:errorMessage,status:code})}}catch(e){if(e.name==="ApiError")throw e}buffer+=chunkString;let delimiterIndex=-1,delimiterLength=0;for(;;){delimiterIndex=-1,delimiterLength=0;for(let delimiter of delimiters){let index=buffer.indexOf(delimiter);index!==-1&&(delimiterIndex===-1||index<delimiterIndex)&&(delimiterIndex=index,delimiterLength=delimiter.length)}if(delimiterIndex===-1)break;let eventString=buffer.substring(0,delimiterIndex);buffer=buffer.substring(delimiterIndex+delimiterLength);let trimmedEvent=eventString.trim();if(trimmedEvent.startsWith(dataPrefix)){let processedChunkString=trimmedEvent.substring(dataPrefix.length).trim();try{let partialResponse=new Response(processedChunkString,{headers:response?.headers,status:response?.status,statusText:response?.statusText});yield yield __await(new HttpResponse(partialResponse))}catch(e){throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`)}}}}}finally{reader.releaseLock()}})}async apiCall(url,requestInit,retryOptions,timeout,abortSignal,fetchFn){var _a2,_b,_c,_d,_e,_f;let fetchFunc=fetchFn??fetch,retryableStatusCodes=(_a2=retryOptions?.httpStatusCodes)!==null&&_a2!==void 0?_a2:DEFAULT_RETRY_HTTP_STATUS_CODES,runFetch=async()=>{let attempt=createAttemptSignal(timeout,abortSignal),response;try{response=await fetchFunc(url,Object.assign(Object.assign({},requestInit),{signal:attempt.signal}))}catch(e){throw attempt.dispose(),e}if(!retryOptions||response.ok||!retryableStatusCodes.includes(response.status))return response;try{await throwErrorIfNotOK(response)}finally{attempt.dispose()}return response};if(!retryOptions)return runFetch();let attempts=Math.max(1,(_b=retryOptions.attempts)!==null&&_b!==void 0?_b:DEFAULT_RETRY_ATTEMPTS),minTimeout=Math.round(((_c=retryOptions.initialDelay)!==null&&_c!==void 0?_c:DEFAULT_RETRY_INITIAL_DELAY)*1e3),maxTimeout=Math.max(minTimeout,Math.round(((_d=retryOptions.maxDelay)!==null&&_d!==void 0?_d:DEFAULT_RETRY_MAX_DELAY)*1e3));return(0,import_p_retry.default)(runFetch,{retries:attempts-1,factor:(_e=retryOptions.expBase)!==null&&_e!==void 0?_e:DEFAULT_RETRY_EXP_BASE,minTimeout,maxTimeout,randomize:((_f=retryOptions.jitter)!==null&&_f!==void 0?_f:DEFAULT_RETRY_JITTER)>0,onFailedAttempt:info=>{var _a3;if(abortSignal?.aborted)throw(_a3=info.error)!==null&&_a3!==void 0?_a3:info}})}getDefaultHeaders(){let headers={},versionHeaderValue=LIBRARY_LABEL+" "+this.clientOptions.userAgentExtra;return headers[USER_AGENT_HEADER]=versionHeaderValue,headers[GOOGLE_API_CLIENT_HEADER]=versionHeaderValue,headers[CONTENT_TYPE_HEADER]="application/json",headers}async getHeadersInternal(httpOptions,url){let headers=new Headers;if(httpOptions&&httpOptions.headers)for(let[key,value]of Object.entries(httpOptions.headers))headers.append(key,value);return httpOptions?.timeout&&httpOptions.timeout>0&&headers.append(SERVER_TIMEOUT_HEADER,String(Math.ceil(httpOptions.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(headers,url),headers}getFileName(file){var _a2;let fileName="";return typeof file=="string"&&(fileName=file.replace(/[/\\]+$/,""),fileName=(_a2=fileName.split(/[/\\]/).pop())!==null&&_a2!==void 0?_a2:""),fileName}async uploadFile(file,config){var _a2;let fileToUpload={};config!=null&&(fileToUpload.mimeType=config.mimeType,fileToUpload.name=config.name,fileToUpload.displayName=config.displayName),fileToUpload.name&&!fileToUpload.name.startsWith("files/")&&(fileToUpload.name=`files/${fileToUpload.name}`);let uploader=this.clientOptions.uploader,fileStat=await uploader.stat(file);fileToUpload.sizeBytes=String(fileStat.size);let mimeType=(_a2=config?.mimeType)!==null&&_a2!==void 0?_a2:fileStat.type;if(mimeType===void 0||mimeType==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");fileToUpload.mimeType=mimeType;let body={file:fileToUpload},fileName=this.getFileName(file),path2=formatMap("upload/v1beta/files",body._url),uploadUrl=await this.fetchUploadUrl(path2,fileToUpload.sizeBytes,fileToUpload.mimeType,fileName,body,config?.httpOptions);return uploader.upload(file,uploadUrl,this)}async uploadFileToFileSearchStore(fileSearchStoreName,file,config){var _a2;let uploader=this.clientOptions.uploader,fileStat=await uploader.stat(file),sizeBytes=String(fileStat.size),mimeType=(_a2=config?.mimeType)!==null&&_a2!==void 0?_a2:fileStat.type;if(mimeType===void 0||mimeType==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let path2=`upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`,fileName=this.getFileName(file),body={};config!=null&&uploadToFileSearchStoreConfigToMldev(config,body);let uploadUrl=await this.fetchUploadUrl(path2,sizeBytes,mimeType,fileName,body,config?.httpOptions);return uploader.uploadToFileSearchStore(file,uploadUrl,this)}async downloadFile(params){await this.clientOptions.downloader.download(params,this)}async fetchUploadUrl(path2,sizeBytes,mimeType,fileName,body,configHttpOptions){var _a2;let httpOptions={};configHttpOptions?httpOptions=configHttpOptions:httpOptions={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${sizeBytes}`,"X-Goog-Upload-Header-Content-Type":`${mimeType}`},fileName?{"X-Goog-Upload-File-Name":fileName}:{})};let httpResponse=await this.request({path:path2,body:JSON.stringify(body),httpMethod:"POST",httpOptions});if(!httpResponse||!httpResponse?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let uploadUrl=(_a2=httpResponse?.headers)===null||_a2===void 0?void 0:_a2["x-goog-upload-url"];if(uploadUrl===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return uploadUrl}};async function throwErrorIfNotOK(response){var _a2;if(response===void 0)throw new Error("response is undefined");if(!response.ok){let status=response.status,errorBody;!((_a2=response.headers.get("content-type"))===null||_a2===void 0)&&_a2.includes("application/json")?errorBody=await response.json():errorBody={error:{message:await response.text(),code:response.status,status:response.statusText}};let errorMessage=JSON.stringify(errorBody);throw status>=400&&status<600?new ApiError({message:errorMessage,status}):new Error(errorMessage)}}function includeExtraBodyToRequestInit(requestInit,extraBody){if(!extraBody||Object.keys(extraBody).length===0)return;if(requestInit.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let currentBodyObject={};if(typeof requestInit.body=="string"&&requestInit.body.length>0)try{let parsedBody=JSON.parse(requestInit.body);if(typeof parsedBody=="object"&&parsedBody!==null&&!Array.isArray(parsedBody))currentBodyObject=parsedBody;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function deepMerge(target,source){let output=Object.assign({},target);for(let key in source)if(Object.prototype.hasOwnProperty.call(source,key)){let sourceValue=source[key],targetValue=output[key];sourceValue&&typeof sourceValue=="object"&&!Array.isArray(sourceValue)&&targetValue&&typeof targetValue=="object"&&!Array.isArray(targetValue)?output[key]=deepMerge(targetValue,sourceValue):(targetValue&&sourceValue&&typeof targetValue!=typeof sourceValue&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`),output[key]=sourceValue)}return output}let mergedBody=deepMerge(currentBodyObject,extraBody);requestInit.body=JSON.stringify(mergedBody)}var MCP_LABEL="mcp_used/unknown",hasMcpToolUsageFromMcpToTool=!1;function hasMcpToolUsage(tools){for(let tool of tools)if(isMcpCallableTool(tool)||typeof tool=="object"&&"inputSchema"in tool)return!0;return hasMcpToolUsageFromMcpToTool}function setMcpUsageHeader(headers){var _a2;let existingHeader=(_a2=headers[GOOGLE_API_CLIENT_HEADER])!==null&&_a2!==void 0?_a2:"";headers[GOOGLE_API_CLIENT_HEADER]=(existingHeader+` ${MCP_LABEL}`).trimStart()}function isMcpCallableTool(object){return object!==null&&typeof object=="object"&&object instanceof McpCallableTool}function listAllTools(mcpClient_1){return __asyncGenerator(this,arguments,function*(mcpClient,maxTools=100){let cursor,numTools=0;for(;numTools<maxTools;){let t=yield __await(mcpClient.listTools({cursor}));for(let tool of t.tools)yield yield __await(tool),numTools++;if(!t.nextCursor)break;cursor=t.nextCursor}})}var McpCallableTool=class _McpCallableTool{constructor(mcpClients=[],config){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=mcpClients,this.config=config}static create(mcpClients,config){return new _McpCallableTool(mcpClients,config)}async initialize(){var _a2,e_1,_b,_c;if(this.mcpTools.length>0)return;let functionMap={},mcpTools=[];for(let mcpClient of this.mcpClients)try{for(var _d=!0,_e=(e_1=void 0,__asyncValues(listAllTools(mcpClient))),_f;_f=await _e.next(),_a2=_f.done,!_a2;_d=!0){_c=_f.value,_d=!1;let mcpTool=_c;mcpTools.push(mcpTool);let mcpToolName=mcpTool.name;if(functionMap[mcpToolName])throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);functionMap[mcpToolName]=mcpClient}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_d&&!_a2&&(_b=_e.return)&&await _b.call(_e)}finally{if(e_1)throw e_1.error}}this.mcpTools=mcpTools,this.functionNameToMcpClient=functionMap}async tool(){return await this.initialize(),mcpToolsToGeminiTool(this.mcpTools,this.config)}async callTool(functionCalls){await this.initialize();let functionCallResponseParts=[];for(let functionCall of functionCalls)if(functionCall.name in this.functionNameToMcpClient){let mcpClient=this.functionNameToMcpClient[functionCall.name],requestOptions;this.config.timeout&&(requestOptions={timeout:this.config.timeout});let callToolResponse=await mcpClient.callTool({name:functionCall.name,arguments:functionCall.args},void 0,requestOptions);functionCallResponseParts.push({functionResponse:{name:functionCall.name,response:callToolResponse.isError?{error:callToolResponse}:callToolResponse}})}return functionCallResponseParts}};async function handleWebSocketMessage$1(apiClient,onmessage,event){let serverMessage=new LiveMusicServerMessage,data;event.data instanceof Blob?data=JSON.parse(await event.data.text()):data=JSON.parse(event.data),Object.assign(serverMessage,data),onmessage(serverMessage)}var LiveMusic=class{constructor(apiClient,auth,webSocketFactory){this.apiClient=apiClient,this.auth=auth,this.webSocketFactory=webSocketFactory}async connect(params){var _a2,_b;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let websocketBaseUrl=this.apiClient.getWebsocketBaseUrl(),apiVersion=this.apiClient.getApiVersion(),headers=mapToHeaders$1(this.apiClient.getDefaultHeaders()),apiKey=this.apiClient.getApiKey(),url=`${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`,onopenResolve=()=>{},onopenPromise=new Promise(resolve=>{onopenResolve=resolve}),callbacks=params.callbacks,onopenAwaitedCallback=function(){onopenResolve({})},apiClient=this.apiClient,websocketCallbacks={onopen:onopenAwaitedCallback,onmessage:event=>{handleWebSocketMessage$1(apiClient,callbacks.onmessage,event)},onerror:(_a2=callbacks?.onerror)!==null&&_a2!==void 0?_a2:function(e){},onclose:(_b=callbacks?.onclose)!==null&&_b!==void 0?_b:function(e){}},conn=this.webSocketFactory.create(url,headersToMap$1(headers),websocketCallbacks);conn.connect(),await onopenPromise;let clientMessage={setup:{model:tModel(this.apiClient,params.model)}};return conn.send(JSON.stringify(clientMessage)),new LiveMusicSession(conn,this.apiClient)}},LiveMusicSession=class{constructor(conn,apiClient){this.conn=conn,this.apiClient=apiClient}async setWeightedPrompts(params){if(!params.weightedPrompts||Object.keys(params.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");let clientContent=liveMusicSetWeightedPromptsParametersToMldev(params);this.conn.send(JSON.stringify({clientContent}))}async setMusicGenerationConfig(params){params.musicGenerationConfig||(params.musicGenerationConfig={});let setConfigParameters=liveMusicSetConfigParametersToMldev(params);this.conn.send(JSON.stringify(setConfigParameters))}sendPlaybackControl(playbackControl){let clientMessage={playbackControl};this.conn.send(JSON.stringify(clientMessage))}play(){this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY)}pause(){this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE)}stop(){this.sendPlaybackControl(LiveMusicPlaybackControl.STOP)}resetContext(){this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT)}close(){this.conn.close()}};function headersToMap$1(headers){let headerMap={};return headers.forEach((value,key)=>{headerMap[key]=value}),headerMap}function mapToHeaders$1(map){let headers=new Headers;for(let[key,value]of Object.entries(map))headers.append(key,value);return headers}var FUNCTION_RESPONSE_REQUIRES_ID="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function handleWebSocketMessage(apiClient,onmessage,event){let serverMessage=new LiveServerMessage,jsonData;event.data instanceof Blob?jsonData=await event.data.text():event.data instanceof ArrayBuffer?jsonData=new TextDecoder().decode(event.data):jsonData=event.data;let data=JSON.parse(jsonData);if(apiClient.isVertexAI()){let resp=liveServerMessageFromVertex(data);Object.assign(serverMessage,resp)}else Object.assign(serverMessage,data);onmessage(serverMessage)}var Live=class{constructor(apiClient,auth,webSocketFactory){this.apiClient=apiClient,this.auth=auth,this.webSocketFactory=webSocketFactory,this.music=new LiveMusic(this.apiClient,this.auth,this.webSocketFactory)}async connect(params){var _a2,_b,_c,_d,_e,_f;if(params.config&¶ms.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.");let websocketBaseUrl=this.apiClient.getWebsocketBaseUrl(),apiVersion=this.apiClient.getApiVersion(),url,clientHeaders=this.apiClient.getHeaders();params.config&¶ms.config.tools&&hasMcpToolUsage(params.config.tools)&&setMcpUsageHeader(clientHeaders);let headers=mapToHeaders(clientHeaders);if(this.apiClient.isVertexAI()){let project=this.apiClient.getProject(),location=this.apiClient.getLocation(),apiKey=this.apiClient.getApiKey(),hasStandardAuth=!!project&&!!location||!!apiKey;this.apiClient.getCustomBaseUrl()&&!hasStandardAuth?url=websocketBaseUrl:(url=`${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(headers,url))}else{let apiKey=this.apiClient.getApiKey(),method="BidiGenerateContent",keyName="key";apiKey?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),apiVersion!=="v1alpha"&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),method="BidiGenerateContentConstrained",keyName="access_token"),url=`${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`}let onopenResolve=()=>{},onopenPromise=new Promise(resolve=>{onopenResolve=resolve}),callbacks=params.callbacks,onopenAwaitedCallback=function(){var _a3;(_a3=callbacks?.onopen)===null||_a3===void 0||_a3.call(callbacks),onopenResolve({})},apiClient=this.apiClient,sessionResolved=!1,messageQueue=[],setupCompleteResolve=()=>{},setupCompletePromise=new Promise(resolve=>{setupCompleteResolve=resolve}),websocketCallbacks={onopen:onopenAwaitedCallback,onmessage:event=>{handleWebSocketMessage(apiClient,msg=>{msg.setupComplete&&!session.setupComplete&&(session.setupComplete=msg.setupComplete,setupCompleteResolve({})),sessionResolved?callbacks.onmessage(msg):messageQueue.push(msg)},event)},onerror:(_a2=callbacks?.onerror)!==null&&_a2!==void 0?_a2:function(e){},onclose:(_b=callbacks?.onclose)!==null&&_b!==void 0?_b:function(e){}},conn=this.webSocketFactory.create(url,headersToMap(headers),websocketCallbacks);conn.connect(),await onopenPromise;let transformedModel=tModel(this.apiClient,params.model);if(this.apiClient.isVertexAI()&&transformedModel.startsWith("publishers/")){let project=this.apiClient.getProject(),location=this.apiClient.getLocation();project&&location&&(transformedModel=`projects/${project}/locations/${location}/`+transformedModel)}let clientMessage={};this.apiClient.isVertexAI()&&((_c=params.config)===null||_c===void 0?void 0:_c.responseModalities)===void 0&&(params.config===void 0?params.config={responseModalities:[Modality.AUDIO]}:params.config.responseModalities=[Modality.AUDIO]),!((_d=params.config)===null||_d===void 0)&&_d.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let inputTools=(_f=(_e=params.config)===null||_e===void 0?void 0:_e.tools)!==null&&_f!==void 0?_f:[],convertedTools=[];for(let tool of inputTools)if(this.isCallableTool(tool)){let callableTool=tool;convertedTools.push(await callableTool.tool())}else convertedTools.push(tool);convertedTools.length>0&&(params.config.tools=convertedTools);let liveConnectParameters={model:transformedModel,config:params.config,callbacks:params.callbacks};this.apiClient.isVertexAI()?clientMessage=liveConnectParametersToVertex(this.apiClient,liveConnectParameters):clientMessage=liveConnectParametersToMldev(this.apiClient,liveConnectParameters),delete clientMessage.config;let session=new Session(conn,this.apiClient);conn.send(JSON.stringify(clientMessage)),await setupCompletePromise,sessionResolved=!0;for(let msg of messageQueue)callbacks.onmessage(msg);return session}isCallableTool(tool){return"callTool"in tool&&typeof tool.callTool=="function"}},defaultLiveSendClientContentParamerters={turnComplete:!0},Session=class{constructor(conn,apiClient){this.conn=conn,this.apiClient=apiClient}tLiveClientContent(apiClient,params){if(params.turns!==null&¶ms.turns!==void 0){let contents=[];try{contents=tContents(params.turns),apiClient.isVertexAI()||(contents=contents.map(item=>contentToMldev$1(item)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`)}return{clientContent:{turns:contents,turnComplete:params.turnComplete}}}return{clientContent:{turnComplete:params.turnComplete}}}tLiveClienttToolResponse(apiClient,params){let functionResponses=[];if(params.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(params.functionResponses)?functionResponses=params.functionResponses:functionResponses=[params.functionResponses],functionResponses.length===0)throw new Error("functionResponses is required.");for(let functionResponse of functionResponses){if(typeof functionResponse!="object"||functionResponse===null||!("name"in functionResponse)||!("response"in functionResponse))throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`);if(!apiClient.isVertexAI()&&!("id"in functionResponse))throw new Error(FUNCTION_RESPONSE_REQUIRES_ID)}return{toolResponse:{functionResponses}}}sendClientContent(params){params=Object.assign(Object.assign({},defaultLiveSendClientContentParamerters),params);let clientMessage=this.tLiveClientContent(this.apiClient,params);this.conn.send(JSON.stringify(clientMessage))}sendRealtimeInput(params){let clientMessage={};this.apiClient.isVertexAI()?clientMessage={realtimeInput:liveSendRealtimeInputParametersToVertex(params)}:clientMessage={realtimeInput:liveSendRealtimeInputParametersToMldev(params)},this.conn.send(JSON.stringify(clientMessage))}sendToolResponse(params){if(params.functionResponses==null)throw new Error("Tool response parameters are required.");let clientMessage=this.tLiveClienttToolResponse(this.apiClient,params);this.conn.send(JSON.stringify(clientMessage))}close(){this.conn.close()}};function headersToMap(headers){let headerMap={};return headers.forEach((value,key)=>{headerMap[key]=value}),headerMap}function mapToHeaders(map){let headers=new Headers;for(let[key,value]of Object.entries(map))headers.append(key,value);return headers}var DEFAULT_MAX_REMOTE_CALLS=10;function shouldDisableAfc(config){var _a2,_b,_c;if(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.disable)return!0;let callableToolsPresent=!1;for(let tool of(_b=config?.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){callableToolsPresent=!0;break}if(!callableToolsPresent)return!0;let maxCalls=(_c=config?.automaticFunctionCalling)===null||_c===void 0?void 0:_c.maximumRemoteCalls;return maxCalls&&(maxCalls<0||!Number.isInteger(maxCalls))||maxCalls==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",maxCalls),!0):!1}function isCallableTool(tool){return"callTool"in tool&&typeof tool.callTool=="function"}function hasCallableTools(params){var _a2,_b,_c;return(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)===null||_b===void 0?void 0:_b.some(tool=>isCallableTool(tool)))!==null&&_c!==void 0?_c:!1}function findAfcIncompatibleToolIndexes(params){var _a2;let afcIncompatibleToolIndexes=[];return!((_a2=params?.config)===null||_a2===void 0)&&_a2.tools&¶ms.config.tools.forEach((tool,index)=>{if(isCallableTool(tool))return;let geminiTool=tool;geminiTool.functionDeclarations&&geminiTool.functionDeclarations.length>0&&afcIncompatibleToolIndexes.push(index)}),afcIncompatibleToolIndexes}function shouldAppendAfcHistory(config){var _a2;return!(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.ignoreCallHistory)}var Models=class _Models extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.embedContent=async params=>{if(!this.apiClient.isVertexAI())return params.model.includes("gemini-embedding-2")&&(params.contents=tContents(params.contents)),await this.embedContentInternal(params);if(params.model.includes("gemini")&¶ms.model!=="gemini-embedding-001"||params.model.includes("maas")){let contents=tContents(params.contents);if(contents.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let paramsPrivate=Object.assign(Object.assign({},params),{content:contents[0],embeddingApiType:EmbeddingApiType.EMBED_CONTENT});return await this.embedContentInternal(paramsPrivate)}else{let paramsPrivate=Object.assign(Object.assign({},params),{embeddingApiType:EmbeddingApiType.PREDICT});return await this.embedContentInternal(paramsPrivate)}},this.generateContent=async params=>{var _a2,_b,_c,_d,_e;let transformedParams=await this.processParamsMaybeAddMcpUsage(params);if(this.maybeMoveToResponseJsonSchema(params),!hasCallableTools(params)||shouldDisableAfc(params.config))return await this.generateContentInternal(transformedParams);let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`)}let response,functionResponseContent,automaticFunctionCallingHistory=tContents(transformedParams.contents),maxRemoteCalls=(_c=(_b=(_a2=transformedParams.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,remoteCalls=0;for(;remoteCalls<maxRemoteCalls&&(response=await this.generateContentInternal(transformedParams),!(!response.functionCalls||response.functionCalls.length===0));){let responseContent=response.candidates[0].content,functionResponseParts=[];for(let tool of(_e=(_d=params.config)===null||_d===void 0?void 0:_d.tools)!==null&&_e!==void 0?_e:[])if(isCallableTool(tool)){let parts=await tool.callTool(response.functionCalls);functionResponseParts.push(...parts)}remoteCalls++,functionResponseContent={role:"user",parts:functionResponseParts},transformedParams.contents=tContents(transformedParams.contents),transformedParams.contents.push(responseContent),transformedParams.contents.push(functionResponseContent),shouldAppendAfcHistory(transformedParams.config)&&(automaticFunctionCallingHistory.push(responseContent),automaticFunctionCallingHistory.push(functionResponseContent))}return shouldAppendAfcHistory(transformedParams.config)&&(response.automaticFunctionCallingHistory=automaticFunctionCallingHistory),response},this.generateContentStream=async params=>{var _a2,_b,_c,_d,_e;if(this.maybeMoveToResponseJsonSchema(params),shouldDisableAfc(params.config)){let transformedParams=await this.processParamsMaybeAddMcpUsage(params);return await this.generateContentStreamInternal(transformedParams)}let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let streamFunctionCall=(_c=(_b=(_a2=params?.config)===null||_a2===void 0?void 0:_a2.toolConfig)===null||_b===void 0?void 0:_b.functionCallingConfig)===null||_c===void 0?void 0:_c.streamFunctionCallArguments,disableAfc=(_e=(_d=params?.config)===null||_d===void 0?void 0:_d.automaticFunctionCalling)===null||_e===void 0?void 0:_e.disable;if(streamFunctionCall&&!disableAfc)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(params)},this.generateImages=async params=>(_Models.loggedGenerateImagesWarning||(_Models.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(params).then(apiResponse=>{var _a2;let positivePromptSafetyAttributes,generatedImages=[];if(apiResponse?.generatedImages)for(let generatedImage of apiResponse.generatedImages)generatedImage&&generatedImage?.safetyAttributes&&((_a2=generatedImage?.safetyAttributes)===null||_a2===void 0?void 0:_a2.contentType)==="Positive Prompt"?positivePromptSafetyAttributes=generatedImage?.safetyAttributes:generatedImages.push(generatedImage);let response;return positivePromptSafetyAttributes?response={generatedImages,positivePromptSafetyAttributes,sdkHttpResponse:apiResponse.sdkHttpResponse}:response={generatedImages,sdkHttpResponse:apiResponse.sdkHttpResponse},response})),this.list=async params=>{var _a2;let actualParams={config:Object.assign(Object.assign({},{queryBase:!0}),params?.config)};if(this.apiClient.isVertexAI()&&!actualParams.config.queryBase){if(!((_a2=actualParams.config)===null||_a2===void 0)&&_a2.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");actualParams.config.filter="labels.tune-type:*"}return new Pager(PagedItem.PAGED_ITEM_MODELS,x=>this.listInternal(x),await this.listInternal(actualParams),actualParams)},this.editImage=async params=>{_Models.loggedEditImageWarning||(_Models.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let paramsInternal={model:params.model,prompt:params.prompt,referenceImages:[],config:params.config};return params.referenceImages&¶ms.referenceImages&&(paramsInternal.referenceImages=params.referenceImages.map(img=>img.toReferenceImageAPI())),await this.editImageInternal(paramsInternal)},this.upscaleImage=async params=>{let apiConfig={numberOfImages:1,mode:"upscale"};params.config&&(apiConfig=Object.assign(Object.assign({},apiConfig),params.config));let apiParams={model:params.model,image:params.image,upscaleFactor:params.upscaleFactor,config:apiConfig};return await this.upscaleImageInternal(apiParams)},this.generateVideos=async params=>{var _a2,_b,_c,_d,_e,_f;if((params.prompt||params.image||params.video)&¶ms.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(params.prompt||params.image||params.video)&&(_Models.loggedGenerateVideosWarning||(_Models.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((_a2=params.video)===null||_a2===void 0)&&_a2.uri&&(!((_b=params.video)===null||_b===void 0)&&_b.videoBytes)?params.video={uri:params.video.uri,mimeType:params.video.mimeType}:!((_d=(_c=params.source)===null||_c===void 0?void 0:_c.video)===null||_d===void 0)&&_d.uri&&(!((_f=(_e=params.source)===null||_e===void 0?void 0:_e.video)===null||_f===void 0)&&_f.videoBytes)&&(params.source.video={uri:params.source.video.uri,mimeType:params.source.video.mimeType})),await this.generateVideosInternal(params)}}maybeMoveToResponseJsonSchema(params){params.config&¶ms.config.responseSchema&&(params.config.responseJsonSchema||Object.keys(params.config.responseSchema).includes("$schema")&&(params.config.responseJsonSchema=params.config.responseSchema,delete params.config.responseSchema))}async processParamsMaybeAddMcpUsage(params){var _a2,_b,_c;let tools=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools;if(!tools)return params;let transformedTools=await Promise.all(tools.map(async tool=>isCallableTool(tool)?await tool.tool():tool)),newParams={model:params.model,contents:params.contents,config:Object.assign(Object.assign({},params.config),{tools:transformedTools})};if(newParams.config.tools=transformedTools,params.config&¶ms.config.tools&&hasMcpToolUsage(params.config.tools)){let headers=(_c=(_b=params.config.httpOptions)===null||_b===void 0?void 0:_b.headers)!==null&&_c!==void 0?_c:{},newHeaders=Object.assign({},headers);Object.keys(newHeaders).length===0&&(newHeaders=this.apiClient.getDefaultHeaders()),setMcpUsageHeader(newHeaders),newParams.config.httpOptions=Object.assign(Object.assign({},params.config.httpOptions),{headers:newHeaders})}return newParams}async initAfcToolsMap(params){var _a2,_b,_c;let afcTools=new Map;for(let tool of(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){let callableTool=tool,toolDeclaration=await callableTool.tool();for(let declaration of(_c=toolDeclaration.functionDeclarations)!==null&&_c!==void 0?_c:[]){if(!declaration.name)throw new Error("Function declaration name is required.");if(afcTools.has(declaration.name))throw new Error(`Duplicate tool declaration name: ${declaration.name}`);afcTools.set(declaration.name,callableTool)}}return afcTools}async processAfcStream(params){var _a2,_b,_c;let maxRemoteCalls=(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,wereFunctionsCalled=!1,remoteCallCount=0,afcToolsMap=await this.initAfcToolsMap(params);return(function(models,afcTools,params2){return __asyncGenerator(this,arguments,function*(){for(var _a3,e_1,_b2,_c2,_d,_e;remoteCallCount<maxRemoteCalls;){wereFunctionsCalled&&(remoteCallCount++,wereFunctionsCalled=!1);let transformedParams=yield __await(models.processParamsMaybeAddMcpUsage(params2)),response=yield __await(models.generateContentStreamInternal(transformedParams)),functionResponses=[],responseContents=[];try{for(var _f=!0,response_1=(e_1=void 0,__asyncValues(response)),response_1_1;response_1_1=yield __await(response_1.next()),_a3=response_1_1.done,!_a3;_f=!0){_c2=response_1_1.value,_f=!1;let chunk=_c2;if(yield yield __await(chunk),chunk.candidates&&(!((_d=chunk.candidates[0])===null||_d===void 0)&&_d.content)){responseContents.push(chunk.candidates[0].content);for(let part of(_e=chunk.candidates[0].content.parts)!==null&&_e!==void 0?_e:[])if(remoteCallCount<maxRemoteCalls&&part.functionCall){if(!part.functionCall.name)throw new Error("Function call name was not returned by the model.");if(afcTools.has(part.functionCall.name)){let responseParts=yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall]));functionResponses.push(...responseParts)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, missing tool: ${part.functionCall.name}`)}}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_f&&!_a3&&(_b2=response_1.return)&&(yield __await(_b2.call(response_1)))}finally{if(e_1)throw e_1.error}}if(functionResponses.length>0){wereFunctionsCalled=!0;let typedResponseChunk=new GenerateContentResponse;typedResponseChunk.candidates=[{content:{role:"user",parts:functionResponses}}],yield yield __await(typedResponseChunk);let newContents=[];newContents.push(...responseContents),newContents.push({role:"user",parts:functionResponses});let updatedContents=tContents(params2.contents).concat(newContents);params2.contents=updatedContents}else break}})})(this,afcToolsMap,params)}async generateContentInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateContentResponseFromVertex(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateContentResponseFromMldev(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateContentStreamInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}),response.then(function(apiResponse){return __asyncGenerator(this,arguments,function*(){var _a3,e_2,_b2,_c2;try{for(var _d2=!0,apiResponse_1=__asyncValues(apiResponse),apiResponse_1_1;apiResponse_1_1=yield __await(apiResponse_1.next()),_a3=apiResponse_1_1.done,!_a3;_d2=!0){_c2=apiResponse_1_1.value,_d2=!1;let chunk=_c2,resp=generateContentResponseFromVertex(yield __await(chunk.json()),params);resp.sdkHttpResponse={headers:chunk.headers};let typedResp=new GenerateContentResponse;Object.assign(typedResp,resp),yield yield __await(typedResp)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{!_d2&&!_a3&&(_b2=apiResponse_1.return)&&(yield __await(_b2.call(apiResponse_1)))}finally{if(e_2)throw e_2.error}}})})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}),response.then(function(apiResponse){return __asyncGenerator(this,arguments,function*(){var _a3,e_3,_b2,_c2;try{for(var _d2=!0,apiResponse_2=__asyncValues(apiResponse),apiResponse_2_1;apiResponse_2_1=yield __await(apiResponse_2.next()),_a3=apiResponse_2_1.done,!_a3;_d2=!0){_c2=apiResponse_2_1.value,_d2=!1;let chunk=_c2,resp=generateContentResponseFromMldev(yield __await(chunk.json()),params);resp.sdkHttpResponse={headers:chunk.headers};let typedResp=new GenerateContentResponse;Object.assign(typedResp,resp),yield yield __await(typedResp)}}catch(e_3_1){e_3={error:e_3_1}}finally{try{!_d2&&!_a3&&(_b2=apiResponse_2.return)&&(yield __await(_b2.call(apiResponse_2)))}finally{if(e_3)throw e_3.error}}})})}}async embedContentInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=embedContentParametersPrivateToVertex(this.apiClient,params,params),endpointUrl=tIsVertexEmbedContentModel(params.model)?"{model}:embedContent":"{model}:predict";return path2=formatMap(endpointUrl,body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=embedContentResponseFromVertex(apiResponse,params),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=embedContentParametersPrivateToMldev(this.apiClient,params);return path2=formatMap("{model}:batchEmbedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=embedContentResponseFromMldev(apiResponse),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateImagesInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateImagesParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateImagesResponseFromVertex(apiResponse),typedResp=new GenerateImagesResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=editImageParametersInternalToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=editImageResponseFromVertex(apiResponse),typedResp=new EditImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=upscaleImageAPIParametersInternalToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=upscaleImageResponseFromVertex(apiResponse),typedResp=new UpscaleImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=recontextImageParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=recontextImageResponseFromVertex(apiResponse),typedResp=new RecontextImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=segmentImageParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=segmentImageResponseFromVertex(apiResponse),typedResp=new SegmentImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getModelParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromVertex(apiResponse))}else{let body=getModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromMldev(apiResponse))}}async listInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listModelsParametersToVertex(this.apiClient,params);return path2=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listModelsResponseFromVertex(apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listModelsParametersToMldev(this.apiClient,params);return path2=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listModelsResponseFromMldev(apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateModelParametersToVertex(this.apiClient,params);return path2=formatMap("{model}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromVertex(apiResponse))}else{let body=updateModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromMldev(apiResponse))}}async delete(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteModelParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteModelResponseFromVertex(apiResponse),typedResp=new DeleteModelResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=deleteModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteModelResponseFromMldev(apiResponse),typedResp=new DeleteModelResponse;return Object.assign(typedResp,resp),typedResp})}}async countTokens(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=countTokensParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=countTokensResponseFromVertex(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=countTokensParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=countTokensResponseFromMldev(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}}async computeTokens(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=computeTokensParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:computeTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=computeTokensResponseFromVertex(apiResponse),typedResp=new ComputeTokensResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateVideosParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=generateVideosOperationFromVertex(apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}else{let body=generateVideosParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=generateVideosOperationFromMldev(apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}}};Models.loggedGenerateImagesWarning=!1;Models.loggedEditImageWarning=!1;Models.loggedGenerateVideosWarning=!1;var Operations=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient}async getVideosOperation(parameters){let operation=parameters.operation,config=parameters.config;if(operation.name===void 0||operation.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let resourceName2=operation.name.split("/operations/")[0],httpOptions;config&&"httpOptions"in config&&(httpOptions=config.httpOptions);let rawOperation=await this.fetchPredictVideosOperationInternal({operationName:operation.name,resourceName:resourceName2,config:{httpOptions}});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!0})}else{let rawOperation=await this.getVideosOperationInternal({operationName:operation.name,config});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!1})}}async get(parameters){let operation=parameters.operation,config=parameters.config;if(operation.name===void 0||operation.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let resourceName2=operation.name.split("/operations/")[0],httpOptions;config&&"httpOptions"in config&&(httpOptions=config.httpOptions);let rawOperation=await this.fetchPredictVideosOperationInternal({operationName:operation.name,resourceName:resourceName2,config:{httpOptions}});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!0})}else{let rawOperation=await this.getVideosOperationInternal({operationName:operation.name,config});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!1})}}async getVideosOperationInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getOperationParametersToVertex(params);return path2=formatMap("{operationName}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response}else{let body=getOperationParametersToMldev(params);return path2=formatMap("{operationName}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response}}async fetchPredictVideosOperationInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=fetchPredictOperationParametersToVertex(params);return path2=formatMap("{resourceName}:fetchPredictOperation",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function authConfigToMldev(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev(fromObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function contentToMldev(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createAuthTokenConfigToMldev(apiClient,fromObject,parentObject){let toObject={},fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromNewSessionExpireTime=getValueByPath(fromObject,["newSessionExpireTime"]);parentObject!==void 0&&fromNewSessionExpireTime!=null&&setValueByPath(parentObject,["newSessionExpireTime"],fromNewSessionExpireTime);let fromUses=getValueByPath(fromObject,["uses"]);parentObject!==void 0&&fromUses!=null&&setValueByPath(parentObject,["uses"],fromUses);let fromLiveConnectConstraints=getValueByPath(fromObject,["liveConnectConstraints"]);parentObject!==void 0&&fromLiveConnectConstraints!=null&&setValueByPath(parentObject,["bidiGenerateContentSetup"],liveConnectConstraintsToMldev(apiClient,fromLiveConnectConstraints));let fromLockAdditionalFields=getValueByPath(fromObject,["lockAdditionalFields"]);return parentObject!==void 0&&fromLockAdditionalFields!=null&&setValueByPath(parentObject,["fieldMask"],fromLockAdditionalFields),toObject}function createAuthTokenParametersToMldev(apiClient,fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],createAuthTokenConfigToMldev(apiClient,fromConfig,toObject)),toObject}function fileDataToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleMapsToMldev(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function liveConnectConfigToMldev(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],fromGenerationConfig);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],tLiveSpeechConfig(fromSpeechConfig));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToMldev(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],sessionResumptionConfigToMldev(fromSessionResumption));let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);if(parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity),getValueByPath(fromObject,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev(item))),setValueByPath(parentObject,["setup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectConstraintsToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],liveConnectConfigToMldev(fromConfig,toObject)),toObject}function partToMldev(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function safetySettingToMldev(fromObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function sessionResumptionConfigToMldev(fromObject){let toObject={},fromHandle=getValueByPath(fromObject,["handle"]);if(fromHandle!=null&&setValueByPath(toObject,["handle"],fromHandle),getValueByPath(fromObject,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function toolToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function getFieldMasks(setup){let fields=[];for(let key in setup)if(Object.prototype.hasOwnProperty.call(setup,key)){let value=setup[key];if(typeof value=="object"&&value!=null&&Object.keys(value).length>0){let field=Object.keys(value).map(kk=>`${key}.${kk}`);fields.push(...field)}else fields.push(key)}return fields.join(",")}function convertBidiSetupToTokenSetup(requestDict,config){let setupForMaskGeneration=null,bidiGenerateContentSetupValue=requestDict.bidiGenerateContentSetup;if(typeof bidiGenerateContentSetupValue=="object"&&bidiGenerateContentSetupValue!==null&&"setup"in bidiGenerateContentSetupValue){let innerSetup=bidiGenerateContentSetupValue.setup;typeof innerSetup=="object"&&innerSetup!==null?(requestDict.bidiGenerateContentSetup=innerSetup,setupForMaskGeneration=innerSetup):delete requestDict.bidiGenerateContentSetup}else bidiGenerateContentSetupValue!==void 0&&delete requestDict.bidiGenerateContentSetup;let preExistingFieldMask=requestDict.fieldMask;if(setupForMaskGeneration){let generatedMaskFromBidi=getFieldMasks(setupForMaskGeneration);if(Array.isArray(config?.lockAdditionalFields)&&config?.lockAdditionalFields.length===0)generatedMaskFromBidi?requestDict.fieldMask=generatedMaskFromBidi:delete requestDict.fieldMask;else if(config?.lockAdditionalFields&&config.lockAdditionalFields.length>0&&preExistingFieldMask!==null&&Array.isArray(preExistingFieldMask)&&preExistingFieldMask.length>0){let generationConfigFields=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],mappedFieldsFromPreExisting=[];preExistingFieldMask.length>0&&(mappedFieldsFromPreExisting=preExistingFieldMask.map(field=>generationConfigFields.includes(field)?`generationConfig.${field}`:field));let finalMaskParts=[];generatedMaskFromBidi&&finalMaskParts.push(generatedMaskFromBidi),mappedFieldsFromPreExisting.length>0&&finalMaskParts.push(...mappedFieldsFromPreExisting),finalMaskParts.length>0?requestDict.fieldMask=finalMaskParts.join(","):delete requestDict.fieldMask}else delete requestDict.fieldMask}else preExistingFieldMask!==null&&Array.isArray(preExistingFieldMask)&&preExistingFieldMask.length>0?requestDict.fieldMask=preExistingFieldMask.join(","):delete requestDict.fieldMask;return requestDict}var Tokens=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient}async create(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let body=createAuthTokenParametersToMldev(this.apiClient,params);path2=formatMap("auth_tokens",body._url),queryParams=body._query,delete body.config,delete body._url,delete body._query;let transformedBody=convertBidiSetupToTokenSetup(body,params.config);return response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(transformedBody),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}};function deleteDocumentConfigToMldev(fromObject,parentObject){let toObject={},fromForce=getValueByPath(fromObject,["force"]);return parentObject!==void 0&&fromForce!=null&&setValueByPath(parentObject,["_query","force"],fromForce),toObject}function deleteDocumentParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],fromName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&deleteDocumentConfigToMldev(fromConfig,toObject),toObject}function getDocumentParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function listDocumentsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listDocumentsParametersToMldev(fromObject){let toObject={},fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["_url","parent"],fromParent);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listDocumentsConfigToMldev(fromConfig,toObject),toObject}function listDocumentsResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromDocuments=getValueByPath(fromObject,["documents"]);if(fromDocuments!=null){let transformedList=fromDocuments;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["documents"],transformedList)}return toObject}var Documents=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async params=>new Pager(PagedItem.PAGED_ITEM_DOCUMENTS,x=>this.listInternal({parent:params.parent,config:x.config}),await this.listInternal(params),params)}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getDocumentParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteDocumentParametersToMldev(params);path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listDocumentsParametersToMldev(params);return path2=formatMap("{parent}/documents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=listDocumentsResponseFromMldev(apiResponse),typedResp=new ListDocumentsResponse;return Object.assign(typedResp,resp),typedResp})}}};var FileSearchStores=class extends BaseModule{constructor(apiClient,documents=new Documents(apiClient)){super(),this.apiClient=apiClient,this.documents=documents,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_FILE_SEARCH_STORES,x=>this.listInternal(x),await this.listInternal(params),params)}async uploadToFileSearchStore(params){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(params.fileSearchStoreName,params.file,params.config)}async downloadMedia(uri,config){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");let parsedUri=new URL(uri,"http://dummy.com"),pathname=parsedUri.pathname;if(pathname.startsWith("/")&&(pathname=pathname.slice(1)),!pathname.includes("/media/"))throw new Error(`Invalid uri format: ${uri}. Expected to contain /media/`);let queryParams={};parsedUri.searchParams.forEach((value,key)=>{queryParams[key]=value}),queryParams.alt="media";let httpOptions=Object.assign({},config?.httpOptions),response=await this.apiClient.request({path:pathname,httpMethod:"GET",queryParams,httpOptions});if(response instanceof HttpResponse){let arrayBuffer=await response.responseInternal.arrayBuffer();return new Uint8Array(arrayBuffer)}else throw new Error("Unexpected response type from downloadMedia")}async create(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createFileSearchStoreParametersToMldev(this.apiClient,params);return path2=formatMap("fileSearchStores",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getFileSearchStoreParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteFileSearchStoreParametersToMldev(params);path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listFileSearchStoresParametersToMldev(params);return path2=formatMap("fileSearchStores",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=listFileSearchStoresResponseFromMldev(apiResponse),typedResp=new ListFileSearchStoresResponse;return Object.assign(typedResp,resp),typedResp})}}async uploadToFileSearchStoreInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=uploadToFileSearchStoreParametersToMldev(params);return path2=formatMap("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=uploadToFileSearchStoreResumableResponseFromMldev(apiResponse),typedResp=new UploadToFileSearchStoreResumableResponse;return Object.assign(typedResp,resp),typedResp})}}async importFile(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=importFileParametersToMldev(params);return path2=formatMap("{file_search_store_name}:importFile",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=importFileOperationFromMldev(apiResponse),typedResp=new ImportFileOperation;return Object.assign(typedResp,resp),typedResp})}}};function isDeno(){return"Deno"in globalThis}var envMemo;function env(){var _a2,_b,_c,_d,_e,_f;if(envMemo)return envMemo;let globals=globalThis,envObject={};return isDeno()?envObject=(_d=(_c=(_b=(_a2=globals.Deno)===null||_a2===void 0?void 0:_a2.env)===null||_b===void 0?void 0:_b.toObject)===null||_c===void 0?void 0:_c.call(_b))!==null&&_d!==void 0?_d:{}:envObject=(_f=(_e=globals.process)===null||_e===void 0?void 0:_e.env)!==null&&_f!==void 0?_f:{},envMemo=envObject,envMemo}function fillGlobals(options){var _a2,_b;let clone=Object.assign({},options),envVars=env();return typeof envVars.GOOGLE_GENAI_API_VERSION<"u"&&((_a2=clone.api_version)!==null&&_a2!==void 0||(clone.api_version=envVars.GOOGLE_GENAI_API_VERSION)),typeof envVars.GOOGLE_GENAI_USER_PROJECT<"u"&&((_b=clone.user_project)!==null&&_b!==void 0||(clone.user_project=envVars.GOOGLE_GENAI_USER_PROJECT)),clone}var GoogleGenAISecurityProvider=class{constructor(options){this.options=options}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(url){return securityFromHeaders(await this.options.getAuthHeaders(url))}},GoogleGenAIAuthHook=class{beforeCreateRequest(_hookCtx,input){return Object.assign(Object.assign({},input),{url:decodeSDKLevelAPIVersionPath(input.url)})}async beforeRequest(hookCtx,request){if(applyDefaultHeaders(request.headers,getStaticDefaultHeaders(hookCtx.security_source)),applyUserProject(hookCtx,request.headers),hasAuthHeaders(request.headers))return request;let security=await resolveSecurity$1(hookCtx.security_source,request.url);return applyDefaultHeaders(request.headers,security?.default_headers),applyAuth(request.headers,security),request}};function decodeSDKLevelAPIVersionPath(url){let[,apiVersion,...rest]=url.pathname.split("/");if(!apiVersion)return url;let decodedAPIVersion=decodeURIComponent(apiVersion);if(!decodedAPIVersion.includes("/"))return url;let nextURL=new URL(url);return nextURL.pathname=`/${decodedAPIVersion}/${rest.join("/")}`,nextURL}async function resolveSecurity$1(securitySource,requestURL){if(isSecurityResolver(securitySource))return securitySource.resolveGoogleGenAISecurity(requestURL);let security=typeof securitySource=="function"?await securitySource():securitySource;return isSecurity(security)?withEnvSecurity(security):withEnvSecurity(void 0)}function getStaticDefaultHeaders(securitySource){var _a2,_b;if(isSecurityResolver(securitySource))return(_b=(_a2=securitySource.getDefaultHeaders)===null||_a2===void 0?void 0:_a2.call(securitySource))!==null&&_b!==void 0?_b:securitySource.defaultHeaders;if(isSecurity(securitySource))return securitySource.default_headers}function withEnvSecurity(security){var _a2,_b;let envVars=env(),nextSecurity=Object.assign(Object.assign({},security),{api_key:(_a2=security?.api_key)!==null&&_a2!==void 0?_a2:envVars.GOOGLE_GENAI_API_KEY,access_token:(_b=security?.access_token)!==null&&_b!==void 0?_b:envVars.GOOGLE_GENAI_ACCESS_TOKEN});return hasSecurityValue(nextSecurity)?nextSecurity:void 0}function securityFromHeaders(headers){var _a2,_b;let defaultHeaders={};for(let[key,value]of headers){let lowerKey=key.toLowerCase();lowerKey!=="authorization"&&lowerKey!=="x-goog-api-key"&&(defaultHeaders[key]=value)}let security={access_token:(_a2=headers.get("authorization"))!==null&&_a2!==void 0?_a2:void 0,api_key:(_b=headers.get("x-goog-api-key"))!==null&&_b!==void 0?_b:void 0,default_headers:Object.keys(defaultHeaders).length?defaultHeaders:void 0};return hasSecurityValue(security)?security:void 0}function applyDefaultHeaders(target,source){if(source)for(let[key,value]of new Headers(source))target.get(key)===null&&target.set(key,value)}function applyUserProject(hookCtx,headers){hookCtx.options.user_project!==void 0&&headers.get("x-goog-user-project")===null&&headers.set("x-goog-user-project",hookCtx.options.user_project)}function applyAuth(headers,security){if(security){if(security.api_key){headers.set("x-goog-api-key",security.api_key);return}security.access_token&&headers.set("Authorization",bearer(security.access_token))}}function hasAuthHeaders(headers){return headers.get("authorization")!==null||headers.get("x-goog-api-key")!==null}function bearer(token){return token.slice(0,7).toLowerCase()==="bearer "?token:`Bearer ${token}`}function isSecurity(value){return typeof value=="object"&&value!==null}function isSecurityResolver(value){return typeof value=="object"&&value!==null&&"resolveGoogleGenAISecurity"in value&&typeof value.resolveGoogleGenAISecurity=="function"}function hasSecurityValue(security){return security.api_key!==void 0||security.access_token!==void 0||security.default_headers!==void 0}var HTTPClientError=class extends Error{constructor(message,opts){let msg=message;opts?.cause&&(msg+=`: ${opts.cause}`),super(msg,opts),this.name="HTTPClientError",typeof this.cause>"u"&&(this.cause=opts?.cause)}},UnexpectedClientError=class extends HTTPClientError{constructor(){super(...arguments),this.name="UnexpectedClientError"}},InvalidRequestError=class extends HTTPClientError{constructor(){super(...arguments),this.name="InvalidRequestError"}},RequestAbortedError=class extends HTTPClientError{constructor(){super(...arguments),this.name="RequestAbortedError"}},RequestTimeoutError=class extends HTTPClientError{constructor(){super(...arguments),this.name="RequestTimeoutError"}},ConnectionError=class extends HTTPClientError{constructor(){super(...arguments),this.name="ConnectionError"}};var GoogleGenAiError=class extends Error{constructor(message,httpMeta){var _a2,_b,_c,_d;super(message),this.statusCode=(_a2=httpMeta?.response)===null||_a2===void 0?void 0:_a2.status,this.body=(_b=httpMeta?.body)!==null&&_b!==void 0?_b:"",this.headers=(_c=httpMeta?.response)===null||_c===void 0?void 0:_c.headers,this.contentType=((_d=httpMeta?.response)===null||_d===void 0?void 0:_d.headers.get("content-type"))||"",this.rawResponse=httpMeta?.response,this.name="GoogleGenAiError"}};var GeminiNextGenAPIClientError=class extends Error{},APIError=class _APIError extends GeminiNextGenAPIClientError{constructor(status,error,message,headers){super(_APIError.makeMessage(status,error,message)),this.status=status,this.headers=headers,this.error=error,this.statusCode=status,this.body=stringifyErrorBody(error),this.contentType=headers?.get("content-type")||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(status,error,message){var _a2;let errorMessage=error&&isPlainObject$2(error)&&typeof error.message=="string"?error.message:void 0,errorBody=stringifyErrorBody(error),msg=(_a2=errorMessage??message)!==null&&_a2!==void 0?_a2:errorBody||"An error occurred";return`${status?`${status} `:""}${msg}`}static generate(status,errorResponse,message,headers){return!status||!headers?new APIConnectionError({message,cause:errorResponse instanceof Error?errorResponse:void 0}):status===400?new BadRequestError(status,errorResponse,message,headers):status===401?new AuthenticationError(status,errorResponse,message,headers):status===403?new PermissionDeniedError(status,errorResponse,message,headers):status===404?new NotFoundError(status,errorResponse,message,headers):status===409?new ConflictError(status,errorResponse,message,headers):status===422?new UnprocessableEntityError(status,errorResponse,message,headers):status===429?new RateLimitError(status,errorResponse,message,headers):status>=500?new InternalServerError(status,errorResponse,message,headers):new _APIError(status,errorResponse,message,headers)}},APIUserAbortError=class extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}},APIConnectionError=class extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0),this.cause=cause}},APIConnectionTimeoutError=class extends APIConnectionError{constructor({message}={}){super({message:message||"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."})}},BadRequestError=class extends APIError{},AuthenticationError=class extends APIError{},PermissionDeniedError=class extends APIError{},NotFoundError=class extends APIError{},ConflictError=class extends APIError{},UnprocessableEntityError=class extends APIError{},RateLimitError=class extends APIError{},InternalServerError=class extends APIError{};function wrapSDKError(error){return isCompatAPIErrorInstance(error)?error:error instanceof GoogleGenAiError?wrapAPIError(error):error instanceof HTTPClientError?wrapHTTPClientError(error):error}function wrapAPIError(error){let errorPayload=getErrorPayload(error),wrapped=APIError.generate(error.statusCode,errorPayload,error.message,error.headers);return defineReadonly(wrapped,"body",error.body),defineReadonly(wrapped,"contentType",error.contentType),defineReadonly(wrapped,"rawResponse",error.rawResponse),defineReadonly(wrapped,"statusCode",error.statusCode),defineReadonly(wrapped,"cause",error),wrapped}function wrapHTTPClientError(error){return error instanceof RequestTimeoutError?new APIConnectionTimeoutError({message:error.message}):error instanceof RequestAbortedError?new APIUserAbortError({message:error.message}):error instanceof ConnectionError?new APIConnectionError({message:error.message,cause:error}):new APIConnectionError({message:error.message,cause:error})}function getErrorPayload(error){let data=getObjectProperty(error,"data$");if(data&&typeof data=="object")return data;try{let parsed=JSON.parse(error.body);if(parsed&&typeof parsed=="object")return parsed}catch{}let dataError=getObjectProperty(error,"error");return dataError&&typeof dataError=="object"?dataError:void 0}function getObjectProperty(value,key){return value&&typeof value=="object"?value[key]:void 0}function stringifyErrorBody(error){if(!error)return"";try{return JSON.stringify(error)}catch{return String(error)}}function isPlainObject$2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isCompatAPIErrorInstance(value){return typeof value=="object"&&value!==null?APIError.prototype.isPrototypeOf(value):!1}function defineReadonly(target,key,value){Object.defineProperty(target,key,{configurable:!0,enumerable:!0,value,writable:!1})}var DEFAULT_FETCHER=(input,init)=>init==null?fetch(input):fetch(input,init),HTTPClient=class _HTTPClient{constructor(options={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=options,this.fetcher=options.fetcher||DEFAULT_FETCHER}async request(request){let req=request;for(let hook of this.requestHooks){let nextRequest=await hook(req);nextRequest&&(req=nextRequest)}try{let res=await this.fetcher(req);for(let hook of this.responseHooks)await hook(res,req);return res}catch(err){for(let hook of this.requestErrorHooks)await hook(err,req);throw err}}addHook(...args){if(args[0]==="beforeRequest")this.requestHooks.push(args[1]);else if(args[0]==="requestError")this.requestErrorHooks.push(args[1]);else if(args[0]==="response")this.responseHooks.push(args[1]);else throw new Error(`Invalid hook type: ${args[0]}`);return this}removeHook(...args){let target;if(args[0]==="beforeRequest")target=this.requestHooks;else if(args[0]==="requestError")target=this.requestErrorHooks;else if(args[0]==="response")target=this.responseHooks;else throw new Error(`Invalid hook type: ${args[0]}`);let index=target.findIndex(v=>v===args[1]);return index>=0&&target.splice(index,1),this}clone(){let child=new _HTTPClient(this.options);return child.requestHooks=this.requestHooks.slice(),child.requestErrorHooks=this.requestErrorHooks.slice(),child.responseHooks=this.responseHooks.slice(),child}},mediaParamSeparator=/\s*;\s*/g;function matchContentType(response,pattern){var _a2;if(pattern==="*")return!0;let contentType=((_a2=response.headers.get("content-type"))===null||_a2===void 0?void 0:_a2.trim())||"application/octet-stream";contentType=contentType.toLowerCase();let wantParts=pattern.toLowerCase().trim().split(mediaParamSeparator),[wantType="",...wantParams]=wantParts;if(wantType.split("/").length!==2)return!1;let gotParts=contentType.split(mediaParamSeparator),[gotType="",...gotParams]=gotParts,[type="",subtype=""]=gotType.split("/");if(!type||!subtype||wantType!=="*/*"&&gotType!==wantType&&`${type}/*`!==wantType&&`*/${subtype}`!==wantType||gotParams.length<wantParams.length)return!1;let params=new Set(gotParams);for(let wantParam of wantParams)if(!params.has(wantParam))return!1;return!0}var codeRangeRE$1=new RegExp("^[0-9]xx$","i");function matchStatusCode(response,codes){let actual=`${response.status}`,expectedCodes=Array.isArray(codes)?codes:[codes];return expectedCodes.length?expectedCodes.some(ec=>{let code=`${ec}`;if(code==="default")return!0;if(!codeRangeRE$1.test(`${code}`))return code===actual;let expectFamily=code.charAt(0);if(!expectFamily)throw new Error("Invalid status code range");let actualFamily=actual.charAt(0);if(!actualFamily)throw new Error(`Invalid response status code: ${actual}`);return actualFamily===expectFamily}):!1}function matchResponse(response,code,contentTypePattern){return matchStatusCode(response,code)&&matchContentType(response,contentTypePattern)}function isConnectionError(err){if(typeof err!="object"||err==null)return!1;let isBrowserErr=err instanceof TypeError&&err.message.toLowerCase().startsWith("failed to fetch"),isNodeErr=err instanceof TypeError&&err.message.toLowerCase().startsWith("fetch failed"),isBunErr="name"in err&&err.name==="ConnectionError",isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnreset";return isBrowserErr||isNodeErr||isGenericErr||isBunErr}function isTimeoutError(err){if(typeof err!="object"||err==null)return!1;let isNative="name"in err&&err.name==="TimeoutError",isLegacyNative="code"in err&&err.code===23,isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnaborted";return isNative||isLegacyNative||isGenericErr}function isAbortError(err){if(typeof err!="object"||err==null)return!1;let isNative="name"in err&&err.name==="AbortError",isLegacyNative="code"in err&&err.code===20,isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnaborted";return isNative||isLegacyNative||isGenericErr}function initHooks(hooks){let googleGenAIAuthHook=new GoogleGenAIAuthHook;hooks.registerBeforeCreateRequestHook(googleGenAIAuthHook),hooks.registerBeforeRequestHook(googleGenAIAuthHook)}var SDKHooks=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let presetHooks=[];for(let hook of presetHooks)"sdkInit"in hook&&this.registerSDKInitHook(hook),"beforeCreateRequest"in hook&&this.registerBeforeCreateRequestHook(hook),"beforeRequest"in hook&&this.registerBeforeRequestHook(hook),"afterSuccess"in hook&&this.registerAfterSuccessHook(hook),"afterError"in hook&&this.registerAfterErrorHook(hook);initHooks(this)}registerSDKInitHook(hook){this.sdkInitHooks.push(hook)}registerBeforeCreateRequestHook(hook){this.beforeCreateRequestHooks.push(hook)}registerBeforeRequestHook(hook){this.beforeRequestHooks.push(hook)}registerAfterSuccessHook(hook){this.afterSuccessHooks.push(hook)}registerAfterErrorHook(hook){this.afterErrorHooks.push(hook)}sdkInit(opts){return this.sdkInitHooks.reduce((opts2,hook)=>hook.sdkInit(opts2),opts)}beforeCreateRequest(hookCtx,input){let inp=input;for(let hook of this.beforeCreateRequestHooks)inp=hook.beforeCreateRequest(hookCtx,inp);return inp}async beforeRequest(hookCtx,request){let req=request;for(let hook of this.beforeRequestHooks)req=await hook.beforeRequest(hookCtx,req);return req}async afterSuccess(hookCtx,response){let res=response;for(let hook of this.afterSuccessHooks)res=await hook.afterSuccess(hookCtx,res);return res}async afterError(hookCtx,response,error){let res=response,err=error;for(let hook of this.afterErrorHooks){let result=await hook.afterError(hookCtx,res,err);res=result.response,err=result.error}return{response:res,error:err}}};function OK(value){return{ok:!0,value}}function ERR(error){return{ok:!1,error}}function bytesToBase64(u8arr){return btoa(String.fromCodePoint(...u8arr))}function stringToBytes(str){return new TextEncoder().encode(str)}function stringToBase64(str){return bytesToBase64(stringToBytes(str))}var hasOwn=Object.prototype.hasOwnProperty;function pathToFunc(pathPattern,options){let paramRE=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(params={}){return pathPattern.replace(paramRE,function(_,placeholder){if(!hasOwn.call(params,placeholder))throw new Error(`Parameter '${placeholder}' is required`);let value=params[placeholder];if(typeof value!="string"&&typeof value!="number")throw new Error(`Parameter '${placeholder}' must be a string or number`);return`${value}`}).replace(/^\/+/,"")}}var ServerList=["https://generativelanguage.googleapis.com"];function serverURLFromOptions(options){var _a2;let serverURL=options.server_url,params={};if(!serverURL){let serverIdx=(_a2=options.server_idx)!==null&&_a2!==void 0?_a2:0;if(serverIdx<0||serverIdx>=ServerList.length)throw new Error(`Invalid server index ${serverIdx}`);serverURL=ServerList[serverIdx]||""}let u=pathToFunc(serverURL)(params);return new URL(u)}var SDK_METADATA={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};function combineSignals(...signals){let filtered=[];for(let signal of signals)signal&&filtered.push(signal);switch(filtered.length){case 0:case 1:return filtered[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(filtered):abortSignalAny(filtered)}}function abortSignalAny(signals){let controller=new AbortController,result=controller.signal;if(!signals.length)return controller.signal;if(signals.length===1)return signals[0]||controller.signal;for(let signal of signals)if(signal.aborted)return signal;function abort(){controller.abort(this.reason),clean()}let signalRefs=[];function clean(){for(let signalRef of signalRefs){let signal=signalRef.deref();signal&&signal.removeEventListener("abort",abort)}}for(let signal of signals)signalRefs.push(new WeakRef(signal)),signal.addEventListener("abort",abort);return result}function compactMap(values){let out={};for(let[k,v]of Object.entries(values))typeof v<"u"&&(out[k]=v);return out}function isPlainObject$1(value){if(value===null||typeof value!="object"||Object.prototype.toString.call(value)!=="[object Object]")return!1;let proto=Object.getPrototypeOf(value);if(proto===null||proto===Object.prototype)return!0;try{return Object.getPrototypeOf(proto)===null}catch{return!1}}var reservedEscapes=/%(2[346bcf]|3[abdf]|40|5[bd])/gi;function encodeKeyChars(v,charEncoding){return encodeChars(v,charEncoding==="percentExceptReserved"?"percent":charEncoding)}function encodeChars(v,charEncoding){switch(charEncoding){case"percent":return encodeURIComponent(v);case"percentExceptReserved":return encodeURIComponent(v).replace(reservedEscapes,m=>decodeURIComponent(m));default:return v}}function formEncoder(sep){return(key,value,options)=>{let out="",pairs=options?.explode?explode(key,value):[[key,value]];if(pairs.every(([_,v])=>v==null))return;let encodeString=v=>encodeChars(v,options?.charEncoding),encodeValue=v=>encodeString(serializeValue(v)),encodedSep=encodeString(sep);return pairs.forEach(([pk,pv])=>{var _a2,_b;let tmp="",encValue=null;pv!=null&&(Array.isArray(pv)?encValue=(_a2=mapDefined(pv,v=>`${encodeValue(v)}`))===null||_a2===void 0?void 0:_a2.join(encodedSep):isPlainObject$1(pv)?encValue=(_b=mapDefinedEntries(Object.entries(pv),([k,v])=>`${encodeString(k)}${encodedSep}${encodeValue(v)}`))===null||_b===void 0?void 0:_b.join(encodedSep):encValue=`${encodeValue(pv)}`,encValue!=null&&(tmp=`${encodeKeyChars(pk,options?.charEncoding)}=${encValue}`,!(!tmp||tmp==="=")&&(out+=`&${tmp}`)))}),out.slice(1)}}var encodeForm=formEncoder(",");function encodeJSON(key,value,options){if(typeof value>"u")return;let encVal=(v=>encodeChars(v,options?.charEncoding))(JSON.stringify(value,jsonReplacer));return options?.explode?encVal:`${encodeKeyChars(key,options?.charEncoding)}=${encVal}`}var encodeSimple=(key,value,options)=>{let out="",pairs=options?.explode?explode(key,value):[[key,value]];if(pairs.every(([_,v])=>v==null))return;let encodeString=v=>encodeChars(v,options?.charEncoding),encodeValue=v=>encodeString(serializeValue(v));return pairs.forEach(([pk,pv])=>{var _a2;let tmp="";if(pv!=null){if(Array.isArray(pv))tmp=(_a2=mapDefined(pv,v=>`${encodeValue(v)}`))===null||_a2===void 0?void 0:_a2.join(",");else if(isPlainObject$1(pv)){let mapped=mapDefinedEntries(Object.entries(pv),([k,v])=>`,${encodeString(k)},${encodeValue(v)}`);tmp=mapped?.join("").slice(1)}else tmp=`${options?.explode&&isPlainObject$1(value)?`${pk}=`:""}${encodeValue(pv)}`;out+=tmp?`,${tmp}`:""}}),out.slice(1)};function explode(key,value){return Array.isArray(value)?value.map(v=>[key,v]):isPlainObject$1(value)?Object.entries(value??{}).map(([k,v])=>[k,v]):[[key,value]]}function serializeValue(value){return value==null?"":value instanceof Date?value.toISOString():value instanceof Uint8Array?bytesToBase64(value):typeof value=="object"?JSON.stringify(value,jsonReplacer):`${value}`}function jsonReplacer(_,value){return value instanceof Uint8Array?bytesToBase64(value):value}function mapDefined(inp,mapper){let res=inp.reduce((acc,v)=>{if(v==null)return acc;let m=mapper(v);return m==null||acc.push(m),acc},[]);return res.length?res:null}function mapDefinedEntries(inp,mapper){let acc=[];for(let[k,v]of inp){if(v==null)continue;let m=mapper([k,v]);m!=null&&acc.push(m)}return acc.length?acc:null}function queryJoin(...args){return args.filter(Boolean).join("&")}function queryEncoder(f){return function(values,options){var _a2,_b,_c;let opts=Object.assign(Object.assign({},options),{explode:(_a2=options?.explode)!==null&&_a2!==void 0?_a2:!0,charEncoding:(_b=options?.charEncoding)!==null&&_b!==void 0?_b:"percent"}),allowEmptySet=new Set((_c=options?.allowEmptyValue)!==null&&_c!==void 0?_c:[]),encoded=Object.entries(values).map(([key,value])=>allowEmptySet.has(key)&&(value==null||value===""||Array.isArray(value)&&value.length===0)?`${encodeURIComponent(key)}=`:f(key,value,opts));return queryJoin(...encoded)}}var encodeFormQuery=queryEncoder(encodeForm);var defaultBackoff={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},PermanentError=class _PermanentError extends Error{constructor(message,options){let msg=message;options?.cause&&(msg+=`: ${options.cause}`),super(msg,options),this.name="PermanentError",typeof this.cause>"u"&&(this.cause=options?.cause),Object.setPrototypeOf(this,_PermanentError.prototype)}},TemporaryError=class _TemporaryError extends Error{constructor(message,response){super(message),this.response=response,this.name="TemporaryError",Object.setPrototypeOf(this,_TemporaryError.prototype)}};async function retry(fetchFn,options){var _a2;switch(options.config.strategy){case"backoff":return retryBackoff(wrapFetcher(fetchFn,{statusCodes:options.statusCodes,retryConnectionErrors:!!options.config.retryConnectionErrors}),(_a2=options.config.backoff)!==null&&_a2!==void 0?_a2:defaultBackoff);case"attempt-count-backoff":return retryAttemptCountBackoff(wrapFetcher(fetchFn,{statusCodes:options.statusCodes,retryConnectionErrors:!!options.config.retryConnectionErrors}),Object.assign(Object.assign({},defaultBackoff),options.config.backoff),options.config);default:return await fetchFn(0)}}function wrapFetcher(fn,options){return async attempt=>{try{let res=await fn(attempt);if(isRetryableResponse(res,options.statusCodes))throw new TemporaryError("Response failed with retryable status code",res);return res}catch(err){throw err instanceof TemporaryError||options.retryConnectionErrors&&(isTimeoutError(err)||isConnectionError(err))?err:new PermanentError("Permanent error",{cause:err})}}}var codeRangeRE=new RegExp("^[0-9]xx$","i");function isRetryableResponse(res,statusCodes){let actual=`${res.status}`;return statusCodes.some(code=>{if(!codeRangeRE.test(code))return code===actual;let expectFamily=code.charAt(0);if(!expectFamily)throw new Error("Invalid status code range");let actualFamily=actual.charAt(0);if(!actualFamily)throw new Error(`Invalid response status code: ${actual}`);return actualFamily===expectFamily})}async function retryBackoff(fn,strategy){let{maxElapsedTime,initialInterval,exponent,maxInterval}=strategy,start=Date.now(),x=0;for(;;)try{return await fn(x)}catch(err){if(err instanceof PermanentError)throw err.cause;if(Date.now()-start>maxElapsedTime){if(err instanceof TemporaryError)return err.response;throw err}let retryInterval=0;err instanceof TemporaryError&&(retryInterval=retryIntervalFromResponse(err.response)),retryInterval<=0&&(retryInterval=initialInterval*Math.pow(x,exponent)+Math.random()*1e3);let d=Math.min(retryInterval,maxInterval);await delay(d),x++}}async function retryAttemptCountBackoff(fn,strategy,config){let attempt=0;for(;;)try{return await fn(attempt)}catch(err){if(err instanceof PermanentError)throw err.cause;if(attempt>=config.maxRetries){if(err instanceof TemporaryError)return err.response;throw err}let retryInterval=0;err instanceof TemporaryError&&(retryInterval=retryIntervalFromResponse(err.response)),retryInterval<=0&&(retryInterval=strategy.initialInterval*Math.pow(strategy.exponent,attempt)*(1-Math.random()*.25));let d=Math.min(retryInterval,strategy.maxInterval);await delay(d),attempt++}}function retryIntervalFromResponse(res){let retryAfterMsVal=res.headers.get("retry-after-ms");if(retryAfterMsVal){let parsedMs=Number(retryAfterMsVal);if(Number.isFinite(parsedMs)&&parsedMs>=0)return parsedMs}let retryVal=res.headers.get("retry-after")||"";if(!retryVal)return 0;let parsedNumber=Number(retryVal);if(Number.isInteger(parsedNumber))return parsedNumber*1e3;let parsedDate=Date.parse(retryVal);if(Number.isInteger(parsedDate)){let deltaMS=parsedDate-Date.now();return deltaMS>0?Math.ceil(deltaMS):0}return 0}async function delay(delay2){return new Promise(resolve=>setTimeout(resolve,delay2))}var gt=typeof globalThis>"u"?null:globalThis,webWorkerLike=typeof gt=="object"&>!=null&&"importScripts"in gt&&typeof gt.importScripts=="function",isBrowserLike=webWorkerLike||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",ClientSDK=class{constructor(options={}){let opt=options;typeof opt=="object"&&opt!=null&&"hooks"in opt&&opt.hooks instanceof SDKHooks?this._hooks=opt.hooks:this._hooks=new SDKHooks;let defaultHttpClient=new HTTPClient;options.http_client=options.http_client||defaultHttpClient,options=this._hooks.sdkInit(options);let url=serverURLFromOptions(options);url&&(url.pathname=url.pathname.replace(/\/+$/,"")+"/"),this._baseURL=url,this._httpClient=options.http_client||defaultHttpClient,this._options=Object.assign(Object.assign({},fillGlobals(options)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&env().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(context,conf,options){var _a2,_b,_c,_d,_e;let{method,path:path2,query,headers:opHeaders,security}=conf,base=(_a2=conf.baseURL)!==null&&_a2!==void 0?_a2:this._baseURL;if(!base)return ERR(new InvalidRequestError("No base URL provided for operation"));let baseURL=new URL(base),reqURL;path2?(baseURL.pathname=baseURL.pathname.replace(/\/+$/,"")+"/",reqURL=new URL(path2,baseURL),!reqURL.search&&baseURL.search&&(reqURL.search=baseURL.search)):reqURL=baseURL,reqURL.hash="";let mergeQuery=(current,additions)=>{if(!additions)return current;let additionKeys=new Set(additions.split("&").filter(pair=>pair!=="").map(pair=>{var _a3;return(_a3=pair.split("=")[0])!==null&&_a3!==void 0?_a3:""}));return[...current.split("&").filter(pair=>{var _a3;return pair!==""&&!additionKeys.has((_a3=pair.split("=")[0])!==null&&_a3!==void 0?_a3:"")}),additions].join("&")},encodeQueryRecord=record=>Object.entries(record).map(([k,v])=>{if(v==null)return;let value=isPlainObject$1(v)?JSON.stringify(v):v;return encodeForm(k,value,{explode:Array.isArray(value),charEncoding:"percent"})}).filter(pair=>typeof pair<"u").join("&"),finalQuery=[query||"",encodeQueryRecord(options?.extra_query||{}),encodeQueryRecord(security?.queryParams||{})].reduce(mergeQuery,reqURL.search.slice(1));finalQuery&&(reqURL.search=`?${finalQuery}`);let headers=new Headers(opHeaders),username=security?.basic.username,password=security?.basic.password;if(username!=null||password!=null){let encoded=stringToBase64([username||"",password||""].join(":"));headers.set("Authorization",`Basic ${encoded}`)}let securityHeaders=new Headers(security?.headers||{});for(let[k,v]of securityHeaders)headers.set(k,v);let cookie=headers.get("cookie")||"";for(let[k,v]of Object.entries(security?.cookies||{}))cookie+=`; ${k}=${v}`;cookie=cookie.startsWith("; ")?cookie.slice(2):cookie,headers.set("cookie",cookie);let userHeaders=new Headers((_b=options?.headers)!==null&&_b!==void 0?_b:(_c=options?.fetch_options)===null||_c===void 0?void 0:_c.headers);for(let[k,v]of userHeaders)headers.set(k,v);isBrowserLike||headers.set((_d=conf.uaHeader)!==null&&_d!==void 0?_d:"user-agent",(_e=conf.userAgent)!==null&&_e!==void 0?_e:SDK_METADATA.userAgent);let reqBody=conf.body,extraBody=Object.fromEntries(Object.entries(options?.extra_body||{}).filter(([,v])=>typeof v<"u"));if(Object.keys(extraBody).length>0){let contentType=new Headers(opHeaders).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(contentType)||typeof reqBody!="string"&&reqBody!=null)return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies"));let parsedBody;try{parsedBody=reqBody?JSON.parse(reqBody):{}}catch(err){return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies",{cause:err}))}if(!isPlainObject$1(parsedBody))return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies"));reqBody=JSON.stringify(Object.assign(Object.assign({},parsedBody),extraBody)),headers.delete("content-length")}let fetchOptions=Object.assign(Object.assign({},options?.fetch_options),options);!fetchOptions?.signal&&conf.timeout_ms!=null&&conf.timeout_ms>0&&(context.timeout_ms=conf.timeout_ms),conf.body instanceof ReadableStream&&Object.assign(fetchOptions,{duplex:"half"});let input;try{input=this._hooks.beforeCreateRequest(context,{url:reqURL,options:Object.assign(Object.assign({},fetchOptions),{body:reqBody??null,headers,method})})}catch(err){return ERR(new UnexpectedClientError("Create request hook failed to execute",{cause:err}))}return OK(new Request(input.url,input.options))}async _do(request,options){let{context,isErrorStatusCode}=options,timeout_ms=context.timeout_ms;return retry(async()=>{var _a2;let cloned=request.clone(),attempt=cloned;if(timeout_ms!=null&&timeout_ms>0){let timeoutSignal=AbortSignal.timeout(timeout_ms),combined=(_a2=combineSignals(cloned.signal,timeoutSignal))!==null&&_a2!==void 0?_a2:timeoutSignal;attempt=new Request(cloned,{signal:combined})}let req=await this._hooks.beforeRequest(context,attempt);await logRequest(this._logger,req).catch(e=>{var _a3;return(_a3=this._logger)===null||_a3===void 0?void 0:_a3.log("Failed to log request:",e)});let response=await this._httpClient.request(req);try{if(isErrorStatusCode(response.status)){let result=await this._hooks.afterError(context,response,null);if(result.error)throw result.error;response=result.response||response}else response=await this._hooks.afterSuccess(context,response)}finally{await logResponse(this._logger,response,req).catch(e=>{var _a3;return(_a3=this._logger)===null||_a3===void 0?void 0:_a3.log("Failed to log response:",e)})}return response},{config:options.retryConfig,statusCodes:options.retryCodes}).then(r=>OK(r),err=>{switch(!0){case isAbortError(err):return ERR(new RequestAbortedError("Request aborted by client",{cause:err}));case isTimeoutError(err):return ERR(new RequestTimeoutError("Request timed out",{cause:err}));case isConnectionError(err):return ERR(new ConnectionError("Unable to make request",{cause:err}));default:return ERR(new UnexpectedClientError("Unexpected HTTP client error",{cause:err}))}})}},jsonLikeContentTypeRE=/^(application|text)\/([^+]+\+)*json.*/,jsonlLikeContentTypeRE=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function logRequest(logger,req){if(!logger)return;let contentType=req.headers.get("content-type"),ct=contentType?.split(";")[0]||"";logger.group(`> Request: ${req.method} ${req.url}`),logger.group("Headers:");for(let[k,v]of req.headers.entries())logger.log(`${k}: ${v}`);switch(logger.groupEnd(),logger.group("Body:"),!0){case jsonLikeContentTypeRE.test(ct):logger.log(await req.clone().json());break;case ct.startsWith("text/"):logger.log(await req.clone().text());break;case ct==="multipart/form-data":{let body=await req.clone().formData();for(let[k,v]of body){let vlabel=v instanceof Blob?"<Blob>":v;logger.log(`${k}: ${vlabel}`)}break}default:logger.log(`<${contentType}>`);break}logger.groupEnd(),logger.groupEnd()}async function logResponse(logger,res,req){if(!logger)return;let contentType=res.headers.get("content-type"),ct=contentType?.split(";")[0]||"";logger.group(`< Response: ${req.method} ${req.url}`),logger.log("Status Code:",res.status,res.statusText),logger.group("Headers:");for(let[k,v]of res.headers.entries())logger.log(`${k}: ${v}`);switch(logger.groupEnd(),logger.group("Body:"),!0){case(matchContentType(res,"application/json")||jsonLikeContentTypeRE.test(ct)&&!jsonlLikeContentTypeRE.test(ct)):logger.log(await res.clone().json());break;case(matchContentType(res,"application/jsonl")||jsonlLikeContentTypeRE.test(ct)):case matchContentType(res,"text/event-stream"):logger.log(`<${contentType}>`);break;case matchContentType(res,"text/*"):logger.log(await res.clone().text());break;case matchContentType(res,"multipart/form-data"):{let body=await res.clone().formData();for(let[k,v]of body){let vlabel=v instanceof Blob?"<Blob>":v;logger.log(`${k}: ${vlabel}`)}break}default:logger.log(`<${contentType}>`);break}logger.groupEnd(),logger.groupEnd()}var GoogleGenAiDefaultError=class extends GoogleGenAiError{constructor(message,httpMeta){message&&(message+=": "),message+=`Status ${httpMeta.response.status}`;let contentType=httpMeta.response.headers.get("content-type")||'""';contentType!=="application/json"&&(message+=` Content-Type ${contentType.includes(" ")?`"${contentType}"`:contentType}`);let body=httpMeta.body||'""';message+=body.length>100?`
`:". ";let bodyDisplay=body;if(body.length>1e4){let truncated=body.substring(0,1e4),remaining=body.length-1e4;bodyDisplay=`${truncated}...and ${remaining} more chars`}message+=`Body: ${bodyDisplay}`,message=message.trim(),super(message,httpMeta),this.name="GoogleGenAiDefaultError"}};function tryParseJson(s){try{return JSON.parse(s)}catch{return s}}function wrapEventStreamResponse(body,opts={}){var _a2,_b;let flattened=opts.flattened===!0,sentinel=(_a2=opts.sentinel)!==null&&_a2!==void 0?_a2:"";return new Stream(body,rawEvent=>sentinel!==""&&rawEvent.data===sentinel?{done:!0,value:void 0}:flattened?{done:!1,value:rawEvent.data==null?void 0:tryParseJson(rawEvent.data)}:{done:!1,value:Object.assign(Object.assign({},rawEvent),{data:rawEvent.data==null?rawEvent.data:tryParseJson(rawEvent.data)})},{dataRequired:(_b=opts.dataRequired)!==null&&_b!==void 0?_b:!0})}var Stream=class extends ReadableStream{constructor(responseBody,parse,opts){var _a2;let upstream=responseBody.getReader(),buffer=new Uint8Array(4096),bufferLen=0,searchStart=0,state={eventId:void 0},dataRequired=(_a2=opts?.dataRequired)!==null&&_a2!==void 0?_a2:!0;super({async pull(downstream){try{for(;;){let match2=findBoundary(buffer,bufferLen,searchStart);if(!match2){searchStart=Math.max(0,bufferLen-MAX_BOUNDARY_LEN+1);let chunk=await upstream.read();if(chunk.done)return downstream.close();if(bufferLen+chunk.value.length>buffer.length){let grown=new Uint8Array(Math.max(buffer.length*2,bufferLen+chunk.value.length));grown.set(buffer.subarray(0,bufferLen)),buffer=grown}buffer.set(chunk.value,bufferLen),bufferLen+=chunk.value.length;continue}let message=buffer.slice(0,match2.index);if(buffer.copyWithin(0,match2.index+match2.length,bufferLen),bufferLen-=match2.index+match2.length,buffer.length>4096&&bufferLen<=buffer.length>>2){let shrunk=new Uint8Array(Math.max(4096,bufferLen*2));shrunk.set(buffer.subarray(0,bufferLen)),buffer=shrunk}searchStart=0;let item=parseMessage(message,parse,state,dataRequired);if(item&&!item.done)return downstream.enqueue(item.value);if(item?.done)return await upstream.cancel("done"),downstream.close()}}catch(e){downstream.error(e),await upstream.cancel(e)}},cancel:reason=>upstream.cancel(reason)})}[Symbol.asyncIterator](options){let fn=ReadableStream.prototype[Symbol.asyncIterator];if(typeof fn=="function")return fn.call(this,options);let reader=this.getReader(),iterator={next:async()=>{let r=await reader.read();return r.done?(reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:r.value}},throw:async e=>(await reader.cancel(e),reader.releaseLock(),{done:!0,value:void 0}),return:async()=>(await reader.cancel("done"),reader.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},asyncDispose=Symbol.asyncDispose;return asyncDispose&&(iterator[asyncDispose]=async()=>{var _a2;await((_a2=iterator.return)===null||_a2===void 0?void 0:_a2.call(iterator))}),iterator}values(options){return this[Symbol.asyncIterator](options)}},CR=13,LF=10,BOUNDARIES=[[CR,LF,CR,LF],[CR,LF,CR],[CR,LF,LF],[CR,CR,LF],[LF,CR,LF],[CR,CR],[LF,CR],[LF,LF]],MAX_BOUNDARY_LEN=BOUNDARIES.reduce((m,b)=>Math.max(m,b.length),0);function findBoundary(buf,len,from){for(let i=from;i<len;i++)if(!(buf[i]!==CR&&buf[i]!==LF))for(let boundary of BOUNDARIES){if(i+boundary.length>len)continue;let match2=!0;for(let j=0;j<boundary.length;j++)if(buf[i+j]!==boundary[j]){match2=!1;break}if(match2)return{index:i,length:boundary.length}}return null}function parseMessage(chunk,parse,state,dataRequired){let lines=new TextDecoder().decode(chunk).split(/\r\n|\r|\n/),dataLines=[],ret={},ignore=!0;for(let line of lines){if(!line||line.startsWith(":"))continue;ignore=!1;let i=line.indexOf(":"),field=line,value="";i>0&&(field=line.slice(0,i),value=line[i+1]===" "?line.slice(i+2):line.slice(i+1)),field==="data"?dataLines.push(value):field==="event"?ret.event=value:field==="id"&&!value.includes("\0")?state.eventId=value:field==="retry"&&/^\d+$/.test(value)&&(ret.retry=Number(value))}if(!ignore){if(ret.id=state.eventId,dataLines.length)ret.data=dataLines.join(`
`);else if(dataRequired)return;return parse(ret)}}var DEFAULT_CONTENT_TYPES={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function jsonErr(codes,errorClass,options){return Object.assign(Object.assign({},options),{err:!0,enc:"json",codes,errorClass})}function json(codes,options){return Object.assign(Object.assign({},options),{enc:"json",codes})}function sse(codes,sse2,options){return Object.assign(Object.assign(Object.assign({},options),{enc:"sse",codes}),sse2?{sse:sse2}:{})}function nil(codes,options){return Object.assign(Object.assign({},options),{enc:"nil",codes})}function fail(codes){return{enc:"fail",codes}}function match(...matchers){return async function(response,request,options){let raw,matcher;for(let match2 of matchers){let{codes}=match2,ctpattern="ctype"in match2?match2.ctype:DEFAULT_CONTENT_TYPES[match2.enc];if(ctpattern&&matchResponse(response,codes,ctpattern)){matcher=match2;break}else if(!ctpattern&&matchStatusCode(response,codes)){matcher=match2;break}}if(!matcher)return[{ok:!1,error:new GoogleGenAiDefaultError("Unexpected Status or Content-Type",{response,request,body:await response.text().catch(()=>"")})},raw];let encoding=matcher.enc,body="";switch(encoding){case"json":body=await response.text();try{raw=JSON.parse(body)}catch(err){if(!("err"in matcher))throw err;raw=body}break;case"jsonl":raw=response.body;break;case"bytes":raw=new Uint8Array(await response.arrayBuffer());break;case"stream":raw=response.body;break;case"text":body=await response.text(),raw=body;break;case"sse":if(response.body){let sseOpts="sse"in matcher&&matcher.sse||{};raw=wrapEventStreamResponse(response.body,sseOpts)}else raw=null;break;case"nil":body=await response.text(),raw=void 0;break;case"fail":body=await response.text(),raw=body;break;default:throw new Error(`Unsupported response type: ${encoding}`)}if(matcher.enc==="fail")return[{ok:!1,error:new GoogleGenAiDefaultError("API error occurred",{request,response,body})},raw];let resultKey=matcher.key||options?.resultKey,data,headersField=matcher.hdrs?{headers:unpackHeaders(response.headers)}:null;return"err"in matcher?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),isPlainObject$1(raw)?raw:null):resultKey?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),{[resultKey]:raw}):matcher.hdrs?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),isPlainObject$1(raw)?raw:null):data=raw,"err"in matcher?[{ok:!1,error:matcher.errorClass?new matcher.errorClass(data,{request,response,body}):data},raw]:[{ok:!0,value:data},raw]}}var headerValRE=/, */;function unpackHeaders(headers){let out={};for(let[k,v]of headers.entries())out[k]=v.split(headerValRE);return out}var SecurityErrorCode={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},SecurityError=class _SecurityError extends Error{constructor(code,message){super(message),this.code=code,this.name="SecurityError"}static incomplete(){return new _SecurityError(SecurityErrorCode.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(type){return new _SecurityError(SecurityErrorCode.UnrecognisedSecurityType,`Unrecognised security type: ${type}`)}};function resolveSecurity(...options){let state={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},option=options.find(opts=>opts.every(o=>{if(o.value==null)return!1;if(o.type==="http:basic")return o.value.username!=null||o.value.password!=null;if(o.type==="http:custom")return null;if(o.type==="oauth2:password")return typeof o.value=="string"&&!!o.value;if(o.type==="oauth2:client_credentials")return typeof o.value=="string"?!!o.value:o.value.client_id!=null||o.value.client_secret!=null;if(typeof o.value=="string")return!!o.value;throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`)}));return option==null?null:(option.forEach(spec=>{if(spec.value==null)return;let{type}=spec;switch(type){case"apiKey:header":state.headers[spec.fieldName]=spec.value;break;case"apiKey:query":state.queryParams[spec.fieldName]=spec.value;break;case"apiKey:cookie":state.cookies[spec.fieldName]=spec.value;break;case"http:basic":applyBasic(state,spec);break;case"http:custom":break;case"http:bearer":applyBearer(state,spec);break;case"oauth2":applyBearer(state,spec);break;case"oauth2:password":applyBearer(state,spec);break;case"oauth2:client_credentials":break;case"openIdConnect":applyBearer(state,spec);break;default:throw SecurityError.unrecognizedType(type)}}),state)}function applyBasic(state,spec){spec.value!=null&&(state.basic=spec.value)}function applyBearer(state,spec){if(typeof spec.value!="string"||!spec.value)return;let value=spec.value;value.slice(0,7).toLowerCase()!=="bearer "&&(value=`Bearer ${value}`),spec.fieldName!==void 0&&(state.headers[spec.fieldName]=value)}function resolveGlobalSecurity(security,allowedFields){var _a2,_b;let inputs=[[{fieldName:"accessToken",type:"http:custom",value:(_a2=security?.access_token)!==null&&_a2!==void 0?_a2:env().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(_b=security?.api_key)!==null&&_b!==void 0?_b:env().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:security?.default_headers}]];return resolveSecurity(...inputs)}async function extractSecurity(sec){if(sec!=null)return typeof sec=="function"?sec():sec}var _a,APIPromise=class _APIPromise{constructor(p,callSource){this[_a]="APIPromise",this._promise=p instanceof Promise?p:Promise.resolve(p),this._unwrapped=p instanceof Promise?null:Promise.resolve(p[0]),this._callSource=callSource??null}_getUnwrapped(){var _b;return(_b=this._unwrapped)!==null&&_b!==void 0?_b:this._unwrapped=this._promise.then(([value])=>value)}then(onfulfilled,onrejected){return this._promise.then(onfulfilled?([value])=>onfulfilled(value):void 0,onrejected)}catch(onrejected){return this._getUnwrapped().catch(onrejected)}finally(onfinally){return this._getUnwrapped().finally(onfinally)}$inspect(){return this._promise}asResponse(){var _b;return((_b=this._callSource)!==null&&_b!==void 0?_b:this._callSource=this._promise.then(([,call])=>call)).then(call=>{if(!call.response)throw new Error("APIPromise.asResponse: response unavailable");return call.response})}async withResponse(){let[[data],response]=await Promise.all([this._promise,this.asResponse()]);return{data,response}}_thenUnwrap(transform){var _b;let data=this._promise.then(([value,call])=>[transform(value),call]);return data.catch(()=>{}),new _APIPromise(data,(_b=this._callSource)!==null&&_b!==void 0?_b:void 0)}};_a=Symbol.toStringTag;function unwrapAsAPIPromise(p){let inner=p.$inspect(),data=inner.then(([r,call])=>{if(!r.ok)throw r.error;return[r.value,call]}),callSource=inner.then(([r,call])=>{var _b;if(!r.ok&&!(!((_b=call.response)===null||_b===void 0)&&_b.ok))throw r.error;return call});return data.catch(()=>{}),callSource.catch(()=>{}),new APIPromise(data,callSource)}function agentsCreate(client,body,api_version,options){return new APIPromise($do$w(client,body,api_version,options))}async function $do$w(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsDelete(client,id,api_version,options){return new APIPromise($do$v(client,id,api_version,options))}async function $do$v(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsGet(client,id,api_version,options){return new APIPromise($do$u(client,id,api_version,options))}async function $do$u(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsList(client,api_version,page_size,page_token,parent,options){return new APIPromise($do$t(client,api_version,page_size,page_token,parent,options))}async function $do$t(client,api_version,page_size,page_token,parent,options){var _a2,_b,_c;let payload={api_version,page_size,page_token,parent},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token,parent:payload?.parent}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Agents=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(agentsList(this,params?.api_version,params?.page_size,params?.page_token,params?.parent,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(agentsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(agentsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(agentsGet(this,id,params?.api_version,options))}};function credentialsCreate(client,body,api_version,options){return new APIPromise($do$s(client,body,api_version,options))}async function $do$s(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/credentials")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateCredential",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function credentialsDelete(client,id,api_version,options){return new APIPromise($do$r(client,id,api_version,options))}async function $do$r(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/credentials/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteCredential",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function credentialsGet(client,id,api_version,options){return new APIPromise($do$q(client,id,api_version,options))}async function $do$q(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/credentials/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetCredential",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function credentialsList(client,api_version,page_size,page_token,options){return new APIPromise($do$p(client,api_version,page_size,page_token,options))}async function $do$p(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/credentials")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListCredentials",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function credentialsUpdate(client,id,body,api_version,update_mask,options){return new APIPromise($do$o(client,id,body,api_version,update_mask,options))}async function $do$o(client,id,body,api_version,update_mask,options){var _a2,_b,_c;let payload={id,body,api_version,update_mask},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/credentials/{id}")(pathParams),query=encodeFormQuery({update_mask:payload.update_mask}),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateCredential",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,query,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Credentials=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(credentialsList(this,params?.api_version,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(credentialsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(credentialsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(credentialsGet(this,id,params?.api_version,options))}update(id,params,options){let{api_version,update_mask}=params,body=__rest(params,["api_version","update_mask"]);return unwrapAsAPIPromise(credentialsUpdate(this,id,body,api_version,update_mask,options))}};function environmentsCreateEnvironment(client,body,api_version,options){return new APIPromise($do$n(client,body,api_version,options))}async function $do$n(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsDeleteEnvironment(client,id,api_version,options){return new APIPromise($do$m(client,id,api_version,options))}async function $do$m(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsGetEnvironment(client,id,api_version,options){return new APIPromise($do$l(client,id,api_version,options))}async function $do$l(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsListEnvironments(client,api_version,page_size,page_token,options){return new APIPromise($do$k(client,api_version,page_size,page_token,options))}async function $do$k(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsFilesList(client,environment,path2,api_version,page_size,page_token,recursive,options){return new APIPromise($do$j(client,environment,path2,api_version,page_size,page_token,recursive,options))}async function $do$j(client,environment,path2,api_version,page_size,page_token,recursive,options){var _a2,_b,_c;let payload={environment,path:path2,api_version,page_size,page_token,recursive},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),environment:encodeSimple("environment",payload.environment,{explode:!1,charEncoding:"percent"}),path:encodeSimple("path",payload.path,{explode:!1,charEncoding:"percentExceptReserved"})},path$=pathToFunc("/{api_version}/environments/{environment}/files/{path}")(pathParams),query=encodeFormQuery({page_size:payload.page_size,page_token:payload.page_token,recursive:payload.recursive}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path$,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Files2=class extends ClientSDK{list(environment,path2,params,options){return unwrapAsAPIPromise(environmentsFilesList(this,environment,path2,params?.api_version,params?.page_size,params?.page_token,params?.recursive,options))}};function environmentsInternalStartUpload(client,environment,path2,x_goog_upload_command,x_goog_upload_header_content_length,x_goog_upload_header_content_type,x_goog_upload_protocol,api_version,extract,overwrite,options){return new APIPromise($do$i(client,environment,path2,x_goog_upload_command,x_goog_upload_header_content_length,x_goog_upload_header_content_type,x_goog_upload_protocol,api_version,extract,overwrite,options))}async function $do$i(client,environment,path2,x_goog_upload_command,x_goog_upload_header_content_length,x_goog_upload_header_content_type,x_goog_upload_protocol,api_version,extract,overwrite,options){var _a2,_b,_c;let payload={environment,path:path2,"X-Goog-Upload-Command":x_goog_upload_command,"X-Goog-Upload-Header-Content-Length":x_goog_upload_header_content_length,"X-Goog-Upload-Header-Content-Type":x_goog_upload_header_content_type,"X-Goog-Upload-Protocol":x_goog_upload_protocol,api_version,extract,overwrite},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),environment:encodeSimple("environment",payload.environment,{explode:!1,charEncoding:"percent"}),path:encodeSimple("path",payload.path,{explode:!1,charEncoding:"percentExceptReserved"})},path$=pathToFunc("/upload/{api_version}/environments/{environment}/files/{path}")(pathParams),query=encodeFormQuery({extract:payload.extract,overwrite:payload.overwrite}),headers=new Headers(compactMap({Accept:"*/*","X-Goog-Upload-Command":encodeSimple("X-Goog-Upload-Command",payload["X-Goog-Upload-Command"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Length":encodeSimple("X-Goog-Upload-Header-Content-Length",payload["X-Goog-Upload-Header-Content-Length"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Header-Content-Type":encodeSimple("X-Goog-Upload-Header-Content-Type",payload["X-Goog-Upload-Header-Content-Type"],{explode:!1,charEncoding:"none"}),"X-Goog-Upload-Protocol":encodeSimple("X-Goog-Upload-Protocol",payload["X-Goog-Upload-Protocol"],{explode:!1,charEncoding:"none"})})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"StartEnvironmentFileUpload",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PUT",baseURL:options?.server_url,path:path$,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(nil(200,{hdrs:!0}),fail("4XX"),fail("5XX"))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Internal=class extends ClientSDK{startUpload(environment,path2,params,options){return unwrapAsAPIPromise(environmentsInternalStartUpload(this,environment,path2,params["X-Goog-Upload-Command"],params["X-Goog-Upload-Header-Content-Length"],params["X-Goog-Upload-Header-Content-Type"],params["X-Goog-Upload-Protocol"],params.api_version,params.extract,params.overwrite,options))}};var Environments=class extends ClientSDK{get internal(){var _a2;return(_a2=this._internal)!==null&&_a2!==void 0?_a2:this._internal=new Internal(this._options)}get files(){var _a2;return(_a2=this._files)!==null&&_a2!==void 0?_a2:this._files=new Files2(this._options)}listEnvironments(params,options){return unwrapAsAPIPromise(environmentsListEnvironments(this,params?.api_version,params?.page_size,params?.page_token,options))}createEnvironment(body,api_version,options){return unwrapAsAPIPromise(environmentsCreateEnvironment(this,body,api_version,options))}deleteEnvironment(id,params,options){return unwrapAsAPIPromise(environmentsDeleteEnvironment(this,id,params?.api_version,options))}getEnvironment(id,params,options){return unwrapAsAPIPromise(environmentsGetEnvironment(this,id,params?.api_version,options))}};var CancelInteractionByIdServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CancelInteractionByIdServerError"}},CancelInteractionByIdClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CancelInteractionByIdClientError"}};var CreateInteractionServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CreateInteractionServerError"}},CreateInteractionClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CreateInteractionClientError"}};var DeleteInteractionServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="DeleteInteractionServerError"}},DeleteInteractionClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="DeleteInteractionClientError"}};var GetInteractionByIdServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="GetInteractionByIdServerError"}},GetInteractionByIdClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="GetInteractionByIdClientError"}};function interactionsCancel(client,id,api_version,options){return new APIPromise($do$h(client,id,api_version,options))}async function $do$h(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}/cancel")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),jsonErr("4XX",CancelInteractionByIdClientError),jsonErr("5XX",CancelInteractionByIdServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsCreate(client,body,api_version,options){return new APIPromise($do$g(client,body,api_version,options))}async function $do$g(client,body,api_version,options){var _a2,_b,_c,_d;let input={body,api_version},payload=input,body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:!((_b=input?.body)===null||_b===void 0)&&_b.stream?"text/event-stream":"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_d=(_c=options?.server_url)!==null&&_c!==void 0?_c:client._baseURL)!==null&&_d!==void 0?_d:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),sse(200,{sentinel:"[DONE]",flattened:!0}),jsonErr("4XX",CreateInteractionClientError),jsonErr("5XX",CreateInteractionServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsDelete(client,id,api_version,options){return new APIPromise($do$f(client,id,api_version,options))}async function $do$f(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(nil(200),jsonErr("4XX",DeleteInteractionClientError),jsonErr("5XX",DeleteInteractionServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsGet(client,id,api_version,include_input,last_event_id,stream,options){return new APIPromise($do$e(client,id,api_version,include_input,last_event_id,stream,options))}async function $do$e(client,id,api_version,include_input,last_event_id,stream,options){var _a2,_b,_c;let input={id,api_version,include_input,last_event_id,stream},payload=input,body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}")(pathParams),query=encodeFormQuery({include_input:payload.include_input,last_event_id:payload.last_event_id,stream:payload.stream}),headers=new Headers(compactMap({Accept:input?.stream?"text/event-stream":"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),sse(200,{sentinel:"[DONE]",flattened:!0}),jsonErr("4XX",GetInteractionByIdClientError),jsonErr("5XX",GetInteractionByIdServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Interactions=class extends ClientSDK{create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(interactionsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(interactionsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(interactionsGet(this,id,params?.api_version,params?.include_input,params?.last_event_id,params?.stream,options))}cancel(id,params,options){return unwrapAsAPIPromise(interactionsCancel(this,id,params?.api_version,options))}};function triggersCreate(client,body,api_version,options){return new APIPromise($do$d(client,body,api_version,options))}async function $do$d(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersDelete(client,id,api_version,options){return new APIPromise($do$c(client,id,api_version,options))}async function $do$c(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersGet(client,id,api_version,options){return new APIPromise($do$b(client,id,api_version,options))}async function $do$b(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersListExecutions(client,trigger_id,api_version,page_size,page_token,options){return new APIPromise($do$a(client,trigger_id,api_version,page_size,page_token,options))}async function $do$a(client,trigger_id,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={trigger_id,api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:encodeSimple("trigger_id",payload.trigger_id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams),query=encodeFormQuery({page_size:payload.page_size,page_token:payload.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersList(client,api_version,filter,page_size,page_token,options){return new APIPromise($do$9(client,api_version,filter,page_size,page_token,options))}async function $do$9(client,api_version,filter,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,filter,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers")(pathParams),query=encodeFormQuery({filter:payload?.filter,page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersRun(client,trigger_id,api_version,options){return new APIPromise($do$8(client,trigger_id,api_version,options))}async function $do$8(client,trigger_id,api_version,options){var _a2,_b,_c;let payload={trigger_id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:encodeSimple("trigger_id",payload.trigger_id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersUpdate(client,id,body,api_version,options){return new APIPromise($do$7(client,id,body,api_version,options))}async function $do$7(client,id,body,api_version,options){var _a2,_b,_c;let payload={id,body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Triggers=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(triggersList(this,params?.api_version,params?.filter,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(triggersCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(triggersDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(triggersGet(this,id,params?.api_version,options))}update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(triggersUpdate(this,id,body,api_version,options))}listExecutions(trigger_id,params,options){return unwrapAsAPIPromise(triggersListExecutions(this,trigger_id,params?.api_version,params?.page_size,params?.page_token,options))}run(trigger_id,params,options){return unwrapAsAPIPromise(triggersRun(this,trigger_id,params?.api_version,options))}};function webhooksCreate(client,body,api_version,options){return new APIPromise($do$6(client,body,api_version,options))}async function $do$6(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksDelete(client,id,api_version,options){return new APIPromise($do$5(client,id,api_version,options))}async function $do$5(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksGet(client,id,api_version,options){return new APIPromise($do$4(client,id,api_version,options))}async function $do$4(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksList(client,api_version,page_size,page_token,options){return new APIPromise($do$3(client,api_version,page_size,page_token,options))}async function $do$3(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksPing(client,id,api_version,body,options){return new APIPromise($do$2(client,id,api_version,body,options))}async function $do$2(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:ping")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksRotateSigningSecret(client,id,api_version,body,options){return new APIPromise($do$1(client,id,api_version,body,options))}async function $do$1(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:rotateSigningSecret")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksUpdate(client,id,api_version,update_mask,body,options){return new APIPromise($do(client,id,api_version,update_mask,body,options))}async function $do(client,id,api_version,update_mask,body,options){var _a2,_b,_c;let payload={id,api_version,update_mask,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),query=encodeFormQuery({update_mask:payload.update_mask}),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,query,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Webhooks=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(webhooksList(this,params?.api_version,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(webhooksCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(webhooksDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(webhooksGet(this,id,params?.api_version,options))}update(id,params,options){let _a2=params??{},{api_version,update_mask}=_a2,body$body=__rest(_a2,["api_version","update_mask"]),body=params===void 0||Object.keys(body$body).length===0?void 0:body$body;return unwrapAsAPIPromise(webhooksUpdate(this,id,api_version,update_mask,body,options))}ping(id,api_version,body,options){return unwrapAsAPIPromise(webhooksPing(this,id,api_version,body,options))}rotateSigningSecret(id,api_version,body,options){return unwrapAsAPIPromise(webhooksRotateSigningSecret(this,id,api_version,body,options))}};var GoogleGenAI$1=class extends ClientSDK{get environments(){var _a2;return(_a2=this._environments)!==null&&_a2!==void 0?_a2:this._environments=new Environments(this._options)}get agents(){var _a2;return(_a2=this._agents)!==null&&_a2!==void 0?_a2:this._agents=new Agents(this._options)}get credentials(){var _a2;return(_a2=this._credentials)!==null&&_a2!==void 0?_a2:this._credentials=new Credentials(this._options)}get interactions(){var _a2;return(_a2=this._interactions)!==null&&_a2!==void 0?_a2:this._interactions=new Interactions(this._options)}get triggers(){var _a2;return(_a2=this._triggers)!==null&&_a2!==void 0?_a2:this._triggers=new Triggers(this._options)}get webhooks(){var _a2;return(_a2=this._webhooks)!==null&&_a2!==void 0?_a2:this._webhooks=new Webhooks(this._options)}};var LEGACY_LYRIA_MODELS=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function getGoogleGenAIServerURL(parentClient){let serverURL=parentClient.getBaseUrl();if(!serverURL)throw new Error("Base URL must be set.");return serverURL.replace(/\/+$/,"")}function getGoogleGenAIAPIVersion(parentClient){let apiVersion=trimSlashes(parentClient.getApiVersion()),project=parentClient.getProject(),location=parentClient.getLocation();return parentClient.isVertexAI()&&apiVersion&&project&&location?`${apiVersion}/projects/${encodeURIComponent(project)}/locations/${encodeURIComponent(location)}`:apiVersion}function buildGoogleGenAIClient(parentClient,options={}){var _a2,_b,_c,_d,_e,_f,_g;let fetchFn=options.http_client||(_a2=parentClient.getFetch)===null||_a2===void 0?void 0:_a2.call(parentClient),httpClient=(_b=options.http_client)!==null&&_b!==void 0?_b:fetchFn?new HTTPClient({fetcher:fetchFn}):void 0;return new GoogleGenAI$1(Object.assign(Object.assign({},options),{http_client:httpClient,api_version:(_c=options.api_version)!==null&&_c!==void 0?_c:getGoogleGenAIAPIVersion(parentClient),security:(_d=options.security)!==null&&_d!==void 0?_d:new GoogleGenAISecurityProvider({defaultHeaders:Object.assign(Object.assign({},(_e=parentClient.getDefaultHeaders)===null||_e===void 0?void 0:_e.call(parentClient)),(_f=parentClient.getHeaders)===null||_f===void 0?void 0:_f.call(parentClient)),getAuthHeaders:url=>parentClient.getAuthHeaders(url)}),server_url:(_g=options.server_url)!==null&&_g!==void 0?_g:getGoogleGenAIServerURL(parentClient)}))}var GeminiNextGenInteractions=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,request=__rest(params,["api_version"]);if(request.stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.create(Object.assign(Object.assign({},request),{stream:!0,api_version}),toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsCreate(this.getClient(api_version),request,api_version,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async get(id,params={},options){let{api_version,stream=!1,last_event_id,include_input}=params??{};if(stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.get(id,{stream,last_event_id,include_input,api_version},toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsGet(this.getClient(api_version),id,api_version,include_input,last_event_id,stream,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async delete(id,params={},options){return wrapSDKCall(()=>this.getClient(params?.api_version).interactions.delete(id,{api_version:params?.api_version},toGoogleGenAIRequestOptions(options)))}async cancel(id,params={},options){return addOutputPropertiesIfInteraction(await unwrapWithSdkHttpResponse(interactionsCancel(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options))))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenAgents=class{constructor(parentClient){this.parentClient=parentClient}async create(params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(agentsCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token,parent}=params??{};return unwrapWithSdkHttpResponse(agentsList(this.getClient(api_version),api_version,page_size,page_token,parent,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(agentsGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(agentsDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenWebhooks=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(webhooksCreate(this.getClient(),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(webhooksList(this.getClient(),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(webhooksGet(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params={},options){let _a2=params??{},{api_version,update_mask}=_a2,body=__rest(_a2,["api_version","update_mask"]);return unwrapWithSdkHttpResponse(webhooksUpdate(this.getClient(),id,api_version,update_mask,body,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(webhooksDelete(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async rotateSigningSecret(id,params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(webhooksRotateSigningSecret(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}async ping(id,params=void 0,options){let{api_version,body}=params??{};return unwrapWithSdkHttpResponse(webhooksPing(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}getClient(){var _a2;return(_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk}},GeminiNextGenTriggers=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,filter,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(triggersList(this.getClient(api_version),api_version,filter,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(triggersGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersUpdate(this.getClient(api_version),id,body,api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(triggersDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async run(trigger_id,params={},options){return unwrapWithSdkHttpResponse(triggersRun(this.getClient(params?.api_version),trigger_id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async listExecutions(trigger_id,params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(triggersListExecutions(this.getClient(api_version),trigger_id,api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};function trimSlashes(value){return value.replace(/^\/+|\/+$/g,"")}function toGoogleGenAIRequestOptions(options,streaming=!1){var _a2,_b,_c,_d;if(!options&&!streaming)return;let _e=options??{},{timeout,maxRetries,defaultBaseURL,query,body,fetchOptions}=_e,rest=__rest(_e,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),nextOptions=Object.assign({},rest);isPlainObject(query)?nextOptions.extra_query=query:warnIgnoredOption("query",query),isPlainObject(body)?nextOptions.extra_body=body:warnIgnoredOption("body",body);let fetch_options=(_a2=rest.fetch_options)!==null&&_a2!==void 0?_a2:fetchOptions;fetch_options&&(nextOptions.fetch_options=fetch_options);let server_url=(_b=rest.server_url)!==null&&_b!==void 0?_b:defaultBaseURL;server_url&&(nextOptions.server_url=server_url);let timeout_ms=(_c=rest.timeout_ms)!==null&&_c!==void 0?_c:timeout;if(timeout_ms!==void 0&&(nextOptions.timeout_ms=timeout_ms),maxRetries!==void 0&&(nextOptions.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries}),streaming){let headers=new Headers((_d=nextOptions.headers)!==null&&_d!==void 0?_d:fetch_options?.headers);headers.set("Accept","text/event-stream"),nextOptions.headers=headers}return nextOptions}function warnIgnoredOption(name,value){value!=null&&console.warn(`GoogleGenAI.interactions: request option ${name} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function unwrapWithSdkHttpResponse(promise){let[result,call]=await promise.$inspect();if(!result.ok)throw wrapSDKError(result.error);return attachSdkHttpResponse(result.value,call)}async function wrapSDKCall(operation){try{return await operation()}catch(error){throw wrapSDKError(error)}}function wrapStreamErrors(stream){let asyncIterable=stream;return new Proxy(stream,{get(target,property){if(property!==Symbol.asyncIterator){let value=Reflect.get(target,property,target);return typeof value=="function"?value.bind(target):value}return function(){let iterator=asyncIterable[Symbol.asyncIterator]();return{async next(...args){try{return await iterator.next(...args)}catch(error){throw wrapSDKError(error)}},async return(value){if(!iterator.return)return{done:!0,value};try{return await iterator.return(value)}catch(error){throw wrapSDKError(error)}},async throw(error){if(!iterator.throw)throw wrapSDKError(error);try{return await iterator.throw(error)}catch(caught){throw wrapSDKError(caught)}},[Symbol.asyncIterator](){return this}}}}})}function attachSdkHttpResponse(value,call){return!isPlainObject(value)||call.status!=="complete"?value:Object.assign(Object.assign({},value),{sdkHttpResponse:createSdkHttpResponse(call.response,value)})}function createSdkHttpResponse(response,parsedBody){let headers={};for(let[key,value]of response.headers.entries())headers[key]=value;return{headers,responseInternal:response,json:async()=>parsedBody}}function addOutputPropertiesIfInteraction(value){let interaction=normalizeInteractionShape(value);return interaction?addOutputProperties(interaction):value}function normalizeInteractionShape(value){if(isPlainObject(value)){if(Array.isArray(value.steps))return value;if(isLegacyLyriaInteraction(value)){let outputs=value.outputs;if(Array.isArray(outputs)){let{outputs:_outputs}=value,rest=__rest(value,["outputs"]);return Object.assign(Object.assign({},rest),{steps:[{type:"model_output",content:outputs}]})}}return Object.assign(Object.assign({},value),{steps:[]})}}function isLegacyLyriaInteraction(value){let model=value.model;return typeof model=="string"&&LEGACY_LYRIA_MODELS.has(model)}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function addOutputProperties(interaction){var _a2,_b;let normalized=normalizeInteractionDates(interaction),steps=(_a2=normalized.steps)!==null&&_a2!==void 0?_a2:[],textParts=[],collecting=!1;outer:for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type!=="model_output"||!step.content){if(collecting)break;continue}let content=step.content;for(let j=content.length-1;j>=0;j--){let item=content[j];if(item.type==="text")collecting=!0,textParts.push((_b=item.text)!==null&&_b!==void 0?_b:"");else if(collecting)break outer}}let output_image,output_audio,output_video;for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type==="model_output"&&step.content)for(let j=step.content.length-1;j>=0;j--){let content=step.content[j];content.type==="image"&&!output_image&&(output_image=content),content.type==="audio"&&!output_audio&&(output_audio=content),content.type==="video"&&!output_video&&(output_video=content)}}let output_text=textParts.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},normalized),output_text&&{output_text}),output_image?{output_image}:{}),output_audio?{output_audio}:{}),output_video?{output_video}:{})}function normalizeInteractionDates(interaction){return Object.assign(Object.assign({},interaction),{created:normalizeDateLike(interaction.created),updated:normalizeDateLike(interaction.updated)})}function normalizeDateLike(value){return value instanceof Date?value.toISOString():value}function inferMimeType(filePath){let ext=filePath.slice(filePath.lastIndexOf(".")+1).toLowerCase();return{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"}[ext]}var GeminiNextGenEnvironmentFiles=class{constructor(resolveClient,parentClient){this.resolveClient=resolveClient,this.parentClient=parentClient}async list(params,options){return unwrapWithSdkHttpResponse(environmentsFilesList(this.resolveClient(params.api_version),params.environment,params.path,params.api_version,params.page_size,params.page_token,params.recursive,toGoogleGenAIRequestOptions(options)))}async download(params,options){var _a2,_b;let targetEnv=params.environment;if(!targetEnv)throw new Error("environment is required.");let envName=targetEnv.startsWith("environments/")?targetEnv:`environments/${targetEnv}`,cleanPath=params.path.replace(/^\/+/,""),downloadPath=`${envName}/files/${cleanPath}`,apiClient=this.parentClient;if(!apiClient||typeof apiClient.request!="function")throw new Error("apiClient is required to download files.");let response=await apiClient.request({path:downloadPath,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:Object.assign(Object.assign({},options?.httpOptions),{apiVersion:(_a2=params.api_version)!==null&&_a2!==void 0?_a2:(_b=options?.httpOptions)===null||_b===void 0?void 0:_b.apiVersion})});if(response&&response.responseInternal&&typeof response.responseInternal.arrayBuffer=="function"){let arrayBuffer=await response.responseInternal.arrayBuffer();return new Uint8Array(arrayBuffer)}throw new Error("Unexpected response type from download")}async upload(params,options){var _a2,_b,_c,_d,_e,_f,_g,_h;let targetEnv=params.environment;if(!targetEnv)throw new Error("environment is required.");targetEnv.startsWith("environments/")||`${targetEnv}`;let cleanPath=params.path.replace(/^\/+/,""),apiClient=this.parentClient;if(!apiClient||typeof apiClient.request!="function")throw new Error("apiClient is required to upload files.");let fileData,sizeBytes=0,mimeType=params.mime_type;if(typeof params.file=="string"){let buffer;try{let req=globalThis.require;req&&(buffer=req("fs").readFileSync(params.file))}catch{}if(!buffer&&typeof globalThis.process<"u")try{let mod=(_b=(_a2=globalThis.process.mainModule)===null||_a2===void 0?void 0:_a2.require)!==null&&_b!==void 0?_b:globalThis.require;mod&&(buffer=mod("fs").readFileSync(params.file))}catch{}if(buffer)fileData=new Uint8Array(buffer.buffer,buffer.byteOffset,buffer.byteLength),sizeBytes=fileData.byteLength;else throw new Error(`Unable to read file from path "${params.file}". File path string inputs are only supported in Node.js environments.`);mimeType||(mimeType=inferMimeType(params.file))}else if(typeof Blob<"u"&¶ms.file instanceof Blob)fileData=params.file,sizeBytes=params.file.size,!mimeType&¶ms.file.type&&(mimeType=params.file.type);else if(params.file instanceof Uint8Array||params.file instanceof ArrayBuffer)fileData=params.file instanceof ArrayBuffer?new Uint8Array(params.file):params.file,sizeBytes=fileData.byteLength;else if(typeof globalThis.Buffer<"u"&&typeof globalThis.Buffer.isBuffer=="function"&&globalThis.Buffer.isBuffer(params.file)){let buf=params.file;fileData=new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength),sizeBytes=fileData.byteLength}else throw new Error("Unsupported file type for upload.");mimeType||(mimeType="application/octet-stream");let cleanEnv=targetEnv.startsWith("environments/")?targetEnv.replace(/^environments\//,""):targetEnv,[result,call]=await environmentsInternalStartUpload(this.resolveClient(params.api_version),cleanEnv,cleanPath,"start",sizeBytes,mimeType,"resumable",params.api_version,params.extract,params.overwrite,toGoogleGenAIRequestOptions(options)).$inspect();if(!result.ok)throw wrapSDKError(result.error);let uploadUrl=call.status==="complete"?(_e=(_d=(_c=call.response)===null||_c===void 0?void 0:_c.headers)===null||_d===void 0?void 0:_d.get("x-goog-upload-url"))!==null&&_e!==void 0?_e:(_g=(_f=call.response)===null||_f===void 0?void 0:_f.headers)===null||_g===void 0?void 0:_g.get("X-Goog-Upload-URL"):void 0;if(!uploadUrl)throw new Error("Failed to get upload URL from upload handshake response.");let CHUNK_SIZE=8*1024*1024,offset=0,uploadResponse,blob=fileData instanceof Blob?fileData:new Blob([fileData]);for(;offset<sizeBytes||sizeBytes===0&&offset===0;){let end=Math.min(offset+CHUNK_SIZE,sizeBytes),chunk=blob.slice(offset,end),isFinal=end>=sizeBytes,uploadCommand=isFinal?"upload, finalize":"upload";if(uploadResponse=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},options?.httpOptions),{apiVersion:"",baseUrl:uploadUrl,headers:Object.assign(Object.assign({},((_h=options?.httpOptions)===null||_h===void 0?void 0:_h.headers)||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":`${offset}`})})}),offset=end,isFinal)break}let resJson;if(uploadResponse&&typeof uploadResponse.json=="function"?resJson=await uploadResponse.json():uploadResponse&&uploadResponse.responseInternal&&typeof uploadResponse.responseInternal.json=="function"&&(resJson=await uploadResponse.responseInternal.json()),resJson&&typeof resJson=="object"){if(Array.isArray(resJson.files))return resJson;if(resJson.name||resJson.path)return{files:[resJson]};if(resJson.file&&typeof resJson.file=="object")return{files:[resJson.file]}}return resJson}},GeminiNextGenEnvironments=class{constructor(parentClient){this.parentClient=parentClient,this.files=new GeminiNextGenEnvironmentFiles(apiVersion=>this.getClient(apiVersion),this.parentClient)}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(environmentsCreateEnvironment(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(environmentsListEnvironments(this.getClient(api_version),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(environmentsGetEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(environmentsDeleteEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenCredentials=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(credentialsCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(credentialsList(this.getClient(api_version),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(credentialsGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params,options){let{api_version,update_mask}=params,body=__rest(params,["api_version","update_mask"]);return unwrapWithSdkHttpResponse(credentialsUpdate(this.getClient(api_version),id,body,api_version,update_mask,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(credentialsDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};var GOOGLE_API_KEY_HEADER="x-goog-api-key",REQUIRED_VERTEX_AI_SCOPE="https://www.googleapis.com/auth/cloud-platform",NodeAuth=class{constructor(opts){if(opts.apiKey!==void 0){this.apiKey=opts.apiKey;return}let vertexAuthOptions=buildGoogleAuthOptions(opts.googleAuthOptions);this.googleAuth=new import_google_auth_library.GoogleAuth(vertexAuthOptions)}async addAuthHeaders(headers,url){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(headers);return}return this.addGoogleAuthHeaders(headers,url)}addKeyHeader(headers){if(headers.get(GOOGLE_API_KEY_HEADER)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");headers.append(GOOGLE_API_KEY_HEADER,this.apiKey)}}async addGoogleAuthHeaders(headers,url){if(this.googleAuth===void 0)throw new Error("Trying to set google-auth headers but googleAuth is unset");let authHeaders=await this.googleAuth.getRequestHeaders(url);for(let[key,value]of authHeaders)headers.get(key)===null&&headers.append(key,value)}};function buildGoogleAuthOptions(googleAuthOptions){let authOptions;if(googleAuthOptions){if(authOptions=googleAuthOptions,authOptions.scopes){if(typeof authOptions.scopes=="string"&&authOptions.scopes!==REQUIRED_VERTEX_AI_SCOPE||Array.isArray(authOptions.scopes)&&authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`)}else return authOptions.scopes=[REQUIRED_VERTEX_AI_SCOPE],authOptions;return authOptions}else return authOptions={scopes:[REQUIRED_VERTEX_AI_SCOPE]},authOptions}var NodeDownloader=class{async download(params,apiClient){if(params.downloadPath){let response=await downloadFile(params,apiClient);if(response instanceof HttpResponse){let writer=createWriteStream(params.downloadPath);Readable.fromWeb(response.responseInternal.body).pipe(writer),await finished(writer)}else try{await writeFile(params.downloadPath,response,{encoding:"base64"})}catch(error){throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`)}}}};async function downloadFile(params,apiClient){var _a2,_b,_c;let name=tFileName(params.file);if(name!==void 0)return await apiClient.request({path:`files/${name}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal});if(isGeneratedVideo(params.file)){let videoBytes=(_c=params.file.video)===null||_c===void 0?void 0:_c.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(isVideo(params.file)){let videoBytes=params.file.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var NodeWebSocketFactory=class{create(url,headers,callbacks){return new NodeWebSocket(url,headers,callbacks)}},NodeWebSocket=class{constructor(url,headers,callbacks){this.url=url,this.headers=headers,this.callbacks=callbacks}connect(){this.ws=new import_websocket.default(this.url,{headers:this.headers}),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(message){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(message)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function cancelTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function cancelTuningJobResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function contentToVertex(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createTuningJobConfigToMldev(fromObject,parentObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);if(parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromTunedModelDisplayName),getValueByPath(fromObject,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);if(fromLearningRateMultiplier!=null&&setValueByPath(toObject,["tuningTask","hyperparameters","learningRateMultiplier"],fromLearningRateMultiplier),getValueByPath(fromObject,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);if(parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","learningRate"],fromLearningRate),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function createTuningJobConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorValidationDataset=getValueByPath(rootObject,["config","method"]);if(discriminatorValidationDataset===void 0&&(discriminatorValidationDataset="SUPERVISED_FINE_TUNING"),discriminatorValidationDataset==="SUPERVISED_FINE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["supervisedTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="PREFERENCE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="DISTILLATION"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["distillationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="REINFORCEMENT_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["reinforcementTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let discriminatorEpochCount=getValueByPath(rootObject,["config","method"]);if(discriminatorEpochCount===void 0&&(discriminatorEpochCount="SUPERVISED_FINE_TUNING"),discriminatorEpochCount==="SUPERVISED_FINE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="PREFERENCE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="DISTILLATION"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="REINFORCEMENT_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","epochCount"],fromEpochCount)}let discriminatorLearningRateMultiplier=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRateMultiplier===void 0&&(discriminatorLearningRateMultiplier="SUPERVISED_FINE_TUNING"),discriminatorLearningRateMultiplier==="SUPERVISED_FINE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="PREFERENCE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="DISTILLATION"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="REINFORCEMENT_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}let discriminatorExportLastCheckpointOnly=getValueByPath(rootObject,["config","method"]);if(discriminatorExportLastCheckpointOnly===void 0&&(discriminatorExportLastCheckpointOnly="SUPERVISED_FINE_TUNING"),discriminatorExportLastCheckpointOnly==="SUPERVISED_FINE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["supervisedTuningSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="PREFERENCE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="DISTILLATION"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["distillationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}let discriminatorAdapterSize=getValueByPath(rootObject,["config","method"]);if(discriminatorAdapterSize===void 0&&(discriminatorAdapterSize="SUPERVISED_FINE_TUNING"),discriminatorAdapterSize==="SUPERVISED_FINE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="PREFERENCE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="DISTILLATION"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="REINFORCEMENT_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}let discriminatorTuningMode=getValueByPath(rootObject,["config","method"]);if(discriminatorTuningMode===void 0&&(discriminatorTuningMode="SUPERVISED_FINE_TUNING"),discriminatorTuningMode==="SUPERVISED_FINE_TUNING"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["supervisedTuningSpec","tuningMode"],fromTuningMode)}else if(discriminatorTuningMode==="DISTILLATION"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["distillationSpec","tuningMode"],fromTuningMode)}let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);parentObject!==void 0&&fromCustomBaseModel!=null&&setValueByPath(parentObject,["customBaseModel"],fromCustomBaseModel);let discriminatorBatchSize=getValueByPath(rootObject,["config","method"]);if(discriminatorBatchSize===void 0&&(discriminatorBatchSize="SUPERVISED_FINE_TUNING"),discriminatorBatchSize==="SUPERVISED_FINE_TUNING"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="DISTILLATION"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="REINFORCEMENT_TUNING"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","batchSize"],fromBatchSize)}let discriminatorLearningRate=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRate===void 0&&(discriminatorLearningRate="SUPERVISED_FINE_TUNING"),discriminatorLearningRate==="SUPERVISED_FINE_TUNING"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRate"],fromLearningRate)}else if(discriminatorLearningRate==="DISTILLATION"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRate"],fromLearningRate)}let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromBeta=getValueByPath(fromObject,["beta"]);parentObject!==void 0&&fromBeta!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","beta"],fromBeta);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);parentObject!==void 0&&fromBaseTeacherModel!=null&&setValueByPath(parentObject,["distillationSpec","baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);parentObject!==void 0&&fromTunedTeacherModelSource!=null&&setValueByPath(parentObject,["distillationSpec","tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromSftLossWeightMultiplier=getValueByPath(fromObject,["sftLossWeightMultiplier"]);parentObject!==void 0&&fromSftLossWeightMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],fromSftLossWeightMultiplier);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);parentObject!==void 0&&fromOutputUri!=null&&setValueByPath(parentObject,["outputUri"],fromOutputUri);let fromRewardConfig=getValueByPath(fromObject,["rewardConfig"]);parentObject!==void 0&&fromRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","singleRewardConfig"],fromRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);parentObject!==void 0&&fromCompositeRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","compositeRewardConfig"],fromCompositeRewardConfig);let fromSamplesPerPrompt=getValueByPath(fromObject,["samplesPerPrompt"]);parentObject!==void 0&&fromSamplesPerPrompt!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],fromSamplesPerPrompt);let fromEvaluateInterval=getValueByPath(fromObject,["evaluateInterval"]);parentObject!==void 0&&fromEvaluateInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],fromEvaluateInterval);let fromCheckpointInterval=getValueByPath(fromObject,["checkpointInterval"]);parentObject!==void 0&&fromCheckpointInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],fromCheckpointInterval);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],fromMaxOutputTokens);let fromThinkingLevel=getValueByPath(fromObject,["thinkingLevel"]);parentObject!==void 0&&fromThinkingLevel!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],fromThinkingLevel);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);parentObject!==void 0&&fromValidationDatasetUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","validationDatasetUri"],fromValidationDatasetUri);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);return parentObject!==void 0&&fromEncryptionSpec!=null&&setValueByPath(parentObject,["encryptionSpec"],fromEncryptionSpec),toObject}function createTuningJobParametersPrivateToMldev(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToMldev(fromTrainingDataset);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToMldev(fromConfig,toObject),toObject}function createTuningJobParametersPrivateToVertex(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToVertex(fromTrainingDataset,toObject,rootObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToVertex(fromConfig,toObject,rootObject),toObject}function distillationHyperParametersFromVertex(fromObject,rootObject){let toObject={},fromEpochCount=getValueByPath(fromObject,["epochCount"]);fromEpochCount!=null&&setValueByPath(toObject,["epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);fromLearningRateMultiplier!=null&&setValueByPath(toObject,["learningRateMultiplier"],fromLearningRateMultiplier);let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);fromAdapterSize!=null&&setValueByPath(toObject,["adapterSize"],fromAdapterSize);let fromBatchSize=getValueByPath(fromObject,["batchSize"]);fromBatchSize!=null&&setValueByPath(toObject,["batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);fromLearningRate!=null&&setValueByPath(toObject,["learningRate"],fromLearningRate);let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return fromGenerationConfig!=null&&setValueByPath(toObject,["generationConfig"],generationConfigFromVertex(fromGenerationConfig)),toObject}function distillationSamplingSpecFromVertex(fromObject,rootObject){let toObject={},fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromHyperparameters=getValueByPath(fromObject,["hyperparameters"]);return fromHyperparameters!=null&&setValueByPath(toObject,["hyperparameters"],distillationHyperParametersFromVertex(fromHyperparameters)),toObject}function distillationSpecFromVertex(fromObject,rootObject){let toObject={},fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromHyperParameters=getValueByPath(fromObject,["hyperParameters"]);fromHyperParameters!=null&&setValueByPath(toObject,["hyperParameters"],distillationHyperParametersFromVertex(fromHyperParameters));let fromPipelineRootDirectory=getValueByPath(fromObject,["pipelineRootDirectory"]);fromPipelineRootDirectory!=null&&setValueByPath(toObject,["pipelineRootDirectory"],fromPipelineRootDirectory);let fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromStudentModel=getValueByPath(fromObject,["studentModel"]);fromStudentModel!=null&&setValueByPath(toObject,["studentModel"],fromStudentModel);let fromTrainingDatasetUri=getValueByPath(fromObject,["trainingDatasetUri"]);fromTrainingDatasetUri!=null&&setValueByPath(toObject,["trainingDatasetUri"],fromTrainingDatasetUri);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);fromTuningMode!=null&&setValueByPath(toObject,["tuningMode"],fromTuningMode);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);return fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri),toObject}function generationConfigFromVertex(fromObject,_rootObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelSelectionConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],fromSpeechConfig);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);return fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),toObject}function getTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function getTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function listTuningJobsConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);return parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter),toObject}function listTuningJobsParametersToVertex(fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listTuningJobsConfigToVertex(fromConfig,toObject),toObject}function listTuningJobsResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromTuningJobs=getValueByPath(fromObject,["tuningJobs"]);if(fromTuningJobs!=null){let transformedList=fromTuningJobs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>tuningJobFromVertex(item))),setValueByPath(toObject,["tuningJobs"],transformedList)}return toObject}function partToVertex(fromObject,_rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function reinforcementTuningExampleToVertex(fromObject,rootObject){let toObject={},fromReferences=getValueByPath(fromObject,["references"]);fromReferences!=null&&setValueByPath(toObject,["references"],fromReferences);let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=fromContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex(item))),setValueByPath(toObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);return fromSystemInstruction!=null&&setValueByPath(toObject,["systemInstruction"],contentToVertex(fromSystemInstruction)),toObject}function tunedModelFromMldev(fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["name"]);fromModel!=null&&setValueByPath(toObject,["model"],fromModel);let fromEndpoint=getValueByPath(fromObject,["name"]);return fromEndpoint!=null&&setValueByPath(toObject,["endpoint"],fromEndpoint),toObject}function tuningDatasetToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromExamples=getValueByPath(fromObject,["examples"]);if(fromExamples!=null){let transformedList=fromExamples;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["examples","examples"],transformedList)}return toObject}function tuningDatasetToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorGcsUri=getValueByPath(rootObject,["config","method"]);if(discriminatorGcsUri===void 0&&(discriminatorGcsUri="SUPERVISED_FINE_TUNING"),discriminatorGcsUri==="SUPERVISED_FINE_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["supervisedTuningSpec","trainingDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="PREFERENCE_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","trainingDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="DISTILLATION"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["distillationSpec","promptDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="REINFORCEMENT_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","trainingDatasetUri"],fromGcsUri)}let discriminatorVertexDatasetResource=getValueByPath(rootObject,["config","method"]);if(discriminatorVertexDatasetResource===void 0&&(discriminatorVertexDatasetResource="SUPERVISED_FINE_TUNING"),discriminatorVertexDatasetResource==="SUPERVISED_FINE_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["supervisedTuningSpec","trainingDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="PREFERENCE_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","trainingDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="DISTILLATION"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["distillationSpec","promptDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="REINFORCEMENT_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","trainingDatasetUri"],fromVertexDatasetResource)}if(getValueByPath(fromObject,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tuningJobFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tTuningJobStatus(fromState));let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["tuningTask","startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["tuningTask","completeTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromTunedModel=getValueByPath(fromObject,["_self"]);return fromTunedModel!=null&&setValueByPath(toObject,["tunedModel"],tunedModelFromMldev(fromTunedModel)),toObject}function tuningJobFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tTuningJobStatus(fromState));let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["endTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromTunedModel=getValueByPath(fromObject,["tunedModel"]);fromTunedModel!=null&&setValueByPath(toObject,["tunedModel"],fromTunedModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromSupervisedTuningSpec=getValueByPath(fromObject,["supervisedTuningSpec"]);fromSupervisedTuningSpec!=null&&setValueByPath(toObject,["supervisedTuningSpec"],fromSupervisedTuningSpec);let fromPreferenceOptimizationSpec=getValueByPath(fromObject,["preferenceOptimizationSpec"]);fromPreferenceOptimizationSpec!=null&&setValueByPath(toObject,["preferenceOptimizationSpec"],fromPreferenceOptimizationSpec);let fromDistillationSamplingSpec=getValueByPath(fromObject,["distillationSamplingSpec"]);fromDistillationSamplingSpec!=null&&setValueByPath(toObject,["distillationSamplingSpec"],distillationSamplingSpecFromVertex(fromDistillationSamplingSpec));let fromDistillationSpec=getValueByPath(fromObject,["distillationSpec"]);fromDistillationSpec!=null&&setValueByPath(toObject,["distillationSpec"],distillationSpecFromVertex(fromDistillationSpec));let fromReinforcementTuningSpec=getValueByPath(fromObject,["reinforcementTuningSpec"]);fromReinforcementTuningSpec!=null&&setValueByPath(toObject,["reinforcementTuningSpec"],fromReinforcementTuningSpec);let fromTuningDataStats=getValueByPath(fromObject,["tuningDataStats"]);fromTuningDataStats!=null&&setValueByPath(toObject,["tuningDataStats"],fromTuningDataStats);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);fromEncryptionSpec!=null&&setValueByPath(toObject,["encryptionSpec"],fromEncryptionSpec);let fromPartnerModelTuningSpec=getValueByPath(fromObject,["partnerModelTuningSpec"]);fromPartnerModelTuningSpec!=null&&setValueByPath(toObject,["partnerModelTuningSpec"],fromPartnerModelTuningSpec);let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);fromCustomBaseModel!=null&&setValueByPath(toObject,["customBaseModel"],fromCustomBaseModel);let fromEvaluateDatasetRuns=getValueByPath(fromObject,["evaluateDatasetRuns"]);if(fromEvaluateDatasetRuns!=null){let transformedList=fromEvaluateDatasetRuns;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["evaluateDatasetRuns"],transformedList)}let fromExperiment=getValueByPath(fromObject,["experiment"]);fromExperiment!=null&&setValueByPath(toObject,["experiment"],fromExperiment);let fromFullFineTuningSpec=getValueByPath(fromObject,["fullFineTuningSpec"]);fromFullFineTuningSpec!=null&&setValueByPath(toObject,["fullFineTuningSpec"],fromFullFineTuningSpec);let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);fromOutputUri!=null&&setValueByPath(toObject,["outputUri"],fromOutputUri);let fromPipelineJob=getValueByPath(fromObject,["pipelineJob"]);fromPipelineJob!=null&&setValueByPath(toObject,["pipelineJob"],fromPipelineJob);let fromServiceAccount=getValueByPath(fromObject,["serviceAccount"]);fromServiceAccount!=null&&setValueByPath(toObject,["serviceAccount"],fromServiceAccount);let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);fromTunedModelDisplayName!=null&&setValueByPath(toObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromTuningJobMetadata=getValueByPath(fromObject,["tuningJobMetadata"]);fromTuningJobMetadata!=null&&setValueByPath(toObject,["tuningJobMetadata"],fromTuningJobMetadata);let fromTuningJobState=getValueByPath(fromObject,["tuningJobState"]);fromTuningJobState!=null&&setValueByPath(toObject,["tuningJobState"],fromTuningJobState);let fromVeoLoraTuningSpec=getValueByPath(fromObject,["veoLoraTuningSpec"]);fromVeoLoraTuningSpec!=null&&setValueByPath(toObject,["veoLoraTuningSpec"],fromVeoLoraTuningSpec);let fromVeoTuningSpec=getValueByPath(fromObject,["veoTuningSpec"]);return fromVeoTuningSpec!=null&&setValueByPath(toObject,["veoTuningSpec"],fromVeoTuningSpec),toObject}function tuningOperationFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function tuningValidationDatasetToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromGcsUri);let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);return fromVertexDatasetResource!=null&&setValueByPath(toObject,["validationDatasetUri"],fromVertexDatasetResource),toObject}function validateRewardParametersToVertex(fromObject,rootObject){let toObject={},fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["_url","parent"],fromParent);let fromSampleResponse=getValueByPath(fromObject,["sampleResponse"]);fromSampleResponse!=null&&setValueByPath(toObject,["sampleResponse"],contentToVertex(fromSampleResponse));let fromExample=getValueByPath(fromObject,["example"]);fromExample!=null&&setValueByPath(toObject,["example"],reinforcementTuningExampleToVertex(fromExample));let fromSingleRewardConfig=getValueByPath(fromObject,["singleRewardConfig"]);fromSingleRewardConfig!=null&&setValueByPath(toObject,["singleRewardConfig"],fromSingleRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);return fromCompositeRewardConfig!=null&&setValueByPath(toObject,["compositeRewardConfig"],fromCompositeRewardConfig),toObject}function validateRewardResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromOverallReward=getValueByPath(fromObject,["overallReward"]);fromOverallReward!=null&&setValueByPath(toObject,["overallReward"],fromOverallReward);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromRewardInfoDetails=getValueByPath(fromObject,["rewardInfoDetails"]);return fromRewardInfoDetails!=null&&setValueByPath(toObject,["rewardInfoDetails"],fromRewardInfoDetails),toObject}var Tunings=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS,x=>this.listInternal(x),await this.listInternal(params),params),this.get=async params=>await this.getInternal(params),this.tune=async params=>{var _a2;if(this.apiClient.isVertexAI())if(params.baseModel.startsWith("projects/")){let preTunedModel={tunedModelName:params.baseModel};!((_a2=params.config)===null||_a2===void 0)&&_a2.preTunedModelCheckpointId&&(preTunedModel.checkpointId=params.config.preTunedModelCheckpointId);let paramsPrivate=Object.assign(Object.assign({},params),{preTunedModel});return paramsPrivate.baseModel=void 0,await this.tuneInternal(paramsPrivate)}else{let paramsPrivate=Object.assign({},params);return await this.tuneInternal(paramsPrivate)}else{let paramsPrivate=Object.assign({},params),operation=await this.tuneMldevInternal(paramsPrivate),tunedModelName="";return operation.metadata!==void 0&&operation.metadata.tunedModel!==void 0?tunedModelName=operation.metadata.tunedModel:operation.name!==void 0&&operation.name.includes("/operations/")&&(tunedModelName=operation.name.split("/operations/")[0]),{name:tunedModelName,state:JobState.JOB_STATE_QUEUED}}}}async getInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getTuningJobParametersToVertex(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromVertex(apiResponse))}else{let body=getTuningJobParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromMldev(apiResponse))}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listTuningJobsParametersToVertex(params);return path2=formatMap("tuningJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listTuningJobsResponseFromVertex(apiResponse),typedResp=new ListTuningJobsResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=cancelTuningJobParametersToVertex(params);return path2=formatMap("{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=cancelTuningJobResponseFromVertex(apiResponse),typedResp=new CancelTuningJobResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=cancelTuningJobParametersToMldev(params);return path2=formatMap("{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=cancelTuningJobResponseFromMldev(apiResponse),typedResp=new CancelTuningJobResponse;return Object.assign(typedResp,resp),typedResp})}}async tuneInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createTuningJobParametersPrivateToVertex(params,params);return path2=formatMap("tuningJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromVertex(apiResponse))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createTuningJobParametersPrivateToMldev(params);return path2=formatMap("tunedModels",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningOperationFromMldev(apiResponse))}}async validateReward(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=validateRewardParametersToVertex(params);return path2=formatMap("{parent}/tuningJobs:validateReinforcementTuningReward",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=validateRewardResponseFromVertex(apiResponse),typedResp=new ValidateRewardResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},MAX_CHUNK_SIZE=1024*1024*8,MAX_RETRY_COUNT=3,INITIAL_RETRY_DELAY_MS=1e3,DELAY_MULTIPLIER=2,X_GOOG_UPLOAD_STATUS_HEADER_FIELD="x-goog-upload-status";async function uploadBlob(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await uploadBlobInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return responseJson.file}async function uploadBlobToFileSearchStore(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await uploadBlobInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let resp=uploadToFileSearchStoreOperationFromMldev(responseJson),typedResp=new UploadToFileSearchStoreOperation;return Object.assign(typedResp,resp),typedResp}async function uploadBlobInternal(file,uploadUrl,apiClient,httpOptions){var _a2,_b,_c;let finalUrl=uploadUrl,effectiveBaseUrl=httpOptions?.baseUrl||((_a2=apiClient.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl);if(effectiveBaseUrl){let baseUri=new URL(effectiveBaseUrl),uploadUri=new URL(uploadUrl);uploadUri.protocol=baseUri.protocol,uploadUri.host=baseUri.host,uploadUri.port=baseUri.port,finalUrl=uploadUri.toString()}let fileSize=0,offset=0,response=new HttpResponse(new Response),uploadCommand="upload";for(fileSize=file.size;offset<fileSize;){let chunkSize=Math.min(MAX_CHUNK_SIZE,fileSize-offset),chunk=file.slice(offset,offset+chunkSize);offset+chunkSize>=fileSize&&(uploadCommand+=", finalize");let retryCount=0,currentDelayMs=INITIAL_RETRY_DELAY_MS;for(;retryCount<MAX_RETRY_COUNT;){let mergedHeaders=Object.assign(Object.assign({},httpOptions?.headers||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":String(offset)});if(response=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},httpOptions),{apiVersion:"",baseUrl:finalUrl,headers:mergedHeaders})}),!((_b=response?.headers)===null||_b===void 0)&&_b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])break;retryCount++,await sleep(currentDelayMs),currentDelayMs=currentDelayMs*DELAY_MULTIPLIER}if(offset+=chunkSize,((_c=response?.headers)===null||_c===void 0?void 0:_c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="active")break;if(fileSize<=offset)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return response}async function getBlobStat(file){return{size:file.size,type:file.type}}function sleep(ms){return new Promise(resolvePromise=>setTimeout(resolvePromise,ms))}var NodeUploader=class{async stat(file){let fileStat={size:0,type:void 0};if(typeof file=="string"){let originalStat=await fs.stat(file);return fileStat.size=originalStat.size,fileStat.type=this.inferMimeType(file),fileStat}else return await getBlobStat(file)}async upload(file,uploadUrl,apiClient,httpOptions){return typeof file=="string"?await this.uploadFileFromPath(file,uploadUrl,apiClient,httpOptions):uploadBlob(file,uploadUrl,apiClient,httpOptions)}async uploadToFileSearchStore(file,uploadUrl,apiClient,httpOptions){return typeof file=="string"?await this.uploadFileToFileSearchStoreFromPath(file,uploadUrl,apiClient,httpOptions):uploadBlobToFileSearchStore(file,uploadUrl,apiClient,httpOptions)}inferMimeType(filePath){let fileExtension=filePath.slice(filePath.lastIndexOf(".")+1);return{aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"}[fileExtension.toLowerCase()]}async uploadFileFromPath(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await this.uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return responseJson.file}async uploadFileToFileSearchStoreFromPath(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await this.uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let resp=uploadToFileSearchStoreOperationFromMldev(responseJson),typedResp=new UploadToFileSearchStoreOperation;return Object.assign(typedResp,resp),typedResp}async uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions){var _a2,_b,_c;let finalUrl=uploadUrl,effectiveBaseUrl=httpOptions?.baseUrl||((_a2=apiClient.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl);if(effectiveBaseUrl){let baseUri=new URL(effectiveBaseUrl),uploadUri=new URL(uploadUrl);uploadUri.protocol=baseUri.protocol,uploadUri.host=baseUri.host,uploadUri.port=baseUri.port,finalUrl=uploadUri.toString()}let fileSize=0,offset=0,response=new HttpResponse(new Response),uploadCommand="upload",fileHandle,fileName=path.basename(file);try{if(fileHandle=await fs.open(file,"r"),!fileHandle)throw new Error("Failed to open file");for(fileSize=(await fileHandle.stat()).size;offset<fileSize;){let chunkSize=Math.min(MAX_CHUNK_SIZE,fileSize-offset);offset+chunkSize>=fileSize&&(uploadCommand+=", finalize");let buffer=new Uint8Array(chunkSize),{bytesRead}=await fileHandle.read(buffer,0,chunkSize,offset);if(bytesRead!==chunkSize)throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`);let chunk=new Blob([buffer]),retryCount=0,currentDelayMs=INITIAL_RETRY_DELAY_MS;for(;retryCount<MAX_RETRY_COUNT;){let mergedHeaders=Object.assign(Object.assign({},httpOptions?.headers||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":String(offset),"X-Goog-Upload-File-Name":fileName});if(response=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},httpOptions),{apiVersion:"",baseUrl:finalUrl,headers:mergedHeaders})}),!((_b=response?.headers)===null||_b===void 0)&&_b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])break;retryCount++,await sleep(currentDelayMs),currentDelayMs=currentDelayMs*DELAY_MULTIPLIER}if(offset+=bytesRead,((_c=response?.headers)===null||_c===void 0?void 0:_c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="active")break;if(fileSize<=offset)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return response}finally{fileHandle&&await fileHandle.close()}}};var NodeFiles=class extends Files$1{async registerFiles(params){if(typeof process>"u"||!process.versions||!process.versions.node)throw new Error("registerFiles is only supported in Node.js environments.");let authHeaders=await params.auth.getRequestHeaders(),config=params.config||{},httpOptions=config.httpOptions||{},headers=Object.assign({},httpOptions.headers||{});if(authHeaders)if(typeof authHeaders[Symbol.iterator]=="function")for(let[key,value]of authHeaders)headers[key]=value;else for(let[key,value]of Object.entries(authHeaders))headers[key]=value;return this._registerFiles({uris:params.uris,config:Object.assign(Object.assign({},config),{httpOptions:Object.assign(Object.assign({},httpOptions),{headers})})})}};var LANGUAGE_LABEL_PREFIX="gl-node/";function resolveCloudFlag(options){var _a2;if(options&&(options.enterprise!==void 0||options.vertexai!==void 0)){if(options.enterprise!==void 0&&options.vertexai!==void 0&&options.enterprise!==options.vertexai)throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(_a2=options.enterprise)!==null&&_a2!==void 0?_a2:options.vertexai}let envEnterpriseStr=getEnv("GOOGLE_GENAI_USE_ENTERPRISE"),envVertexaiStr=getEnv("GOOGLE_GENAI_USE_VERTEXAI"),useEnterpriseEnv=stringToBoolean(envEnterpriseStr),useVertexaiEnv=stringToBoolean(envVertexaiStr);return envEnterpriseStr!==void 0&&envVertexaiStr!==void 0&&useEnterpriseEnv!==useVertexaiEnv&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),envEnterpriseStr!==void 0?useEnterpriseEnv:envVertexaiStr!==void 0?useVertexaiEnv:!1}var GoogleGenAI2=class{getNextGenClient(){let httpOpts=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=buildGoogleGenAIClient(this.apiClient,{timeout_ms:httpOpts?.timeout})),httpOpts?.extraBody&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(this._interactions=new GeminiNextGenInteractions(this.apiClient),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new GeminiNextGenWebhooks(this.apiClient),this._webhooks)}get agents(){return this._agents!==void 0?this._agents:(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new GeminiNextGenAgents(this.apiClient),this._agents)}get triggers(){return this._triggers!==void 0?this._triggers:(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new GeminiNextGenTriggers(this.apiClient),this._triggers)}get environments(){return this._environments!==void 0?this._environments:(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new GeminiNextGenEnvironments(this.apiClient),this._environments)}get credentials(){return this._credentials!==void 0?this._credentials:(console.warn("GoogleGenAI.credentials: Credentials usage is experimental and may change in future versions."),this._credentials=new GeminiNextGenCredentials(this.apiClient),this._credentials)}constructor(options={}){var _a2,_b,_c,_d;if(this.vertexai=resolveCloudFlag(options),(options.project||options.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let envApiKey=getApiKeyFromEnv(),envProject=getEnv("GOOGLE_CLOUD_PROJECT"),envLocation=getEnv("GOOGLE_CLOUD_LOCATION");this.apiKey=(_a2=options.apiKey)!==null&&_a2!==void 0?_a2:envApiKey,this.project=(_b=options.project)!==null&&_b!==void 0?_b:envProject,this.location=(_c=options.location)!==null&&_c!==void 0?_c:envLocation,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((_d=options.googleAuthOptions)===null||_d===void 0)&&_d.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!options.project&&!options.location&&(envProject||envLocation)&&options.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(options.project||options.location)&&!options.apiKey&&envApiKey?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!options.project&&!options.location&&!options.apiKey&&(envProject||envLocation)&&envApiKey&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),!this.location&&!this.apiKey&&(this.location="global"));let baseUrl=getBaseUrl(options.httpOptions,this.vertexai,getEnv("GOOGLE_VERTEX_BASE_URL"),getEnv("GOOGLE_GEMINI_BASE_URL"));baseUrl&&(options.httpOptions?options.httpOptions.baseUrl=baseUrl:options.httpOptions={baseUrl}),this.apiVersion=options.apiVersion,this.httpOptions=options.httpOptions;let auth=new NodeAuth({apiKey:this.apiKey,googleAuthOptions:options.googleAuthOptions});this.apiClient=new ApiClient({auth,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:LANGUAGE_LABEL_PREFIX+process.version,uploader:new NodeUploader,downloader:new NodeDownloader}),this.models=new Models(this.apiClient),this.live=new Live(this.apiClient,auth,new NodeWebSocketFactory),this.batches=new Batches(this.apiClient),this.chats=new Chats(this.models,this.apiClient),this.caches=new Caches(this.apiClient),this.files=new NodeFiles(this.apiClient),this.operations=new Operations(this.apiClient),this.authTokens=new Tokens(this.apiClient),this.tunings=new Tunings(this.apiClient),this.fileSearchStores=new FileSearchStores(this.apiClient)}};function getEnv(env2){var _a2,_b,_c;return(_c=(_b=(_a2=process==null?void 0:process.env)===null||_a2===void 0?void 0:_a2[env2])===null||_b===void 0?void 0:_b.trim())!==null&&_c!==void 0?_c:void 0}function stringToBoolean(str){return str===void 0?!1:str.toLowerCase()==="true"}function getApiKeyFromEnv(){let envGoogleApiKey=getEnv("GOOGLE_API_KEY"),envGeminiApiKey=getEnv("GEMINI_API_KEY");return envGoogleApiKey&&envGeminiApiKey&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),envGoogleApiKey||envGeminiApiKey||void 0}var GOOGLE_SDK_THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH};function resolveGoogleThinkingLevel(model,level){let mapped=model.thinkingLevelMap?.[level],resolvedLevel=typeof mapped=="string"?mapped.toLowerCase():level;switch(resolvedLevel){case"minimal":case"low":case"medium":case"high":return resolvedLevel;default:throw new Error(`Unsupported Google thinking level mapping for ${model.provider}/${model.id}: ${level} -> ${String(mapped)}`)}}function usesGoogleThinkingLevel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(id)||isGoogleGeneration4OrLaterModelId(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"||/gemma-?4/.test(id)}function toGoogleThinkingLevel(level){switch(level){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function toGoogleSdkThinkingLevel(level){return GOOGLE_SDK_THINKING_LEVEL_MAP[level]}function getDisabledGoogleThinkingConfig(model){if(!usesGoogleThinkingLevel(model))return{thinkingBudget:0};let fallback=clampThinkingLevel(model,"off");if(fallback==="off")return{thinkingBudget:0};let resolvedLevel=resolveGoogleThinkingLevel(model,fallback),apiLevel=toGoogleThinkingLevel(resolvedLevel);return{thinkingLevel:toGoogleSdkThinkingLevel(apiLevel)}}function isThinkingPart(part){return part.thought===!0}function retainThoughtSignature(existing,incoming){return typeof incoming=="string"&&incoming.length>0?incoming:existing}var base64SignaturePattern=/^[A-Za-z0-9+/]+={0,2}$/;function isValidThoughtSignature(signature){return!signature||signature.length%4!==0?!1:base64SignaturePattern.test(signature)}function resolveThoughtSignature(isSameProviderAndModel,signature){return isSameProviderAndModel&&isValidThoughtSignature(signature)?signature:void 0}function requiresToolCallId(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return modelId.startsWith("claude-")||modelId.startsWith("gpt-oss-")||geminiMajorVersion!==void 0&&geminiMajorVersion>=3}function requiresThoughtSignatureReplay(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return geminiMajorVersion!==void 0&&geminiMajorVersion>=3}function getGeminiMajorVersion(modelId){let match2=modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(match2)return Number.parseInt(match2[1],10)}function supportsMultimodalFunctionResponse(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return geminiMajorVersion!==void 0?geminiMajorVersion>=3:!0}function appendContent(contents,content){let previous=contents[contents.length-1];if(previous?.role===content.role&&previous.parts&&content.parts){previous.parts.push(...content.parts);return}contents.push(content)}function findLastUserContentMessageIndex(messages){for(let i=messages.length-1;i>=0;i--){let msg=messages[i];if(msg.role==="user"){if(typeof msg.content=="string"){if(msg.content.trim().length>0)return i}else if(msg.content.some(item=>item.type==="text"?item.text.trim().length>0:!0))return i}}return-1}function convertMessages(model,context,options={}){let conversation=withoutInitialSystemMessage(collapseSystemMessages(context).messages),contents=[],textToolCallIds=new Set,transformedMessages=transformMessages(conversation,model,id=>requiresToolCallId(model.id)?normalizeToolCallId(id):id,{preserveThinking:options.preserveThinking}),lastUserContentIndex=findLastUserContentMessageIndex(transformedMessages);for(let msgIndex=0;msgIndex<transformedMessages.length;msgIndex++){let msg=transformedMessages[msgIndex];if(msg.role==="user")if(typeof msg.content=="string")appendContent(contents,{role:"user",parts:[{text:sanitizeSurrogates(msg.content)}]});else{let parts=msg.content.map(item=>item.type==="text"?{text:sanitizeSurrogates(item.text)}:{inlineData:{mimeType:item.mimeType,data:item.data}});if(parts.length===0)continue;appendContent(contents,{role:"user",parts})}else if(msg.role==="assistant"){let parts=[],isSameProviderAndModel=msg.provider===model.provider&&msg.model===model.id,isCurrentTurn=msgIndex>lastUserContentIndex,firstToolCall=msg.content.find(b=>b.type==="toolCall"),hasValidFirstSignature=firstToolCall!==void 0&&resolveThoughtSignature(isSameProviderAndModel,firstToolCall.thoughtSignature)!==void 0,replayUnsignedToolCallsAsText=requiresThoughtSignatureReplay(model.id)&&isCurrentTurn&&!hasValidFirstSignature;for(let block of msg.content)if(block.type==="text"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.textSignature);if((!block.text||block.text.trim()==="")&&!thoughtSignature)continue;parts.push({text:sanitizeSurrogates(block.text),...thoughtSignature&&{thoughtSignature}})}else if(block.type==="thinking")if(isSameProviderAndModel){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thinkingSignature);if((!block.thinking||block.thinking.trim()==="")&&!thoughtSignature)continue;parts.push({thought:!0,text:sanitizeSurrogates(block.thinking),...thoughtSignature&&{thoughtSignature}})}else{if(!block.thinking||block.thinking.trim()==="")continue;parts.push({text:sanitizeSurrogates(block.thinking)})}else if(block.type==="toolCall")if(replayUnsignedToolCallsAsText)textToolCallIds.add(block.id),parts.push({text:sanitizeSurrogates(`[Tool Call: ${block.name} (id: ${block.id})]
Arguments: ${JSON.stringify(block.arguments??{},null,2)}`)});else{let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thoughtSignature),part={functionCall:{name:block.name,args:block.arguments??{},...requiresToolCallId(model.id)?{id:block.id}:{}},...thoughtSignature&&{thoughtSignature}};parts.push(part)}else block.type;if(parts.length===0)continue;appendContent(contents,{role:"model",parts})}else if(msg.role==="toolResult"){let textResult=msg.content.filter(c=>c.type==="text").map(c=>c.text).join(`
`),allImageBlocks=msg.content.filter(c=>c.type==="image"),imageContent=model.input.includes("image")?allImageBlocks:[],imageParts=imageContent.map(imageBlock=>({inlineData:{mimeType:imageBlock.mimeType,data:imageBlock.data}})),sanitizedToolName=sanitizeSurrogates(msg.toolName);if(textToolCallIds.has(msg.toolCallId)){let bodyText="";textResult.length>0?bodyText=`
${sanitizeSurrogates(textResult)}`:allImageBlocks.length===0&&(bodyText=`
(no output)`);let errorMarker=msg.isError?" (error)":"",callIdPart=` (id: ${msg.toolCallId})`;appendContent(contents,{role:"user",parts:[{text:`[Tool Result: ${sanitizedToolName}${callIdPart}]${errorMarker}${bodyText}`},...imageParts]});continue}let hasText=textResult.length>0,hasImages=imageContent.length>0,modelSupportsMultimodalFunctionResponse=supportsMultimodalFunctionResponse(model.id),responseValue=hasText?sanitizeSurrogates(textResult):hasImages?"(see attached image)":"",includeId=requiresToolCallId(model.id),functionResponsePart={functionResponse:{name:sanitizedToolName,response:msg.isError?{error:responseValue}:{output:responseValue},...hasImages&&modelSupportsMultimodalFunctionResponse&&{parts:imageParts},...includeId?{id:msg.toolCallId}:{}}};appendContent(contents,{role:"user",parts:[functionResponsePart]}),hasImages&&!modelSupportsMultimodalFunctionResponse&&appendContent(contents,{role:"user",parts:[{text:"Tool result image:"},...imageParts]})}}return contents}function dominantPartKey(part){return Object.entries(part).find(([,value])=>value!=null)?.[0]??"unknown"}function toProviderNativeContent(part){return part.executableCode!==void 0?{type:"providerNative",subtype:"executableCode",raw:{executableCode:part.executableCode}}:part.codeExecutionResult!==void 0?{type:"providerNative",subtype:"codeExecutionResult",raw:{codeExecutionResult:part.codeExecutionResult}}:{type:"providerNative",subtype:dominantPartKey(part),raw:part}}var JSON_SCHEMA_META_DECLARATIONS=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function sanitizeForOpenApi(schema){if(typeof schema!="object"||schema===null)return schema;if(Array.isArray(schema))return schema.map(sanitizeForOpenApi);let result={};for(let[key,value]of Object.entries(schema))JSON_SCHEMA_META_DECLARATIONS.has(key)||(result[key]=sanitizeForOpenApi(value));return result}var SCHEMA_VALUE_KEYWORDS=new Set(["const","default","examples","enum"]),SCHEMA_MAP_KEYS_STRIP=new Set(["properties","patternProperties","$defs","definitions"]);function stripOptional(schema){if(typeof schema!="object"||schema===null)return schema;if(Array.isArray(schema))return schema.map(stripOptional);let result={};for(let[key,value]of Object.entries(schema))if(key!=="optional"){if(SCHEMA_VALUE_KEYWORDS.has(key)){result[key]=value;continue}if(SCHEMA_MAP_KEYS_STRIP.has(key)&&typeof value=="object"&&value!==null&&!Array.isArray(value)){let map={};for(let[name,subschema]of Object.entries(value))map[name]=stripOptional(subschema);result[key]=map;continue}result[key]=stripOptional(value)}return result}function convertTools(tools,useParameters=!1,supportsStrictMode=!0){if(tools.length!==0)return[{functionDeclarations:tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode),parameters=getJsonSchemaToolParameters(tool,strict);return{name:tool.name,description:tool.description,...useParameters?{parameters:stripOptional(sanitizeForOpenApi(parameters))}:{parametersJsonSchema:stripOptional(parameters)}}})}]}function supportsGoogleStrictToolSampling(modelId){let majorVersion=getGeminiMajorVersion(modelId);return majorVersion!==void 0&&majorVersion>=3}function mapToolChoice(choice){switch(choice){case"auto":return FunctionCallingConfigMode.AUTO;case"none":return FunctionCallingConfigMode.NONE;case"any":return FunctionCallingConfigMode.ANY;default:return FunctionCallingConfigMode.AUTO}}function resolveGoogleFunctionCallingMode(tools,toolChoice,supportsStrictMode){let useStrictMode=tools.some(tool=>resolveJsonSchemaStrictSampling(tool,supportsStrictMode)===!0);return toolChoice==="none"||toolChoice==="any"?mapToolChoice(toolChoice):useStrictMode?FunctionCallingConfigMode.VALIDATED:toolChoice?mapToolChoice(toolChoice):void 0}function mapStopReason(reason){switch(reason){case FinishReason.STOP:return"stop";case FinishReason.MAX_TOKENS:return"length";case FinishReason.BLOCKLIST:case FinishReason.PROHIBITED_CONTENT:case FinishReason.SPII:case FinishReason.SAFETY:case FinishReason.IMAGE_SAFETY:case FinishReason.IMAGE_PROHIBITED_CONTENT:case FinishReason.IMAGE_RECITATION:case FinishReason.IMAGE_OTHER:case FinishReason.RECITATION:case FinishReason.FINISH_REASON_UNSPECIFIED:case FinishReason.OTHER:case FinishReason.LANGUAGE:case FinishReason.MALFORMED_FUNCTION_CALL:case FinishReason.UNEXPECTED_TOOL_CALL:case FinishReason.TOO_MANY_TOOL_CALLS:case FinishReason.NO_IMAGE:return"error";default:{let _exhaustive=reason;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}function retryGoogleRequest(request,options){return retryProviderRequest(async()=>{try{return await request()}catch(error){throw error instanceof Error&&"status"in error&&!("headers"in error)&&(error.headers=void 0),error}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal})}export{ResourceScope,GoogleGenAI2 as GoogleGenAI,resolveGoogleThinkingLevel,usesGoogleThinkingLevel,toGoogleThinkingLevel,toGoogleSdkThinkingLevel,getDisabledGoogleThinkingConfig,isThinkingPart,retainThoughtSignature,convertMessages,toProviderNativeContent,convertTools,supportsGoogleStrictToolSampling,resolveGoogleFunctionCallingMode,mapStopReason,retryGoogleRequest};