import{s as re}from"./sanitize-unicode-B62XMGgN.js";import{t as ii}from"./transform-messages-DSNYjDRn.js";function ri(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ge={exports:{}},qe={},Be,yt;function si(){if(yt)return Be;yt=1;function t(e,n){typeof n=="boolean"&&(n={forever:n}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=n||{},this._maxRetryTime=n&&n.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Be=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var n=new Date().getTime();if(e&&n-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var o=this._timeouts.shift();if(o===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),o=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},o),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,n){this._fn=e,n&&(n.timeout&&(this._operationTimeout=n.timeout),n.cb&&(this._operationTimeoutCb=n.cb));var o=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){o._operationTimeoutCb()},o._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},n=null,o=0,r=0;r=o&&(n=l,o=u)}return n},Be}var Tt;function li(){return Tt||(Tt=1,(function(t){var e=si();t.operation=function(n){var o=t.timeouts(n);return new e(o,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},t.timeouts=function(n){if(n instanceof Array)return[].concat(n);var o={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var r in n)o[r]=n[r];if(o.minTimeout>o.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var l=[],a=0;a{const d=c.retries-(u-1);return a.attemptNumber=u,a.retriesLeft=d,a},r=a=>e.includes(a),l=(a,u)=>new Promise((c,d)=>{u={onFailedAttempt:()=>{},retries:10,...u};const f=t.operation(u);f.attempt(async p=>{try{c(await a(p))}catch(h){if(!(h instanceof Error)){d(new TypeError(`Non-error was thrown: "${h}". You should only throw errors.`));return}if(h instanceof n)f.stop(),d(h.originalError);else if(h instanceof TypeError&&!r(h.message))f.stop(),d(h);else{o(h,p,u);try{await u.onFailedAttempt(h)}catch(m){d(m);return}f.retry(h)||d(f.mainError())}}})});return ge.exports=l,ge.exports.default=l,ge.exports.AbortError=n,ge.exports}var uo=ui();const di=ri(uo);var ci={};let fi,pi;function hi(){return{geminiUrl:fi,vertexUrl:pi}}function mi(t,e,n,o){var r,l;if(!t?.baseUrl){const a=hi();return e?(r=a.vertexUrl)!==null&&r!==void 0?r:n:(l=a.geminiUrl)!==null&&l!==void 0?l:o}return t.baseUrl}class Q{}function _(t,e){const n=/\{([^}]+)\}/g;return t.replace(n,(o,r)=>{if(Object.prototype.hasOwnProperty.call(e,r)){const l=e[r];return l!=null?String(l):""}else throw new Error(`Key '${r}' not found in valueMap.`)})}function s(t,e,n){for(let l=0;l({}));else throw new Error(`Value must be a list given an array path ${a}`);if(Array.isArray(t[u])){const c=t[u];if(Array.isArray(n))for(let d=0;di(u,e.slice(o+1),n)):n}else return n}else t=t[r]}return t}catch(o){if(o instanceof TypeError)return n;throw o}}function gi(t,e){for(const[n,o]of Object.entries(e)){const r=n.split("."),l=o.split("."),a=new Set;let u=-1;for(let c=0;cu)for(let c=u;c=e.length||typeof t!="object"||t===null)return;const l=e[o];if(l.endsWith("[]")){const a=l.slice(0,-2),u=t;if(a in u&&Array.isArray(u[a]))for(const c of u[a])We(c,e,n,o+1,r)}else if(l==="*"){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){const a=t,u=Object.keys(a).filter(d=>!d.startsWith("_")&&!r.has(d)),c={};for(const d of u)c[d]=a[d];for(const[d,f]of Object.entries(c)){const p=[];for(const h of n.slice(o))h==="*"?p.push(d):p.push(h);s(a,p,f)}for(const d of u)delete a[d]}}else{const a=t;l in a&&We(a[l],e,n,o+1,r)}}function at(t){if(typeof t!="string")throw new Error("fromImageBytes must be a string");return t}function Ei(t){const e={},n=i(t,["operationName"]);n!=null&&s(e,["operationName"],n);const o=i(t,["resourceName"]);return o!=null&&s(e,["_url","resourceName"],o),e}function vi(t){const e={},n=i(t,["name"]);n!=null&&s(e,["name"],n);const o=i(t,["metadata"]);o!=null&&s(e,["metadata"],o);const r=i(t,["done"]);r!=null&&s(e,["done"],r);const l=i(t,["error"]);l!=null&&s(e,["error"],l);const a=i(t,["response","generateVideoResponse"]);return a!=null&&s(e,["response"],Ti(a)),e}function yi(t){const e={},n=i(t,["name"]);n!=null&&s(e,["name"],n);const o=i(t,["metadata"]);o!=null&&s(e,["metadata"],o);const r=i(t,["done"]);r!=null&&s(e,["done"],r);const l=i(t,["error"]);l!=null&&s(e,["error"],l);const a=i(t,["response"]);return a!=null&&s(e,["response"],_i(a)),e}function Ti(t){const e={},n=i(t,["generatedSamples"]);if(n!=null){let l=n;Array.isArray(l)&&(l=l.map(a=>Ii(a))),s(e,["generatedVideos"],l)}const o=i(t,["raiMediaFilteredCount"]);o!=null&&s(e,["raiMediaFilteredCount"],o);const r=i(t,["raiMediaFilteredReasons"]);return r!=null&&s(e,["raiMediaFilteredReasons"],r),e}function _i(t){const e={},n=i(t,["videos"]);if(n!=null){let l=n;Array.isArray(l)&&(l=l.map(a=>Ci(a))),s(e,["generatedVideos"],l)}const o=i(t,["raiMediaFilteredCount"]);o!=null&&s(e,["raiMediaFilteredCount"],o);const r=i(t,["raiMediaFilteredReasons"]);return r!=null&&s(e,["raiMediaFilteredReasons"],r),e}function Ii(t){const e={},n=i(t,["video"]);return n!=null&&s(e,["video"],wi(n)),e}function Ci(t){const e={},n=i(t,["_self"]);return n!=null&&s(e,["video"],Mi(n)),e}function Ai(t){const e={},n=i(t,["operationName"]);return n!=null&&s(e,["_url","operationName"],n),e}function Si(t){const e={},n=i(t,["operationName"]);return n!=null&&s(e,["_url","operationName"],n),e}function Ri(t){const e={},n=i(t,["name"]);n!=null&&s(e,["name"],n);const o=i(t,["metadata"]);o!=null&&s(e,["metadata"],o);const r=i(t,["done"]);r!=null&&s(e,["done"],r);const l=i(t,["error"]);l!=null&&s(e,["error"],l);const a=i(t,["response"]);return a!=null&&s(e,["response"],Pi(a)),e}function Pi(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["parent"]);o!=null&&s(e,["parent"],o);const r=i(t,["documentName"]);return r!=null&&s(e,["documentName"],r),e}function co(t){const e={},n=i(t,["name"]);n!=null&&s(e,["name"],n);const o=i(t,["metadata"]);o!=null&&s(e,["metadata"],o);const r=i(t,["done"]);r!=null&&s(e,["done"],r);const l=i(t,["error"]);l!=null&&s(e,["error"],l);const a=i(t,["response"]);return a!=null&&s(e,["response"],Ni(a)),e}function Ni(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["parent"]);o!=null&&s(e,["parent"],o);const r=i(t,["documentName"]);return r!=null&&s(e,["documentName"],r),e}function wi(t){const e={},n=i(t,["uri"]);n!=null&&s(e,["uri"],n);const o=i(t,["encodedVideo"]);o!=null&&s(e,["videoBytes"],at(o));const r=i(t,["encoding"]);return r!=null&&s(e,["mimeType"],r),e}function Mi(t){const e={},n=i(t,["gcsUri"]);n!=null&&s(e,["uri"],n);const o=i(t,["bytesBase64Encoded"]);o!=null&&s(e,["videoBytes"],at(o));const r=i(t,["mimeType"]);return r!=null&&s(e,["mimeType"],r),e}var Ct;(function(t){t.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",t.PYTHON="PYTHON"})(Ct||(Ct={}));var At;(function(t){t.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",t.OUTCOME_OK="OUTCOME_OK",t.OUTCOME_FAILED="OUTCOME_FAILED",t.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(At||(At={}));var St;(function(t){t.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",t.SILENT="SILENT",t.WHEN_IDLE="WHEN_IDLE",t.INTERRUPT="INTERRUPT"})(St||(St={}));var j;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.STRING="STRING",t.NUMBER="NUMBER",t.INTEGER="INTEGER",t.BOOLEAN="BOOLEAN",t.ARRAY="ARRAY",t.OBJECT="OBJECT",t.NULL="NULL"})(j||(j={}));var Rt;(function(t){t.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",t.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(Rt||(Rt={}));var Pt;(function(t){t.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",t.NO_AUTH="NO_AUTH",t.API_KEY_AUTH="API_KEY_AUTH",t.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",t.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",t.OAUTH="OAUTH",t.OIDC_AUTH="OIDC_AUTH"})(Pt||(Pt={}));var Nt;(function(t){t.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",t.HTTP_IN_QUERY="HTTP_IN_QUERY",t.HTTP_IN_HEADER="HTTP_IN_HEADER",t.HTTP_IN_PATH="HTTP_IN_PATH",t.HTTP_IN_BODY="HTTP_IN_BODY",t.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(Nt||(Nt={}));var wt;(function(t){t.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",t.SIMPLE_SEARCH="SIMPLE_SEARCH",t.ELASTIC_SEARCH="ELASTIC_SEARCH"})(wt||(wt={}));var Mt;(function(t){t.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",t.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",t.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",t.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(Mt||(Mt={}));var Dt;(function(t){t.UNSPECIFIED="UNSPECIFIED",t.BLOCKING="BLOCKING",t.NON_BLOCKING="NON_BLOCKING"})(Dt||(Dt={}));var xt;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(xt||(xt={}));var se;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE",t.VALIDATED="VALIDATED"})(se||(se={}));var Ut;(function(t){t.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",t.MINIMAL="MINIMAL",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Ut||(Ut={}));var Lt;(function(t){t.DONT_ALLOW="DONT_ALLOW",t.ALLOW_ADULT="ALLOW_ADULT",t.ALLOW_ALL="ALLOW_ALL"})(Lt||(Lt={}));var Gt;(function(t){t.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",t.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",t.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(Gt||(Gt={}));var kt;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",t.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",t.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",t.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",t.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"})(kt||(kt={}));var Ft;(function(t){t.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",t.SEVERITY="SEVERITY",t.PROBABILITY="PROBABILITY"})(Ft||(Ft={}));var Vt;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE",t.OFF="OFF"})(Vt||(Vt={}));var L;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.IMAGE_SAFETY="IMAGE_SAFETY",t.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",t.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",t.NO_IMAGE="NO_IMAGE",t.IMAGE_RECITATION="IMAGE_RECITATION",t.IMAGE_OTHER="IMAGE_OTHER"})(L||(L={}));var Ht;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Ht||(Ht={}));var qt;(function(t){t.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",t.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",t.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",t.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",t.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(qt||(qt={}));var Bt;(function(t){t.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",t.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",t.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",t.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",t.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(Bt||(Bt={}));var Jt;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.IMAGE_SAFETY="IMAGE_SAFETY",t.MODEL_ARMOR="MODEL_ARMOR",t.JAILBREAK="JAILBREAK"})(Jt||(Jt={}));var bt;(function(t){t.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",t.ON_DEMAND="ON_DEMAND",t.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",t.ON_DEMAND_FLEX="ON_DEMAND_FLEX",t.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(bt||(bt={}));var Re;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.AUDIO="AUDIO",t.VIDEO="VIDEO"})(Re||(Re={}));var $t;(function(t){t.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",t.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",t.EXPERIMENTAL="EXPERIMENTAL",t.PREVIEW="PREVIEW",t.STABLE="STABLE",t.LEGACY="LEGACY",t.DEPRECATED="DEPRECATED",t.RETIRED="RETIRED"})($t||($t={}));var Ot;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(Ot||(Ot={}));var Yt;(function(t){t.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",t.TUNING_MODE_FULL="TUNING_MODE_FULL",t.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(Yt||(Yt={}));var Kt;(function(t){t.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",t.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",t.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",t.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",t.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",t.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",t.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(Kt||(Kt={}));var ze;(function(t){t.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",t.JOB_STATE_QUEUED="JOB_STATE_QUEUED",t.JOB_STATE_PENDING="JOB_STATE_PENDING",t.JOB_STATE_RUNNING="JOB_STATE_RUNNING",t.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",t.JOB_STATE_FAILED="JOB_STATE_FAILED",t.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",t.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",t.JOB_STATE_PAUSED="JOB_STATE_PAUSED",t.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",t.JOB_STATE_UPDATING="JOB_STATE_UPDATING",t.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(ze||(ze={}));var Wt;(function(t){t.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",t.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",t.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",t.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",t.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",t.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(Wt||(Wt={}));var zt;(function(t){t.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",t.AVERAGE="AVERAGE",t.MODE="MODE",t.STANDARD_DEVIATION="STANDARD_DEVIATION",t.VARIANCE="VARIANCE",t.MINIMUM="MINIMUM",t.MAXIMUM="MAXIMUM",t.MEDIAN="MEDIAN",t.PERCENTILE_P90="PERCENTILE_P90",t.PERCENTILE_P95="PERCENTILE_P95",t.PERCENTILE_P99="PERCENTILE_P99"})(zt||(zt={}));var Xt;(function(t){t.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",t.BASELINE="BASELINE",t.CANDIDATE="CANDIDATE",t.TIE="TIE"})(Xt||(Xt={}));var Qt;(function(t){t.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",t.TUNING_TASK_I2V="TUNING_TASK_I2V",t.TUNING_TASK_T2V="TUNING_TASK_T2V",t.TUNING_TASK_R2V="TUNING_TASK_R2V"})(Qt||(Qt={}));var Zt;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.STATE_PENDING="STATE_PENDING",t.STATE_ACTIVE="STATE_ACTIVE",t.STATE_FAILED="STATE_FAILED"})(Zt||(Zt={}));var jt;(function(t){t.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",t.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",t.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",t.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",t.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(jt||(jt={}));var en;(function(t){t.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",t.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",t.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",t.URL_CONTEXT="URL_CONTEXT",t.GOOGLE_MAPS="GOOGLE_MAPS",t.FILE_SEARCH="FILE_SEARCH"})(en||(en={}));var Xe;(function(t){t.COLLECTION="COLLECTION"})(Xe||(Xe={}));var tn;(function(t){t.UNSPECIFIED="unspecified",t.FLEX="flex",t.STANDARD="standard",t.PRIORITY="priority"})(tn||(tn={}));var nn;(function(t){t.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",t.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",t.BALANCED="BALANCED",t.PRIORITIZE_COST="PRIORITIZE_COST"})(nn||(nn={}));var Pe;(function(t){t.PREDICT="PREDICT",t.EMBED_CONTENT="EMBED_CONTENT"})(Pe||(Pe={}));var on;(function(t){t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(on||(on={}));var rn;(function(t){t.auto="auto",t.en="en",t.ja="ja",t.ko="ko",t.hi="hi",t.zh="zh",t.pt="pt",t.es="es"})(rn||(rn={}));var sn;(function(t){t.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",t.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",t.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",t.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",t.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(sn||(sn={}));var ln;(function(t){t.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",t.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",t.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",t.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(ln||(ln={}));var an;(function(t){t.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",t.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",t.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",t.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(an||(an={}));var un;(function(t){t.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",t.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",t.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",t.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",t.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",t.EDIT_MODE_STYLE="EDIT_MODE_STYLE",t.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",t.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(un||(un={}));var dn;(function(t){t.FOREGROUND="FOREGROUND",t.BACKGROUND="BACKGROUND",t.PROMPT="PROMPT",t.SEMANTIC="SEMANTIC",t.INTERACTIVE="INTERACTIVE"})(dn||(dn={}));var cn;(function(t){t.ASSET="ASSET",t.STYLE="STYLE"})(cn||(cn={}));var fn;(function(t){t.INSERT="INSERT",t.REMOVE="REMOVE",t.REMOVE_STATIC="REMOVE_STATIC",t.OUTPAINT="OUTPAINT"})(fn||(fn={}));var pn;(function(t){t.OPTIMIZED="OPTIMIZED",t.LOSSLESS="LOSSLESS"})(pn||(pn={}));var hn;(function(t){t.CROP="CROP",t.PAD="PAD"})(hn||(hn={}));var mn;(function(t){t.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",t.PREFERENCE_TUNING="PREFERENCE_TUNING",t.DISTILLATION="DISTILLATION"})(mn||(mn={}));var gn;(function(t){t.STATE_UNSPECIFIED="STATE_UNSPECIFIED",t.PROCESSING="PROCESSING",t.ACTIVE="ACTIVE",t.FAILED="FAILED"})(gn||(gn={}));var En;(function(t){t.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",t.UPLOADED="UPLOADED",t.GENERATED="GENERATED",t.REGISTERED="REGISTERED"})(En||(En={}));var vn;(function(t){t.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.RESPONSE_REJECTED="RESPONSE_REJECTED",t.NEED_MORE_INPUT="NEED_MORE_INPUT",t.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",t.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",t.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",t.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",t.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",t.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",t.INPUT_OTHER="INPUT_OTHER",t.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",t.BLOCKLIST="BLOCKLIST",t.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",t.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",t.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",t.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",t.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",t.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",t.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",t.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",t.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",t.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",t.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",t.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",t.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",t.GENERATED_OTHER="GENERATED_OTHER",t.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(vn||(vn={}));var yn;(function(t){t.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",t.TEXT="TEXT",t.IMAGE="IMAGE",t.VIDEO="VIDEO",t.AUDIO="AUDIO",t.DOCUMENT="DOCUMENT"})(yn||(yn={}));var Tn;(function(t){t.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",t.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",t.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(Tn||(Tn={}));var _n;(function(t){t.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",t.ACTIVITY_START="ACTIVITY_START",t.ACTIVITY_END="ACTIVITY_END"})(_n||(_n={}));var In;(function(t){t.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",t.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",t.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(In||(In={}));var Cn;(function(t){t.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",t.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",t.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(Cn||(Cn={}));var An;(function(t){t.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",t.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",t.NO_INTERRUPTION="NO_INTERRUPTION"})(An||(An={}));var Sn;(function(t){t.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",t.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",t.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",t.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(Sn||(Sn={}));var Rn;(function(t){t.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",t.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",t.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",t.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",t.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",t.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",t.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",t.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",t.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",t.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",t.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",t.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",t.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(Rn||(Rn={}));var Pn;(function(t){t.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",t.QUALITY="QUALITY",t.DIVERSITY="DIVERSITY",t.VOCALIZATION="VOCALIZATION"})(Pn||(Pn={}));var le;(function(t){t.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",t.PLAY="PLAY",t.PAUSE="PAUSE",t.STOP="STOP",t.RESET_CONTEXT="RESET_CONTEXT"})(le||(le={}));class Ne{constructor(e){const n={};for(const o of e.headers.entries())n[o[0]]=o[1];this.headers=n,this.responseInternal=e}json(){return this.responseInternal.json()}}class Ee{get text(){var e,n,o,r,l,a,u,c;if(((r=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||r===void 0?void 0:r.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 d="",f=!1;const p=[];for(const h of(c=(u=(a=(l=this.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(const[m,g]of Object.entries(h))m!=="text"&&m!=="thought"&&m!=="thoughtSignature"&&(g!==null||g!==void 0)&&p.push(m);if(typeof h.text=="string"){if(typeof h.thought=="boolean"&&h.thought)continue;f=!0,d+=h.text}}return p.length>0&&console.warn(`there are non-text parts ${p} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),f?d:void 0}get data(){var e,n,o,r,l,a,u,c;if(((r=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||r===void 0?void 0:r.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 d="";const f=[];for(const p of(c=(u=(a=(l=this.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)!==null&&c!==void 0?c:[]){for(const[h,m]of Object.entries(p))h!=="inlineData"&&(m!==null||m!==void 0)&&f.push(h);p.inlineData&&typeof p.inlineData.data=="string"&&(d+=atob(p.inlineData.data))}return f.length>0&&console.warn(`there are non-data parts ${f} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),d.length>0?btoa(d):void 0}get functionCalls(){var e,n,o,r,l,a,u,c;if(((r=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||r===void 0?void 0:r.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");const d=(c=(u=(a=(l=this.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(f=>f.functionCall).map(f=>f.functionCall).filter(f=>f!==void 0);if(d?.length!==0)return d}get executableCode(){var e,n,o,r,l,a,u,c,d;if(((r=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||r===void 0?void 0:r.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");const f=(c=(u=(a=(l=this.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(p=>p.executableCode).map(p=>p.executableCode).filter(p=>p!==void 0);if(f?.length!==0)return(d=f?.[0])===null||d===void 0?void 0:d.code}get codeExecutionResult(){var e,n,o,r,l,a,u,c,d;if(((r=(o=(n=(e=this.candidates)===null||e===void 0?void 0:e[0])===null||n===void 0?void 0:n.content)===null||o===void 0?void 0:o.parts)===null||r===void 0?void 0:r.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");const f=(c=(u=(a=(l=this.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content)===null||u===void 0?void 0:u.parts)===null||c===void 0?void 0:c.filter(p=>p.codeExecutionResult).map(p=>p.codeExecutionResult).filter(p=>p!==void 0);if(f?.length!==0)return(d=f?.[0])===null||d===void 0?void 0:d.output}}class Nn{}class wn{}class Di{}class xi{}class Ui{}class Li{}class Mn{}class Dn{}class xn{}class Gi{}class we{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const o=new we;let r;const l=e;return n?r=yi(l):r=vi(l),Object.assign(o,r),o}}class ki{}class Un{}class Ln{}class Gn{}class Fi{}class Vi{}class Hi{}class ut{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const o=new ut,l=Ri(e);return Object.assign(o,l),o}}class qi{}class Bi{}class Ji{}class bi{}class kn{}class $i{get text(){var e,n,o;let r="",l=!1;const a=[];for(const u of(o=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&o!==void 0?o:[]){for(const[c,d]of Object.entries(u))c!=="text"&&c!=="thought"&&d!==null&&a.push(c);if(typeof u.text=="string"){if(typeof u.thought=="boolean"&&u.thought)continue;l=!0,r+=u.text}}return a.length>0&&console.warn(`there are non-text parts ${a} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),l?r:void 0}get data(){var e,n,o;let r="";const l=[];for(const a of(o=(n=(e=this.serverContent)===null||e===void 0?void 0:e.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&o!==void 0?o:[]){for(const[u,c]of Object.entries(a))u!=="inlineData"&&c!==null&&l.push(u);a.inlineData&&typeof a.inlineData.data=="string"&&(r+=atob(a.inlineData.data))}return l.length>0&&console.warn(`there are non-data parts ${l} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),r.length>0?btoa(r):void 0}}class Oi{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class dt{_fromAPIResponse({apiResponse:e,_isVertexAI:n}){const o=new dt,l=co(e);return Object.assign(o,l),o}}function D(t,e){if(!e||typeof e!="string")throw new Error("model is required and must be a string");if(e.includes("..")||e.includes("?")||e.includes("&"))throw new Error("invalid model parameter");if(t.isVertexAI()){if(e.startsWith("publishers/")||e.startsWith("projects/")||e.startsWith("models/"))return e;if(e.indexOf("/")>=0){const n=e.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else return`publishers/google/models/${e}`}else return e.startsWith("models/")||e.startsWith("tunedModels/")?e:`models/${e}`}function fo(t,e){const n=D(t,e);return n?n.startsWith("publishers/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}`:n.startsWith("models/")&&t.isVertexAI()?`projects/${t.getProject()}/locations/${t.getLocation()}/publishers/google/${n}`:n:""}function po(t){return Array.isArray(t)?t.map(e=>Me(e)):[Me(t)]}function Me(t){if(typeof t=="object"&&t!==null)return t;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof t}`)}function ho(t){const e=Me(t);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function mo(t){const e=Me(t);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}function Fn(t){if(t==null)throw new Error("PartUnion is required");if(typeof t=="object")return t;if(typeof t=="string")return{text:t};throw new Error(`Unsupported part type: ${typeof t}`)}function go(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("PartListUnion is required");return Array.isArray(t)?t.map(e=>Fn(e)):[Fn(t)]}function Qe(t){return t!=null&&typeof t=="object"&&"parts"in t&&Array.isArray(t.parts)}function Vn(t){return t!=null&&typeof t=="object"&&"functionCall"in t}function Hn(t){return t!=null&&typeof t=="object"&&"functionResponse"in t}function F(t){if(t==null)throw new Error("ContentUnion is required");return Qe(t)?t:{role:"user",parts:go(t)}}function ct(t,e){if(!e)return[];if(t.isVertexAI()&&Array.isArray(e))return e.flatMap(n=>{const o=F(n);return o.parts&&o.parts.length>0&&o.parts[0].text!==void 0?[o.parts[0].text]:[]});if(t.isVertexAI()){const n=F(e);return n.parts&&n.parts.length>0&&n.parts[0].text!==void 0?[n.parts[0].text]:[]}return Array.isArray(e)?e.map(n=>F(n)):[F(e)]}function q(t){if(t==null||Array.isArray(t)&&t.length===0)throw new Error("contents are required");if(!Array.isArray(t)){if(Vn(t)||Hn(t))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[F(t)]}const e=[],n=[],o=Qe(t[0]);for(const r of t){const l=Qe(r);if(l!=o)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(l)e.push(r);else{if(Vn(r)||Hn(r))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");n.push(r)}}return o||e.push({role:"user",parts:go(n)}),e}function Yi(t,e){t.includes("null")&&(e.nullable=!0);const n=t.filter(o=>o!=="null");if(n.length===1)e.type=Object.values(j).includes(n[0].toUpperCase())?n[0].toUpperCase():j.TYPE_UNSPECIFIED;else{e.anyOf=[];for(const o of n)e.anyOf.push({type:Object.values(j).includes(o.toUpperCase())?o.toUpperCase():j.TYPE_UNSPECIFIED})}}function ue(t){const e={},n=["items"],o=["anyOf"],r=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");const l=t.anyOf;l!=null&&l.length==2&&(l[0].type==="null"?(e.nullable=!0,t=l[1]):l[1].type==="null"&&(e.nullable=!0,t=l[0])),t.type instanceof Array&&Yi(t.type,e);for(const[a,u]of Object.entries(t))if(u!=null)if(a=="type"){if(u==="null")throw new Error("type: null can not be the only possible type for the field.");if(u instanceof Array)continue;e.type=Object.values(j).includes(u.toUpperCase())?u.toUpperCase():j.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=ue(u);else if(o.includes(a)){const c=[];for(const d of u){if(d.type=="null"){e.nullable=!0;continue}c.push(ue(d))}e[a]=c}else if(r.includes(a)){const c={};for(const[d,f]of Object.entries(u))c[d]=ue(f);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=u}return e}function ft(t){return ue(t)}function pt(t){if(typeof t=="object")return t;if(typeof t=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:t}}};throw new Error(`Unsupported speechConfig type: ${typeof t}`)}function ht(t){if("multiSpeakerVoiceConfig"in t)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return t}function ce(t){if(t.functionDeclarations)for(const e of t.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=ue(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=ue(e.response));return t}function fe(t){if(t==null)throw new Error("tools is required");if(!Array.isArray(t))throw new Error("tools is required and must be an array of Tools");const e=[];for(const n of t)e.push(n);return e}function Ki(t,e,n,o=1){const r=!e.startsWith(`${n}/`)&&e.split("/").length===o;return t.isVertexAI()?e.startsWith("projects/")?e:e.startsWith("locations/")?`projects/${t.getProject()}/${e}`:e.startsWith(`${n}/`)?`projects/${t.getProject()}/locations/${t.getLocation()}/${e}`:r?`projects/${t.getProject()}/locations/${t.getLocation()}/${n}/${e}`:e:r?`${n}/${e}`:e}function Z(t,e){if(typeof e!="string")throw new Error("name must be a string");return Ki(t,e,"cachedContents")}function Eo(t){switch(t){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return t}}function te(t){return at(t)}function Wi(t){return t!=null&&typeof t=="object"&&"name"in t}function zi(t){return t!=null&&typeof t=="object"&&"video"in t}function Xi(t){return t!=null&&typeof t=="object"&&"uri"in t}function vo(t){var e;let n;if(Wi(t)&&(n=t.name),!(Xi(t)&&(n=t.uri,n===void 0))&&!(zi(t)&&(n=(e=t.video)===null||e===void 0?void 0:e.uri,n===void 0))){if(typeof t=="string"&&(n=t),n===void 0)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){const r=n.split("files/")[1].match(/[a-z0-9]+/);if(r===null)throw new Error(`Could not extract file name from URI ${n}`);n=r[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function yo(t,e){let n;return t.isVertexAI()?n=e?"publishers/google/models":"models":n=e?"models":"tunedModels",n}function To(t){for(const e of["models","tunedModels","publisherModels"])if(Qi(t,e))return t[e];return[]}function Qi(t,e){return t!==null&&typeof t=="object"&&e in t}function Zi(t,e={}){const n=t,o={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(o.responseJsonSchema=n.outputSchema),e.behavior&&(o.behavior=e.behavior),{functionDeclarations:[o]}}function ji(t,e={}){const n=[],o=new Set;for(const r of t){const l=r.name;if(o.has(l))throw new Error(`Duplicate function name ${l} found in MCP tools. Please ensure function names are unique.`);o.add(l);const a=Zi(r,e);a.functionDeclarations&&n.push(...a.functionDeclarations)}return{functionDeclarations:n}}function _o(t,e){let n;if(typeof e=="string")if(t.isVertexAI())if(e.startsWith("gs://"))n={format:"jsonl",gcsUri:[e]};else if(e.startsWith("bq://"))n={format:"bigquery",bigqueryUri:e};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(e))n={format:"vertex-dataset",vertexDatasetName:e};else throw new Error(`Unsupported string source for Vertex AI: ${e}`);else if(e.startsWith("files/"))n={fileName:e};else throw new Error(`Unsupported string source for Gemini API: ${e}`);else if(Array.isArray(e)){if(t.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:e}}else n=e;const o=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,r=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(t.isVertexAI()){if(r>0||o!==1)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(o>0||r!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function er(t){if(typeof t!="string")return t;const e=t;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw new Error(`Unsupported destination: ${e}`)}function Io(t){if(typeof t!="object"||t===null)return{};const e=t,n=e.inlinedResponses;if(typeof n!="object"||n===null)return t;const r=n.inlinedResponses;if(!Array.isArray(r)||r.length===0)return t;let l=!1;for(const a of r){if(typeof a!="object"||a===null)continue;const c=a.response;if(typeof c!="object"||c===null)continue;if(c.embedding!==void 0){l=!0;break}}return l&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),t}function pe(t,e){const n=e;if(!t.isVertexAI()){if(/batches\/[^/]+$/.test(n))return n.split("/").pop();throw new Error(`Invalid batch job name: ${n}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();if(/^\d+$/.test(n))return n;throw new Error(`Invalid batch job name: ${n}.`)}function Co(t){const e=t;return e==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":e==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":e==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":e==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":e==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":e==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":e==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":e}function tr(t){return t.includes("gemini")&&t!=="gemini-embedding-001"||t.includes("maas")}function nr(t){const e={},n=i(t,["apiKey"]);if(n!=null&&s(e,["apiKey"],n),i(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(i(t,["authType"])!==void 0)throw new Error("authType parameter is not supported in Gemini API.");if(i(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(i(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(i(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is not supported in Gemini API.");if(i(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is not supported in Gemini API.");return e}function or(t){const e={},n=i(t,["responsesFile"]);n!=null&&s(e,["fileName"],n);const o=i(t,["inlinedResponses","inlinedResponses"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(a=>Fr(a))),s(e,["inlinedResponses"],l)}const r=i(t,["inlinedEmbedContentResponses","inlinedResponses"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>a)),s(e,["inlinedEmbedContentResponses"],l)}return e}function ir(t){const e={},n=i(t,["predictionsFormat"]);n!=null&&s(e,["format"],n);const o=i(t,["gcsDestination","outputUriPrefix"]);o!=null&&s(e,["gcsUri"],o);const r=i(t,["bigqueryDestination","outputUri"]);r!=null&&s(e,["bigqueryUri"],r);const l=i(t,["vertexMultimodalDatasetDestination"]);return l!=null&&s(e,["vertexDataset"],Wr(l)),e}function rr(t){const e={},n=i(t,["format"]);n!=null&&s(e,["predictionsFormat"],n);const o=i(t,["gcsUri"]);o!=null&&s(e,["gcsDestination","outputUriPrefix"],o);const r=i(t,["bigqueryUri"]);if(r!=null&&s(e,["bigqueryDestination","outputUri"],r),i(t,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(i(t,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(i(t,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const l=i(t,["vertexDataset"]);return l!=null&&s(e,["vertexMultimodalDatasetDestination"],zr(l)),e}function Ae(t){const e={},n=i(t,["name"]);n!=null&&s(e,["name"],n);const o=i(t,["metadata","displayName"]);o!=null&&s(e,["displayName"],o);const r=i(t,["metadata","state"]);r!=null&&s(e,["state"],Co(r));const l=i(t,["metadata","createTime"]);l!=null&&s(e,["createTime"],l);const a=i(t,["metadata","endTime"]);a!=null&&s(e,["endTime"],a);const u=i(t,["metadata","updateTime"]);u!=null&&s(e,["updateTime"],u);const c=i(t,["metadata","model"]);c!=null&&s(e,["model"],c);const d=i(t,["metadata","output"]);return d!=null&&s(e,["dest"],or(Io(d))),e}function Ze(t){const e={},n=i(t,["name"]);n!=null&&s(e,["name"],n);const o=i(t,["displayName"]);o!=null&&s(e,["displayName"],o);const r=i(t,["state"]);r!=null&&s(e,["state"],Co(r));const l=i(t,["error"]);l!=null&&s(e,["error"],l);const a=i(t,["createTime"]);a!=null&&s(e,["createTime"],a);const u=i(t,["startTime"]);u!=null&&s(e,["startTime"],u);const c=i(t,["endTime"]);c!=null&&s(e,["endTime"],c);const d=i(t,["updateTime"]);d!=null&&s(e,["updateTime"],d);const f=i(t,["model"]);f!=null&&s(e,["model"],f);const p=i(t,["inputConfig"]);p!=null&&s(e,["src"],sr(p));const h=i(t,["outputConfig"]);h!=null&&s(e,["dest"],ir(Io(h)));const m=i(t,["completionStats"]);m!=null&&s(e,["completionStats"],m);const g=i(t,["outputInfo"]);return g!=null&&s(e,["outputInfo"],g),e}function sr(t){const e={},n=i(t,["instancesFormat"]);n!=null&&s(e,["format"],n);const o=i(t,["gcsSource","uris"]);o!=null&&s(e,["gcsUri"],o);const r=i(t,["bigquerySource","inputUri"]);r!=null&&s(e,["bigqueryUri"],r);const l=i(t,["vertexMultimodalDatasetSource","datasetName"]);return l!=null&&s(e,["vertexDatasetName"],l),e}function lr(t,e){const n={};if(i(e,["format"])!==void 0)throw new Error("format parameter is not supported in Gemini API.");if(i(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(i(e,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is not supported in Gemini API.");const o=i(e,["fileName"]);o!=null&&s(n,["fileName"],o);const r=i(e,["inlinedRequests"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>kr(t,a))),s(n,["requests","requests"],l)}if(i(e,["vertexDatasetName"])!==void 0)throw new Error("vertexDatasetName parameter is not supported in Gemini API.");return n}function ar(t){const e={},n=i(t,["format"]);n!=null&&s(e,["instancesFormat"],n);const o=i(t,["gcsUri"]);o!=null&&s(e,["gcsSource","uris"],o);const r=i(t,["bigqueryUri"]);if(r!=null&&s(e,["bigquerySource","inputUri"],r),i(t,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(i(t,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const l=i(t,["vertexDatasetName"]);return l!=null&&s(e,["vertexMultimodalDatasetSource","datasetName"],l),e}function ur(t){const e={},n=i(t,["data"]);if(n!=null&&s(e,["data"],n),i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const o=i(t,["mimeType"]);return o!=null&&s(e,["mimeType"],o),e}function dr(t,e){const n={},o=i(e,["name"]);return o!=null&&s(n,["_url","name"],pe(t,o)),n}function cr(t,e){const n={},o=i(e,["name"]);return o!=null&&s(n,["_url","name"],pe(t,o)),n}function fr(t){const e={},n=i(t,["content"]);n!=null&&s(e,["content"],n);const o=i(t,["citationMetadata"]);o!=null&&s(e,["citationMetadata"],pr(o));const r=i(t,["tokenCount"]);r!=null&&s(e,["tokenCount"],r);const l=i(t,["finishReason"]);l!=null&&s(e,["finishReason"],l);const a=i(t,["groundingMetadata"]);a!=null&&s(e,["groundingMetadata"],a);const u=i(t,["avgLogprobs"]);u!=null&&s(e,["avgLogprobs"],u);const c=i(t,["index"]);c!=null&&s(e,["index"],c);const d=i(t,["logprobsResult"]);d!=null&&s(e,["logprobsResult"],d);const f=i(t,["safetyRatings"]);if(f!=null){let h=f;Array.isArray(h)&&(h=h.map(m=>m)),s(e,["safetyRatings"],h)}const p=i(t,["urlContextMetadata"]);return p!=null&&s(e,["urlContextMetadata"],p),e}function pr(t){const e={},n=i(t,["citationSources"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(r=>r)),s(e,["citations"],o)}return e}function Ao(t){const e={},n=i(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(l=>$r(l))),s(e,["parts"],r)}const o=i(t,["role"]);return o!=null&&s(e,["role"],o),e}function hr(t,e){const n={},o=i(t,["displayName"]);if(e!==void 0&&o!=null&&s(e,["batch","displayName"],o),i(t,["dest"])!==void 0)throw new Error("dest parameter is not supported in Gemini API.");const r=i(t,["webhookConfig"]);return e!==void 0&&r!=null&&s(e,["batch","webhookConfig"],r),n}function mr(t,e){const n={},o=i(t,["displayName"]);e!==void 0&&o!=null&&s(e,["displayName"],o);const r=i(t,["dest"]);if(e!==void 0&&r!=null&&s(e,["outputConfig"],rr(er(r))),i(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function qn(t,e){const n={},o=i(e,["model"]);o!=null&&s(n,["_url","model"],D(t,o));const r=i(e,["src"]);r!=null&&s(n,["batch","inputConfig"],lr(t,_o(t,r)));const l=i(e,["config"]);return l!=null&&hr(l,n),n}function gr(t,e){const n={},o=i(e,["model"]);o!=null&&s(n,["model"],D(t,o));const r=i(e,["src"]);r!=null&&s(n,["inputConfig"],ar(_o(t,r)));const l=i(e,["config"]);return l!=null&&mr(l,n),n}function Er(t,e){const n={},o=i(t,["displayName"]);return e!==void 0&&o!=null&&s(e,["batch","displayName"],o),n}function vr(t,e){const n={},o=i(e,["model"]);o!=null&&s(n,["_url","model"],D(t,o));const r=i(e,["src"]);r!=null&&s(n,["batch","inputConfig"],Sr(t,r));const l=i(e,["config"]);return l!=null&&Er(l,n),n}function yr(t,e){const n={},o=i(e,["name"]);return o!=null&&s(n,["_url","name"],pe(t,o)),n}function Tr(t,e){const n={},o=i(e,["name"]);return o!=null&&s(n,["_url","name"],pe(t,o)),n}function _r(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["name"]);o!=null&&s(e,["name"],o);const r=i(t,["done"]);r!=null&&s(e,["done"],r);const l=i(t,["error"]);return l!=null&&s(e,["error"],l),e}function Ir(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["name"]);o!=null&&s(e,["name"],o);const r=i(t,["done"]);r!=null&&s(e,["done"],r);const l=i(t,["error"]);return l!=null&&s(e,["error"],l),e}function Cr(t,e){const n={},o=i(e,["contents"]);if(o!=null){let l=ct(t,o);Array.isArray(l)&&(l=l.map(a=>a)),s(n,["requests[]","request","content"],l)}const r=i(e,["config"]);return r!=null&&(s(n,["_self"],Ar(r,n)),gi(n,{"requests[].*":"requests[].request.*"})),n}function Ar(t,e){const n={},o=i(t,["taskType"]);e!==void 0&&o!=null&&s(e,["requests[]","taskType"],o);const r=i(t,["title"]);e!==void 0&&r!=null&&s(e,["requests[]","title"],r);const l=i(t,["outputDimensionality"]);if(e!==void 0&&l!=null&&s(e,["requests[]","outputDimensionality"],l),i(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(i(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");if(i(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is not supported in Gemini API.");if(i(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is not supported in Gemini API.");return n}function Sr(t,e){const n={},o=i(e,["fileName"]);o!=null&&s(n,["file_name"],o);const r=i(e,["inlinedRequests"]);return r!=null&&s(n,["requests"],Cr(t,r)),n}function Rr(t){const e={};if(i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=i(t,["fileUri"]);n!=null&&s(e,["fileUri"],n);const o=i(t,["mimeType"]);return o!=null&&s(e,["mimeType"],o),e}function Pr(t){const e={},n=i(t,["id"]);n!=null&&s(e,["id"],n);const o=i(t,["args"]);o!=null&&s(e,["args"],o);const r=i(t,["name"]);if(r!=null&&s(e,["name"],r),i(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(i(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function Nr(t){const e={},n=i(t,["allowedFunctionNames"]);n!=null&&s(e,["allowedFunctionNames"],n);const o=i(t,["mode"]);if(o!=null&&s(e,["mode"],o),i(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}function wr(t,e,n){const o={},r=i(e,["systemInstruction"]);n!==void 0&&r!=null&&s(n,["systemInstruction"],Ao(F(r)));const l=i(e,["temperature"]);l!=null&&s(o,["temperature"],l);const a=i(e,["topP"]);a!=null&&s(o,["topP"],a);const u=i(e,["topK"]);u!=null&&s(o,["topK"],u);const c=i(e,["candidateCount"]);c!=null&&s(o,["candidateCount"],c);const d=i(e,["maxOutputTokens"]);d!=null&&s(o,["maxOutputTokens"],d);const f=i(e,["stopSequences"]);f!=null&&s(o,["stopSequences"],f);const p=i(e,["responseLogprobs"]);p!=null&&s(o,["responseLogprobs"],p);const h=i(e,["logprobs"]);h!=null&&s(o,["logprobs"],h);const m=i(e,["presencePenalty"]);m!=null&&s(o,["presencePenalty"],m);const g=i(e,["frequencyPenalty"]);g!=null&&s(o,["frequencyPenalty"],g);const v=i(e,["seed"]);v!=null&&s(o,["seed"],v);const E=i(e,["responseMimeType"]);E!=null&&s(o,["responseMimeType"],E);const y=i(e,["responseSchema"]);y!=null&&s(o,["responseSchema"],ft(y));const A=i(e,["responseJsonSchema"]);if(A!=null&&s(o,["responseJsonSchema"],A),i(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(i(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");const I=i(e,["safetySettings"]);if(n!==void 0&&I!=null){let k=I;Array.isArray(k)&&(k=k.map(U=>Or(U))),s(n,["safetySettings"],k)}const S=i(e,["tools"]);if(n!==void 0&&S!=null){let k=fe(S);Array.isArray(k)&&(k=k.map(U=>Kr(ce(U)))),s(n,["tools"],k)}const R=i(e,["toolConfig"]);if(n!==void 0&&R!=null&&s(n,["toolConfig"],Yr(R)),i(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const T=i(e,["cachedContent"]);n!==void 0&&T!=null&&s(n,["cachedContent"],Z(t,T));const w=i(e,["responseModalities"]);w!=null&&s(o,["responseModalities"],w);const P=i(e,["mediaResolution"]);P!=null&&s(o,["mediaResolution"],P);const C=i(e,["speechConfig"]);if(C!=null&&s(o,["speechConfig"],pt(C)),i(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");const M=i(e,["thinkingConfig"]);M!=null&&s(o,["thinkingConfig"],M);const x=i(e,["imageConfig"]);x!=null&&s(o,["imageConfig"],Gr(x));const B=i(e,["enableEnhancedCivicAnswers"]);if(B!=null&&s(o,["enableEnhancedCivicAnswers"],B),i(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is not supported in Gemini API.");const b=i(e,["serviceTier"]);return n!==void 0&&b!=null&&s(n,["serviceTier"],b),o}function Mr(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["candidates"]);if(o!=null){let d=o;Array.isArray(d)&&(d=d.map(f=>fr(f))),s(e,["candidates"],d)}const r=i(t,["modelVersion"]);r!=null&&s(e,["modelVersion"],r);const l=i(t,["promptFeedback"]);l!=null&&s(e,["promptFeedback"],l);const a=i(t,["responseId"]);a!=null&&s(e,["responseId"],a);const u=i(t,["usageMetadata"]);u!=null&&s(e,["usageMetadata"],u);const c=i(t,["modelStatus"]);return c!=null&&s(e,["modelStatus"],c),e}function Dr(t,e){const n={},o=i(e,["name"]);return o!=null&&s(n,["_url","name"],pe(t,o)),n}function xr(t,e){const n={},o=i(e,["name"]);return o!=null&&s(n,["_url","name"],pe(t,o)),n}function Ur(t){const e={},n=i(t,["authConfig"]);n!=null&&s(e,["authConfig"],nr(n));const o=i(t,["enableWidget"]);return o!=null&&s(e,["enableWidget"],o),e}function Lr(t){const e={},n=i(t,["searchTypes"]);if(n!=null&&s(e,["searchTypes"],n),i(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(i(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");const o=i(t,["timeRangeFilter"]);return o!=null&&s(e,["timeRangeFilter"],o),e}function Gr(t){const e={},n=i(t,["aspectRatio"]);n!=null&&s(e,["aspectRatio"],n);const o=i(t,["imageSize"]);if(o!=null&&s(e,["imageSize"],o),i(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is not supported in Gemini API.");if(i(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is not supported in Gemini API.");if(i(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(i(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");if(i(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is not supported in Gemini API.");return e}function kr(t,e){const n={},o=i(e,["model"]);o!=null&&s(n,["request","model"],D(t,o));const r=i(e,["contents"]);if(r!=null){let u=q(r);Array.isArray(u)&&(u=u.map(c=>Ao(c))),s(n,["request","contents"],u)}const l=i(e,["metadata"]);l!=null&&s(n,["metadata"],l);const a=i(e,["config"]);return a!=null&&s(n,["request","generationConfig"],wr(t,a,i(n,["request"],{}))),n}function Fr(t){const e={},n=i(t,["response"]);n!=null&&s(e,["response"],Mr(n));const o=i(t,["metadata"]);o!=null&&s(e,["metadata"],o);const r=i(t,["error"]);return r!=null&&s(e,["error"],r),e}function Vr(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&s(e,["_query","pageSize"],o);const r=i(t,["pageToken"]);if(e!==void 0&&r!=null&&s(e,["_query","pageToken"],r),i(t,["filter"])!==void 0)throw new Error("filter parameter is not supported in Gemini API.");return n}function Hr(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&s(e,["_query","pageSize"],o);const r=i(t,["pageToken"]);e!==void 0&&r!=null&&s(e,["_query","pageToken"],r);const l=i(t,["filter"]);return e!==void 0&&l!=null&&s(e,["_query","filter"],l),n}function qr(t){const e={},n=i(t,["config"]);return n!=null&&Vr(n,e),e}function Br(t){const e={},n=i(t,["config"]);return n!=null&&Hr(n,e),e}function Jr(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&s(e,["nextPageToken"],o);const r=i(t,["operations"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>Ae(a))),s(e,["batchJobs"],l)}return e}function br(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&s(e,["nextPageToken"],o);const r=i(t,["batchPredictionJobs"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>Ze(a))),s(e,["batchJobs"],l)}return e}function $r(t){const e={},n=i(t,["mediaResolution"]);n!=null&&s(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&s(e,["codeExecutionResult"],o);const r=i(t,["executableCode"]);r!=null&&s(e,["executableCode"],r);const l=i(t,["fileData"]);l!=null&&s(e,["fileData"],Rr(l));const a=i(t,["functionCall"]);a!=null&&s(e,["functionCall"],Pr(a));const u=i(t,["functionResponse"]);u!=null&&s(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&s(e,["inlineData"],ur(c));const d=i(t,["text"]);d!=null&&s(e,["text"],d);const f=i(t,["thought"]);f!=null&&s(e,["thought"],f);const p=i(t,["thoughtSignature"]);p!=null&&s(e,["thoughtSignature"],p);const h=i(t,["videoMetadata"]);h!=null&&s(e,["videoMetadata"],h);const m=i(t,["toolCall"]);m!=null&&s(e,["toolCall"],m);const g=i(t,["toolResponse"]);g!=null&&s(e,["toolResponse"],g);const v=i(t,["partMetadata"]);return v!=null&&s(e,["partMetadata"],v),e}function Or(t){const e={},n=i(t,["category"]);if(n!=null&&s(e,["category"],n),i(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");const o=i(t,["threshold"]);return o!=null&&s(e,["threshold"],o),e}function Yr(t){const e={},n=i(t,["retrievalConfig"]);n!=null&&s(e,["retrievalConfig"],n);const o=i(t,["functionCallingConfig"]);o!=null&&s(e,["functionCallingConfig"],Nr(o));const r=i(t,["includeServerSideToolInvocations"]);return r!=null&&s(e,["includeServerSideToolInvocations"],r),e}function Kr(t){const e={};if(i(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const n=i(t,["computerUse"]);n!=null&&s(e,["computerUse"],n);const o=i(t,["fileSearch"]);o!=null&&s(e,["fileSearch"],o);const r=i(t,["googleSearch"]);r!=null&&s(e,["googleSearch"],Lr(r));const l=i(t,["googleMaps"]);l!=null&&s(e,["googleMaps"],Ur(l));const a=i(t,["codeExecution"]);if(a!=null&&s(e,["codeExecution"],a),i(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=i(t,["functionDeclarations"]);if(u!=null){let p=u;Array.isArray(p)&&(p=p.map(h=>h)),s(e,["functionDeclarations"],p)}const c=i(t,["googleSearchRetrieval"]);if(c!=null&&s(e,["googleSearchRetrieval"],c),i(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is not supported in Gemini API.");const d=i(t,["urlContext"]);d!=null&&s(e,["urlContext"],d);const f=i(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),s(e,["mcpServers"],p)}return e}function Wr(t){const e={},n=i(t,["bigqueryDestination","outputUri"]);n!=null&&s(e,["bigqueryDestination"],n);const o=i(t,["displayName"]);return o!=null&&s(e,["displayName"],o),e}function zr(t){const e={},n=i(t,["bigqueryDestination"]);n!=null&&s(e,["bigqueryDestination","outputUri"],n);const o=i(t,["displayName"]);return o!=null&&s(e,["displayName"],o),e}var X;(function(t){t.PAGED_ITEM_BATCH_JOBS="batchJobs",t.PAGED_ITEM_MODELS="models",t.PAGED_ITEM_TUNING_JOBS="tuningJobs",t.PAGED_ITEM_FILES="files",t.PAGED_ITEM_CACHED_CONTENTS="cachedContents",t.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",t.PAGED_ITEM_DOCUMENTS="documents"})(X||(X={}));class ie{constructor(e,n,o,r){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(e,o,r)}init(e,n,o){var r,l;this.nameInternal=e,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n?.sdkHttpResponse,this.idxInternal=0;let a={config:{}};!o||Object.keys(o).length===0?a={config:{}}:typeof o=="object"?a=Object.assign({},o):a=o,a.config&&(a.config.pageToken=n.nextPageToken),this.paramsInternal=a,this.pageInternalSize=(l=(r=a.config)===null||r===void 0?void 0:r.pageSize)!==null&&l!==void 0?l:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};const e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");const e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return((e=this.params.config)===null||e===void 0?void 0:e.pageToken)!==void 0}}class Xr extends Q{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ie(X.PAGED_ITEM_BATCH_JOBS,o=>this.listInternal(o),await this.listInternal(n),n),this.create=async n=>(this.apiClient.isVertexAI()&&(n.config=this.formatDestination(n.src,n.config)),this.createInternal(n)),this.createEmbeddings=async n=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(n)}}createInlinedGenerateContentRequest(e){const n=qn(this.apiClient,e),o=n._url,r=_("{model}:batchGenerateContent",o),u=n.batch.inputConfig.requests,c=u.requests,d=[];for(const f of c){const p=Object.assign({},f);if(p.systemInstruction){const h=p.systemInstruction;delete p.systemInstruction;const m=p.request;m.systemInstruction=h,p.request=m}d.push(p)}return u.requests=d,delete n.config,delete n._url,delete n._query,{path:r,body:n}}getGcsUri(e){if(typeof e=="string")return e.startsWith("gs://")?e:void 0;if(!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0)return e.gcsUri[0]}getBigqueryUri(e){if(typeof e=="string")return e.startsWith("bq://")?e:void 0;if(!Array.isArray(e))return e.bigqueryUri}formatDestination(e,n){const o=n?Object.assign({},n):{},r=Date.now().toString();if(o.displayName||(o.displayName=`genaiBatchJob_${r}`),o.dest===void 0){const l=this.getGcsUri(e),a=this.getBigqueryUri(e);if(l)l.endsWith(".jsonl")?o.dest=`${l.slice(0,-6)}/dest`:o.dest=`${l}_dest_${r}`;else if(a)o.dest=`${a}_dest_${r}`;else throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return o}async createInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=gr(this.apiClient,e);return u=_("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>Ze(f))}else{const d=qn(this.apiClient,e);return u=_("{model}:batchGenerateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>Ae(f))}}async createEmbeddingsInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=vr(this.apiClient,e);return l=_("{model}:asyncBatchEmbedContent",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>Ae(c))}}async get(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=xr(this.apiClient,e);return u=_("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>Ze(f))}else{const d=Dr(this.apiClient,e);return u=_("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>Ae(f))}}async cancel(e){var n,o,r,l;let a="",u={};if(this.apiClient.isVertexAI()){const c=cr(this.apiClient,e);a=_("batchPredictionJobs/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}else{const c=dr(this.apiClient,e);a=_("batches/{name}:cancel",c._url),u=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:u,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal})}}async listInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Br(e);return u=_("batchPredictionJobs",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=br(f),h=new kn;return Object.assign(h,p),h})}else{const d=qr(e);return u=_("batches",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=Jr(f),h=new kn;return Object.assign(h,p),h})}}async delete(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Tr(this.apiClient,e);return u=_("batchPredictionJobs/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>Ir(f))}else{const d=yr(this.apiClient,e);return u=_("batches/{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>_r(f))}}}function Qr(t){const e={},n=i(t,["apiKey"]);if(n!=null&&s(e,["apiKey"],n),i(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(i(t,["authType"])!==void 0)throw new Error("authType parameter is not supported in Gemini API.");if(i(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(i(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(i(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is not supported in Gemini API.");if(i(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is not supported in Gemini API.");return e}function Zr(t){const e={},n=i(t,["data"]);if(n!=null&&s(e,["data"],n),i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const o=i(t,["mimeType"]);return o!=null&&s(e,["mimeType"],o),e}function Bn(t){const e={},n=i(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(l=>_s(l))),s(e,["parts"],r)}const o=i(t,["role"]);return o!=null&&s(e,["role"],o),e}function Jn(t){const e={},n=i(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(l=>Is(l))),s(e,["parts"],r)}const o=i(t,["role"]);return o!=null&&s(e,["role"],o),e}function jr(t,e){const n={},o=i(t,["ttl"]);e!==void 0&&o!=null&&s(e,["ttl"],o);const r=i(t,["expireTime"]);e!==void 0&&r!=null&&s(e,["expireTime"],r);const l=i(t,["displayName"]);e!==void 0&&l!=null&&s(e,["displayName"],l);const a=i(t,["contents"]);if(e!==void 0&&a!=null){let f=q(a);Array.isArray(f)&&(f=f.map(p=>Bn(p))),s(e,["contents"],f)}const u=i(t,["systemInstruction"]);e!==void 0&&u!=null&&s(e,["systemInstruction"],Bn(F(u)));const c=i(t,["tools"]);if(e!==void 0&&c!=null){let f=c;Array.isArray(f)&&(f=f.map(p=>Ss(p))),s(e,["tools"],f)}const d=i(t,["toolConfig"]);if(e!==void 0&&d!=null&&s(e,["toolConfig"],Cs(d)),i(t,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return n}function es(t,e){const n={},o=i(t,["ttl"]);e!==void 0&&o!=null&&s(e,["ttl"],o);const r=i(t,["expireTime"]);e!==void 0&&r!=null&&s(e,["expireTime"],r);const l=i(t,["displayName"]);e!==void 0&&l!=null&&s(e,["displayName"],l);const a=i(t,["contents"]);if(e!==void 0&&a!=null){let p=q(a);Array.isArray(p)&&(p=p.map(h=>Jn(h))),s(e,["contents"],p)}const u=i(t,["systemInstruction"]);e!==void 0&&u!=null&&s(e,["systemInstruction"],Jn(F(u)));const c=i(t,["tools"]);if(e!==void 0&&c!=null){let p=c;Array.isArray(p)&&(p=p.map(h=>Rs(h))),s(e,["tools"],p)}const d=i(t,["toolConfig"]);e!==void 0&&d!=null&&s(e,["toolConfig"],As(d));const f=i(t,["kmsKeyName"]);return e!==void 0&&f!=null&&s(e,["encryption_spec","kmsKeyName"],f),n}function ts(t,e){const n={},o=i(e,["model"]);o!=null&&s(n,["model"],fo(t,o));const r=i(e,["config"]);return r!=null&&jr(r,n),n}function ns(t,e){const n={},o=i(e,["model"]);o!=null&&s(n,["model"],fo(t,o));const r=i(e,["config"]);return r!=null&&es(r,n),n}function os(t,e){const n={},o=i(e,["name"]);return o!=null&&s(n,["_url","name"],Z(t,o)),n}function is(t,e){const n={},o=i(e,["name"]);return o!=null&&s(n,["_url","name"],Z(t,o)),n}function rs(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&s(e,["sdkHttpResponse"],n),e}function ss(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&s(e,["sdkHttpResponse"],n),e}function ls(t){const e={};if(i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=i(t,["fileUri"]);n!=null&&s(e,["fileUri"],n);const o=i(t,["mimeType"]);return o!=null&&s(e,["mimeType"],o),e}function as(t){const e={},n=i(t,["id"]);n!=null&&s(e,["id"],n);const o=i(t,["args"]);o!=null&&s(e,["args"],o);const r=i(t,["name"]);if(r!=null&&s(e,["name"],r),i(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(i(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function us(t){const e={},n=i(t,["allowedFunctionNames"]);n!=null&&s(e,["allowedFunctionNames"],n);const o=i(t,["mode"]);if(o!=null&&s(e,["mode"],o),i(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return e}function ds(t){const e={},n=i(t,["description"]);n!=null&&s(e,["description"],n);const o=i(t,["name"]);o!=null&&s(e,["name"],o);const r=i(t,["parameters"]);r!=null&&s(e,["parameters"],r);const l=i(t,["parametersJsonSchema"]);l!=null&&s(e,["parametersJsonSchema"],l);const a=i(t,["response"]);a!=null&&s(e,["response"],a);const u=i(t,["responseJsonSchema"]);if(u!=null&&s(e,["responseJsonSchema"],u),i(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function cs(t,e){const n={},o=i(e,["name"]);return o!=null&&s(n,["_url","name"],Z(t,o)),n}function fs(t,e){const n={},o=i(e,["name"]);return o!=null&&s(n,["_url","name"],Z(t,o)),n}function ps(t){const e={},n=i(t,["authConfig"]);n!=null&&s(e,["authConfig"],Qr(n));const o=i(t,["enableWidget"]);return o!=null&&s(e,["enableWidget"],o),e}function hs(t){const e={},n=i(t,["searchTypes"]);if(n!=null&&s(e,["searchTypes"],n),i(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(i(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");const o=i(t,["timeRangeFilter"]);return o!=null&&s(e,["timeRangeFilter"],o),e}function ms(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&s(e,["_query","pageSize"],o);const r=i(t,["pageToken"]);return e!==void 0&&r!=null&&s(e,["_query","pageToken"],r),n}function gs(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&s(e,["_query","pageSize"],o);const r=i(t,["pageToken"]);return e!==void 0&&r!=null&&s(e,["_query","pageToken"],r),n}function Es(t){const e={},n=i(t,["config"]);return n!=null&&ms(n,e),e}function vs(t){const e={},n=i(t,["config"]);return n!=null&&gs(n,e),e}function ys(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&s(e,["nextPageToken"],o);const r=i(t,["cachedContents"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>a)),s(e,["cachedContents"],l)}return e}function Ts(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&s(e,["nextPageToken"],o);const r=i(t,["cachedContents"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>a)),s(e,["cachedContents"],l)}return e}function _s(t){const e={},n=i(t,["mediaResolution"]);n!=null&&s(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&s(e,["codeExecutionResult"],o);const r=i(t,["executableCode"]);r!=null&&s(e,["executableCode"],r);const l=i(t,["fileData"]);l!=null&&s(e,["fileData"],ls(l));const a=i(t,["functionCall"]);a!=null&&s(e,["functionCall"],as(a));const u=i(t,["functionResponse"]);u!=null&&s(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&s(e,["inlineData"],Zr(c));const d=i(t,["text"]);d!=null&&s(e,["text"],d);const f=i(t,["thought"]);f!=null&&s(e,["thought"],f);const p=i(t,["thoughtSignature"]);p!=null&&s(e,["thoughtSignature"],p);const h=i(t,["videoMetadata"]);h!=null&&s(e,["videoMetadata"],h);const m=i(t,["toolCall"]);m!=null&&s(e,["toolCall"],m);const g=i(t,["toolResponse"]);g!=null&&s(e,["toolResponse"],g);const v=i(t,["partMetadata"]);return v!=null&&s(e,["partMetadata"],v),e}function Is(t){const e={},n=i(t,["mediaResolution"]);n!=null&&s(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&s(e,["codeExecutionResult"],o);const r=i(t,["executableCode"]);r!=null&&s(e,["executableCode"],r);const l=i(t,["fileData"]);l!=null&&s(e,["fileData"],l);const a=i(t,["functionCall"]);a!=null&&s(e,["functionCall"],a);const u=i(t,["functionResponse"]);u!=null&&s(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&s(e,["inlineData"],c);const d=i(t,["text"]);d!=null&&s(e,["text"],d);const f=i(t,["thought"]);f!=null&&s(e,["thought"],f);const p=i(t,["thoughtSignature"]);p!=null&&s(e,["thoughtSignature"],p);const h=i(t,["videoMetadata"]);if(h!=null&&s(e,["videoMetadata"],h),i(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(i(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(i(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function Cs(t){const e={},n=i(t,["retrievalConfig"]);n!=null&&s(e,["retrievalConfig"],n);const o=i(t,["functionCallingConfig"]);o!=null&&s(e,["functionCallingConfig"],us(o));const r=i(t,["includeServerSideToolInvocations"]);return r!=null&&s(e,["includeServerSideToolInvocations"],r),e}function As(t){const e={},n=i(t,["retrievalConfig"]);n!=null&&s(e,["retrievalConfig"],n);const o=i(t,["functionCallingConfig"]);if(o!=null&&s(e,["functionCallingConfig"],o),i(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function Ss(t){const e={};if(i(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const n=i(t,["computerUse"]);n!=null&&s(e,["computerUse"],n);const o=i(t,["fileSearch"]);o!=null&&s(e,["fileSearch"],o);const r=i(t,["googleSearch"]);r!=null&&s(e,["googleSearch"],hs(r));const l=i(t,["googleMaps"]);l!=null&&s(e,["googleMaps"],ps(l));const a=i(t,["codeExecution"]);if(a!=null&&s(e,["codeExecution"],a),i(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=i(t,["functionDeclarations"]);if(u!=null){let p=u;Array.isArray(p)&&(p=p.map(h=>h)),s(e,["functionDeclarations"],p)}const c=i(t,["googleSearchRetrieval"]);if(c!=null&&s(e,["googleSearchRetrieval"],c),i(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is not supported in Gemini API.");const d=i(t,["urlContext"]);d!=null&&s(e,["urlContext"],d);const f=i(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),s(e,["mcpServers"],p)}return e}function Rs(t){const e={},n=i(t,["retrieval"]);n!=null&&s(e,["retrieval"],n);const o=i(t,["computerUse"]);if(o!=null&&s(e,["computerUse"],o),i(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const r=i(t,["googleSearch"]);r!=null&&s(e,["googleSearch"],r);const l=i(t,["googleMaps"]);l!=null&&s(e,["googleMaps"],l);const a=i(t,["codeExecution"]);a!=null&&s(e,["codeExecution"],a);const u=i(t,["enterpriseWebSearch"]);u!=null&&s(e,["enterpriseWebSearch"],u);const c=i(t,["functionDeclarations"]);if(c!=null){let h=c;Array.isArray(h)&&(h=h.map(m=>ds(m))),s(e,["functionDeclarations"],h)}const d=i(t,["googleSearchRetrieval"]);d!=null&&s(e,["googleSearchRetrieval"],d);const f=i(t,["parallelAiSearch"]);f!=null&&s(e,["parallelAiSearch"],f);const p=i(t,["urlContext"]);if(p!=null&&s(e,["urlContext"],p),i(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function Ps(t,e){const n={},o=i(t,["ttl"]);e!==void 0&&o!=null&&s(e,["ttl"],o);const r=i(t,["expireTime"]);return e!==void 0&&r!=null&&s(e,["expireTime"],r),n}function Ns(t,e){const n={},o=i(t,["ttl"]);e!==void 0&&o!=null&&s(e,["ttl"],o);const r=i(t,["expireTime"]);return e!==void 0&&r!=null&&s(e,["expireTime"],r),n}function ws(t,e){const n={},o=i(e,["name"]);o!=null&&s(n,["_url","name"],Z(t,o));const r=i(e,["config"]);return r!=null&&Ps(r,n),n}function Ms(t,e){const n={},o=i(e,["name"]);o!=null&&s(n,["_url","name"],Z(t,o));const r=i(e,["config"]);return r!=null&&Ns(r,n),n}class Ds extends Q{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ie(X.PAGED_ITEM_CACHED_CONTENTS,o=>this.listInternal(o),await this.listInternal(n),n)}async create(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=ns(this.apiClient,e);return u=_("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{const d=ts(this.apiClient,e);return u=_("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async get(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=fs(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{const d=cs(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async delete(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=is(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=ss(f),h=new Ln;return Object.assign(h,p),h})}else{const d=os(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=rs(f),h=new Ln;return Object.assign(h,p),h})}}async update(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Ms(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>f)}else{const d=ws(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>f)}}async listInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=vs(e);return u=_("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=Ts(f),h=new Gn;return Object.assign(h,p),h})}else{const d=Es(e);return u=_("cachedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=ys(f),h=new Gn;return Object.assign(h,p),h})}}}function ee(t,e){var n={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,o=Object.getOwnPropertySymbols(t);r=t.length&&(t=void 0),{value:t&&t[o++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function N(t){return this instanceof N?(this.v=t,this):new N(t)}function Y(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=n.apply(t,e||[]),r,l=[];return r=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",a),r[Symbol.asyncIterator]=function(){return this},r;function a(m){return function(g){return Promise.resolve(g).then(m,p)}}function u(m,g){o[m]&&(r[m]=function(v){return new Promise(function(E,y){l.push([m,v,E,y])>1||c(m,v)})},g&&(r[m]=g(r[m])))}function c(m,g){try{d(o[m](g))}catch(v){h(l[0][3],v)}}function d(m){m.value instanceof N?Promise.resolve(m.value.v).then(f,p):h(l[0][2],m)}function f(m){c("next",m)}function p(m){c("throw",m)}function h(m,g){m(g),l.shift(),l.length&&c(l[0][0],l[0][1])}}function K(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof bn=="function"?bn(t):t[Symbol.iterator](),n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n);function o(l){n[l]=t[l]&&function(a){return new Promise(function(u,c){a=t[l](a),r(u,c,a.done,a.value)})}}function r(l,a,u,c){Promise.resolve(c).then(function(d){l({value:d,done:u})},a)}}function xs(t){var e;if(t.candidates==null||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;return n===void 0?!1:So(n)}function So(t){if(t.parts===void 0||t.parts.length===0)return!1;for(const e of t.parts)if(e===void 0||Object.keys(e).length===0)return!1;return!0}function Us(t){if(t.length!==0){for(const e of t)if(e.role!=="user"&&e.role!=="model")throw new Error(`Role must be user or model, but got ${e.role}.`)}}function $n(t){if(t===void 0||t.length===0)return[];const e=[],n=t.length;let o=0;for(;o{var l,a,u;const c=await r,d=(a=(l=c.candidates)===null||l===void 0?void 0:l[0])===null||a===void 0?void 0:a.content,f=c.automaticFunctionCallingHistory,p=this.getHistory(!0).length;let h=[];f!=null&&(h=(u=f.slice(p))!==null&&u!==void 0?u:[]);const m=d?[d]:[];this.recordHistory(o,m,h)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),r}async sendMessageStream(e){var n;await this.sendPromise;const o=F(e.message),r=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(o),config:(n=e.config)!==null&&n!==void 0?n:this.config});this.sendPromise=r.then(()=>{}).catch(()=>{});const l=await r;return this.processStreamResponse(l,o)}getHistory(e=!1){const n=e?$n(this.history):this.history;return structuredClone(n)}processStreamResponse(e,n){return Y(this,arguments,function*(){var r,l,a,u,c,d;const f=[];try{for(var p=!0,h=K(e),m;m=yield N(h.next()),r=m.done,!r;p=!0){u=m.value,p=!1;const g=u;if(xs(g)){const v=(d=(c=g.candidates)===null||c===void 0?void 0:c[0])===null||d===void 0?void 0:d.content;v!==void 0&&f.push(v)}yield yield N(g)}}catch(g){l={error:g}}finally{try{!p&&!r&&(a=h.return)&&(yield N(a.call(h)))}finally{if(l)throw l.error}}this.recordHistory(n,f)})}recordHistory(e,n,o){let r=[];n.length>0&&n.every(l=>l.role!==void 0)?r=n:r.push({role:"model",parts:[]}),o&&o.length>0?this.history.push(...$n(o)):this.history.push(e),this.history.push(...r)}}class Ue extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,Ue.prototype)}}function ks(t){const e={},n=i(t,["file"]);return n!=null&&s(e,["file"],n),e}function Fs(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&s(e,["sdkHttpResponse"],n),e}function Vs(t){const e={},n=i(t,["name"]);return n!=null&&s(e,["_url","file"],vo(n)),e}function Hs(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&s(e,["sdkHttpResponse"],n),e}function qs(t){const e={},n=i(t,["name"]);return n!=null&&s(e,["_url","file"],vo(n)),e}function Bs(t){const e={},n=i(t,["uris"]);return n!=null&&s(e,["uris"],n),e}function Js(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&s(e,["_query","pageSize"],o);const r=i(t,["pageToken"]);return e!==void 0&&r!=null&&s(e,["_query","pageToken"],r),n}function bs(t){const e={},n=i(t,["config"]);return n!=null&&Js(n,e),e}function $s(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&s(e,["nextPageToken"],o);const r=i(t,["files"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>a)),s(e,["files"],l)}return e}function Os(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["files"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>l)),s(e,["files"],r)}return e}class Ys extends Q{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ie(X.PAGED_ITEM_FILES,o=>this.listInternal(o),await this.listInternal(n),n)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(n=>n)}async download(e){await this.apiClient.downloadFile(e)}async registerFiles(e){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=bs(e);return l=_("files",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),r.then(c=>{const d=$s(c),f=new qi;return Object.assign(f,d),f})}}async createInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=ks(e);return l=_("upload/v1beta/files",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>{const d=Fs(c),f=new Bi;return Object.assign(f,d),f})}}async get(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=qs(e);return l=_("files/{file}",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>c)}}async delete(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Vs(e);return l=_("files/{file}",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),r.then(c=>{const d=Hs(c),f=new Ji;return Object.assign(f,d),f})}}async registerFilesInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Bs(e);return l=_("files:register",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>{const d=Os(c),f=new bi;return Object.assign(f,d),f})}}}function On(t){const e={};if(i(t,["languageCodes"])!==void 0)throw new Error("languageCodes parameter is not supported in Gemini API.");return e}function Ks(t){const e={},n=i(t,["apiKey"]);if(n!=null&&s(e,["apiKey"],n),i(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(i(t,["authType"])!==void 0)throw new Error("authType parameter is not supported in Gemini API.");if(i(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(i(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(i(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is not supported in Gemini API.");if(i(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is not supported in Gemini API.");return e}function Se(t){const e={},n=i(t,["data"]);if(n!=null&&s(e,["data"],n),i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const o=i(t,["mimeType"]);return o!=null&&s(e,["mimeType"],o),e}function Ws(t){const e={},n=i(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(l=>cl(l))),s(e,["parts"],r)}const o=i(t,["role"]);return o!=null&&s(e,["role"],o),e}function zs(t){const e={},n=i(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(l=>fl(l))),s(e,["parts"],r)}const o=i(t,["role"]);return o!=null&&s(e,["role"],o),e}function Xs(t){const e={};if(i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=i(t,["fileUri"]);n!=null&&s(e,["fileUri"],n);const o=i(t,["mimeType"]);return o!=null&&s(e,["mimeType"],o),e}function Qs(t){const e={},n=i(t,["id"]);n!=null&&s(e,["id"],n);const o=i(t,["args"]);o!=null&&s(e,["args"],o);const r=i(t,["name"]);if(r!=null&&s(e,["name"],r),i(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(i(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function Zs(t){const e={},n=i(t,["description"]);n!=null&&s(e,["description"],n);const o=i(t,["name"]);o!=null&&s(e,["name"],o);const r=i(t,["parameters"]);r!=null&&s(e,["parameters"],r);const l=i(t,["parametersJsonSchema"]);l!=null&&s(e,["parametersJsonSchema"],l);const a=i(t,["response"]);a!=null&&s(e,["response"],a);const u=i(t,["responseJsonSchema"]);if(u!=null&&s(e,["responseJsonSchema"],u),i(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function js(t){const e={},n=i(t,["modelSelectionConfig"]);n!=null&&s(e,["modelConfig"],n);const o=i(t,["responseJsonSchema"]);o!=null&&s(e,["responseJsonSchema"],o);const r=i(t,["audioTimestamp"]);r!=null&&s(e,["audioTimestamp"],r);const l=i(t,["candidateCount"]);l!=null&&s(e,["candidateCount"],l);const a=i(t,["enableAffectiveDialog"]);a!=null&&s(e,["enableAffectiveDialog"],a);const u=i(t,["frequencyPenalty"]);u!=null&&s(e,["frequencyPenalty"],u);const c=i(t,["logprobs"]);c!=null&&s(e,["logprobs"],c);const d=i(t,["maxOutputTokens"]);d!=null&&s(e,["maxOutputTokens"],d);const f=i(t,["mediaResolution"]);f!=null&&s(e,["mediaResolution"],f);const p=i(t,["presencePenalty"]);p!=null&&s(e,["presencePenalty"],p);const h=i(t,["responseLogprobs"]);h!=null&&s(e,["responseLogprobs"],h);const m=i(t,["responseMimeType"]);m!=null&&s(e,["responseMimeType"],m);const g=i(t,["responseModalities"]);g!=null&&s(e,["responseModalities"],g);const v=i(t,["responseSchema"]);v!=null&&s(e,["responseSchema"],v);const E=i(t,["routingConfig"]);E!=null&&s(e,["routingConfig"],E);const y=i(t,["seed"]);y!=null&&s(e,["seed"],y);const A=i(t,["speechConfig"]);A!=null&&s(e,["speechConfig"],A);const I=i(t,["stopSequences"]);I!=null&&s(e,["stopSequences"],I);const S=i(t,["temperature"]);S!=null&&s(e,["temperature"],S);const R=i(t,["thinkingConfig"]);R!=null&&s(e,["thinkingConfig"],R);const T=i(t,["topK"]);T!=null&&s(e,["topK"],T);const w=i(t,["topP"]);if(w!=null&&s(e,["topP"],w),i(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function el(t){const e={},n=i(t,["authConfig"]);n!=null&&s(e,["authConfig"],Ks(n));const o=i(t,["enableWidget"]);return o!=null&&s(e,["enableWidget"],o),e}function tl(t){const e={},n=i(t,["searchTypes"]);if(n!=null&&s(e,["searchTypes"],n),i(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(i(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");const o=i(t,["timeRangeFilter"]);return o!=null&&s(e,["timeRangeFilter"],o),e}function nl(t,e){const n={},o=i(t,["generationConfig"]);e!==void 0&&o!=null&&s(e,["setup","generationConfig"],o);const r=i(t,["responseModalities"]);e!==void 0&&r!=null&&s(e,["setup","generationConfig","responseModalities"],r);const l=i(t,["temperature"]);e!==void 0&&l!=null&&s(e,["setup","generationConfig","temperature"],l);const a=i(t,["topP"]);e!==void 0&&a!=null&&s(e,["setup","generationConfig","topP"],a);const u=i(t,["topK"]);e!==void 0&&u!=null&&s(e,["setup","generationConfig","topK"],u);const c=i(t,["maxOutputTokens"]);e!==void 0&&c!=null&&s(e,["setup","generationConfig","maxOutputTokens"],c);const d=i(t,["mediaResolution"]);e!==void 0&&d!=null&&s(e,["setup","generationConfig","mediaResolution"],d);const f=i(t,["seed"]);e!==void 0&&f!=null&&s(e,["setup","generationConfig","seed"],f);const p=i(t,["speechConfig"]);e!==void 0&&p!=null&&s(e,["setup","generationConfig","speechConfig"],ht(p));const h=i(t,["thinkingConfig"]);e!==void 0&&h!=null&&s(e,["setup","generationConfig","thinkingConfig"],h);const m=i(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&s(e,["setup","generationConfig","enableAffectiveDialog"],m);const g=i(t,["systemInstruction"]);e!==void 0&&g!=null&&s(e,["setup","systemInstruction"],Ws(F(g)));const v=i(t,["tools"]);if(e!==void 0&&v!=null){let P=fe(v);Array.isArray(P)&&(P=P.map(C=>ml(ce(C)))),s(e,["setup","tools"],P)}const E=i(t,["sessionResumption"]);e!==void 0&&E!=null&&s(e,["setup","sessionResumption"],hl(E));const y=i(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&s(e,["setup","inputAudioTranscription"],On(y));const A=i(t,["outputAudioTranscription"]);e!==void 0&&A!=null&&s(e,["setup","outputAudioTranscription"],On(A));const I=i(t,["realtimeInputConfig"]);e!==void 0&&I!=null&&s(e,["setup","realtimeInputConfig"],I);const S=i(t,["contextWindowCompression"]);e!==void 0&&S!=null&&s(e,["setup","contextWindowCompression"],S);const R=i(t,["proactivity"]);if(e!==void 0&&R!=null&&s(e,["setup","proactivity"],R),i(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");const T=i(t,["avatarConfig"]);e!==void 0&&T!=null&&s(e,["setup","avatarConfig"],T);const w=i(t,["safetySettings"]);if(e!==void 0&&w!=null){let P=w;Array.isArray(P)&&(P=P.map(C=>pl(C))),s(e,["setup","safetySettings"],P)}return n}function ol(t,e){const n={},o=i(t,["generationConfig"]);e!==void 0&&o!=null&&s(e,["setup","generationConfig"],js(o));const r=i(t,["responseModalities"]);e!==void 0&&r!=null&&s(e,["setup","generationConfig","responseModalities"],r);const l=i(t,["temperature"]);e!==void 0&&l!=null&&s(e,["setup","generationConfig","temperature"],l);const a=i(t,["topP"]);e!==void 0&&a!=null&&s(e,["setup","generationConfig","topP"],a);const u=i(t,["topK"]);e!==void 0&&u!=null&&s(e,["setup","generationConfig","topK"],u);const c=i(t,["maxOutputTokens"]);e!==void 0&&c!=null&&s(e,["setup","generationConfig","maxOutputTokens"],c);const d=i(t,["mediaResolution"]);e!==void 0&&d!=null&&s(e,["setup","generationConfig","mediaResolution"],d);const f=i(t,["seed"]);e!==void 0&&f!=null&&s(e,["setup","generationConfig","seed"],f);const p=i(t,["speechConfig"]);e!==void 0&&p!=null&&s(e,["setup","generationConfig","speechConfig"],ht(p));const h=i(t,["thinkingConfig"]);e!==void 0&&h!=null&&s(e,["setup","generationConfig","thinkingConfig"],h);const m=i(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&s(e,["setup","generationConfig","enableAffectiveDialog"],m);const g=i(t,["systemInstruction"]);e!==void 0&&g!=null&&s(e,["setup","systemInstruction"],zs(F(g)));const v=i(t,["tools"]);if(e!==void 0&&v!=null){let C=fe(v);Array.isArray(C)&&(C=C.map(M=>gl(ce(M)))),s(e,["setup","tools"],C)}const E=i(t,["sessionResumption"]);e!==void 0&&E!=null&&s(e,["setup","sessionResumption"],E);const y=i(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&s(e,["setup","inputAudioTranscription"],y);const A=i(t,["outputAudioTranscription"]);e!==void 0&&A!=null&&s(e,["setup","outputAudioTranscription"],A);const I=i(t,["realtimeInputConfig"]);e!==void 0&&I!=null&&s(e,["setup","realtimeInputConfig"],I);const S=i(t,["contextWindowCompression"]);e!==void 0&&S!=null&&s(e,["setup","contextWindowCompression"],S);const R=i(t,["proactivity"]);e!==void 0&&R!=null&&s(e,["setup","proactivity"],R);const T=i(t,["explicitVadSignal"]);e!==void 0&&T!=null&&s(e,["setup","explicitVadSignal"],T);const w=i(t,["avatarConfig"]);e!==void 0&&w!=null&&s(e,["setup","avatarConfig"],w);const P=i(t,["safetySettings"]);if(e!==void 0&&P!=null){let C=P;Array.isArray(C)&&(C=C.map(M=>M)),s(e,["setup","safetySettings"],C)}return n}function il(t,e){const n={},o=i(e,["model"]);o!=null&&s(n,["setup","model"],D(t,o));const r=i(e,["config"]);return r!=null&&s(n,["config"],nl(r,n)),n}function rl(t,e){const n={},o=i(e,["model"]);o!=null&&s(n,["setup","model"],D(t,o));const r=i(e,["config"]);return r!=null&&s(n,["config"],ol(r,n)),n}function sl(t){const e={},n=i(t,["musicGenerationConfig"]);return n!=null&&s(e,["musicGenerationConfig"],n),e}function ll(t){const e={},n=i(t,["weightedPrompts"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(r=>r)),s(e,["weightedPrompts"],o)}return e}function al(t){const e={},n=i(t,["media"]);if(n!=null){let d=po(n);Array.isArray(d)&&(d=d.map(f=>Se(f))),s(e,["mediaChunks"],d)}const o=i(t,["audio"]);o!=null&&s(e,["audio"],Se(mo(o)));const r=i(t,["audioStreamEnd"]);r!=null&&s(e,["audioStreamEnd"],r);const l=i(t,["video"]);l!=null&&s(e,["video"],Se(ho(l)));const a=i(t,["text"]);a!=null&&s(e,["text"],a);const u=i(t,["activityStart"]);u!=null&&s(e,["activityStart"],u);const c=i(t,["activityEnd"]);return c!=null&&s(e,["activityEnd"],c),e}function ul(t){const e={},n=i(t,["media"]);if(n!=null){let d=po(n);Array.isArray(d)&&(d=d.map(f=>f)),s(e,["mediaChunks"],d)}const o=i(t,["audio"]);o!=null&&s(e,["audio"],mo(o));const r=i(t,["audioStreamEnd"]);r!=null&&s(e,["audioStreamEnd"],r);const l=i(t,["video"]);l!=null&&s(e,["video"],ho(l));const a=i(t,["text"]);a!=null&&s(e,["text"],a);const u=i(t,["activityStart"]);u!=null&&s(e,["activityStart"],u);const c=i(t,["activityEnd"]);return c!=null&&s(e,["activityEnd"],c),e}function dl(t){const e={},n=i(t,["setupComplete"]);n!=null&&s(e,["setupComplete"],n);const o=i(t,["serverContent"]);o!=null&&s(e,["serverContent"],o);const r=i(t,["toolCall"]);r!=null&&s(e,["toolCall"],r);const l=i(t,["toolCallCancellation"]);l!=null&&s(e,["toolCallCancellation"],l);const a=i(t,["usageMetadata"]);a!=null&&s(e,["usageMetadata"],El(a));const u=i(t,["goAway"]);u!=null&&s(e,["goAway"],u);const c=i(t,["sessionResumptionUpdate"]);c!=null&&s(e,["sessionResumptionUpdate"],c);const d=i(t,["voiceActivityDetectionSignal"]);d!=null&&s(e,["voiceActivityDetectionSignal"],d);const f=i(t,["voiceActivity"]);return f!=null&&s(e,["voiceActivity"],vl(f)),e}function cl(t){const e={},n=i(t,["mediaResolution"]);n!=null&&s(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&s(e,["codeExecutionResult"],o);const r=i(t,["executableCode"]);r!=null&&s(e,["executableCode"],r);const l=i(t,["fileData"]);l!=null&&s(e,["fileData"],Xs(l));const a=i(t,["functionCall"]);a!=null&&s(e,["functionCall"],Qs(a));const u=i(t,["functionResponse"]);u!=null&&s(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&s(e,["inlineData"],Se(c));const d=i(t,["text"]);d!=null&&s(e,["text"],d);const f=i(t,["thought"]);f!=null&&s(e,["thought"],f);const p=i(t,["thoughtSignature"]);p!=null&&s(e,["thoughtSignature"],p);const h=i(t,["videoMetadata"]);h!=null&&s(e,["videoMetadata"],h);const m=i(t,["toolCall"]);m!=null&&s(e,["toolCall"],m);const g=i(t,["toolResponse"]);g!=null&&s(e,["toolResponse"],g);const v=i(t,["partMetadata"]);return v!=null&&s(e,["partMetadata"],v),e}function fl(t){const e={},n=i(t,["mediaResolution"]);n!=null&&s(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&s(e,["codeExecutionResult"],o);const r=i(t,["executableCode"]);r!=null&&s(e,["executableCode"],r);const l=i(t,["fileData"]);l!=null&&s(e,["fileData"],l);const a=i(t,["functionCall"]);a!=null&&s(e,["functionCall"],a);const u=i(t,["functionResponse"]);u!=null&&s(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&s(e,["inlineData"],c);const d=i(t,["text"]);d!=null&&s(e,["text"],d);const f=i(t,["thought"]);f!=null&&s(e,["thought"],f);const p=i(t,["thoughtSignature"]);p!=null&&s(e,["thoughtSignature"],p);const h=i(t,["videoMetadata"]);if(h!=null&&s(e,["videoMetadata"],h),i(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(i(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(i(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function pl(t){const e={},n=i(t,["category"]);if(n!=null&&s(e,["category"],n),i(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");const o=i(t,["threshold"]);return o!=null&&s(e,["threshold"],o),e}function hl(t){const e={},n=i(t,["handle"]);if(n!=null&&s(e,["handle"],n),i(t,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}function ml(t){const e={};if(i(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const n=i(t,["computerUse"]);n!=null&&s(e,["computerUse"],n);const o=i(t,["fileSearch"]);o!=null&&s(e,["fileSearch"],o);const r=i(t,["googleSearch"]);r!=null&&s(e,["googleSearch"],tl(r));const l=i(t,["googleMaps"]);l!=null&&s(e,["googleMaps"],el(l));const a=i(t,["codeExecution"]);if(a!=null&&s(e,["codeExecution"],a),i(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=i(t,["functionDeclarations"]);if(u!=null){let p=u;Array.isArray(p)&&(p=p.map(h=>h)),s(e,["functionDeclarations"],p)}const c=i(t,["googleSearchRetrieval"]);if(c!=null&&s(e,["googleSearchRetrieval"],c),i(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is not supported in Gemini API.");const d=i(t,["urlContext"]);d!=null&&s(e,["urlContext"],d);const f=i(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),s(e,["mcpServers"],p)}return e}function gl(t){const e={},n=i(t,["retrieval"]);n!=null&&s(e,["retrieval"],n);const o=i(t,["computerUse"]);if(o!=null&&s(e,["computerUse"],o),i(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const r=i(t,["googleSearch"]);r!=null&&s(e,["googleSearch"],r);const l=i(t,["googleMaps"]);l!=null&&s(e,["googleMaps"],l);const a=i(t,["codeExecution"]);a!=null&&s(e,["codeExecution"],a);const u=i(t,["enterpriseWebSearch"]);u!=null&&s(e,["enterpriseWebSearch"],u);const c=i(t,["functionDeclarations"]);if(c!=null){let h=c;Array.isArray(h)&&(h=h.map(m=>Zs(m))),s(e,["functionDeclarations"],h)}const d=i(t,["googleSearchRetrieval"]);d!=null&&s(e,["googleSearchRetrieval"],d);const f=i(t,["parallelAiSearch"]);f!=null&&s(e,["parallelAiSearch"],f);const p=i(t,["urlContext"]);if(p!=null&&s(e,["urlContext"],p),i(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return e}function El(t){const e={},n=i(t,["promptTokenCount"]);n!=null&&s(e,["promptTokenCount"],n);const o=i(t,["cachedContentTokenCount"]);o!=null&&s(e,["cachedContentTokenCount"],o);const r=i(t,["candidatesTokenCount"]);r!=null&&s(e,["responseTokenCount"],r);const l=i(t,["toolUsePromptTokenCount"]);l!=null&&s(e,["toolUsePromptTokenCount"],l);const a=i(t,["thoughtsTokenCount"]);a!=null&&s(e,["thoughtsTokenCount"],a);const u=i(t,["totalTokenCount"]);u!=null&&s(e,["totalTokenCount"],u);const c=i(t,["promptTokensDetails"]);if(c!=null){let m=c;Array.isArray(m)&&(m=m.map(g=>g)),s(e,["promptTokensDetails"],m)}const d=i(t,["cacheTokensDetails"]);if(d!=null){let m=d;Array.isArray(m)&&(m=m.map(g=>g)),s(e,["cacheTokensDetails"],m)}const f=i(t,["candidatesTokensDetails"]);if(f!=null){let m=f;Array.isArray(m)&&(m=m.map(g=>g)),s(e,["responseTokensDetails"],m)}const p=i(t,["toolUsePromptTokensDetails"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(g=>g)),s(e,["toolUsePromptTokensDetails"],m)}const h=i(t,["trafficType"]);return h!=null&&s(e,["trafficType"],h),e}function vl(t){const e={},n=i(t,["type"]);return n!=null&&s(e,["voiceActivityType"],n),e}function yl(t,e){const n={},o=i(t,["apiKey"]);if(o!=null&&s(n,["apiKey"],o),i(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(i(t,["authType"])!==void 0)throw new Error("authType parameter is not supported in Gemini API.");if(i(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(i(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(i(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is not supported in Gemini API.");if(i(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is not supported in Gemini API.");return n}function Tl(t,e){const n={},o=i(t,["data"]);if(o!=null&&s(n,["data"],o),i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const r=i(t,["mimeType"]);return r!=null&&s(n,["mimeType"],r),n}function _l(t,e){const n={},o=i(t,["content"]);o!=null&&s(n,["content"],o);const r=i(t,["citationMetadata"]);r!=null&&s(n,["citationMetadata"],Il(r));const l=i(t,["tokenCount"]);l!=null&&s(n,["tokenCount"],l);const a=i(t,["finishReason"]);a!=null&&s(n,["finishReason"],a);const u=i(t,["groundingMetadata"]);u!=null&&s(n,["groundingMetadata"],u);const c=i(t,["avgLogprobs"]);c!=null&&s(n,["avgLogprobs"],c);const d=i(t,["index"]);d!=null&&s(n,["index"],d);const f=i(t,["logprobsResult"]);f!=null&&s(n,["logprobsResult"],f);const p=i(t,["safetyRatings"]);if(p!=null){let m=p;Array.isArray(m)&&(m=m.map(g=>g)),s(n,["safetyRatings"],m)}const h=i(t,["urlContextMetadata"]);return h!=null&&s(n,["urlContextMetadata"],h),n}function Il(t,e){const n={},o=i(t,["citationSources"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>l)),s(n,["citations"],r)}return n}function Cl(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["contents"]);if(l!=null){let a=q(l);Array.isArray(a)&&(a=a.map(u=>he(u))),s(o,["contents"],a)}return o}function Al(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["tokensInfo"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>a)),s(n,["tokensInfo"],l)}return n}function Sl(t,e){const n={},o=i(t,["values"]);o!=null&&s(n,["values"],o);const r=i(t,["statistics"]);return r!=null&&s(n,["statistics"],Rl(r)),n}function Rl(t,e){const n={},o=i(t,["truncated"]);o!=null&&s(n,["truncated"],o);const r=i(t,["token_count"]);return r!=null&&s(n,["tokenCount"],r),n}function Te(t,e){const n={},o=i(t,["parts"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(a=>Ga(a))),s(n,["parts"],l)}const r=i(t,["role"]);return r!=null&&s(n,["role"],r),n}function he(t,e){const n={},o=i(t,["parts"]);if(o!=null){let l=o;Array.isArray(l)&&(l=l.map(a=>ka(a))),s(n,["parts"],l)}const r=i(t,["role"]);return r!=null&&s(n,["role"],r),n}function Pl(t,e){const n={},o=i(t,["controlType"]);o!=null&&s(n,["controlType"],o);const r=i(t,["enableControlImageComputation"]);return r!=null&&s(n,["computeControl"],r),n}function Nl(t,e){const n={};if(i(t,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is not supported in Gemini API.");if(i(t,["tools"])!==void 0)throw new Error("tools parameter is not supported in Gemini API.");if(i(t,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is not supported in Gemini API.");return n}function wl(t,e,n){const o={},r=i(t,["systemInstruction"]);e!==void 0&&r!=null&&s(e,["systemInstruction"],he(F(r)));const l=i(t,["tools"]);if(e!==void 0&&l!=null){let u=l;Array.isArray(u)&&(u=u.map(c=>wo(c))),s(e,["tools"],u)}const a=i(t,["generationConfig"]);return e!==void 0&&a!=null&&s(e,["generationConfig"],Ta(a)),o}function Ml(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["contents"]);if(l!=null){let u=q(l);Array.isArray(u)&&(u=u.map(c=>Te(c))),s(o,["contents"],u)}const a=i(e,["config"]);return a!=null&&Nl(a),o}function Dl(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["contents"]);if(l!=null){let u=q(l);Array.isArray(u)&&(u=u.map(c=>he(c))),s(o,["contents"],u)}const a=i(e,["config"]);return a!=null&&wl(a,o),o}function xl(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["totalTokens"]);r!=null&&s(n,["totalTokens"],r);const l=i(t,["cachedContentTokenCount"]);return l!=null&&s(n,["cachedContentTokenCount"],l),n}function Ul(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["totalTokens"]);return r!=null&&s(n,["totalTokens"],r),n}function Ll(t,e,n){const o={},r=i(e,["model"]);return r!=null&&s(o,["_url","name"],D(t,r)),o}function Gl(t,e,n){const o={},r=i(e,["model"]);return r!=null&&s(o,["_url","name"],D(t,r)),o}function kl(t,e){const n={},o=i(t,["sdkHttpResponse"]);return o!=null&&s(n,["sdkHttpResponse"],o),n}function Fl(t,e){const n={},o=i(t,["sdkHttpResponse"]);return o!=null&&s(n,["sdkHttpResponse"],o),n}function Vl(t,e,n){const o={},r=i(t,["outputGcsUri"]);e!==void 0&&r!=null&&s(e,["parameters","storageUri"],r);const l=i(t,["negativePrompt"]);e!==void 0&&l!=null&&s(e,["parameters","negativePrompt"],l);const a=i(t,["numberOfImages"]);e!==void 0&&a!=null&&s(e,["parameters","sampleCount"],a);const u=i(t,["aspectRatio"]);e!==void 0&&u!=null&&s(e,["parameters","aspectRatio"],u);const c=i(t,["guidanceScale"]);e!==void 0&&c!=null&&s(e,["parameters","guidanceScale"],c);const d=i(t,["seed"]);e!==void 0&&d!=null&&s(e,["parameters","seed"],d);const f=i(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&s(e,["parameters","safetySetting"],f);const p=i(t,["personGeneration"]);e!==void 0&&p!=null&&s(e,["parameters","personGeneration"],p);const h=i(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&s(e,["parameters","includeSafetyAttributes"],h);const m=i(t,["includeRaiReason"]);e!==void 0&&m!=null&&s(e,["parameters","includeRaiReason"],m);const g=i(t,["language"]);e!==void 0&&g!=null&&s(e,["parameters","language"],g);const v=i(t,["outputMimeType"]);e!==void 0&&v!=null&&s(e,["parameters","outputOptions","mimeType"],v);const E=i(t,["outputCompressionQuality"]);e!==void 0&&E!=null&&s(e,["parameters","outputOptions","compressionQuality"],E);const y=i(t,["addWatermark"]);e!==void 0&&y!=null&&s(e,["parameters","addWatermark"],y);const A=i(t,["labels"]);e!==void 0&&A!=null&&s(e,["labels"],A);const I=i(t,["editMode"]);e!==void 0&&I!=null&&s(e,["parameters","editMode"],I);const S=i(t,["baseSteps"]);return e!==void 0&&S!=null&&s(e,["parameters","editConfig","baseSteps"],S),o}function Hl(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["prompt"]);l!=null&&s(o,["instances[0]","prompt"],l);const a=i(e,["referenceImages"]);if(a!=null){let c=a;Array.isArray(c)&&(c=c.map(d=>Ja(d))),s(o,["instances[0]","referenceImages"],c)}const u=i(e,["config"]);return u!=null&&Vl(u,o),o}function ql(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["predictions"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>Le(a))),s(n,["generatedImages"],l)}return n}function Bl(t,e,n){const o={},r=i(t,["taskType"]);e!==void 0&&r!=null&&s(e,["requests[]","taskType"],r);const l=i(t,["title"]);e!==void 0&&l!=null&&s(e,["requests[]","title"],l);const a=i(t,["outputDimensionality"]);if(e!==void 0&&a!=null&&s(e,["requests[]","outputDimensionality"],a),i(t,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(i(t,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");if(i(t,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is not supported in Gemini API.");if(i(t,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is not supported in Gemini API.");return o}function Jl(t,e,n){const o={};let r=i(n,["embeddingApiType"]);if(r===void 0&&(r="PREDICT"),r==="PREDICT"){const p=i(t,["taskType"]);e!==void 0&&p!=null&&s(e,["instances[]","task_type"],p)}else if(r==="EMBED_CONTENT"){const p=i(t,["taskType"]);e!==void 0&&p!=null&&s(e,["embedContentConfig","taskType"],p)}let l=i(n,["embeddingApiType"]);if(l===void 0&&(l="PREDICT"),l==="PREDICT"){const p=i(t,["title"]);e!==void 0&&p!=null&&s(e,["instances[]","title"],p)}else if(l==="EMBED_CONTENT"){const p=i(t,["title"]);e!==void 0&&p!=null&&s(e,["embedContentConfig","title"],p)}let a=i(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="PREDICT"){const p=i(t,["outputDimensionality"]);e!==void 0&&p!=null&&s(e,["parameters","outputDimensionality"],p)}else if(a==="EMBED_CONTENT"){const p=i(t,["outputDimensionality"]);e!==void 0&&p!=null&&s(e,["embedContentConfig","outputDimensionality"],p)}let u=i(n,["embeddingApiType"]);if(u===void 0&&(u="PREDICT"),u==="PREDICT"){const p=i(t,["mimeType"]);e!==void 0&&p!=null&&s(e,["instances[]","mimeType"],p)}let c=i(n,["embeddingApiType"]);if(c===void 0&&(c="PREDICT"),c==="PREDICT"){const p=i(t,["autoTruncate"]);e!==void 0&&p!=null&&s(e,["parameters","autoTruncate"],p)}else if(c==="EMBED_CONTENT"){const p=i(t,["autoTruncate"]);e!==void 0&&p!=null&&s(e,["embedContentConfig","autoTruncate"],p)}let d=i(n,["embeddingApiType"]);if(d===void 0&&(d="PREDICT"),d==="EMBED_CONTENT"){const p=i(t,["documentOcr"]);e!==void 0&&p!=null&&s(e,["embedContentConfig","documentOcr"],p)}let f=i(n,["embeddingApiType"]);if(f===void 0&&(f="PREDICT"),f==="EMBED_CONTENT"){const p=i(t,["audioTrackExtraction"]);e!==void 0&&p!=null&&s(e,["embedContentConfig","audioTrackExtraction"],p)}return o}function bl(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["contents"]);if(l!=null){let d=ct(t,l);Array.isArray(d)&&(d=d.map(f=>f)),s(o,["requests[]","content"],d)}const a=i(e,["content"]);a!=null&&Te(F(a));const u=i(e,["config"]);u!=null&&Bl(u,o);const c=i(e,["model"]);return c!==void 0&&s(o,["requests[]","model"],D(t,c)),o}function $l(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));let l=i(n,["embeddingApiType"]);if(l===void 0&&(l="PREDICT"),l==="PREDICT"){const c=i(e,["contents"]);if(c!=null){let d=ct(t,c);Array.isArray(d)&&(d=d.map(f=>f)),s(o,["instances[]","content"],d)}}let a=i(n,["embeddingApiType"]);if(a===void 0&&(a="PREDICT"),a==="EMBED_CONTENT"){const c=i(e,["content"]);c!=null&&s(o,["content"],he(F(c)))}const u=i(e,["config"]);return u!=null&&Jl(u,o,n),o}function Ol(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["embeddings"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>u)),s(n,["embeddings"],a)}const l=i(t,["metadata"]);return l!=null&&s(n,["metadata"],l),n}function Yl(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["predictions[]","embeddings"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>Sl(u))),s(n,["embeddings"],a)}const l=i(t,["metadata"]);if(l!=null&&s(n,["metadata"],l),e&&i(e,["embeddingApiType"])==="EMBED_CONTENT"){const a=i(t,["embedding"]),u=i(t,["usageMetadata"]),c=i(t,["truncated"]);if(a){const d={};u&&u.promptTokenCount&&(d.tokenCount=u.promptTokenCount),c&&(d.truncated=c),a.statistics=d,s(n,["embeddings"],[a])}}return n}function Kl(t,e){const n={},o=i(t,["endpoint"]);o!=null&&s(n,["name"],o);const r=i(t,["deployedModelId"]);return r!=null&&s(n,["deployedModelId"],r),n}function Wl(t,e){const n={};if(i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const o=i(t,["fileUri"]);o!=null&&s(n,["fileUri"],o);const r=i(t,["mimeType"]);return r!=null&&s(n,["mimeType"],r),n}function zl(t,e){const n={},o=i(t,["id"]);o!=null&&s(n,["id"],o);const r=i(t,["args"]);r!=null&&s(n,["args"],r);const l=i(t,["name"]);if(l!=null&&s(n,["name"],l),i(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(i(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return n}function Xl(t,e){const n={},o=i(t,["allowedFunctionNames"]);o!=null&&s(n,["allowedFunctionNames"],o);const r=i(t,["mode"]);if(r!=null&&s(n,["mode"],r),i(t,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return n}function Ql(t,e){const n={},o=i(t,["description"]);o!=null&&s(n,["description"],o);const r=i(t,["name"]);r!=null&&s(n,["name"],r);const l=i(t,["parameters"]);l!=null&&s(n,["parameters"],l);const a=i(t,["parametersJsonSchema"]);a!=null&&s(n,["parametersJsonSchema"],a);const u=i(t,["response"]);u!=null&&s(n,["response"],u);const c=i(t,["responseJsonSchema"]);if(c!=null&&s(n,["responseJsonSchema"],c),i(t,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function Zl(t,e,n,o){const r={},l=i(e,["systemInstruction"]);n!==void 0&&l!=null&&s(n,["systemInstruction"],Te(F(l)));const a=i(e,["temperature"]);a!=null&&s(r,["temperature"],a);const u=i(e,["topP"]);u!=null&&s(r,["topP"],u);const c=i(e,["topK"]);c!=null&&s(r,["topK"],c);const d=i(e,["candidateCount"]);d!=null&&s(r,["candidateCount"],d);const f=i(e,["maxOutputTokens"]);f!=null&&s(r,["maxOutputTokens"],f);const p=i(e,["stopSequences"]);p!=null&&s(r,["stopSequences"],p);const h=i(e,["responseLogprobs"]);h!=null&&s(r,["responseLogprobs"],h);const m=i(e,["logprobs"]);m!=null&&s(r,["logprobs"],m);const g=i(e,["presencePenalty"]);g!=null&&s(r,["presencePenalty"],g);const v=i(e,["frequencyPenalty"]);v!=null&&s(r,["frequencyPenalty"],v);const E=i(e,["seed"]);E!=null&&s(r,["seed"],E);const y=i(e,["responseMimeType"]);y!=null&&s(r,["responseMimeType"],y);const A=i(e,["responseSchema"]);A!=null&&s(r,["responseSchema"],ft(A));const I=i(e,["responseJsonSchema"]);if(I!=null&&s(r,["responseJsonSchema"],I),i(e,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(i(e,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");const S=i(e,["safetySettings"]);if(n!==void 0&&S!=null){let U=S;Array.isArray(U)&&(U=U.map(z=>ba(z))),s(n,["safetySettings"],U)}const R=i(e,["tools"]);if(n!==void 0&&R!=null){let U=fe(R);Array.isArray(U)&&(U=U.map(z=>Qa(ce(z)))),s(n,["tools"],U)}const T=i(e,["toolConfig"]);if(n!==void 0&&T!=null&&s(n,["toolConfig"],za(T)),i(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const w=i(e,["cachedContent"]);n!==void 0&&w!=null&&s(n,["cachedContent"],Z(t,w));const P=i(e,["responseModalities"]);P!=null&&s(r,["responseModalities"],P);const C=i(e,["mediaResolution"]);C!=null&&s(r,["mediaResolution"],C);const M=i(e,["speechConfig"]);if(M!=null&&s(r,["speechConfig"],pt(M)),i(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");const x=i(e,["thinkingConfig"]);x!=null&&s(r,["thinkingConfig"],x);const B=i(e,["imageConfig"]);B!=null&&s(r,["imageConfig"],Sa(B));const b=i(e,["enableEnhancedCivicAnswers"]);if(b!=null&&s(r,["enableEnhancedCivicAnswers"],b),i(e,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is not supported in Gemini API.");const k=i(e,["serviceTier"]);return n!==void 0&&k!=null&&s(n,["serviceTier"],k),r}function jl(t,e,n,o){const r={},l=i(e,["systemInstruction"]);n!==void 0&&l!=null&&s(n,["systemInstruction"],he(F(l)));const a=i(e,["temperature"]);a!=null&&s(r,["temperature"],a);const u=i(e,["topP"]);u!=null&&s(r,["topP"],u);const c=i(e,["topK"]);c!=null&&s(r,["topK"],c);const d=i(e,["candidateCount"]);d!=null&&s(r,["candidateCount"],d);const f=i(e,["maxOutputTokens"]);f!=null&&s(r,["maxOutputTokens"],f);const p=i(e,["stopSequences"]);p!=null&&s(r,["stopSequences"],p);const h=i(e,["responseLogprobs"]);h!=null&&s(r,["responseLogprobs"],h);const m=i(e,["logprobs"]);m!=null&&s(r,["logprobs"],m);const g=i(e,["presencePenalty"]);g!=null&&s(r,["presencePenalty"],g);const v=i(e,["frequencyPenalty"]);v!=null&&s(r,["frequencyPenalty"],v);const E=i(e,["seed"]);E!=null&&s(r,["seed"],E);const y=i(e,["responseMimeType"]);y!=null&&s(r,["responseMimeType"],y);const A=i(e,["responseSchema"]);A!=null&&s(r,["responseSchema"],ft(A));const I=i(e,["responseJsonSchema"]);I!=null&&s(r,["responseJsonSchema"],I);const S=i(e,["routingConfig"]);S!=null&&s(r,["routingConfig"],S);const R=i(e,["modelSelectionConfig"]);R!=null&&s(r,["modelConfig"],R);const T=i(e,["safetySettings"]);if(n!==void 0&&T!=null){let $=T;Array.isArray($)&&($=$.map(He=>He)),s(n,["safetySettings"],$)}const w=i(e,["tools"]);if(n!==void 0&&w!=null){let $=fe(w);Array.isArray($)&&($=$.map(He=>wo(ce(He)))),s(n,["tools"],$)}const P=i(e,["toolConfig"]);n!==void 0&&P!=null&&s(n,["toolConfig"],Xa(P));const C=i(e,["labels"]);n!==void 0&&C!=null&&s(n,["labels"],C);const M=i(e,["cachedContent"]);n!==void 0&&M!=null&&s(n,["cachedContent"],Z(t,M));const x=i(e,["responseModalities"]);x!=null&&s(r,["responseModalities"],x);const B=i(e,["mediaResolution"]);B!=null&&s(r,["mediaResolution"],B);const b=i(e,["speechConfig"]);b!=null&&s(r,["speechConfig"],pt(b));const k=i(e,["audioTimestamp"]);k!=null&&s(r,["audioTimestamp"],k);const U=i(e,["thinkingConfig"]);U!=null&&s(r,["thinkingConfig"],U);const z=i(e,["imageConfig"]);if(z!=null&&s(r,["imageConfig"],Ra(z)),i(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const me=i(e,["modelArmorConfig"]);n!==void 0&&me!=null&&s(n,["modelArmorConfig"],me);const ne=i(e,["serviceTier"]);return n!==void 0&&ne!=null&&s(n,["serviceTier"],ne),r}function Yn(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["contents"]);if(l!=null){let u=q(l);Array.isArray(u)&&(u=u.map(c=>Te(c))),s(o,["contents"],u)}const a=i(e,["config"]);return a!=null&&s(o,["generationConfig"],Zl(t,a,o)),o}function Kn(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["contents"]);if(l!=null){let u=q(l);Array.isArray(u)&&(u=u.map(c=>he(c))),s(o,["contents"],u)}const a=i(e,["config"]);return a!=null&&s(o,["generationConfig"],jl(t,a,o)),o}function Wn(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["candidates"]);if(r!=null){let f=r;Array.isArray(f)&&(f=f.map(p=>_l(p))),s(n,["candidates"],f)}const l=i(t,["modelVersion"]);l!=null&&s(n,["modelVersion"],l);const a=i(t,["promptFeedback"]);a!=null&&s(n,["promptFeedback"],a);const u=i(t,["responseId"]);u!=null&&s(n,["responseId"],u);const c=i(t,["usageMetadata"]);c!=null&&s(n,["usageMetadata"],c);const d=i(t,["modelStatus"]);return d!=null&&s(n,["modelStatus"],d),n}function zn(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["candidates"]);if(r!=null){let f=r;Array.isArray(f)&&(f=f.map(p=>p)),s(n,["candidates"],f)}const l=i(t,["createTime"]);l!=null&&s(n,["createTime"],l);const a=i(t,["modelVersion"]);a!=null&&s(n,["modelVersion"],a);const u=i(t,["promptFeedback"]);u!=null&&s(n,["promptFeedback"],u);const c=i(t,["responseId"]);c!=null&&s(n,["responseId"],c);const d=i(t,["usageMetadata"]);return d!=null&&s(n,["usageMetadata"],d),n}function ea(t,e,n){const o={};if(i(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(i(t,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is not supported in Gemini API.");const r=i(t,["numberOfImages"]);e!==void 0&&r!=null&&s(e,["parameters","sampleCount"],r);const l=i(t,["aspectRatio"]);e!==void 0&&l!=null&&s(e,["parameters","aspectRatio"],l);const a=i(t,["guidanceScale"]);if(e!==void 0&&a!=null&&s(e,["parameters","guidanceScale"],a),i(t,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");const u=i(t,["safetyFilterLevel"]);e!==void 0&&u!=null&&s(e,["parameters","safetySetting"],u);const c=i(t,["personGeneration"]);e!==void 0&&c!=null&&s(e,["parameters","personGeneration"],c);const d=i(t,["includeSafetyAttributes"]);e!==void 0&&d!=null&&s(e,["parameters","includeSafetyAttributes"],d);const f=i(t,["includeRaiReason"]);e!==void 0&&f!=null&&s(e,["parameters","includeRaiReason"],f);const p=i(t,["language"]);e!==void 0&&p!=null&&s(e,["parameters","language"],p);const h=i(t,["outputMimeType"]);e!==void 0&&h!=null&&s(e,["parameters","outputOptions","mimeType"],h);const m=i(t,["outputCompressionQuality"]);if(e!==void 0&&m!=null&&s(e,["parameters","outputOptions","compressionQuality"],m),i(t,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is not supported in Gemini API.");if(i(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const g=i(t,["imageSize"]);if(e!==void 0&&g!=null&&s(e,["parameters","sampleImageSize"],g),i(t,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is not supported in Gemini API.");return o}function ta(t,e,n){const o={},r=i(t,["outputGcsUri"]);e!==void 0&&r!=null&&s(e,["parameters","storageUri"],r);const l=i(t,["negativePrompt"]);e!==void 0&&l!=null&&s(e,["parameters","negativePrompt"],l);const a=i(t,["numberOfImages"]);e!==void 0&&a!=null&&s(e,["parameters","sampleCount"],a);const u=i(t,["aspectRatio"]);e!==void 0&&u!=null&&s(e,["parameters","aspectRatio"],u);const c=i(t,["guidanceScale"]);e!==void 0&&c!=null&&s(e,["parameters","guidanceScale"],c);const d=i(t,["seed"]);e!==void 0&&d!=null&&s(e,["parameters","seed"],d);const f=i(t,["safetyFilterLevel"]);e!==void 0&&f!=null&&s(e,["parameters","safetySetting"],f);const p=i(t,["personGeneration"]);e!==void 0&&p!=null&&s(e,["parameters","personGeneration"],p);const h=i(t,["includeSafetyAttributes"]);e!==void 0&&h!=null&&s(e,["parameters","includeSafetyAttributes"],h);const m=i(t,["includeRaiReason"]);e!==void 0&&m!=null&&s(e,["parameters","includeRaiReason"],m);const g=i(t,["language"]);e!==void 0&&g!=null&&s(e,["parameters","language"],g);const v=i(t,["outputMimeType"]);e!==void 0&&v!=null&&s(e,["parameters","outputOptions","mimeType"],v);const E=i(t,["outputCompressionQuality"]);e!==void 0&&E!=null&&s(e,["parameters","outputOptions","compressionQuality"],E);const y=i(t,["addWatermark"]);e!==void 0&&y!=null&&s(e,["parameters","addWatermark"],y);const A=i(t,["labels"]);e!==void 0&&A!=null&&s(e,["labels"],A);const I=i(t,["imageSize"]);e!==void 0&&I!=null&&s(e,["parameters","sampleImageSize"],I);const S=i(t,["enhancePrompt"]);return e!==void 0&&S!=null&&s(e,["parameters","enhancePrompt"],S),o}function na(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["prompt"]);l!=null&&s(o,["instances[0]","prompt"],l);const a=i(e,["config"]);return a!=null&&ea(a,o),o}function oa(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["prompt"]);l!=null&&s(o,["instances[0]","prompt"],l);const a=i(e,["config"]);return a!=null&&ta(a,o),o}function ia(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["predictions"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>ga(u))),s(n,["generatedImages"],a)}const l=i(t,["positivePromptSafetyAttributes"]);return l!=null&&s(n,["positivePromptSafetyAttributes"],Po(l)),n}function ra(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["predictions"]);if(r!=null){let a=r;Array.isArray(a)&&(a=a.map(u=>Le(u))),s(n,["generatedImages"],a)}const l=i(t,["positivePromptSafetyAttributes"]);return l!=null&&s(n,["positivePromptSafetyAttributes"],No(l)),n}function sa(t,e,n){const o={},r=i(t,["numberOfVideos"]);if(e!==void 0&&r!=null&&s(e,["parameters","sampleCount"],r),i(t,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(i(t,["fps"])!==void 0)throw new Error("fps parameter is not supported in Gemini API.");const l=i(t,["durationSeconds"]);if(e!==void 0&&l!=null&&s(e,["parameters","durationSeconds"],l),i(t,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");const a=i(t,["aspectRatio"]);e!==void 0&&a!=null&&s(e,["parameters","aspectRatio"],a);const u=i(t,["resolution"]);e!==void 0&&u!=null&&s(e,["parameters","resolution"],u);const c=i(t,["personGeneration"]);if(e!==void 0&&c!=null&&s(e,["parameters","personGeneration"],c),i(t,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is not supported in Gemini API.");const d=i(t,["negativePrompt"]);e!==void 0&&d!=null&&s(e,["parameters","negativePrompt"],d);const f=i(t,["enhancePrompt"]);if(e!==void 0&&f!=null&&s(e,["parameters","enhancePrompt"],f),i(t,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is not supported in Gemini API.");const p=i(t,["lastFrame"]);e!==void 0&&p!=null&&s(e,["instances[0]","lastFrame"],Ge(p));const h=i(t,["referenceImages"]);if(e!==void 0&&h!=null){let g=h;Array.isArray(g)&&(g=g.map(v=>du(v))),s(e,["instances[0]","referenceImages"],g)}if(i(t,["mask"])!==void 0)throw new Error("mask parameter is not supported in Gemini API.");if(i(t,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is not supported in Gemini API.");if(i(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const m=i(t,["webhookConfig"]);if(e!==void 0&&m!=null&&s(e,["webhookConfig"],m),i(t,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is not supported in Gemini API.");return o}function la(t,e,n){const o={},r=i(t,["numberOfVideos"]);e!==void 0&&r!=null&&s(e,["parameters","sampleCount"],r);const l=i(t,["outputGcsUri"]);e!==void 0&&l!=null&&s(e,["parameters","storageUri"],l);const a=i(t,["fps"]);e!==void 0&&a!=null&&s(e,["parameters","fps"],a);const u=i(t,["durationSeconds"]);e!==void 0&&u!=null&&s(e,["parameters","durationSeconds"],u);const c=i(t,["seed"]);e!==void 0&&c!=null&&s(e,["parameters","seed"],c);const d=i(t,["aspectRatio"]);e!==void 0&&d!=null&&s(e,["parameters","aspectRatio"],d);const f=i(t,["resolution"]);e!==void 0&&f!=null&&s(e,["parameters","resolution"],f);const p=i(t,["personGeneration"]);e!==void 0&&p!=null&&s(e,["parameters","personGeneration"],p);const h=i(t,["pubsubTopic"]);e!==void 0&&h!=null&&s(e,["parameters","pubsubTopic"],h);const m=i(t,["negativePrompt"]);e!==void 0&&m!=null&&s(e,["parameters","negativePrompt"],m);const g=i(t,["enhancePrompt"]);e!==void 0&&g!=null&&s(e,["parameters","enhancePrompt"],g);const v=i(t,["generateAudio"]);e!==void 0&&v!=null&&s(e,["parameters","generateAudio"],v);const E=i(t,["lastFrame"]);e!==void 0&&E!=null&&s(e,["instances[0]","lastFrame"],W(E));const y=i(t,["referenceImages"]);if(e!==void 0&&y!=null){let T=y;Array.isArray(T)&&(T=T.map(w=>cu(w))),s(e,["instances[0]","referenceImages"],T)}const A=i(t,["mask"]);e!==void 0&&A!=null&&s(e,["instances[0]","mask"],uu(A));const I=i(t,["compressionQuality"]);e!==void 0&&I!=null&&s(e,["parameters","compressionQuality"],I);const S=i(t,["labels"]);if(e!==void 0&&S!=null&&s(e,["labels"],S),i(t,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const R=i(t,["resizeMode"]);return e!==void 0&&R!=null&&s(e,["parameters","resizeMode"],R),o}function aa(t,e){const n={},o=i(t,["name"]);o!=null&&s(n,["name"],o);const r=i(t,["metadata"]);r!=null&&s(n,["metadata"],r);const l=i(t,["done"]);l!=null&&s(n,["done"],l);const a=i(t,["error"]);a!=null&&s(n,["error"],a);const u=i(t,["response","generateVideoResponse"]);return u!=null&&s(n,["response"],fa(u)),n}function ua(t,e){const n={},o=i(t,["name"]);o!=null&&s(n,["name"],o);const r=i(t,["metadata"]);r!=null&&s(n,["metadata"],r);const l=i(t,["done"]);l!=null&&s(n,["done"],l);const a=i(t,["error"]);a!=null&&s(n,["error"],a);const u=i(t,["response"]);return u!=null&&s(n,["response"],pa(u)),n}function da(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["prompt"]);l!=null&&s(o,["instances[0]","prompt"],l);const a=i(e,["image"]);a!=null&&s(o,["instances[0]","image"],Ge(a));const u=i(e,["video"]);u!=null&&s(o,["instances[0]","video"],Mo(u));const c=i(e,["source"]);c!=null&&ha(c,o);const d=i(e,["config"]);return d!=null&&sa(d,o),o}function ca(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["prompt"]);l!=null&&s(o,["instances[0]","prompt"],l);const a=i(e,["image"]);a!=null&&s(o,["instances[0]","image"],W(a));const u=i(e,["video"]);u!=null&&s(o,["instances[0]","video"],Do(u));const c=i(e,["source"]);c!=null&&ma(c,o);const d=i(e,["config"]);return d!=null&&la(d,o),o}function fa(t,e){const n={},o=i(t,["generatedSamples"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>va(u))),s(n,["generatedVideos"],a)}const r=i(t,["raiMediaFilteredCount"]);r!=null&&s(n,["raiMediaFilteredCount"],r);const l=i(t,["raiMediaFilteredReasons"]);return l!=null&&s(n,["raiMediaFilteredReasons"],l),n}function pa(t,e){const n={},o=i(t,["videos"]);if(o!=null){let a=o;Array.isArray(a)&&(a=a.map(u=>ya(u))),s(n,["generatedVideos"],a)}const r=i(t,["raiMediaFilteredCount"]);r!=null&&s(n,["raiMediaFilteredCount"],r);const l=i(t,["raiMediaFilteredReasons"]);return l!=null&&s(n,["raiMediaFilteredReasons"],l),n}function ha(t,e,n){const o={},r=i(t,["prompt"]);e!==void 0&&r!=null&&s(e,["instances[0]","prompt"],r);const l=i(t,["image"]);e!==void 0&&l!=null&&s(e,["instances[0]","image"],Ge(l));const a=i(t,["video"]);return e!==void 0&&a!=null&&s(e,["instances[0]","video"],Mo(a)),o}function ma(t,e,n){const o={},r=i(t,["prompt"]);e!==void 0&&r!=null&&s(e,["instances[0]","prompt"],r);const l=i(t,["image"]);e!==void 0&&l!=null&&s(e,["instances[0]","image"],W(l));const a=i(t,["video"]);return e!==void 0&&a!=null&&s(e,["instances[0]","video"],Do(a)),o}function ga(t,e){const n={},o=i(t,["_self"]);o!=null&&s(n,["image"],Pa(o));const r=i(t,["raiFilteredReason"]);r!=null&&s(n,["raiFilteredReason"],r);const l=i(t,["_self"]);return l!=null&&s(n,["safetyAttributes"],Po(l)),n}function Le(t,e){const n={},o=i(t,["_self"]);o!=null&&s(n,["image"],Ro(o));const r=i(t,["raiFilteredReason"]);r!=null&&s(n,["raiFilteredReason"],r);const l=i(t,["_self"]);l!=null&&s(n,["safetyAttributes"],No(l));const a=i(t,["prompt"]);return a!=null&&s(n,["enhancedPrompt"],a),n}function Ea(t,e){const n={},o=i(t,["_self"]);o!=null&&s(n,["mask"],Ro(o));const r=i(t,["labels"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>a)),s(n,["labels"],l)}return n}function va(t,e){const n={},o=i(t,["video"]);return o!=null&&s(n,["video"],lu(o)),n}function ya(t,e){const n={},o=i(t,["_self"]);return o!=null&&s(n,["video"],au(o)),n}function Ta(t,e){const n={},o=i(t,["modelSelectionConfig"]);o!=null&&s(n,["modelConfig"],o);const r=i(t,["responseJsonSchema"]);r!=null&&s(n,["responseJsonSchema"],r);const l=i(t,["audioTimestamp"]);l!=null&&s(n,["audioTimestamp"],l);const a=i(t,["candidateCount"]);a!=null&&s(n,["candidateCount"],a);const u=i(t,["enableAffectiveDialog"]);u!=null&&s(n,["enableAffectiveDialog"],u);const c=i(t,["frequencyPenalty"]);c!=null&&s(n,["frequencyPenalty"],c);const d=i(t,["logprobs"]);d!=null&&s(n,["logprobs"],d);const f=i(t,["maxOutputTokens"]);f!=null&&s(n,["maxOutputTokens"],f);const p=i(t,["mediaResolution"]);p!=null&&s(n,["mediaResolution"],p);const h=i(t,["presencePenalty"]);h!=null&&s(n,["presencePenalty"],h);const m=i(t,["responseLogprobs"]);m!=null&&s(n,["responseLogprobs"],m);const g=i(t,["responseMimeType"]);g!=null&&s(n,["responseMimeType"],g);const v=i(t,["responseModalities"]);v!=null&&s(n,["responseModalities"],v);const E=i(t,["responseSchema"]);E!=null&&s(n,["responseSchema"],E);const y=i(t,["routingConfig"]);y!=null&&s(n,["routingConfig"],y);const A=i(t,["seed"]);A!=null&&s(n,["seed"],A);const I=i(t,["speechConfig"]);I!=null&&s(n,["speechConfig"],I);const S=i(t,["stopSequences"]);S!=null&&s(n,["stopSequences"],S);const R=i(t,["temperature"]);R!=null&&s(n,["temperature"],R);const T=i(t,["thinkingConfig"]);T!=null&&s(n,["thinkingConfig"],T);const w=i(t,["topK"]);w!=null&&s(n,["topK"],w);const P=i(t,["topP"]);if(P!=null&&s(n,["topP"],P),i(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function _a(t,e,n){const o={},r=i(e,["model"]);return r!=null&&s(o,["_url","name"],D(t,r)),o}function Ia(t,e,n){const o={},r=i(e,["model"]);return r!=null&&s(o,["_url","name"],D(t,r)),o}function Ca(t,e){const n={},o=i(t,["authConfig"]);o!=null&&s(n,["authConfig"],yl(o));const r=i(t,["enableWidget"]);return r!=null&&s(n,["enableWidget"],r),n}function Aa(t,e){const n={},o=i(t,["searchTypes"]);if(o!=null&&s(n,["searchTypes"],o),i(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(i(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");const r=i(t,["timeRangeFilter"]);return r!=null&&s(n,["timeRangeFilter"],r),n}function Sa(t,e){const n={},o=i(t,["aspectRatio"]);o!=null&&s(n,["aspectRatio"],o);const r=i(t,["imageSize"]);if(r!=null&&s(n,["imageSize"],r),i(t,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is not supported in Gemini API.");if(i(t,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is not supported in Gemini API.");if(i(t,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(i(t,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");if(i(t,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is not supported in Gemini API.");return n}function Ra(t,e){const n={},o=i(t,["aspectRatio"]);o!=null&&s(n,["aspectRatio"],o);const r=i(t,["imageSize"]);r!=null&&s(n,["imageSize"],r);const l=i(t,["personGeneration"]);l!=null&&s(n,["personGeneration"],l);const a=i(t,["prominentPeople"]);a!=null&&s(n,["prominentPeople"],a);const u=i(t,["outputMimeType"]);u!=null&&s(n,["imageOutputOptions","mimeType"],u);const c=i(t,["outputCompressionQuality"]);c!=null&&s(n,["imageOutputOptions","compressionQuality"],c);const d=i(t,["imageOutputOptions"]);return d!=null&&s(n,["imageOutputOptions"],d),n}function Pa(t,e){const n={},o=i(t,["bytesBase64Encoded"]);o!=null&&s(n,["imageBytes"],te(o));const r=i(t,["mimeType"]);return r!=null&&s(n,["mimeType"],r),n}function Ro(t,e){const n={},o=i(t,["gcsUri"]);o!=null&&s(n,["gcsUri"],o);const r=i(t,["bytesBase64Encoded"]);r!=null&&s(n,["imageBytes"],te(r));const l=i(t,["mimeType"]);return l!=null&&s(n,["mimeType"],l),n}function Ge(t,e){const n={};if(i(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");const o=i(t,["imageBytes"]);o!=null&&s(n,["bytesBase64Encoded"],te(o));const r=i(t,["mimeType"]);return r!=null&&s(n,["mimeType"],r),n}function W(t,e){const n={},o=i(t,["gcsUri"]);o!=null&&s(n,["gcsUri"],o);const r=i(t,["imageBytes"]);r!=null&&s(n,["bytesBase64Encoded"],te(r));const l=i(t,["mimeType"]);return l!=null&&s(n,["mimeType"],l),n}function Na(t,e,n,o){const r={},l=i(e,["pageSize"]);n!==void 0&&l!=null&&s(n,["_query","pageSize"],l);const a=i(e,["pageToken"]);n!==void 0&&a!=null&&s(n,["_query","pageToken"],a);const u=i(e,["filter"]);n!==void 0&&u!=null&&s(n,["_query","filter"],u);const c=i(e,["queryBase"]);return n!==void 0&&c!=null&&s(n,["_url","models_url"],yo(t,c)),r}function wa(t,e,n,o){const r={},l=i(e,["pageSize"]);n!==void 0&&l!=null&&s(n,["_query","pageSize"],l);const a=i(e,["pageToken"]);n!==void 0&&a!=null&&s(n,["_query","pageToken"],a);const u=i(e,["filter"]);n!==void 0&&u!=null&&s(n,["_query","filter"],u);const c=i(e,["queryBase"]);return n!==void 0&&c!=null&&s(n,["_url","models_url"],yo(t,c)),r}function Ma(t,e,n){const o={},r=i(e,["config"]);return r!=null&&Na(t,r,o),o}function Da(t,e,n){const o={},r=i(e,["config"]);return r!=null&&wa(t,r,o),o}function xa(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["nextPageToken"]);r!=null&&s(n,["nextPageToken"],r);const l=i(t,["_self"]);if(l!=null){let a=To(l);Array.isArray(a)&&(a=a.map(u=>je(u))),s(n,["models"],a)}return n}function Ua(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["nextPageToken"]);r!=null&&s(n,["nextPageToken"],r);const l=i(t,["_self"]);if(l!=null){let a=To(l);Array.isArray(a)&&(a=a.map(u=>et(u))),s(n,["models"],a)}return n}function La(t,e){const n={},o=i(t,["maskMode"]);o!=null&&s(n,["maskMode"],o);const r=i(t,["segmentationClasses"]);r!=null&&s(n,["maskClasses"],r);const l=i(t,["maskDilation"]);return l!=null&&s(n,["dilation"],l),n}function je(t,e){const n={},o=i(t,["name"]);o!=null&&s(n,["name"],o);const r=i(t,["displayName"]);r!=null&&s(n,["displayName"],r);const l=i(t,["description"]);l!=null&&s(n,["description"],l);const a=i(t,["version"]);a!=null&&s(n,["version"],a);const u=i(t,["_self"]);u!=null&&s(n,["tunedModelInfo"],Za(u));const c=i(t,["inputTokenLimit"]);c!=null&&s(n,["inputTokenLimit"],c);const d=i(t,["outputTokenLimit"]);d!=null&&s(n,["outputTokenLimit"],d);const f=i(t,["supportedGenerationMethods"]);f!=null&&s(n,["supportedActions"],f);const p=i(t,["temperature"]);p!=null&&s(n,["temperature"],p);const h=i(t,["maxTemperature"]);h!=null&&s(n,["maxTemperature"],h);const m=i(t,["topP"]);m!=null&&s(n,["topP"],m);const g=i(t,["topK"]);g!=null&&s(n,["topK"],g);const v=i(t,["thinking"]);return v!=null&&s(n,["thinking"],v),n}function et(t,e){const n={},o=i(t,["name"]);o!=null&&s(n,["name"],o);const r=i(t,["displayName"]);r!=null&&s(n,["displayName"],r);const l=i(t,["description"]);l!=null&&s(n,["description"],l);const a=i(t,["versionId"]);a!=null&&s(n,["version"],a);const u=i(t,["deployedModels"]);if(u!=null){let h=u;Array.isArray(h)&&(h=h.map(m=>Kl(m))),s(n,["endpoints"],h)}const c=i(t,["labels"]);c!=null&&s(n,["labels"],c);const d=i(t,["_self"]);d!=null&&s(n,["tunedModelInfo"],ja(d));const f=i(t,["defaultCheckpointId"]);f!=null&&s(n,["defaultCheckpointId"],f);const p=i(t,["checkpoints"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(m=>m)),s(n,["checkpoints"],h)}return n}function Ga(t,e){const n={},o=i(t,["mediaResolution"]);o!=null&&s(n,["mediaResolution"],o);const r=i(t,["codeExecutionResult"]);r!=null&&s(n,["codeExecutionResult"],r);const l=i(t,["executableCode"]);l!=null&&s(n,["executableCode"],l);const a=i(t,["fileData"]);a!=null&&s(n,["fileData"],Wl(a));const u=i(t,["functionCall"]);u!=null&&s(n,["functionCall"],zl(u));const c=i(t,["functionResponse"]);c!=null&&s(n,["functionResponse"],c);const d=i(t,["inlineData"]);d!=null&&s(n,["inlineData"],Tl(d));const f=i(t,["text"]);f!=null&&s(n,["text"],f);const p=i(t,["thought"]);p!=null&&s(n,["thought"],p);const h=i(t,["thoughtSignature"]);h!=null&&s(n,["thoughtSignature"],h);const m=i(t,["videoMetadata"]);m!=null&&s(n,["videoMetadata"],m);const g=i(t,["toolCall"]);g!=null&&s(n,["toolCall"],g);const v=i(t,["toolResponse"]);v!=null&&s(n,["toolResponse"],v);const E=i(t,["partMetadata"]);return E!=null&&s(n,["partMetadata"],E),n}function ka(t,e){const n={},o=i(t,["mediaResolution"]);o!=null&&s(n,["mediaResolution"],o);const r=i(t,["codeExecutionResult"]);r!=null&&s(n,["codeExecutionResult"],r);const l=i(t,["executableCode"]);l!=null&&s(n,["executableCode"],l);const a=i(t,["fileData"]);a!=null&&s(n,["fileData"],a);const u=i(t,["functionCall"]);u!=null&&s(n,["functionCall"],u);const c=i(t,["functionResponse"]);c!=null&&s(n,["functionResponse"],c);const d=i(t,["inlineData"]);d!=null&&s(n,["inlineData"],d);const f=i(t,["text"]);f!=null&&s(n,["text"],f);const p=i(t,["thought"]);p!=null&&s(n,["thought"],p);const h=i(t,["thoughtSignature"]);h!=null&&s(n,["thoughtSignature"],h);const m=i(t,["videoMetadata"]);if(m!=null&&s(n,["videoMetadata"],m),i(t,["toolCall"])!==void 0)throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(i(t,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(i(t,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function Fa(t,e){const n={},o=i(t,["productImage"]);return o!=null&&s(n,["image"],W(o)),n}function Va(t,e,n){const o={},r=i(t,["numberOfImages"]);e!==void 0&&r!=null&&s(e,["parameters","sampleCount"],r);const l=i(t,["baseSteps"]);e!==void 0&&l!=null&&s(e,["parameters","baseSteps"],l);const a=i(t,["outputGcsUri"]);e!==void 0&&a!=null&&s(e,["parameters","storageUri"],a);const u=i(t,["seed"]);e!==void 0&&u!=null&&s(e,["parameters","seed"],u);const c=i(t,["safetyFilterLevel"]);e!==void 0&&c!=null&&s(e,["parameters","safetySetting"],c);const d=i(t,["personGeneration"]);e!==void 0&&d!=null&&s(e,["parameters","personGeneration"],d);const f=i(t,["addWatermark"]);e!==void 0&&f!=null&&s(e,["parameters","addWatermark"],f);const p=i(t,["outputMimeType"]);e!==void 0&&p!=null&&s(e,["parameters","outputOptions","mimeType"],p);const h=i(t,["outputCompressionQuality"]);e!==void 0&&h!=null&&s(e,["parameters","outputOptions","compressionQuality"],h);const m=i(t,["enhancePrompt"]);e!==void 0&&m!=null&&s(e,["parameters","enhancePrompt"],m);const g=i(t,["labels"]);return e!==void 0&&g!=null&&s(e,["labels"],g),o}function Ha(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["source"]);l!=null&&Ba(l,o);const a=i(e,["config"]);return a!=null&&Va(a,o),o}function qa(t,e){const n={},o=i(t,["predictions"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>Le(l))),s(n,["generatedImages"],r)}return n}function Ba(t,e,n){const o={},r=i(t,["prompt"]);e!==void 0&&r!=null&&s(e,["instances[0]","prompt"],r);const l=i(t,["personImage"]);e!==void 0&&l!=null&&s(e,["instances[0]","personImage","image"],W(l));const a=i(t,["productImages"]);if(e!==void 0&&a!=null){let u=a;Array.isArray(u)&&(u=u.map(c=>Fa(c))),s(e,["instances[0]","productImages"],u)}return o}function Ja(t,e){const n={},o=i(t,["referenceImage"]);o!=null&&s(n,["referenceImage"],W(o));const r=i(t,["referenceId"]);r!=null&&s(n,["referenceId"],r);const l=i(t,["referenceType"]);l!=null&&s(n,["referenceType"],l);const a=i(t,["maskImageConfig"]);a!=null&&s(n,["maskImageConfig"],La(a));const u=i(t,["controlImageConfig"]);u!=null&&s(n,["controlImageConfig"],Pl(u));const c=i(t,["styleImageConfig"]);c!=null&&s(n,["styleImageConfig"],c);const d=i(t,["subjectImageConfig"]);return d!=null&&s(n,["subjectImageConfig"],d),n}function Po(t,e){const n={},o=i(t,["safetyAttributes","categories"]);o!=null&&s(n,["categories"],o);const r=i(t,["safetyAttributes","scores"]);r!=null&&s(n,["scores"],r);const l=i(t,["contentType"]);return l!=null&&s(n,["contentType"],l),n}function No(t,e){const n={},o=i(t,["safetyAttributes","categories"]);o!=null&&s(n,["categories"],o);const r=i(t,["safetyAttributes","scores"]);r!=null&&s(n,["scores"],r);const l=i(t,["contentType"]);return l!=null&&s(n,["contentType"],l),n}function ba(t,e){const n={},o=i(t,["category"]);if(o!=null&&s(n,["category"],o),i(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");const r=i(t,["threshold"]);return r!=null&&s(n,["threshold"],r),n}function $a(t,e){const n={},o=i(t,["image"]);return o!=null&&s(n,["image"],W(o)),n}function Oa(t,e,n){const o={},r=i(t,["mode"]);e!==void 0&&r!=null&&s(e,["parameters","mode"],r);const l=i(t,["maxPredictions"]);e!==void 0&&l!=null&&s(e,["parameters","maxPredictions"],l);const a=i(t,["confidenceThreshold"]);e!==void 0&&a!=null&&s(e,["parameters","confidenceThreshold"],a);const u=i(t,["maskDilation"]);e!==void 0&&u!=null&&s(e,["parameters","maskDilation"],u);const c=i(t,["binaryColorThreshold"]);e!==void 0&&c!=null&&s(e,["parameters","binaryColorThreshold"],c);const d=i(t,["labels"]);return e!==void 0&&d!=null&&s(e,["labels"],d),o}function Ya(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["source"]);l!=null&&Wa(l,o);const a=i(e,["config"]);return a!=null&&Oa(a,o),o}function Ka(t,e){const n={},o=i(t,["predictions"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>Ea(l))),s(n,["generatedMasks"],r)}return n}function Wa(t,e,n){const o={},r=i(t,["prompt"]);e!==void 0&&r!=null&&s(e,["instances[0]","prompt"],r);const l=i(t,["image"]);e!==void 0&&l!=null&&s(e,["instances[0]","image"],W(l));const a=i(t,["scribbleImage"]);return e!==void 0&&a!=null&&s(e,["instances[0]","scribble"],$a(a)),o}function za(t,e){const n={},o=i(t,["retrievalConfig"]);o!=null&&s(n,["retrievalConfig"],o);const r=i(t,["functionCallingConfig"]);r!=null&&s(n,["functionCallingConfig"],Xl(r));const l=i(t,["includeServerSideToolInvocations"]);return l!=null&&s(n,["includeServerSideToolInvocations"],l),n}function Xa(t,e){const n={},o=i(t,["retrievalConfig"]);o!=null&&s(n,["retrievalConfig"],o);const r=i(t,["functionCallingConfig"]);if(r!=null&&s(n,["functionCallingConfig"],r),i(t,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function Qa(t,e){const n={};if(i(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const o=i(t,["computerUse"]);o!=null&&s(n,["computerUse"],o);const r=i(t,["fileSearch"]);r!=null&&s(n,["fileSearch"],r);const l=i(t,["googleSearch"]);l!=null&&s(n,["googleSearch"],Aa(l));const a=i(t,["googleMaps"]);a!=null&&s(n,["googleMaps"],Ca(a));const u=i(t,["codeExecution"]);if(u!=null&&s(n,["codeExecution"],u),i(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const c=i(t,["functionDeclarations"]);if(c!=null){let h=c;Array.isArray(h)&&(h=h.map(m=>m)),s(n,["functionDeclarations"],h)}const d=i(t,["googleSearchRetrieval"]);if(d!=null&&s(n,["googleSearchRetrieval"],d),i(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is not supported in Gemini API.");const f=i(t,["urlContext"]);f!=null&&s(n,["urlContext"],f);const p=i(t,["mcpServers"]);if(p!=null){let h=p;Array.isArray(h)&&(h=h.map(m=>m)),s(n,["mcpServers"],h)}return n}function wo(t,e){const n={},o=i(t,["retrieval"]);o!=null&&s(n,["retrieval"],o);const r=i(t,["computerUse"]);if(r!=null&&s(n,["computerUse"],r),i(t,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const l=i(t,["googleSearch"]);l!=null&&s(n,["googleSearch"],l);const a=i(t,["googleMaps"]);a!=null&&s(n,["googleMaps"],a);const u=i(t,["codeExecution"]);u!=null&&s(n,["codeExecution"],u);const c=i(t,["enterpriseWebSearch"]);c!=null&&s(n,["enterpriseWebSearch"],c);const d=i(t,["functionDeclarations"]);if(d!=null){let m=d;Array.isArray(m)&&(m=m.map(g=>Ql(g))),s(n,["functionDeclarations"],m)}const f=i(t,["googleSearchRetrieval"]);f!=null&&s(n,["googleSearchRetrieval"],f);const p=i(t,["parallelAiSearch"]);p!=null&&s(n,["parallelAiSearch"],p);const h=i(t,["urlContext"]);if(h!=null&&s(n,["urlContext"],h),i(t,["mcpServers"])!==void 0)throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function Za(t,e){const n={},o=i(t,["baseModel"]);o!=null&&s(n,["baseModel"],o);const r=i(t,["createTime"]);r!=null&&s(n,["createTime"],r);const l=i(t,["updateTime"]);return l!=null&&s(n,["updateTime"],l),n}function ja(t,e){const n={},o=i(t,["labels","google-vertex-llm-tuning-base-model-id"]);o!=null&&s(n,["baseModel"],o);const r=i(t,["createTime"]);r!=null&&s(n,["createTime"],r);const l=i(t,["updateTime"]);return l!=null&&s(n,["updateTime"],l),n}function eu(t,e,n){const o={},r=i(t,["displayName"]);e!==void 0&&r!=null&&s(e,["displayName"],r);const l=i(t,["description"]);e!==void 0&&l!=null&&s(e,["description"],l);const a=i(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&s(e,["defaultCheckpointId"],a),o}function tu(t,e,n){const o={},r=i(t,["displayName"]);e!==void 0&&r!=null&&s(e,["displayName"],r);const l=i(t,["description"]);e!==void 0&&l!=null&&s(e,["description"],l);const a=i(t,["defaultCheckpointId"]);return e!==void 0&&a!=null&&s(e,["defaultCheckpointId"],a),o}function nu(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","name"],D(t,r));const l=i(e,["config"]);return l!=null&&eu(l,o),o}function ou(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["config"]);return l!=null&&tu(l,o),o}function iu(t,e,n){const o={},r=i(t,["outputGcsUri"]);e!==void 0&&r!=null&&s(e,["parameters","storageUri"],r);const l=i(t,["safetyFilterLevel"]);e!==void 0&&l!=null&&s(e,["parameters","safetySetting"],l);const a=i(t,["personGeneration"]);e!==void 0&&a!=null&&s(e,["parameters","personGeneration"],a);const u=i(t,["includeRaiReason"]);e!==void 0&&u!=null&&s(e,["parameters","includeRaiReason"],u);const c=i(t,["outputMimeType"]);e!==void 0&&c!=null&&s(e,["parameters","outputOptions","mimeType"],c);const d=i(t,["outputCompressionQuality"]);e!==void 0&&d!=null&&s(e,["parameters","outputOptions","compressionQuality"],d);const f=i(t,["enhanceInputImage"]);e!==void 0&&f!=null&&s(e,["parameters","upscaleConfig","enhanceInputImage"],f);const p=i(t,["imagePreservationFactor"]);e!==void 0&&p!=null&&s(e,["parameters","upscaleConfig","imagePreservationFactor"],p);const h=i(t,["labels"]);e!==void 0&&h!=null&&s(e,["labels"],h);const m=i(t,["numberOfImages"]);e!==void 0&&m!=null&&s(e,["parameters","sampleCount"],m);const g=i(t,["mode"]);return e!==void 0&&g!=null&&s(e,["parameters","mode"],g),o}function ru(t,e,n){const o={},r=i(e,["model"]);r!=null&&s(o,["_url","model"],D(t,r));const l=i(e,["image"]);l!=null&&s(o,["instances[0]","image"],W(l));const a=i(e,["upscaleFactor"]);a!=null&&s(o,["parameters","upscaleConfig","upscaleFactor"],a);const u=i(e,["config"]);return u!=null&&iu(u,o),o}function su(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["predictions"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>Le(a))),s(n,["generatedImages"],l)}return n}function lu(t,e){const n={},o=i(t,["uri"]);o!=null&&s(n,["uri"],o);const r=i(t,["encodedVideo"]);r!=null&&s(n,["videoBytes"],te(r));const l=i(t,["encoding"]);return l!=null&&s(n,["mimeType"],l),n}function au(t,e){const n={},o=i(t,["gcsUri"]);o!=null&&s(n,["uri"],o);const r=i(t,["bytesBase64Encoded"]);r!=null&&s(n,["videoBytes"],te(r));const l=i(t,["mimeType"]);return l!=null&&s(n,["mimeType"],l),n}function uu(t,e){const n={},o=i(t,["image"]);o!=null&&s(n,["_self"],W(o));const r=i(t,["maskMode"]);return r!=null&&s(n,["maskMode"],r),n}function du(t,e){const n={},o=i(t,["image"]);o!=null&&s(n,["image"],Ge(o));const r=i(t,["referenceType"]);return r!=null&&s(n,["referenceType"],r),n}function cu(t,e){const n={},o=i(t,["image"]);o!=null&&s(n,["image"],W(o));const r=i(t,["referenceType"]);return r!=null&&s(n,["referenceType"],r),n}function Mo(t,e){const n={},o=i(t,["uri"]);o!=null&&s(n,["uri"],o);const r=i(t,["videoBytes"]);r!=null&&s(n,["encodedVideo"],te(r));const l=i(t,["mimeType"]);return l!=null&&s(n,["encoding"],l),n}function Do(t,e){const n={},o=i(t,["uri"]);o!=null&&s(n,["gcsUri"],o);const r=i(t,["videoBytes"]);r!=null&&s(n,["bytesBase64Encoded"],te(r));const l=i(t,["mimeType"]);return l!=null&&s(n,["mimeType"],l),n}function fu(t,e,n){const o={},r=i(e,["displayName"]);n!==void 0&&r!=null&&s(n,["displayName"],r);const l=i(e,["embeddingModel"]);return n!==void 0&&l!=null&&s(n,["embeddingModel"],D(t,l)),o}function pu(t,e){const n={},o=i(e,["config"]);return o!=null&&fu(t,o,n),n}function hu(t,e){const n={},o=i(t,["force"]);return e!==void 0&&o!=null&&s(e,["_query","force"],o),n}function mu(t){const e={},n=i(t,["name"]);n!=null&&s(e,["_url","name"],n);const o=i(t,["config"]);return o!=null&&hu(o,e),e}function gu(t){const e={},n=i(t,["name"]);return n!=null&&s(e,["_url","name"],n),e}function Eu(t,e){const n={},o=i(t,["customMetadata"]);if(e!==void 0&&o!=null){let l=o;Array.isArray(l)&&(l=l.map(a=>a)),s(e,["customMetadata"],l)}const r=i(t,["chunkingConfig"]);return e!==void 0&&r!=null&&s(e,["chunkingConfig"],r),n}function vu(t){const e={},n=i(t,["name"]);n!=null&&s(e,["name"],n);const o=i(t,["metadata"]);o!=null&&s(e,["metadata"],o);const r=i(t,["done"]);r!=null&&s(e,["done"],r);const l=i(t,["error"]);l!=null&&s(e,["error"],l);const a=i(t,["response"]);return a!=null&&s(e,["response"],Tu(a)),e}function yu(t){const e={},n=i(t,["fileSearchStoreName"]);n!=null&&s(e,["_url","file_search_store_name"],n);const o=i(t,["fileName"]);o!=null&&s(e,["fileName"],o);const r=i(t,["config"]);return r!=null&&Eu(r,e),e}function Tu(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["parent"]);o!=null&&s(e,["parent"],o);const r=i(t,["documentName"]);return r!=null&&s(e,["documentName"],r),e}function _u(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&s(e,["_query","pageSize"],o);const r=i(t,["pageToken"]);return e!==void 0&&r!=null&&s(e,["_query","pageToken"],r),n}function Iu(t){const e={},n=i(t,["config"]);return n!=null&&_u(n,e),e}function Cu(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&s(e,["nextPageToken"],o);const r=i(t,["fileSearchStores"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>a)),s(e,["fileSearchStores"],l)}return e}function xo(t,e){const n={},o=i(t,["mimeType"]);e!==void 0&&o!=null&&s(e,["mimeType"],o);const r=i(t,["displayName"]);e!==void 0&&r!=null&&s(e,["displayName"],r);const l=i(t,["customMetadata"]);if(e!==void 0&&l!=null){let u=l;Array.isArray(u)&&(u=u.map(c=>c)),s(e,["customMetadata"],u)}const a=i(t,["chunkingConfig"]);return e!==void 0&&a!=null&&s(e,["chunkingConfig"],a),n}function Au(t){const e={},n=i(t,["fileSearchStoreName"]);n!=null&&s(e,["_url","file_search_store_name"],n);const o=i(t,["config"]);return o!=null&&xo(o,e),e}function Su(t){const e={},n=i(t,["sdkHttpResponse"]);return n!=null&&s(e,["sdkHttpResponse"],n),e}const Ru="Content-Type",Pu="X-Server-Timeout",Nu="User-Agent",tt="x-goog-api-client",wu="1.52.0",Mu=`google-genai-sdk/${wu}`,Du="v1beta1",xu="v1beta",Uu=new Set(["us","eu"]),Lu=5,Gu=[408,429,500,502,503,504];class ku{constructor(e){var n,o,r;this.clientOptions=Object.assign({},e),this.customBaseUrl=(n=e.httpOptions)===null||n===void 0?void 0:n.baseUrl,this.clientOptions.vertexai&&(this.clientOptions.project&&this.clientOptions.location?this.clientOptions.apiKey=void 0:this.clientOptions.apiKey&&(this.clientOptions.project=void 0,this.clientOptions.location=void 0));const l={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");const u=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!u?(l.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey||this.clientOptions.location==="global"?l.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&Uu.has(this.clientOptions.location)?l.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(l.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),l.apiVersion=(o=this.clientOptions.apiVersion)!==null&&o!==void 0?o:Du}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),l.apiVersion=(r=this.clientOptions.apiVersion)!==null&&r!==void 0?r:xu,l.baseUrl="https://generativelanguage.googleapis.com/";l.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=l,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(l,e.httpOptions))}isVertexAI(){var e;return(e=this.clientOptions.vertexai)!==null&&e!==void 0?e:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){const e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||e.baseUrl===void 0||e.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");const o=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&e.apiVersion!==""&&o.push(e.apiVersion),o.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const e=this.getBaseUrl(),n=new URL(e);return n.protocol=n.protocol=="http:"?"ws":"wss",n.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw new Error("HTTP options are not correctly set.")}constructUrl(e,n,o){const r=[this.getRequestUrlInternal(n)];return o&&r.push(this.getBaseResourcePath()),e!==""&&r.push(e),new URL(`${r.join("/")}`)}shouldPrependVertexProjectPath(e,n){return!(n.baseUrl&&n.baseUrlResourceScope===Xe.COLLECTION||this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||e.httpMethod==="GET"&&e.path.startsWith("publishers/google/models"))}async request(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const o=this.shouldPrependVertexProjectPath(e,n),r=this.constructUrl(e.path,n,o);if(e.queryParams)for(const[a,u]of Object.entries(e.queryParams))r.searchParams.append(a,String(u));let l={};if(e.httpMethod==="GET"){if(e.body&&e.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else l.body=e.body;return l=await this.includeExtraHttpOptionsToRequestInit(l,n,r.toString(),e.abortSignal),this.unaryApiCall(r,l,e.httpMethod)}patchHttpOptions(e,n){const o=JSON.parse(JSON.stringify(e));for(const[r,l]of Object.entries(n))typeof l=="object"?o[r]=Object.assign(Object.assign({},o[r]),l):l!==void 0&&(o[r]=l);return o}async requestStream(e){let n=this.clientOptions.httpOptions;e.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const o=this.shouldPrependVertexProjectPath(e,n),r=this.constructUrl(e.path,n,o);(!r.searchParams.has("alt")||r.searchParams.get("alt")!=="sse")&&r.searchParams.set("alt","sse");let l={};return l.body=e.body,l=await this.includeExtraHttpOptionsToRequestInit(l,n,r.toString(),e.abortSignal),this.streamApiCall(r,l,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,n,o,r){if(n&&n.timeout||r){const l=new AbortController,a=l.signal;if(n.timeout&&n?.timeout>0){const u=setTimeout(()=>l.abort(),n.timeout);u&&typeof u.unref=="function"&&u.unref()}r&&r.addEventListener("abort",()=>{l.abort()}),e.signal=a}return n&&n.extraBody!==null&&Fu(e,n.extraBody),e.headers=await this.getHeadersInternal(n,o),e}async unaryApiCall(e,n,o){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:o})).then(async r=>(await Xn(r),new Ne(r))).catch(r=>{throw r instanceof Error?r:new Error(JSON.stringify(r))})}async streamApiCall(e,n,o){return this.apiCall(e.toString(),Object.assign(Object.assign({},n),{method:o})).then(async r=>(await Xn(r),this.processStreamResponse(r))).catch(r=>{throw r instanceof Error?r:new Error(JSON.stringify(r))})}processStreamResponse(e){return Y(this,arguments,function*(){var o;const r=(o=e?.body)===null||o===void 0?void 0:o.getReader(),l=new TextDecoder("utf-8");if(!r)throw new Error("Response body is empty");try{let a="";const u="data:",c=[` `,"\r\r",`\r \r `];for(;;){const{done:d,value:f}=yield N(r.read());if(d){if(a.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}const p=l.decode(f,{stream:!0});try{const g=JSON.parse(p);if("error"in g){const v=JSON.parse(JSON.stringify(g.error)),E=v.status,y=v.code,A=`got status: ${E}. ${JSON.stringify(g)}`;if(y>=400&&y<600)throw new Ue({message:A,status:y})}}catch(g){if(g.name==="ApiError")throw g}a+=p;let h=-1,m=0;for(;;){h=-1,m=0;for(const E of c){const y=a.indexOf(E);y!==-1&&(h===-1||y{const a=await fetch(e,n);if(a.ok)return a;throw Gu.includes(a.status)?new Error(`Retryable HTTP Error: ${a.statusText}`):new uo.AbortError(`Non-retryable exception ${a.statusText} sending request`)},{retries:((o=r.attempts)!==null&&o!==void 0?o:Lu)-1})}getDefaultHeaders(){const e={},n=Mu+" "+this.clientOptions.userAgentExtra;return e[Nu]=n,e[tt]=n,e[Ru]="application/json",e}async getHeadersInternal(e,n){const o=new Headers;if(e&&e.headers){for(const[r,l]of Object.entries(e.headers))o.append(r,l);e.timeout&&e.timeout>0&&o.append(Pu,String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(o,n),o}getFileName(e){var n;let o="";return typeof e=="string"&&(o=e.replace(/[/\\]+$/,""),o=(n=o.split(/[/\\]/).pop())!==null&&n!==void 0?n:""),o}async uploadFile(e,n){var o;const r={};n!=null&&(r.mimeType=n.mimeType,r.name=n.name,r.displayName=n.displayName),r.name&&!r.name.startsWith("files/")&&(r.name=`files/${r.name}`);const l=this.clientOptions.uploader,a=await l.stat(e);r.sizeBytes=String(a.size);const u=(o=n?.mimeType)!==null&&o!==void 0?o:a.type;if(u===void 0||u==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");r.mimeType=u;const c={file:r},d=this.getFileName(e),f=_("upload/v1beta/files",c._url),p=await this.fetchUploadUrl(f,r.sizeBytes,r.mimeType,d,c,n?.httpOptions);return l.upload(e,p,this)}async uploadFileToFileSearchStore(e,n,o){var r;const l=this.clientOptions.uploader,a=await l.stat(n),u=String(a.size),c=(r=o?.mimeType)!==null&&r!==void 0?r:a.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");const d=`upload/v1beta/${e}:uploadToFileSearchStore`,f=this.getFileName(n),p={};o!=null&&xo(o,p);const h=await this.fetchUploadUrl(d,u,c,f,p,o?.httpOptions);return l.uploadToFileSearchStore(n,h,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,n,o,r,l,a){var u;let c={};a?c=a:c={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${o}`},r?{"X-Goog-Upload-File-Name":r}:{})};const d=await this.request({path:e,body:JSON.stringify(l),httpMethod:"POST",httpOptions:c});if(!d||!d?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");const f=(u=d?.headers)===null||u===void 0?void 0:u["x-goog-upload-url"];if(f===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return f}}async function Xn(t){var e;if(t===void 0)throw new Error("response is undefined");if(!t.ok){const n=t.status;let o;!((e=t.headers.get("content-type"))===null||e===void 0)&&e.includes("application/json")?o=await t.json():o={error:{message:await t.text(),code:t.status,status:t.statusText}};const r=JSON.stringify(o);throw n>=400&&n<600?new Ue({message:r,status:n}):new Error(r)}}function Fu(t,e){if(!e||Object.keys(e).length===0)return;if(t.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof t.body=="string"&&t.body.length>0)try{const l=JSON.parse(t.body);if(typeof l=="object"&&l!==null&&!Array.isArray(l))n=l;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function o(l,a){const u=Object.assign({},l);for(const c in a)if(Object.prototype.hasOwnProperty.call(a,c)){const d=a[c],f=u[c];d&&typeof d=="object"&&!Array.isArray(d)&&f&&typeof f=="object"&&!Array.isArray(f)?u[c]=o(f,d):(f&&d&&typeof f!=typeof d&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${c}". Original type: ${typeof f}, New type: ${typeof d}. Overwriting.`),u[c]=d)}return u}const r=o(n,e);t.body=JSON.stringify(r)}const Vu="mcp_used/unknown";let Hu=!1;function Uo(t){for(const e of t)if(qu(e)||typeof e=="object"&&"inputSchema"in e)return!0;return Hu}function Lo(t){var e;const n=(e=t[tt])!==null&&e!==void 0?e:"";t[tt]=(n+` ${Vu}`).trimStart()}function qu(t){return t!==null&&typeof t=="object"&&t instanceof mt}function Bu(t){return Y(this,arguments,function*(n,o=100){let r,l=0;for(;l0)return;const l={},a=[];for(const f of this.mcpClients)try{for(var u=!0,c=(n=void 0,K(Bu(f))),d;d=await c.next(),e=d.done,!e;u=!0){r=d.value,u=!1;const p=r;a.push(p);const h=p.name;if(l[h])throw new Error(`Duplicate function name ${h} found in MCP tools. Please ensure function names are unique.`);l[h]=f}}catch(p){n={error:p}}finally{try{!u&&!e&&(o=c.return)&&await o.call(c)}finally{if(n)throw n.error}}this.mcpTools=a,this.functionNameToMcpClient=l}async tool(){return await this.initialize(),ji(this.mcpTools,this.config)}async callTool(e){await this.initialize();const n=[];for(const o of e)if(o.name in this.functionNameToMcpClient){const r=this.functionNameToMcpClient[o.name];let l;this.config.timeout&&(l={timeout:this.config.timeout});const a=await r.callTool({name:o.name,arguments:o.args},void 0,l);n.push({functionResponse:{name:o.name,response:a.isError?{error:a}:a}})}return n}}async function Ju(t,e,n){const o=new Oi;let r;n.data instanceof Blob?r=JSON.parse(await n.data.text()):r=JSON.parse(n.data),Object.assign(o,r),e(o)}class bu{constructor(e,n,o){this.apiClient=e,this.auth=n,this.webSocketFactory=o}async connect(e){var n,o;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");const r=this.apiClient.getWebsocketBaseUrl(),l=this.apiClient.getApiVersion(),a=Yu(this.apiClient.getDefaultHeaders()),u=this.apiClient.getApiKey(),c=`${r}/ws/google.ai.generativelanguage.${l}.GenerativeService.BidiGenerateMusic?key=${u}`;let d=()=>{};const f=new Promise(I=>{d=I}),p=e.callbacks,h=function(){d({})},m=this.apiClient,g={onopen:h,onmessage:I=>{Ju(m,p.onmessage,I)},onerror:(n=p?.onerror)!==null&&n!==void 0?n:function(I){},onclose:(o=p?.onclose)!==null&&o!==void 0?o:function(I){}},v=this.webSocketFactory.create(c,Ou(a),g);v.connect(),await f;const A={setup:{model:D(this.apiClient,e.model)}};return v.send(JSON.stringify(A)),new $u(v,this.apiClient)}}class $u{constructor(e,n){this.conn=e,this.apiClient=n}async setWeightedPrompts(e){if(!e.weightedPrompts||Object.keys(e.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");const n=ll(e);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});const n=sl(e);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){const n={playbackControl:e};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(le.PLAY)}pause(){this.sendPlaybackControl(le.PAUSE)}stop(){this.sendPlaybackControl(le.STOP)}resetContext(){this.sendPlaybackControl(le.RESET_CONTEXT)}close(){this.conn.close()}}function Ou(t){const e={};return t.forEach((n,o)=>{e[o]=n}),e}function Yu(t){const e=new Headers;for(const[n,o]of Object.entries(t))e.append(n,o);return e}const Ku="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function Wu(t,e,n){const o=new $i;let r;n.data instanceof Blob?r=await n.data.text():n.data instanceof ArrayBuffer?r=new TextDecoder().decode(n.data):r=n.data;const l=JSON.parse(r);if(t.isVertexAI()){const a=dl(l);Object.assign(o,a)}else Object.assign(o,l);e(o)}class zu{constructor(e,n,o){this.apiClient=e,this.auth=n,this.webSocketFactory=o,this.music=new bu(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var n,o,r,l,a,u;if(e.config&&e.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");const c=this.apiClient.getWebsocketBaseUrl(),d=this.apiClient.getApiVersion();let f;const p=this.apiClient.getHeaders();e.config&&e.config.tools&&Uo(e.config.tools)&&Lo(p);const h=ju(p);if(this.apiClient.isVertexAI()){const C=this.apiClient.getProject(),M=this.apiClient.getLocation(),x=this.apiClient.getApiKey(),B=!!C&&!!M||!!x;this.apiClient.getCustomBaseUrl()&&!B?f=c:(f=`${c}/ws/google.cloud.aiplatform.${d}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(h,f))}else{const C=this.apiClient.getApiKey();let M="BidiGenerateContent",x="key";C?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),d!=="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."),M="BidiGenerateContentConstrained",x="access_token"),f=`${c}/ws/google.ai.generativelanguage.${d}.GenerativeService.${M}?${x}=${C}`}let m=()=>{};const g=new Promise(C=>{m=C}),v=e.callbacks,E=function(){var C;(C=v?.onopen)===null||C===void 0||C.call(v),m({})},y=this.apiClient,A={onopen:E,onmessage:C=>{Wu(y,v.onmessage,C)},onerror:(n=v?.onerror)!==null&&n!==void 0?n:function(C){},onclose:(o=v?.onclose)!==null&&o!==void 0?o:function(C){}},I=this.webSocketFactory.create(f,Zu(h),A);I.connect(),await g;let S=D(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&S.startsWith("publishers/")){const C=this.apiClient.getProject(),M=this.apiClient.getLocation();C&&M&&(S=`projects/${C}/locations/${M}/`+S)}let R={};this.apiClient.isVertexAI()&&((r=e.config)===null||r===void 0?void 0:r.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[Re.AUDIO]}:e.config.responseModalities=[Re.AUDIO]),!((l=e.config)===null||l===void 0)&&l.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");const T=(u=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&u!==void 0?u:[],w=[];for(const C of T)if(this.isCallableTool(C)){const M=C;w.push(await M.tool())}else w.push(C);w.length>0&&(e.config.tools=w);const P={model:S,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?R=rl(this.apiClient,P):R=il(this.apiClient,P),delete R.config,I.send(JSON.stringify(R)),new Qu(I,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}}const Xu={turnComplete:!0};class Qu{constructor(e,n){this.conn=e,this.apiClient=n}tLiveClientContent(e,n){if(n.turns!==null&&n.turns!==void 0){let o=[];try{o=q(n.turns),e.isVertexAI()||(o=o.map(r=>Te(r)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof n.turns}'`)}return{clientContent:{turns:o,turnComplete:n.turnComplete}}}return{clientContent:{turnComplete:n.turnComplete}}}tLiveClienttToolResponse(e,n){let o=[];if(n.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(n.functionResponses)?o=n.functionResponses:o=[n.functionResponses],o.length===0)throw new Error("functionResponses is required.");for(const l of o){if(typeof l!="object"||l===null||!("name"in l)||!("response"in l))throw new Error(`Could not parse function response, type '${typeof l}'.`);if(!e.isVertexAI()&&!("id"in l))throw new Error(Ku)}return{toolResponse:{functionResponses:o}}}sendClientContent(e){e=Object.assign(Object.assign({},Xu),e);const n=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(n))}sendRealtimeInput(e){let n={};this.apiClient.isVertexAI()?n={realtimeInput:ul(e)}:n={realtimeInput:al(e)},this.conn.send(JSON.stringify(n))}sendToolResponse(e){if(e.functionResponses==null)throw new Error("Tool response parameters are required.");const n=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}}function Zu(t){const e={};return t.forEach((n,o)=>{e[o]=n}),e}function ju(t){const e=new Headers;for(const[n,o]of Object.entries(t))e.append(n,o);return e}const Qn=10;function Zn(t){var e,n,o;if(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.disable)return!0;let r=!1;for(const a of(n=t?.tools)!==null&&n!==void 0?n:[])if(de(a)){r=!0;break}if(!r)return!0;const l=(o=t?.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls;return l&&(l<0||!Number.isInteger(l))||l==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:",l),!0):!1}function de(t){return"callTool"in t&&typeof t.callTool=="function"}function ed(t){var e,n,o;return(o=(n=(e=t.config)===null||e===void 0?void 0:e.tools)===null||n===void 0?void 0:n.some(r=>de(r)))!==null&&o!==void 0?o:!1}function jn(t){var e;const n=[];return!((e=t?.config)===null||e===void 0)&&e.tools&&t.config.tools.forEach((o,r)=>{if(de(o))return;const l=o;l.functionDeclarations&&l.functionDeclarations.length>0&&n.push(r)}),n}function eo(t){var e;return!(!((e=t?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}class td extends Q{constructor(e){super(),this.apiClient=e,this.embedContent=async n=>{if(!this.apiClient.isVertexAI())return n.model.includes("gemini-embedding-2")&&(n.contents=q(n.contents)),await this.embedContentInternal(n);if(n.model.includes("gemini")&&n.model!=="gemini-embedding-001"||n.model.includes("maas")){const r=q(n.contents);if(r.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");const l=Object.assign(Object.assign({},n),{content:r[0],embeddingApiType:Pe.EMBED_CONTENT});return await this.embedContentInternal(l)}else{const r=Object.assign(Object.assign({},n),{embeddingApiType:Pe.PREDICT});return await this.embedContentInternal(r)}},this.generateContent=async n=>{var o,r,l,a,u;const c=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchem(n),!ed(n)||Zn(n.config))return await this.generateContentInternal(c);const d=jn(n);if(d.length>0){const v=d.map(E=>`tools[${E}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${v}.`)}let f,p;const h=q(c.contents),m=(l=(r=(o=c.config)===null||o===void 0?void 0:o.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls)!==null&&l!==void 0?l:Qn;let g=0;for(;g{var o,r,l,a,u;if(this.maybeMoveToResponseJsonSchem(n),Zn(n.config)){const p=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(p)}const c=jn(n);if(c.length>0){const p=c.map(h=>`tools[${h}]`).join(", ");throw new Error(`Incompatible tools found at ${p}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}const d=(l=(r=(o=n?.config)===null||o===void 0?void 0:o.toolConfig)===null||r===void 0?void 0:r.functionCallingConfig)===null||l===void 0?void 0:l.streamFunctionCallArguments,f=(u=(a=n?.config)===null||a===void 0?void 0:a.automaticFunctionCalling)===null||u===void 0?void 0:u.disable;if(d&&!f)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(n)},this.generateImages=async n=>await this.generateImagesInternal(n).then(o=>{var r;let l;const a=[];if(o?.generatedImages)for(const c of o.generatedImages)c&&c?.safetyAttributes&&((r=c?.safetyAttributes)===null||r===void 0?void 0:r.contentType)==="Positive Prompt"?l=c?.safetyAttributes:a.push(c);let u;return l?u={generatedImages:a,positivePromptSafetyAttributes:l,sdkHttpResponse:o.sdkHttpResponse}:u={generatedImages:a,sdkHttpResponse:o.sdkHttpResponse},u}),this.list=async n=>{var o;const a={config:Object.assign(Object.assign({},{queryBase:!0}),n?.config)};if(this.apiClient.isVertexAI()&&!a.config.queryBase){if(!((o=a.config)===null||o===void 0)&&o.filter)throw new Error("Filtering tuned models list for Gemini Enterprise Agent Platform (previously known as Vertex AI) is not currently supported");a.config.filter="labels.tune-type:*"}return new ie(X.PAGED_ITEM_MODELS,u=>this.listInternal(u),await this.listInternal(a),a)},this.editImage=async n=>{const o={model:n.model,prompt:n.prompt,referenceImages:[],config:n.config};return n.referenceImages&&n.referenceImages&&(o.referenceImages=n.referenceImages.map(r=>r.toReferenceImageAPI())),await this.editImageInternal(o)},this.upscaleImage=async n=>{let o={numberOfImages:1,mode:"upscale"};n.config&&(o=Object.assign(Object.assign({},o),n.config));const r={model:n.model,image:n.image,upscaleFactor:n.upscaleFactor,config:o};return await this.upscaleImageInternal(r)},this.generateVideos=async n=>{var o,r,l,a,u,c;if((n.prompt||n.image||n.video)&&n.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return this.apiClient.isVertexAI()||(!((o=n.video)===null||o===void 0)&&o.uri&&(!((r=n.video)===null||r===void 0)&&r.videoBytes)?n.video={uri:n.video.uri,mimeType:n.video.mimeType}:!((a=(l=n.source)===null||l===void 0?void 0:l.video)===null||a===void 0)&&a.uri&&(!((c=(u=n.source)===null||u===void 0?void 0:u.video)===null||c===void 0)&&c.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&(e.config.responseJsonSchema||Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema))}async processParamsMaybeAddMcpUsage(e){var n,o,r;const l=(n=e.config)===null||n===void 0?void 0:n.tools;if(!l)return e;const a=await Promise.all(l.map(async c=>de(c)?await c.tool():c)),u={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:a})};if(u.config.tools=a,e.config&&e.config.tools&&Uo(e.config.tools)){const c=(r=(o=e.config.httpOptions)===null||o===void 0?void 0:o.headers)!==null&&r!==void 0?r:{};let d=Object.assign({},c);Object.keys(d).length===0&&(d=this.apiClient.getDefaultHeaders()),Lo(d),u.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:d})}return u}async initAfcToolsMap(e){var n,o,r;const l=new Map;for(const a of(o=(n=e.config)===null||n===void 0?void 0:n.tools)!==null&&o!==void 0?o:[])if(de(a)){const u=a,c=await u.tool();for(const d of(r=c.functionDeclarations)!==null&&r!==void 0?r:[]){if(!d.name)throw new Error("Function declaration name is required.");if(l.has(d.name))throw new Error(`Duplicate tool declaration name: ${d.name}`);l.set(d.name,u)}}return l}async processAfcStream(e){var n,o,r;const l=(r=(o=(n=e.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&r!==void 0?r:Qn;let a=!1,u=0;const c=await this.initAfcToolsMap(e);return(function(d,f,p){return Y(this,arguments,function*(){for(var h,m,g,v,E,y;u0){a=!0;const C=new Ee;C.candidates=[{content:{role:"user",parts:w}}],yield yield N(C);const M=[];M.push(...P),M.push({role:"user",parts:w});const x=q(p.contents).concat(M);p.contents=x}else break}})})(this,c,e)}async generateContentInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Kn(this.apiClient,e);return u=_("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=zn(f),h=new Ee;return Object.assign(h,p),h})}else{const d=Yn(this.apiClient,e);return u=_("{model}:generateContent",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=Wn(f),h=new Ee;return Object.assign(h,p),h})}}async generateContentStreamInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Kn(this.apiClient,e);return u=_("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}),a.then(function(p){return Y(this,arguments,function*(){var h,m,g,v;try{for(var E=!0,y=K(p),A;A=yield N(y.next()),h=A.done,!h;E=!0){v=A.value,E=!1;const I=v,S=zn(yield N(I.json()),e);S.sdkHttpResponse={headers:I.headers};const R=new Ee;Object.assign(R,S),yield yield N(R)}}catch(I){m={error:I}}finally{try{!E&&!h&&(g=y.return)&&(yield N(g.call(y)))}finally{if(m)throw m.error}}})})}else{const d=Yn(this.apiClient,e);return u=_("{model}:streamGenerateContent?alt=sse",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.requestStream({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}),a.then(function(p){return Y(this,arguments,function*(){var h,m,g,v;try{for(var E=!0,y=K(p),A;A=yield N(y.next()),h=A.done,!h;E=!0){v=A.value,E=!1;const I=v,S=Wn(yield N(I.json()),e);S.sdkHttpResponse={headers:I.headers};const R=new Ee;Object.assign(R,S),yield yield N(R)}}catch(I){m={error:I}}finally{try{!E&&!h&&(g=y.return)&&(yield N(g.call(y)))}finally{if(m)throw m.error}}})})}}async embedContentInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=$l(this.apiClient,e,e),f=tr(e.model)?"{model}:embedContent":"{model}:predict";return u=_(f,d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(p=>p.json().then(h=>{const m=h;return m.sdkHttpResponse={headers:p.headers},m})),a.then(p=>{const h=Yl(p,e),m=new Nn;return Object.assign(m,h),m})}else{const d=bl(this.apiClient,e);return u=_("{model}:batchEmbedContents",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=Ol(f),h=new Nn;return Object.assign(h,p),h})}}async generateImagesInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=oa(this.apiClient,e);return u=_("{model}:predict",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=ra(f),h=new wn;return Object.assign(h,p),h})}else{const d=na(this.apiClient,e);return u=_("{model}:predict",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=ia(f),h=new wn;return Object.assign(h,p),h})}}async editImageInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI()){const u=Hl(this.apiClient,e);return l=_("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),r.then(c=>{const d=ql(c),f=new Di;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI()){const u=ru(this.apiClient,e);return l=_("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),r.then(c=>{const d=su(c),f=new xi;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI()){const u=Ha(this.apiClient,e);return l=_("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>{const d=qa(c),f=new Ui;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI()){const u=Ya(this.apiClient,e);return l=_("{model}:predict",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>{const d=Ka(c),f=new Li;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Ia(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>et(f))}else{const d=_a(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>je(f))}}async listInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Da(this.apiClient,e);return u=_("{models_url}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=Ua(f),h=new Mn;return Object.assign(h,p),h})}else{const d=Ma(this.apiClient,e);return u=_("{models_url}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=xa(f),h=new Mn;return Object.assign(h,p),h})}}async update(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=ou(this.apiClient,e);return u=_("{model}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>et(f))}else{const d=nu(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>je(f))}}async delete(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Gl(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=Fl(f),h=new Dn;return Object.assign(h,p),h})}else{const d=Ll(this.apiClient,e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"DELETE",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=kl(f),h=new Dn;return Object.assign(h,p),h})}}async countTokens(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Dl(this.apiClient,e);return u=_("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=Ul(f),h=new xn;return Object.assign(h,p),h})}else{const d=Ml(this.apiClient,e);return u=_("{model}:countTokens",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=xl(f),h=new xn;return Object.assign(h,p),h})}}async computeTokens(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI()){const u=Cl(this.apiClient,e);return l=_("{model}:computeTokens",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),r.then(c=>{const d=Al(c),f=new Gi;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=ca(this.apiClient,e);return u=_("{model}:predictLongRunning",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a.then(f=>{const p=ua(f),h=new we;return Object.assign(h,p),h})}else{const d=da(this.apiClient,e);return u=_("{model}:predictLongRunning",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a.then(f=>{const p=aa(f),h=new we;return Object.assign(h,p),h})}}}class nd extends Q{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){const n=e.operation,o=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const r=n.name.split("/operations/")[0];let l;o&&"httpOptions"in o&&(l=o.httpOptions);const a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:r,config:{httpOptions:l}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{const r=await this.getVideosOperationInternal({operationName:n.name,config:o});return n._fromAPIResponse({apiResponse:r,_isVertexAI:!1})}}async get(e){const n=e.operation,o=e.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const r=n.name.split("/operations/")[0];let l;o&&"httpOptions"in o&&(l=o.httpOptions);const a=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:r,config:{httpOptions:l}});return n._fromAPIResponse({apiResponse:a,_isVertexAI:!0})}else{const r=await this.getVideosOperationInternal({operationName:n.name,config:o});return n._fromAPIResponse({apiResponse:r,_isVertexAI:!1})}}async getVideosOperationInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=Si(e);return u=_("{operationName}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json()),a}else{const d=Ai(e);return u=_("{operationName}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json()),a}}async fetchPredictVideosOperationInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI()){const u=Ei(e);return l=_("{resourceName}:fetchPredictOperation",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}function to(t){const e={};if(i(t,["languageCodes"])!==void 0)throw new Error("languageCodes parameter is not supported in Gemini API.");return e}function od(t){const e={},n=i(t,["apiKey"]);if(n!=null&&s(e,["apiKey"],n),i(t,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(i(t,["authType"])!==void 0)throw new Error("authType parameter is not supported in Gemini API.");if(i(t,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(i(t,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(i(t,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is not supported in Gemini API.");if(i(t,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is not supported in Gemini API.");return e}function id(t){const e={},n=i(t,["data"]);if(n!=null&&s(e,["data"],n),i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const o=i(t,["mimeType"]);return o!=null&&s(e,["mimeType"],o),e}function rd(t){const e={},n=i(t,["parts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(l=>hd(l))),s(e,["parts"],r)}const o=i(t,["role"]);return o!=null&&s(e,["role"],o),e}function sd(t,e,n){const o={},r=i(e,["expireTime"]);n!==void 0&&r!=null&&s(n,["expireTime"],r);const l=i(e,["newSessionExpireTime"]);n!==void 0&&l!=null&&s(n,["newSessionExpireTime"],l);const a=i(e,["uses"]);n!==void 0&&a!=null&&s(n,["uses"],a);const u=i(e,["liveConnectConstraints"]);n!==void 0&&u!=null&&s(n,["bidiGenerateContentSetup"],pd(t,u));const c=i(e,["lockAdditionalFields"]);return n!==void 0&&c!=null&&s(n,["fieldMask"],c),o}function ld(t,e){const n={},o=i(e,["config"]);return o!=null&&s(n,["config"],sd(t,o,n)),n}function ad(t){const e={};if(i(t,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=i(t,["fileUri"]);n!=null&&s(e,["fileUri"],n);const o=i(t,["mimeType"]);return o!=null&&s(e,["mimeType"],o),e}function ud(t){const e={},n=i(t,["id"]);n!=null&&s(e,["id"],n);const o=i(t,["args"]);o!=null&&s(e,["args"],o);const r=i(t,["name"]);if(r!=null&&s(e,["name"],r),i(t,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(i(t,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return e}function dd(t){const e={},n=i(t,["authConfig"]);n!=null&&s(e,["authConfig"],od(n));const o=i(t,["enableWidget"]);return o!=null&&s(e,["enableWidget"],o),e}function cd(t){const e={},n=i(t,["searchTypes"]);if(n!=null&&s(e,["searchTypes"],n),i(t,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(i(t,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");const o=i(t,["timeRangeFilter"]);return o!=null&&s(e,["timeRangeFilter"],o),e}function fd(t,e){const n={},o=i(t,["generationConfig"]);e!==void 0&&o!=null&&s(e,["setup","generationConfig"],o);const r=i(t,["responseModalities"]);e!==void 0&&r!=null&&s(e,["setup","generationConfig","responseModalities"],r);const l=i(t,["temperature"]);e!==void 0&&l!=null&&s(e,["setup","generationConfig","temperature"],l);const a=i(t,["topP"]);e!==void 0&&a!=null&&s(e,["setup","generationConfig","topP"],a);const u=i(t,["topK"]);e!==void 0&&u!=null&&s(e,["setup","generationConfig","topK"],u);const c=i(t,["maxOutputTokens"]);e!==void 0&&c!=null&&s(e,["setup","generationConfig","maxOutputTokens"],c);const d=i(t,["mediaResolution"]);e!==void 0&&d!=null&&s(e,["setup","generationConfig","mediaResolution"],d);const f=i(t,["seed"]);e!==void 0&&f!=null&&s(e,["setup","generationConfig","seed"],f);const p=i(t,["speechConfig"]);e!==void 0&&p!=null&&s(e,["setup","generationConfig","speechConfig"],ht(p));const h=i(t,["thinkingConfig"]);e!==void 0&&h!=null&&s(e,["setup","generationConfig","thinkingConfig"],h);const m=i(t,["enableAffectiveDialog"]);e!==void 0&&m!=null&&s(e,["setup","generationConfig","enableAffectiveDialog"],m);const g=i(t,["systemInstruction"]);e!==void 0&&g!=null&&s(e,["setup","systemInstruction"],rd(F(g)));const v=i(t,["tools"]);if(e!==void 0&&v!=null){let P=fe(v);Array.isArray(P)&&(P=P.map(C=>Ed(ce(C)))),s(e,["setup","tools"],P)}const E=i(t,["sessionResumption"]);e!==void 0&&E!=null&&s(e,["setup","sessionResumption"],gd(E));const y=i(t,["inputAudioTranscription"]);e!==void 0&&y!=null&&s(e,["setup","inputAudioTranscription"],to(y));const A=i(t,["outputAudioTranscription"]);e!==void 0&&A!=null&&s(e,["setup","outputAudioTranscription"],to(A));const I=i(t,["realtimeInputConfig"]);e!==void 0&&I!=null&&s(e,["setup","realtimeInputConfig"],I);const S=i(t,["contextWindowCompression"]);e!==void 0&&S!=null&&s(e,["setup","contextWindowCompression"],S);const R=i(t,["proactivity"]);if(e!==void 0&&R!=null&&s(e,["setup","proactivity"],R),i(t,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");const T=i(t,["avatarConfig"]);e!==void 0&&T!=null&&s(e,["setup","avatarConfig"],T);const w=i(t,["safetySettings"]);if(e!==void 0&&w!=null){let P=w;Array.isArray(P)&&(P=P.map(C=>md(C))),s(e,["setup","safetySettings"],P)}return n}function pd(t,e){const n={},o=i(e,["model"]);o!=null&&s(n,["setup","model"],D(t,o));const r=i(e,["config"]);return r!=null&&s(n,["config"],fd(r,n)),n}function hd(t){const e={},n=i(t,["mediaResolution"]);n!=null&&s(e,["mediaResolution"],n);const o=i(t,["codeExecutionResult"]);o!=null&&s(e,["codeExecutionResult"],o);const r=i(t,["executableCode"]);r!=null&&s(e,["executableCode"],r);const l=i(t,["fileData"]);l!=null&&s(e,["fileData"],ad(l));const a=i(t,["functionCall"]);a!=null&&s(e,["functionCall"],ud(a));const u=i(t,["functionResponse"]);u!=null&&s(e,["functionResponse"],u);const c=i(t,["inlineData"]);c!=null&&s(e,["inlineData"],id(c));const d=i(t,["text"]);d!=null&&s(e,["text"],d);const f=i(t,["thought"]);f!=null&&s(e,["thought"],f);const p=i(t,["thoughtSignature"]);p!=null&&s(e,["thoughtSignature"],p);const h=i(t,["videoMetadata"]);h!=null&&s(e,["videoMetadata"],h);const m=i(t,["toolCall"]);m!=null&&s(e,["toolCall"],m);const g=i(t,["toolResponse"]);g!=null&&s(e,["toolResponse"],g);const v=i(t,["partMetadata"]);return v!=null&&s(e,["partMetadata"],v),e}function md(t){const e={},n=i(t,["category"]);if(n!=null&&s(e,["category"],n),i(t,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");const o=i(t,["threshold"]);return o!=null&&s(e,["threshold"],o),e}function gd(t){const e={},n=i(t,["handle"]);if(n!=null&&s(e,["handle"],n),i(t,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return e}function Ed(t){const e={};if(i(t,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const n=i(t,["computerUse"]);n!=null&&s(e,["computerUse"],n);const o=i(t,["fileSearch"]);o!=null&&s(e,["fileSearch"],o);const r=i(t,["googleSearch"]);r!=null&&s(e,["googleSearch"],cd(r));const l=i(t,["googleMaps"]);l!=null&&s(e,["googleMaps"],dd(l));const a=i(t,["codeExecution"]);if(a!=null&&s(e,["codeExecution"],a),i(t,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const u=i(t,["functionDeclarations"]);if(u!=null){let p=u;Array.isArray(p)&&(p=p.map(h=>h)),s(e,["functionDeclarations"],p)}const c=i(t,["googleSearchRetrieval"]);if(c!=null&&s(e,["googleSearchRetrieval"],c),i(t,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is not supported in Gemini API.");const d=i(t,["urlContext"]);d!=null&&s(e,["urlContext"],d);const f=i(t,["mcpServers"]);if(f!=null){let p=f;Array.isArray(p)&&(p=p.map(h=>h)),s(e,["mcpServers"],p)}return e}function vd(t){const e=[];for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(typeof o=="object"&&o!=null&&Object.keys(o).length>0){const r=Object.keys(o).map(l=>`${n}.${l}`);e.push(...r)}else e.push(n)}return e.join(",")}function yd(t,e){let n=null;const o=t.bidiGenerateContentSetup;if(typeof o=="object"&&o!==null&&"setup"in o){const l=o.setup;typeof l=="object"&&l!==null?(t.bidiGenerateContentSetup=l,n=l):delete t.bidiGenerateContentSetup}else o!==void 0&&delete t.bidiGenerateContentSetup;const r=t.fieldMask;if(n){const l=vd(n);if(Array.isArray(e?.lockAdditionalFields)&&e?.lockAdditionalFields.length===0)l?t.fieldMask=l:delete t.fieldMask;else if(e?.lockAdditionalFields&&e.lockAdditionalFields.length>0&&r!==null&&Array.isArray(r)&&r.length>0){const a=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let u=[];r.length>0&&(u=r.map(d=>a.includes(d)?`generationConfig.${d}`:d));const c=[];l&&c.push(l),u.length>0&&c.push(...u),c.length>0?t.fieldMask=c.join(","):delete t.fieldMask}else delete t.fieldMask}else r!==null&&Array.isArray(r)&&r.length>0?t.fieldMask=r.join(","):delete t.fieldMask;return t}class Td extends Q{constructor(e){super(),this.apiClient=e}async create(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{const u=ld(this.apiClient,e);l=_("auth_tokens",u._url),a=u._query,delete u.config,delete u._url,delete u._query;const c=yd(u,e.config);return r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(d=>d.json()),r.then(d=>d)}}}function _d(t,e){const n={},o=i(t,["force"]);return e!==void 0&&o!=null&&s(e,["_query","force"],o),n}function Id(t){const e={},n=i(t,["name"]);n!=null&&s(e,["_url","name"],n);const o=i(t,["config"]);return o!=null&&_d(o,e),e}function Cd(t){const e={},n=i(t,["name"]);return n!=null&&s(e,["_url","name"],n),e}function Ad(t,e){const n={},o=i(t,["pageSize"]);e!==void 0&&o!=null&&s(e,["_query","pageSize"],o);const r=i(t,["pageToken"]);return e!==void 0&&r!=null&&s(e,["_query","pageToken"],r),n}function Sd(t){const e={},n=i(t,["parent"]);n!=null&&s(e,["_url","parent"],n);const o=i(t,["config"]);return o!=null&&Ad(o,e),e}function Rd(t){const e={},n=i(t,["sdkHttpResponse"]);n!=null&&s(e,["sdkHttpResponse"],n);const o=i(t,["nextPageToken"]);o!=null&&s(e,["nextPageToken"],o);const r=i(t,["documents"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(a=>a)),s(e,["documents"],l)}return e}class Pd extends Q{constructor(e){super(),this.apiClient=e,this.list=async n=>new ie(X.PAGED_ITEM_DOCUMENTS,o=>this.listInternal({parent:n.parent,config:o.config}),await this.listInternal(n),n)}async get(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Cd(e);return l=_("{name}",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>c)}}async delete(e){var n,o;let r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=Id(e);r=_("{name}",a._url),l=a._query,delete a._url,delete a._query,await this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Sd(e);return l=_("{parent}/documents",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>{const d=Rd(c),f=new Fi;return Object.assign(f,d),f})}}}class Nd extends Q{constructor(e,n=new Pd(e)){super(),this.apiClient=e,this.documents=n,this.list=async(o={})=>new ie(X.PAGED_ITEM_FILE_SEARCH_STORES,r=>this.listInternal(r),await this.listInternal(o),o)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async downloadMedia(e,n){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");const o=new URL(e,"http://dummy.com");let r=o.pathname;if(r.startsWith("/")&&(r=r.slice(1)),!r.includes("/media/"))throw new Error(`Invalid uri format: ${e}. Expected to contain /media/`);const l={};o.searchParams.forEach((c,d)=>{l[d]=c}),l.alt="media";const a=Object.assign({},n?.httpOptions),u=await this.apiClient.request({path:r,httpMethod:"GET",queryParams:l,httpOptions:a});if(u instanceof Ne){const c=await u.responseInternal.arrayBuffer();return new Uint8Array(c)}else throw new Error("Unexpected response type from downloadMedia")}async create(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=pu(this.apiClient,e);return l=_("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>c)}}async get(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=gu(e);return l=_("{name}",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>c)}}async delete(e){var n,o;let r="",l={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=mu(e);r=_("{name}",a._url),l=a._query,delete a._url,delete a._query,await this.apiClient.request({path:r,queryParams:l,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Iu(e);return l=_("fileSearchStores",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>{const d=Cu(c),f=new Vi;return Object.assign(f,d),f})}}async uploadToFileSearchStoreInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=Au(e);return l=_("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>{const d=Su(c),f=new Hi;return Object.assign(f,d),f})}}async importFile(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=yu(e);return l=_("{file_search_store_name}:importFile",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),r.then(c=>{const d=vu(c),f=new ut;return Object.assign(f,d),f})}}}let Go=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return Go=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,o=>(+o^n()&15>>+o/4).toString(16))};const wd=()=>Go();function nt(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const ot=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class J extends Error{}class H extends J{constructor(e,n,o,r){super(`${H.makeMessage(e,n,o)}`),this.status=e,this.headers=r,this.error=n}static makeMessage(e,n,o){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):o;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,o,r){if(!e||!r)return new ke({message:o,cause:ot(n)});const l=n;return e===400?new Fo(e,l,o,r):e===401?new Vo(e,l,o,r):e===403?new Ho(e,l,o,r):e===404?new qo(e,l,o,r):e===409?new Bo(e,l,o,r):e===422?new Jo(e,l,o,r):e===429?new bo(e,l,o,r):e>=500?new $o(e,l,o,r):new H(e,l,o,r)}}class it extends H{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ke extends H{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class ko extends ke{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Fo extends H{}class Vo extends H{}class Ho extends H{}class qo extends H{}class Bo extends H{}class Jo extends H{}class bo extends H{}class $o extends H{}const Md=/^[a-z][a-z0-9+.-]*:/i,Dd=t=>Md.test(t);let rt=t=>(rt=Array.isArray,rt(t));const xd=rt;let Ud=xd;const no=Ud;function oo(t){if(!t)return!0;for(const e in t)return!1;return!0}function Ld(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const Gd=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new J(`${t} must be an integer`);if(e<0)throw new J(`${t} must be a positive integer`);return e},kd=t=>{try{return JSON.parse(t)}catch{return}};const Fd=t=>new Promise(e=>setTimeout(e,t));function Vd(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Oo(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Hd(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Oo({start(){},async pull(n){const{done:o,value:r}=await e.next();o?n.close():n.enqueue(r)},async cancel(){var n;await((n=e.return)===null||n===void 0?void 0:n.call(e))}})}function Yo(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function qd(t){var e,n;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((n=(e=t[Symbol.asyncIterator]()).return)===null||n===void 0?void 0:n.call(e));return}const o=t.getReader(),r=o.cancel();o.releaseLock(),await r}const Bd=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function Jd(t){return Object.entries(t).filter(([e,n])=>typeof n<"u").map(([e,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(e)}=`;throw new J(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}const bd="0.0.1";const Ko=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e?.versions)===null||t===void 0?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function be(t,e,n){return Ko(),new File(t,e??"unknown_file",n)}function $d(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const Od=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";const Wo=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Yd=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Wo(t),Kd=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Wd(t,e,n){if(Ko(),t=await t,Yd(t))return t instanceof File?t:be([await t.arrayBuffer()],t.name);if(Kd(t)){const r=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),be(await st(r),e,n)}const o=await st(t);if(e||(e=$d(t)),!n?.type){const r=o.find(l=>typeof l=="object"&&"type"in l&&l.type);typeof r=="string"&&(n=Object.assign(Object.assign({},n),{type:r}))}return be(o,e,n)}async function st(t){var e,n,o,r,l;let a=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)a.push(t);else if(Wo(t))a.push(t instanceof Blob?t:await t.arrayBuffer());else if(Od(t))try{for(var u=!0,c=K(t),d;d=await c.next(),e=d.done,!e;u=!0){r=d.value,u=!1;const f=r;a.push(...await st(f))}}catch(f){n={error:f}}finally{try{!u&&!e&&(o=c.return)&&await o.call(c)}finally{if(n)throw n.error}}else{const f=(l=t?.constructor)===null||l===void 0?void 0:l.name;throw new Error(`Unexpected data type: ${typeof t}${f?`; constructor: ${f}`:""}${zd(t)}`)}return a}function zd(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class gt{constructor(e){this._client=e}}gt._key=[];function zo(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const io=Object.freeze(Object.create(null)),Xd=(t=zo)=>(function(n,...o){if(n.length===1)return n[0];let r=!1;const l=[],a=n.reduce((f,p,h)=>{var m,g,v;/[?#]/.test(p)&&(r=!0);const E=o[h];let y=(r?encodeURIComponent:t)(""+E);return h!==o.length&&(E==null||typeof E=="object"&&E.toString===((v=Object.getPrototypeOf((g=Object.getPrototypeOf((m=E.hasOwnProperty)!==null&&m!==void 0?m:io))!==null&&g!==void 0?g:io))===null||v===void 0?void 0:v.toString))&&(y=E+"",l.push({start:f.length+p.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(E).slice(8,-1)} is not a valid path parameter`})),f+p+(h===o.length?"":y)},""),u=a.split(/[?#]/,1)[0],c=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let d;for(;(d=c.exec(u))!==null;){const f=d[0].startsWith("/"),p=f?1:0,h=f?d[0].slice(1):d[0];l.push({start:d.index+p,length:h.length,error:`Value "${h}" can't be safely passed as a path parameter`})}if(l.sort((f,p)=>f.start-p.start),l.length>0){let f=0;const p=l.reduce((h,m)=>{const g=" ".repeat(m.start-f),v="^".repeat(m.length);return f=m.start+m.length,h+g+v},"");throw new J(`Path parameters result in path with invalid segments: ${l.map(h=>h.error).join(` `)} ${a} ${p}`)}return a}),O=Xd(zo);class Xo extends gt{create(e,n){var o;const{api_version:r=this._client.apiVersion}=e,l=ee(e,["api_version"]);if("model"in l&&"agent_config"in l)throw new J("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in l&&"generation_config"in l)throw new J("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(O`/${r}/interactions`,Object.assign(Object.assign({body:l},n),{stream:(o=e.stream)!==null&&o!==void 0?o:!1}))}delete(e,n={},o){const{api_version:r=this._client.apiVersion}=n??{};return this._client.delete(O`/${r}/interactions/${e}`,o)}cancel(e,n={},o){const{api_version:r=this._client.apiVersion}=n??{};return this._client.post(O`/${r}/interactions/${e}/cancel`,o)}get(e,n={},o){var r;const l=n??{},{api_version:a=this._client.apiVersion}=l,u=ee(l,["api_version"]);return this._client.get(O`/${a}/interactions/${e}`,Object.assign(Object.assign({query:u},o),{stream:(r=n?.stream)!==null&&r!==void 0?r:!1}))}}Xo._key=Object.freeze(["interactions"]);class Qo extends Xo{}class Zo extends gt{create(e,n){const{api_version:o=this._client.apiVersion}=e,r=ee(e,["api_version"]);return this._client.post(O`/${o}/webhooks`,Object.assign({body:r},n))}update(e,n={},o){const r=n??{},{api_version:l=this._client.apiVersion,update_mask:a}=r,u=ee(r,["api_version","update_mask"]);return this._client.patch(O`/${l}/webhooks/${e}`,Object.assign({query:{update_mask:a},body:u},o))}list(e={},n){const o=e??{},{api_version:r=this._client.apiVersion}=o,l=ee(o,["api_version"]);return this._client.get(O`/${r}/webhooks`,Object.assign({query:l},n))}delete(e,n={},o){const{api_version:r=this._client.apiVersion}=n??{};return this._client.delete(O`/${r}/webhooks/${e}`,o)}get(e,n={},o){const{api_version:r=this._client.apiVersion}=n??{};return this._client.get(O`/${r}/webhooks/${e}`,o)}ping(e,n=void 0,o){const{api_version:r=this._client.apiVersion,body:l}=n??{};return this._client.post(O`/${r}/webhooks/${e}:ping`,Object.assign({body:l},o))}rotateSigningSecret(e,n={},o){const r=n??{},{api_version:l=this._client.apiVersion}=r,a=ee(r,["api_version"]);return this._client.post(O`/${l}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:a},o))}}Zo._key=Object.freeze(["webhooks"]);class jo extends Zo{}function Qd(t){let e=0;for(const r of t)e+=r.length;const n=new Uint8Array(e);let o=0;for(const r of t)n.set(r,o),o+=r.length;return n}let _e;function Et(t){let e;return(_e??(e=new globalThis.TextEncoder,_e=e.encode.bind(e)))(t)}let Ie;function ro(t){let e;return(Ie??(e=new globalThis.TextDecoder,Ie=e.decode.bind(e)))(t)}class Fe{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null,this.searchIndex=0}decode(e){var n;if(e==null)return[];const o=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Et(e):e;this.buffer=Qd([this.buffer,o]);const r=[];let l;for(;(l=Zd(this.buffer,(n=this.carriageReturnIndex)!==null&&n!==void 0?n:this.searchIndex))!=null;){if(l.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=l.index;continue}if(this.carriageReturnIndex!=null&&(l.index!==this.carriageReturnIndex+1||l.carriage)){r.push(ro(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null,this.searchIndex=0;continue}const a=this.carriageReturnIndex!==null?l.preceding-1:l.preceding,u=ro(this.buffer.subarray(0,a));r.push(u),this.buffer=this.buffer.subarray(l.index),this.carriageReturnIndex=null,this.searchIndex=0}return this.searchIndex=Math.max(0,this.buffer.length-1),r}flush(){return this.buffer.length?this.decode(` `):[]}}Fe.NEWLINE_CHARS=new Set([` `,"\r"]);Fe.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Zd(t,e){const r=e??0,l=t.indexOf(10,r),a=t.indexOf(13,r);if(l===-1&&a===-1)return null;let u;return l!==-1&&a!==-1?u=Math.min(l,a):u=l!==-1?l:a,t[u]===10?{preceding:u,index:u+1,carriage:!1}:{preceding:u,index:u+1,carriage:!0}}const De={off:0,error:200,warn:300,info:400,debug:500},so=(t,e,n)=>{if(t){if(Ld(De,t))return t;V(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(De))}`)}};function ye(){}function Ce(t,e,n){return!e||De[t]>De[n]?ye:e[t].bind(e)}const jd={error:ye,warn:ye,info:ye,debug:ye};let lo=new WeakMap;function V(t){var e;const n=t.logger,o=(e=t.logLevel)!==null&&e!==void 0?e:"off";if(!n)return jd;const r=lo.get(n);if(r&&r[0]===o)return r[1];const l={error:Ce("error",n,o),warn:Ce("warn",n,o),info:Ce("info",n,o),debug:Ce("debug",n,o)};return lo.set(n,[o,l]),l}const oe=t=>(t.options&&(t.options=Object.assign({},t.options),delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-goog-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);class ae{constructor(e,n,o){this.iterator=e,this.controller=n,this.client=o}static fromSSEResponse(e,n,o){let r=!1;const l=o?V(o):console;function a(){return Y(this,arguments,function*(){var c,d,f,p;if(r)throw new J("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let h=!1;try{try{for(var m=!0,g=K(ec(e,n)),v;v=yield N(g.next()),c=v.done,!c;m=!0){p=v.value,m=!1;const E=p;if(!h)if(E.data.startsWith("[DONE]")){h=!0;continue}else try{yield yield N(JSON.parse(E.data))}catch(y){throw l.error("Could not parse message into JSON:",E.data),l.error("From chunk:",E.raw),y}}}catch(E){d={error:E}}finally{try{!m&&!c&&(f=g.return)&&(yield N(f.call(g)))}finally{if(d)throw d.error}}h=!0}catch(E){if(nt(E))return yield N(void 0);throw E}finally{h||n.abort()}})}return new ae(a,n,o)}static fromReadableStream(e,n,o){let r=!1;function l(){return Y(this,arguments,function*(){var c,d,f,p;const h=new Fe,m=Yo(e);try{for(var g=!0,v=K(m),E;E=yield N(v.next()),c=E.done,!c;g=!0){p=E.value,g=!1;const y=p;for(const A of h.decode(y))yield yield N(A)}}catch(y){d={error:y}}finally{try{!g&&!c&&(f=v.return)&&(yield N(f.call(v)))}finally{if(d)throw d.error}}for(const y of h.flush())yield yield N(y)})}function a(){return Y(this,arguments,function*(){var c,d,f,p;if(r)throw new J("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let h=!1;try{try{for(var m=!0,g=K(l()),v;v=yield N(g.next()),c=v.done,!c;m=!0){p=v.value,m=!1;const E=p;h||E&&(yield yield N(JSON.parse(E)))}}catch(E){d={error:E}}finally{try{!m&&!c&&(f=g.return)&&(yield N(f.call(g)))}finally{if(d)throw d.error}}h=!0}catch(E){if(nt(E))return yield N(void 0);throw E}finally{h||n.abort()}})}return new ae(a,n,o)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],n=[],o=this.iterator(),r=l=>({next:()=>{if(l.length===0){const a=o.next();e.push(a),n.push(a)}return l.shift()}});return[new ae(()=>r(e),this.controller,this.client),new ae(()=>r(n),this.controller,this.client)]}toReadableStream(){const e=this;let n;return Oo({async start(){n=e[Symbol.asyncIterator]()},async pull(o){try{const{value:r,done:l}=await n.next();if(l)return o.close();const a=Et(JSON.stringify(r)+` `);o.enqueue(a)}catch(r){o.error(r)}},async cancel(){var o;await((o=n.return)===null||o===void 0?void 0:o.call(n))}})}}function ec(t,e){return Y(this,arguments,function*(){var o,r,l,a;if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new J("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new J("Attempted to iterate over a response with no body");const u=new nc,c=new Fe,d=Yo(t.body);try{for(var f=!0,p=K(tc(d)),h;h=yield N(p.next()),o=h.done,!o;f=!0){a=h.value,f=!1;const m=a;for(const g of c.decode(m)){const v=u.decode(g);v&&(yield yield N(v))}}}catch(m){r={error:m}}finally{try{!f&&!o&&(l=p.return)&&(yield N(l.call(p)))}finally{if(r)throw r.error}}for(const m of c.flush()){const g=u.decode(m);g&&(yield yield N(g))}})}function tc(t){return Y(this,arguments,function*(){var n,o,r,l;try{for(var a=!0,u=K(t),c;c=yield N(u.next()),n=c.done,!n;a=!0){l=c.value,a=!1;const d=l;if(d==null)continue;const f=d instanceof ArrayBuffer?new Uint8Array(d):typeof d=="string"?Et(d):d;yield yield N(f)}}catch(d){o={error:d}}finally{try{!a&&!n&&(r=u.return)&&(yield N(r.call(u)))}finally{if(o)throw o.error}}})}class nc{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const l={event:this.event,data:this.data.join(` `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],l}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,o,r]=oc(e,":");return r.startsWith(" ")&&(r=r.substring(1)),n==="event"?this.event=r:n==="data"&&this.data.push(r),null}}function oc(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function ic(t,e){const{response:n,requestLogID:o,retryOfRequestLogID:r,startTime:l}=e,a=await(async()=>{var u;if(e.options.stream)return V(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):ae.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const c=n.headers.get("content-type"),d=(u=c?.split(";")[0])===null||u===void 0?void 0:u.trim();return d?.includes("application/json")||d?.endsWith("+json")?n.headers.get("content-length")==="0"?void 0:await n.json():await n.text()})();return V(t).debug(`[${o}] response parsed`,oe({retryOfRequestLogID:r,url:n.url,status:n.status,body:a,durationMs:Date.now()-l})),a}class vt extends Promise{constructor(e,n,o=ic){super(r=>{r(null)}),this.responsePromise=n,this.parseResponse=o,this.client=e}_thenUnwrap(e){return new vt(this.client,this.responsePromise,async(n,o)=>e(await this.parseResponse(n,o),o))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}const ei=Symbol("brand.privateNullableHeaders");function*rc(t){if(!t)return;if(ei in t){const{values:o,nulls:r}=t;yield*o.entries();for(const l of r)yield[l,null];return}let e=!1,n;t instanceof Headers?n=t.entries():no(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let o of n){const r=o[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const l=no(o[1])?o[1]:[o[1]];let a=!1;for(const u of l)u!==void 0&&(e&&!a&&(a=!0,yield[r,null]),yield[r,u])}}const ve=t=>{const e=new Headers,n=new Set;for(const o of t){const r=new Set;for(const[l,a]of rc(o)){const u=l.toLowerCase();r.has(u)||(e.delete(l),r.add(u)),a===null?(e.delete(l),n.add(u)):(e.append(l,a),n.delete(u))}}return{[ei]:!0,values:e,nulls:n}};const $e=t=>{var e,n,o,r,l;if(typeof globalThis.process<"u")return((n=(e=ci)===null||e===void 0?void 0:e[t])===null||n===void 0?void 0:n.trim())||void 0;if(typeof globalThis.Deno<"u")return((l=(r=(o=globalThis.Deno.env)===null||o===void 0?void 0:o.get)===null||r===void 0?void 0:r.call(o,t))===null||l===void 0?void 0:l.trim())||void 0};var ti;class Ve{constructor(e){var n,o,r,l,a,u,c,{baseURL:d=$e("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:f=(n=$e("GEMINI_API_KEY"))!==null&&n!==void 0?n:null,apiVersion:p="v1beta"}=e,h=ee(e,["baseURL","apiKey","apiVersion"]);const m=Object.assign(Object.assign({apiKey:f,apiVersion:p},h),{baseURL:d||"https://generativelanguage.googleapis.com"});this.baseURL=m.baseURL,this.timeout=(o=m.timeout)!==null&&o!==void 0?o:Ve.DEFAULT_TIMEOUT,this.logger=(r=m.logger)!==null&&r!==void 0?r:console;const g="warn";this.logLevel=g,this.logLevel=(a=(l=so(m.logLevel,"ClientOptions.logLevel",this))!==null&&l!==void 0?l:so($e("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&a!==void 0?a:g,this.fetchOptions=m.fetchOptions,this.maxRetries=(u=m.maxRetries)!==null&&u!==void 0?u:2,this.fetch=(c=m.fetch)!==null&&c!==void 0?c:Vd(),this.encoder=Bd,this._options=m,this.apiKey=f,this.apiVersion=p,this.clientAdapter=m.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.has("authorization")||e.has("x-goog-api-key"))&&!(this.apiKey&&e.get("x-goog-api-key"))&&!n.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){const n=ve([e.headers]);if(!(n.values.has("authorization")||n.values.has("x-goog-api-key"))){if(this.apiKey)return ve([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter&&this.clientAdapter.isVertexAI())return ve([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Jd(e)}getUserAgent(){return`${this.constructor.name}/JS ${bd}`}defaultIdempotencyKey(){return`stainless-node-retry-${wd()}`}makeStatusError(e,n,o,r){return H.generate(e,n,o,r)}buildURL(e,n,o){const r=!this.baseURLOverridden()&&o||this.baseURL,l=Dd(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),u=Object.fromEntries(l.searchParams);return(!oo(a)||!oo(u))&&(n=Object.assign(Object.assign(Object.assign({},u),a),n)),typeof n=="object"&&n&&!Array.isArray(n)&&(l.search=this.stringifyQuery(n)),l.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){const n=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${n}`}}async prepareRequest(e,{url:n,options:o}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,o){return this.request(Promise.resolve(o).then(r=>Object.assign({method:e,path:n},r)))}request(e,n=null){return new vt(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,o){var r,l,a;const u=await e,c=(r=u.maxRetries)!==null&&r!==void 0?r:this.maxRetries;n==null&&(n=c),await this.prepareOptions(u);const{req:d,url:f,timeout:p}=await this.buildRequest(u,{retryCount:c-n});await this.prepareRequest(d,{url:f,options:u});const h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=o===void 0?"":`, retryOf: ${o}`,g=Date.now();if(V(this).debug(`[${h}] sending request`,oe({retryOfRequestLogID:o,method:u.method,url:f,options:u,headers:d.headers})),!((l=u.signal)===null||l===void 0)&&l.aborted)throw new it;const v=new AbortController,E=await this.fetchWithTimeout(f,d,p,v).catch(ot),y=Date.now();if(E instanceof globalThis.Error){const I=`retrying, ${n} attempts remaining`;if(!((a=u.signal)===null||a===void 0)&&a.aborted)throw new it;const S=nt(E)||/timed? ?out/i.test(String(E)+("cause"in E?String(E.cause):""));if(n)return V(this).info(`[${h}] connection ${S?"timed out":"failed"} - ${I}`),V(this).debug(`[${h}] connection ${S?"timed out":"failed"} (${I})`,oe({retryOfRequestLogID:o,url:f,durationMs:y-g,message:E.message})),this.retryRequest(u,n,o??h);throw V(this).info(`[${h}] connection ${S?"timed out":"failed"} - error; no more retries left`),V(this).debug(`[${h}] connection ${S?"timed out":"failed"} (error; no more retries left)`,oe({retryOfRequestLogID:o,url:f,durationMs:y-g,message:E.message})),S?new ko:new ke({cause:E})}const A=`[${h}${m}] ${d.method} ${f} ${E.ok?"succeeded":"failed"} with status ${E.status} in ${y-g}ms`;if(!E.ok){const I=await this.shouldRetry(E);if(n&&I){const C=`retrying, ${n} attempts remaining`;return await qd(E.body),V(this).info(`${A} - ${C}`),V(this).debug(`[${h}] response error (${C})`,oe({retryOfRequestLogID:o,url:E.url,status:E.status,headers:E.headers,durationMs:y-g})),this.retryRequest(u,n,o??h,E.headers)}const S=I?"error; no more retries left":"error; not retryable";V(this).info(`${A} - ${S}`);const R=await E.text().catch(C=>ot(C).message),T=kd(R),w=T?void 0:R;throw V(this).debug(`[${h}] response error (${S})`,oe({retryOfRequestLogID:o,url:E.url,status:E.status,headers:E.headers,message:w,durationMs:Date.now()-g})),this.makeStatusError(E.status,T,w,E.headers)}return V(this).info(A),V(this).debug(`[${h}] response start`,oe({retryOfRequestLogID:o,url:E.url,status:E.status,headers:E.headers,durationMs:y-g})),{response:E,options:u,controller:v,requestLogID:h,retryOfRequestLogID:o,startTime:g}}async fetchWithTimeout(e,n,o,r){const l=n||{},{signal:a,method:u}=l,c=ee(l,["signal","method"]),d=this._makeAbort(r);a&&a.addEventListener("abort",d,{once:!0});const f=setTimeout(d,o),p=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,h=Object.assign(Object.assign(Object.assign({signal:r.signal},p?{duplex:"half"}:{}),{method:"GET"}),c);u&&(h.method=u.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(f)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,o,r){var l;let a;const u=r?.get("retry-after-ms");if(u){const d=parseFloat(u);Number.isNaN(d)||(a=d)}const c=r?.get("retry-after");if(c&&!a){const d=parseFloat(c);Number.isNaN(d)?a=Date.parse(c)-Date.now():a=d*1e3}if(a===void 0){const d=(l=e.maxRetries)!==null&&l!==void 0?l:this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(n,d)}return await Fd(a),this.makeRequest(e,n-1,o)}calculateDefaultRetryTimeoutMillis(e,n){const l=n-e,a=Math.min(.5*Math.pow(2,l),8),u=1-Math.random()*.25;return a*u*1e3}async buildRequest(e,{retryCount:n=0}={}){var o,r,l;const a=Object.assign({},e),{method:u,path:c,query:d,defaultBaseURL:f}=a,p=this.buildURL(c,d,f);"timeout"in a&&Gd("timeout",a.timeout),a.timeout=(o=a.timeout)!==null&&o!==void 0?o:this.timeout;const{bodyHeaders:h,body:m}=this.buildBody({options:a}),g=await this.buildHeaders({options:e,method:u,bodyHeaders:h,retryCount:n});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:u,headers:g},a.signal&&{signal:a.signal}),globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"}),m&&{body:m}),(r=this.fetchOptions)!==null&&r!==void 0?r:{}),(l=a.fetchOptions)!==null&&l!==void 0?l:{}),url:p,timeout:a.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:o,retryCount:r}){let l={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),l[this.idempotencyHeader]=e.idempotencyKey);const a=await this.authHeaders(e);let u=ve([l,{Accept:"application/json","User-Agent":this.getUserAgent()},this._options.defaultHeaders,o,e.headers,a]);return this.validateHeaders(u),u.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const o=ve([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&o.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Hd(e)}:typeof e=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:o})}}Ve.DEFAULT_TIMEOUT=6e4;class G extends Ve{constructor(){super(...arguments),this.interactions=new Qo(this),this.webhooks=new jo(this)}}ti=G;G.GeminiNextGenAPIClient=ti;G.GeminiNextGenAPIClientError=J;G.APIError=H;G.APIConnectionError=ke;G.APIConnectionTimeoutError=ko;G.APIUserAbortError=it;G.NotFoundError=qo;G.ConflictError=Bo;G.RateLimitError=bo;G.BadRequestError=Fo;G.AuthenticationError=Vo;G.InternalServerError=$o;G.PermissionDeniedError=Ho;G.UnprocessableEntityError=Jo;G.toFile=Wd;G.Interactions=Qo;G.Webhooks=jo;function sc(t,e){const n={},o=i(t,["name"]);return o!=null&&s(n,["_url","name"],o),n}function lc(t,e){const n={},o=i(t,["name"]);return o!=null&&s(n,["_url","name"],o),n}function ac(t,e){const n={},o=i(t,["sdkHttpResponse"]);return o!=null&&s(n,["sdkHttpResponse"],o),n}function uc(t,e){const n={},o=i(t,["sdkHttpResponse"]);return o!=null&&s(n,["sdkHttpResponse"],o),n}function dc(t,e,n){const o={};if(i(t,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is not supported in Gemini API.");const r=i(t,["tunedModelDisplayName"]);if(e!==void 0&&r!=null&&s(e,["displayName"],r),i(t,["description"])!==void 0)throw new Error("description parameter is not supported in Gemini API.");const l=i(t,["epochCount"]);e!==void 0&&l!=null&&s(e,["tuningTask","hyperparameters","epochCount"],l);const a=i(t,["learningRateMultiplier"]);if(a!=null&&s(o,["tuningTask","hyperparameters","learningRateMultiplier"],a),i(t,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(i(t,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(i(t,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is not supported in Gemini API.");if(i(t,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is not supported in Gemini API.");if(i(t,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is not supported in Gemini API.");const u=i(t,["batchSize"]);e!==void 0&&u!=null&&s(e,["tuningTask","hyperparameters","batchSize"],u);const c=i(t,["learningRate"]);if(e!==void 0&&c!=null&&s(e,["tuningTask","hyperparameters","learningRate"],c),i(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");if(i(t,["beta"])!==void 0)throw new Error("beta parameter is not supported in Gemini API.");if(i(t,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is not supported in Gemini API.");if(i(t,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is not supported in Gemini API.");if(i(t,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is not supported in Gemini API.");if(i(t,["outputUri"])!==void 0)throw new Error("outputUri parameter is not supported in Gemini API.");if(i(t,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is not supported in Gemini API.");return o}function cc(t,e,n){const o={};let r=i(n,["config","method"]);if(r===void 0&&(r="SUPERVISED_FINE_TUNING"),r==="SUPERVISED_FINE_TUNING"){const T=i(t,["validationDataset"]);e!==void 0&&T!=null&&s(e,["supervisedTuningSpec"],Oe(T))}else if(r==="PREFERENCE_TUNING"){const T=i(t,["validationDataset"]);e!==void 0&&T!=null&&s(e,["preferenceOptimizationSpec"],Oe(T))}else if(r==="DISTILLATION"){const T=i(t,["validationDataset"]);e!==void 0&&T!=null&&s(e,["distillationSpec"],Oe(T))}const l=i(t,["tunedModelDisplayName"]);e!==void 0&&l!=null&&s(e,["tunedModelDisplayName"],l);const a=i(t,["description"]);e!==void 0&&a!=null&&s(e,["description"],a);let u=i(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){const T=i(t,["epochCount"]);e!==void 0&&T!=null&&s(e,["supervisedTuningSpec","hyperParameters","epochCount"],T)}else if(u==="PREFERENCE_TUNING"){const T=i(t,["epochCount"]);e!==void 0&&T!=null&&s(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],T)}else if(u==="DISTILLATION"){const T=i(t,["epochCount"]);e!==void 0&&T!=null&&s(e,["distillationSpec","hyperParameters","epochCount"],T)}let c=i(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){const T=i(t,["learningRateMultiplier"]);e!==void 0&&T!=null&&s(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],T)}else if(c==="PREFERENCE_TUNING"){const T=i(t,["learningRateMultiplier"]);e!==void 0&&T!=null&&s(e,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],T)}else if(c==="DISTILLATION"){const T=i(t,["learningRateMultiplier"]);e!==void 0&&T!=null&&s(e,["distillationSpec","hyperParameters","learningRateMultiplier"],T)}let d=i(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){const T=i(t,["exportLastCheckpointOnly"]);e!==void 0&&T!=null&&s(e,["supervisedTuningSpec","exportLastCheckpointOnly"],T)}else if(d==="PREFERENCE_TUNING"){const T=i(t,["exportLastCheckpointOnly"]);e!==void 0&&T!=null&&s(e,["preferenceOptimizationSpec","exportLastCheckpointOnly"],T)}else if(d==="DISTILLATION"){const T=i(t,["exportLastCheckpointOnly"]);e!==void 0&&T!=null&&s(e,["distillationSpec","exportLastCheckpointOnly"],T)}let f=i(n,["config","method"]);if(f===void 0&&(f="SUPERVISED_FINE_TUNING"),f==="SUPERVISED_FINE_TUNING"){const T=i(t,["adapterSize"]);e!==void 0&&T!=null&&s(e,["supervisedTuningSpec","hyperParameters","adapterSize"],T)}else if(f==="PREFERENCE_TUNING"){const T=i(t,["adapterSize"]);e!==void 0&&T!=null&&s(e,["preferenceOptimizationSpec","hyperParameters","adapterSize"],T)}else if(f==="DISTILLATION"){const T=i(t,["adapterSize"]);e!==void 0&&T!=null&&s(e,["distillationSpec","hyperParameters","adapterSize"],T)}let p=i(n,["config","method"]);if(p===void 0&&(p="SUPERVISED_FINE_TUNING"),p==="SUPERVISED_FINE_TUNING"){const T=i(t,["tuningMode"]);e!==void 0&&T!=null&&s(e,["supervisedTuningSpec","tuningMode"],T)}else if(p==="DISTILLATION"){const T=i(t,["tuningMode"]);e!==void 0&&T!=null&&s(e,["distillationSpec","tuningMode"],T)}const h=i(t,["customBaseModel"]);e!==void 0&&h!=null&&s(e,["customBaseModel"],h);let m=i(n,["config","method"]);if(m===void 0&&(m="SUPERVISED_FINE_TUNING"),m==="SUPERVISED_FINE_TUNING"){const T=i(t,["batchSize"]);e!==void 0&&T!=null&&s(e,["supervisedTuningSpec","hyperParameters","batchSize"],T)}else if(m==="DISTILLATION"){const T=i(t,["batchSize"]);e!==void 0&&T!=null&&s(e,["distillationSpec","hyperParameters","batchSize"],T)}let g=i(n,["config","method"]);if(g===void 0&&(g="SUPERVISED_FINE_TUNING"),g==="SUPERVISED_FINE_TUNING"){const T=i(t,["learningRate"]);e!==void 0&&T!=null&&s(e,["supervisedTuningSpec","hyperParameters","learningRate"],T)}else if(g==="DISTILLATION"){const T=i(t,["learningRate"]);e!==void 0&&T!=null&&s(e,["distillationSpec","hyperParameters","learningRate"],T)}const v=i(t,["labels"]);e!==void 0&&v!=null&&s(e,["labels"],v);const E=i(t,["beta"]);e!==void 0&&E!=null&&s(e,["preferenceOptimizationSpec","hyperParameters","beta"],E);const y=i(t,["baseTeacherModel"]);e!==void 0&&y!=null&&s(e,["distillationSpec","baseTeacherModel"],y);const A=i(t,["tunedTeacherModelSource"]);e!==void 0&&A!=null&&s(e,["distillationSpec","tunedTeacherModelSource"],A);const I=i(t,["sftLossWeightMultiplier"]);e!==void 0&&I!=null&&s(e,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],I);const S=i(t,["outputUri"]);e!==void 0&&S!=null&&s(e,["outputUri"],S);const R=i(t,["encryptionSpec"]);return e!==void 0&&R!=null&&s(e,["encryptionSpec"],R),o}function fc(t,e){const n={},o=i(t,["baseModel"]);o!=null&&s(n,["baseModel"],o);const r=i(t,["preTunedModel"]);r!=null&&s(n,["preTunedModel"],r);const l=i(t,["trainingDataset"]);l!=null&&Tc(l);const a=i(t,["config"]);return a!=null&&dc(a,n),n}function pc(t,e){const n={},o=i(t,["baseModel"]);o!=null&&s(n,["baseModel"],o);const r=i(t,["preTunedModel"]);r!=null&&s(n,["preTunedModel"],r);const l=i(t,["trainingDataset"]);l!=null&&_c(l,n,e);const a=i(t,["config"]);return a!=null&&cc(a,n,e),n}function hc(t,e){const n={},o=i(t,["name"]);return o!=null&&s(n,["_url","name"],o),n}function mc(t,e){const n={},o=i(t,["name"]);return o!=null&&s(n,["_url","name"],o),n}function gc(t,e,n){const o={},r=i(t,["pageSize"]);e!==void 0&&r!=null&&s(e,["_query","pageSize"],r);const l=i(t,["pageToken"]);e!==void 0&&l!=null&&s(e,["_query","pageToken"],l);const a=i(t,["filter"]);return e!==void 0&&a!=null&&s(e,["_query","filter"],a),o}function Ec(t,e){const n={},o=i(t,["config"]);return o!=null&&gc(o,n),n}function vc(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["nextPageToken"]);r!=null&&s(n,["nextPageToken"],r);const l=i(t,["tuningJobs"]);if(l!=null){let a=l;Array.isArray(a)&&(a=a.map(u=>lt(u))),s(n,["tuningJobs"],a)}return n}function yc(t,e){const n={},o=i(t,["name"]);o!=null&&s(n,["model"],o);const r=i(t,["name"]);return r!=null&&s(n,["endpoint"],r),n}function Tc(t,e){const n={};if(i(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(i(t,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");const o=i(t,["examples"]);if(o!=null){let r=o;Array.isArray(r)&&(r=r.map(l=>l)),s(n,["examples","examples"],r)}return n}function _c(t,e,n){const o={};let r=i(n,["config","method"]);if(r===void 0&&(r="SUPERVISED_FINE_TUNING"),r==="SUPERVISED_FINE_TUNING"){const a=i(t,["gcsUri"]);e!==void 0&&a!=null&&s(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(r==="PREFERENCE_TUNING"){const a=i(t,["gcsUri"]);e!==void 0&&a!=null&&s(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}else if(r==="DISTILLATION"){const a=i(t,["gcsUri"]);e!==void 0&&a!=null&&s(e,["distillationSpec","promptDatasetUri"],a)}let l=i(n,["config","method"]);if(l===void 0&&(l="SUPERVISED_FINE_TUNING"),l==="SUPERVISED_FINE_TUNING"){const a=i(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&s(e,["supervisedTuningSpec","trainingDatasetUri"],a)}else if(l==="PREFERENCE_TUNING"){const a=i(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&s(e,["preferenceOptimizationSpec","trainingDatasetUri"],a)}else if(l==="DISTILLATION"){const a=i(t,["vertexDatasetResource"]);e!==void 0&&a!=null&&s(e,["distillationSpec","promptDatasetUri"],a)}if(i(t,["examples"])!==void 0)throw new Error("examples parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return o}function Ic(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["name"]);r!=null&&s(n,["name"],r);const l=i(t,["state"]);l!=null&&s(n,["state"],Eo(l));const a=i(t,["createTime"]);a!=null&&s(n,["createTime"],a);const u=i(t,["tuningTask","startTime"]);u!=null&&s(n,["startTime"],u);const c=i(t,["tuningTask","completeTime"]);c!=null&&s(n,["endTime"],c);const d=i(t,["updateTime"]);d!=null&&s(n,["updateTime"],d);const f=i(t,["description"]);f!=null&&s(n,["description"],f);const p=i(t,["baseModel"]);p!=null&&s(n,["baseModel"],p);const h=i(t,["_self"]);return h!=null&&s(n,["tunedModel"],yc(h)),n}function lt(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["name"]);r!=null&&s(n,["name"],r);const l=i(t,["state"]);l!=null&&s(n,["state"],Eo(l));const a=i(t,["createTime"]);a!=null&&s(n,["createTime"],a);const u=i(t,["startTime"]);u!=null&&s(n,["startTime"],u);const c=i(t,["endTime"]);c!=null&&s(n,["endTime"],c);const d=i(t,["updateTime"]);d!=null&&s(n,["updateTime"],d);const f=i(t,["error"]);f!=null&&s(n,["error"],f);const p=i(t,["description"]);p!=null&&s(n,["description"],p);const h=i(t,["baseModel"]);h!=null&&s(n,["baseModel"],h);const m=i(t,["tunedModel"]);m!=null&&s(n,["tunedModel"],m);const g=i(t,["preTunedModel"]);g!=null&&s(n,["preTunedModel"],g);const v=i(t,["supervisedTuningSpec"]);v!=null&&s(n,["supervisedTuningSpec"],v);const E=i(t,["preferenceOptimizationSpec"]);E!=null&&s(n,["preferenceOptimizationSpec"],E);const y=i(t,["distillationSpec"]);y!=null&&s(n,["distillationSpec"],y);const A=i(t,["tuningDataStats"]);A!=null&&s(n,["tuningDataStats"],A);const I=i(t,["encryptionSpec"]);I!=null&&s(n,["encryptionSpec"],I);const S=i(t,["partnerModelTuningSpec"]);S!=null&&s(n,["partnerModelTuningSpec"],S);const R=i(t,["customBaseModel"]);R!=null&&s(n,["customBaseModel"],R);const T=i(t,["evaluateDatasetRuns"]);if(T!=null){let ne=T;Array.isArray(ne)&&(ne=ne.map($=>$)),s(n,["evaluateDatasetRuns"],ne)}const w=i(t,["experiment"]);w!=null&&s(n,["experiment"],w);const P=i(t,["fullFineTuningSpec"]);P!=null&&s(n,["fullFineTuningSpec"],P);const C=i(t,["labels"]);C!=null&&s(n,["labels"],C);const M=i(t,["outputUri"]);M!=null&&s(n,["outputUri"],M);const x=i(t,["pipelineJob"]);x!=null&&s(n,["pipelineJob"],x);const B=i(t,["serviceAccount"]);B!=null&&s(n,["serviceAccount"],B);const b=i(t,["tunedModelDisplayName"]);b!=null&&s(n,["tunedModelDisplayName"],b);const k=i(t,["tuningJobState"]);k!=null&&s(n,["tuningJobState"],k);const U=i(t,["veoTuningSpec"]);U!=null&&s(n,["veoTuningSpec"],U);const z=i(t,["distillationSamplingSpec"]);z!=null&&s(n,["distillationSamplingSpec"],z);const me=i(t,["tuningJobMetadata"]);return me!=null&&s(n,["tuningJobMetadata"],me),n}function Cc(t,e){const n={},o=i(t,["sdkHttpResponse"]);o!=null&&s(n,["sdkHttpResponse"],o);const r=i(t,["name"]);r!=null&&s(n,["name"],r);const l=i(t,["metadata"]);l!=null&&s(n,["metadata"],l);const a=i(t,["done"]);a!=null&&s(n,["done"],a);const u=i(t,["error"]);return u!=null&&s(n,["error"],u),n}function Oe(t,e){const n={},o=i(t,["gcsUri"]);o!=null&&s(n,["validationDatasetUri"],o);const r=i(t,["vertexDatasetResource"]);return r!=null&&s(n,["validationDatasetUri"],r),n}class Ac extends Q{constructor(e){super(),this.apiClient=e,this.list=async(n={})=>new ie(X.PAGED_ITEM_TUNING_JOBS,o=>this.listInternal(o),await this.listInternal(n),n),this.get=async n=>await this.getInternal(n),this.tune=async n=>{var o;if(this.apiClient.isVertexAI())if(n.baseModel.startsWith("projects/")){const r={tunedModelName:n.baseModel};!((o=n.config)===null||o===void 0)&&o.preTunedModelCheckpointId&&(r.checkpointId=n.config.preTunedModelCheckpointId);const l=Object.assign(Object.assign({},n),{preTunedModel:r});return l.baseModel=void 0,await this.tuneInternal(l)}else{const r=Object.assign({},n);return await this.tuneInternal(r)}else{const r=Object.assign({},n),l=await this.tuneMldevInternal(r);let a="";return l.metadata!==void 0&&l.metadata.tunedModel!==void 0?a=l.metadata.tunedModel:l.name!==void 0&&l.name.includes("/operations/")&&(a=l.name.split("/operations/")[0]),{name:a,state:ze.JOB_STATE_QUEUED}}}}async getInternal(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=mc(e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>lt(f))}else{const d=hc(e);return u=_("{name}",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"GET",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>Ic(f))}}async listInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI()){const u=Ec(e);return l=_("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),r.then(c=>{const d=vc(c),f=new ki;return Object.assign(f,d),f})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var n,o,r,l;let a,u="",c={};if(this.apiClient.isVertexAI()){const d=lc(e);return u=_("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=uc(f),h=new Un;return Object.assign(h,p),h})}else{const d=sc(e);return u=_("{name}:cancel",d._url),c=d._query,delete d._url,delete d._query,a=this.apiClient.request({path:u,queryParams:c,body:JSON.stringify(d),httpMethod:"POST",httpOptions:(r=e.config)===null||r===void 0?void 0:r.httpOptions,abortSignal:(l=e.config)===null||l===void 0?void 0:l.abortSignal}).then(f=>f.json().then(p=>{const h=p;return h.sdkHttpResponse={headers:f.headers},h})),a.then(f=>{const p=ac(f),h=new Un;return Object.assign(h,p),h})}}async tuneInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI()){const u=pc(e,e);return l=_("tuningJobs",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),r.then(c=>lt(c))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var n,o;let r,l="",a={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const u=fc(e);return l=_("tunedModels",u._url),a=u._query,delete u._url,delete u._query,r=this.apiClient.request({path:l,queryParams:a,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=e.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(o=e.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const f=d;return f.sdkHttpResponse={headers:c.headers},f})),r.then(c=>Cc(c))}}}class Sc{async download(e,n){throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an tag.")}}const Rc=1024*1024*8,Pc=3,Nc=1e3,wc=2,xe="x-goog-upload-status";async function Mc(t,e,n,o){var r;const l=await ni(t,e,n,o),a=await l?.json();if(((r=l?.headers)===null||r===void 0?void 0:r[xe])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return a.file}async function Dc(t,e,n,o){var r;const l=await ni(t,e,n,o),a=await l?.json();if(((r=l?.headers)===null||r===void 0?void 0:r[xe])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");const u=co(a),c=new dt;return Object.assign(c,u),c}async function ni(t,e,n,o){var r,l,a;let u=e;const c=o?.baseUrl||((r=n.clientOptions.httpOptions)===null||r===void 0?void 0:r.baseUrl);if(c){const m=new URL(c),g=new URL(e);g.protocol=m.protocol,g.host=m.host,g.port=m.port,u=g.toString()}let d=0,f=0,p=new Ne(new Response),h="upload";for(d=t.size;f=d&&(h+=", finalize");let v=0,E=Nc;for(;vsetTimeout(e,t))}class Lc{async upload(e,n,o,r){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await Mc(e,n,o,r)}async uploadToFileSearchStore(e,n,o,r){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await Dc(e,n,o,r)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await xc(e)}}class Gc{create(e,n,o){return new kc(e,n,o)}}class kc{constructor(e,n,o){this.url=e,this.headers=n,this.callbacks=o}connect(){this.ws=new WebSocket(this.url),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}}const ao="x-goog-api-key";class Fc{constructor(e){this.apiKey=e}async addAuthHeaders(e,n){if(e.get(ao)===null){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");if(!this.apiKey)throw new Error("API key is missing. Please provide a valid API key.");e.append(ao,this.apiKey)}}}const Vc="gl-node/";class Yc{getNextGenClient(){var e;const n=this.httpOptions;if(this._nextGenClient===void 0){const o=this.httpOptions;this._nextGenClient=new G({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:o?.timeout,maxRetries:(e=o?.retryOptions)===null||e===void 0?void 0:e.attempts})}return n?.extraBody&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions."),this._interactions=this.getNextGenClient().interactions,this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=this.getNextGenClient().webhooks,this._webhooks)}constructor(e){var n;if(e.apiKey==null)throw new Error("An API Key must be set when running in a browser");if(e.project||e.location)throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.");this.vertexai=(n=e.vertexai)!==null&&n!==void 0?n:!1,this.apiKey=e.apiKey;const o=mi(e.httpOptions,e.vertexai,void 0,void 0);o&&(e.httpOptions?e.httpOptions.baseUrl=o:e.httpOptions={baseUrl:o}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;const r=new Fc(this.apiKey);this.apiClient=new ku({auth:r,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:Vc+"web",uploader:new Lc,downloader:new Sc}),this.models=new td(this.apiClient),this.live=new zu(this.apiClient,r,new Gc),this.batches=new Xr(this.apiClient),this.chats=new Ls(this.models,this.apiClient),this.caches=new Ds(this.apiClient),this.files=new Ys(this.apiClient),this.operations=new nd(this.apiClient),this.authTokens=new Td(this.apiClient),this.tunings=new Ac(this.apiClient),this.fileSearchStores=new Nd(this.apiClient)}}function Kc(t){return t.thought===!0}function Wc(t,e){return typeof e=="string"&&e.length>0?e:t}const Hc=/^[A-Za-z0-9+/]+={0,2}$/;function qc(t){return!t||t.length%4!==0?!1:Hc.test(t)}function Ye(t,e){return t&&qc(e)?e:void 0}function Ke(t){return t.startsWith("claude-")||t.startsWith("gpt-oss-")}function Bc(t){const e=t.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(e)return Number.parseInt(e[1],10)}function Jc(t){const e=Bc(t);return e!==void 0?e>=3:!0}function zc(t,e){const n=[],o=l=>Ke(t.id)?l.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):l,r=ii(e.messages,t,o);for(const l of r)if(l.role==="user")if(typeof l.content=="string")n.push({role:"user",parts:[{text:re(l.content)}]});else{const a=l.content.map(u=>u.type==="text"?{text:re(u.text)}:{inlineData:{mimeType:u.mimeType,data:u.data}});if(a.length===0)continue;n.push({role:"user",parts:a})}else if(l.role==="assistant"){const a=[],u=l.provider===t.provider&&l.model===t.id;for(const c of l.content)if(c.type==="text"){if(!c.text||c.text.trim()==="")continue;const d=Ye(u,c.textSignature);a.push({text:re(c.text),...d&&{thoughtSignature:d}})}else if(c.type==="thinking"){if(!c.thinking||c.thinking.trim()==="")continue;if(u){const d=Ye(u,c.thinkingSignature);a.push({thought:!0,text:re(c.thinking),...d&&{thoughtSignature:d}})}else a.push({text:re(c.thinking)})}else if(c.type==="toolCall"){const d=Ye(u,c.thoughtSignature),f={functionCall:{name:c.name,args:c.arguments??{},...Ke(t.id)?{id:c.id}:{}},...d&&{thoughtSignature:d}};a.push(f)}if(a.length===0)continue;n.push({role:"model",parts:a})}else if(l.role==="toolResult"){const u=l.content.filter(y=>y.type==="text").map(y=>y.text).join(` `),c=t.input.includes("image")?l.content.filter(y=>y.type==="image"):[],d=u.length>0,f=c.length>0,p=Jc(t.id),h=d?re(u):f?"(see attached image)":"",m=c.map(y=>({inlineData:{mimeType:y.mimeType,data:y.data}})),g=Ke(t.id),v={functionResponse:{name:l.toolName,response:l.isError?{error:h}:{output:h},...f&&p&&{parts:m},...g?{id:l.toolCallId}:{}}},E=n[n.length-1];E?.role==="user"&&E.parts?.some(y=>y.functionResponse)?E.parts.push(v):n.push({role:"user",parts:[v]}),f&&!p&&n.push({role:"user",parts:[{text:"Tool result image:"},...m]})}return n}const bc=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function oi(t){if(typeof t!="object"||t===null||Array.isArray(t))return t;const e={};for(const[n,o]of Object.entries(t))bc.has(n)||(e[n]=oi(o));return e}function Xc(t,e=!1){if(t.length!==0)return[{functionDeclarations:t.map(n=>({name:n.name,description:n.description,...e?{parameters:oi(n.parameters)}:{parametersJsonSchema:n.parameters}}))}]}function Qc(t){switch(t){case"auto":return se.AUTO;case"none":return se.NONE;case"any":return se.ANY;default:return se.AUTO}}function Zc(t){switch(t){case L.STOP:return"stop";case L.MAX_TOKENS:return"length";case L.BLOCKLIST:case L.PROHIBITED_CONTENT:case L.SPII:case L.SAFETY:case L.IMAGE_SAFETY:case L.IMAGE_PROHIBITED_CONTENT:case L.IMAGE_RECITATION:case L.IMAGE_OTHER:case L.RECITATION:case L.FINISH_REASON_UNSPECIFIED:case L.OTHER:case L.LANGUAGE:case L.MALFORMED_FUNCTION_CALL:case L.UNEXPECTED_TOOL_CALL:case L.NO_IMAGE:return"error";default:{const e=t;throw new Error(`Unhandled stop reason: ${e}`)}}}export{Yc as G,Xe as R,Ut as T,Xc as a,Qc as b,zc as c,Kc as i,Zc as m,Wc as r};