@hintergrund/ui 0.3.10 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/BuilderAgentPane-Cf2EQd0U.js +1 -0
  2. package/dist/IntegrationHealth-CBFYmR_K.js +1 -0
  3. package/dist/admin.js +2 -23351
  4. package/dist/anthropic-messages-CXPLHUpk.js +1 -0
  5. package/dist/assets/index-DI9TbuA9.js +34669 -0
  6. package/dist/builder.js +1 -28
  7. package/dist/config.types-CElC76m0.js +1 -0
  8. package/dist/deferred-tools-8QtAASke.js +1 -0
  9. package/dist/error-body-B13t5xBI.js +1 -0
  10. package/dist/github-copilot-headers-n6Dqf6oj.js +1 -0
  11. package/dist/global-BmWXMWNY.js +2 -0
  12. package/dist/google-generative-ai-CNHCOvQN.js +1 -0
  13. package/dist/legacy-DcJfom53.js +1 -0
  14. package/dist/login.js +1 -133
  15. package/dist/mail.js +1 -698
  16. package/dist/openai-completions-CSZJSCfj.js +1 -0
  17. package/dist/openai-prompt-cache-Mi5dPc0-.js +1 -0
  18. package/dist/openai-responses-BU24JgAs.js +1 -0
  19. package/dist/setup.js +1 -402
  20. package/dist/transform-messages-C1f-L9_8.js +1 -0
  21. package/package.json +4 -3
  22. package/dist/BuilderAgentPane-B6zkx8zw.js +0 -23164
  23. package/dist/IntegrationHealth-2p7QXJqB.js +0 -218
  24. package/dist/anthropic-messages-k-Bsbioz.js +0 -3772
  25. package/dist/azure-openai-responses-DZenJI-m.js +0 -168
  26. package/dist/config.types-DZ5yfeqq.js +0 -20
  27. package/dist/deferred-tools-nxpq94I4.js +0 -34
  28. package/dist/diagnostics-x5QOwca_.js +0 -91
  29. package/dist/error-body-pXgvw5vV.js +0 -68
  30. package/dist/font-pool/LICENSES.txt +0 -22
  31. package/dist/font-pool/inter.ttf +0 -0
  32. package/dist/font-pool/inter.woff2 +0 -0
  33. package/dist/font-pool/jetbrains-mono.ttf +0 -0
  34. package/dist/font-pool/jetbrains-mono.woff2 +0 -0
  35. package/dist/font-pool/lora.ttf +0 -0
  36. package/dist/font-pool/lora.woff2 +0 -0
  37. package/dist/font-pool/merriweather.ttf +0 -0
  38. package/dist/font-pool/merriweather.woff2 +0 -0
  39. package/dist/font-pool/montserrat.ttf +0 -0
  40. package/dist/font-pool/montserrat.woff2 +0 -0
  41. package/dist/font-pool/playfair-display.ttf +0 -0
  42. package/dist/font-pool/playfair-display.woff2 +0 -0
  43. package/dist/font-pool/poppins.ttf +0 -0
  44. package/dist/font-pool/poppins.woff2 +0 -0
  45. package/dist/font-pool/roboto.ttf +0 -0
  46. package/dist/font-pool/roboto.woff2 +0 -0
  47. package/dist/font-pool/space-grotesk.ttf +0 -0
  48. package/dist/font-pool/space-grotesk.woff2 +0 -0
  49. package/dist/font-pool/work-sans.ttf +0 -0
  50. package/dist/font-pool/work-sans.woff2 +0 -0
  51. package/dist/github-copilot-headers-pRo3v4t7.js +0 -27
  52. package/dist/global-DMXVTUMq.js +0 -33351
  53. package/dist/google-generative-ai-D2RQTVlL.js +0 -291
  54. package/dist/google-shared-CG2Lbh1z.js +0 -8746
  55. package/dist/google-vertex-BjniYIZ1.js +0 -329
  56. package/dist/hash-BixfZjoG.js +0 -21
  57. package/dist/headers-CnTiKpOL.js +0 -24
  58. package/dist/json-parse-CxjAnWaM.js +0 -231
  59. package/dist/legacy-C2ziK2Om.js +0 -14
  60. package/dist/mistral-conversations-CPZ7CuMx.js +0 -558
  61. package/dist/openai-ClxLHXsh.js +0 -5371
  62. package/dist/openai-codex-responses-CqmMU3UY.js +0 -909
  63. package/dist/openai-completions-Dc8OEKqJ.js +0 -730
  64. package/dist/openai-prompt-cache-Bm8Re6Vv.js +0 -17
  65. package/dist/openai-responses-DZ1U8uxZ.js +0 -192
  66. package/dist/openai-responses-shared-B0rkV1lD.js +0 -481
  67. package/dist/pi-messages-CRx0yqMp.js +0 -268
  68. package/dist/pi-user-agent-CsXkkH60.js +0 -20
  69. package/dist/provider-env-Cj6X7Wly.js +0 -35
  70. package/dist/provider-retry-BGImU1PV.js +0 -68
  71. package/dist/rolldown-runtime-nTTD767F.js +0 -37
  72. package/dist/transform-messages-DvxSeyBQ.js +0 -383
@@ -0,0 +1 @@
1
+ void 0===globalThis.process&&(globalThis.process={env:{},platform:"browser",version:"",versions:{},browser:!0,nextTick:function(e){return Promise.resolve().then(e)}});import{o as e,u as t}from"./github-copilot-headers-n6Dqf6oj.js";import{h as n,m as o,p as i}from"./BuilderAgentPane-Cf2EQd0U.js";import{f as r,g as s,i as l,m as a,p as u,t as c,u as p}from"./transform-messages-C1f-L9_8.js";import{n as d,t as h}from"./error-body-B13t5xBI.js";var f,m,g,E,y,v,I,_,T,A,C,O,S,b,w,R,N,P,D,M,U,G,x,L,k,q,H,F,V,j,B,J,Y,$,K,W,z,X,Q,Z,ee,te,ne,oe,ie,re,se,le,ae,ue,ce,pe,de,he,fe,me,ge,Ee,ye,ve,Ie,_e,Te,Ae,Ce,Oe,Se=/* @__PURE__ */e((e,t)=>{function n(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=/* @__PURE__ */(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(/* @__PURE__ */new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(void 0===n){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1)}var o=this;return this._timer=setTimeout(function(){o._attempts++,o._operationTimeoutCb&&(o._timeout=setTimeout(function(){o._operationTimeoutCb(o._attempts)},o._operationTimeout),o._options.unref&&o._timeout.unref()),o._fn(o._attempts)},n),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=/* @__PURE__ */(new Date).getTime(),this._fn(this._attempts)},n.prototype.try=function(e){this.attempt(e)},n.prototype.start=function(e){this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,n=0,o=0;o<this._errors.length;o++){var i=this._errors[o],r=i.message,s=(e[r]||0)+1;e[r]=s,s>=n&&(t=i,n=s)}return t}}),be=/* @__PURE__ */e(e=>{var t=Se();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],i=0;i<t.retries;i++)o.push(this.createTimeout(i,t));return e&&e.forever&&!o.length&&o.push(this.createTimeout(i,t)),o.sort(function(e,t){return e-t}),o},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,o=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(o,t.maxTimeout)},e.wrap=function(t,n,o){if(n instanceof Array&&(o=n,n=null),!o)for(var i in o=[],t)"function"==typeof t[i]&&o.push(i);for(var r=0;r<o.length;r++){var s=o[r],l=t[s];t[s]=function(o){var i=e.operation(n),r=Array.prototype.slice.call(arguments,1),s=r.pop();r.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),s.apply(this,arguments))}),i.attempt(function(){o.apply(t,r)})}.bind(t,l),t[s].options=n}}}),we=/* @__PURE__ */e((e,t)=>{t.exports=be()}),Re=/* @__PURE__ */t(/* @__PURE__ */e((e,t)=>{var n=we(),o=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],i=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},r=(e,t)=>new Promise((r,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};const l=n.operation(t);l.attempt(async n=>{try{r(await e(n))}catch(u){if(!(u instanceof Error))return void s(/* @__PURE__ */new TypeError(`Non-error was thrown: "${u}". You should only throw errors.`));if(u instanceof i)l.stop(),s(u.originalError);else if(u instanceof TypeError&&(a=u.message,!o.includes(a)))l.stop(),s(u);else{((e,t,n)=>{const o=n.retries-(t-1);e.attemptNumber=t,e.retriesLeft=o})(u,n,t);try{await t.onFailedAttempt(u)}catch(u){return void s(u)}l.retry(u)||s(l.mainError())}}var a})});t.exports=r,t.exports.default=r,t.exports.AbortError=i})(),1),Ne=class{};function Pe(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{if(Object.prototype.hasOwnProperty.call(t,n)){const e=t[n];return null!=e?String(e):""}throw new Error(`Key '${n}' not found in valueMap.`)})}function De(e,t,n){for(let r=0;r<t.length-1;r++){const o=t[r];if(o.endsWith("[]")){const i=o.slice(0,-2);if(!(i in e)){if(!Array.isArray(n))throw new Error(`Value must be a list given an array path ${o}`);e[i]=Array.from({length:n.length},()=>({}))}if(Array.isArray(e[i])){const o=e[i];if(Array.isArray(n))for(let e=0;e<o.length;e++)De(o[e],t.slice(r+1),n[e]);else for(const e of o)De(e,t.slice(r+1),n)}return}if(o.endsWith("[0]")){const i=o.slice(0,-3);return i in e||(e[i]=[{}]),void De(e[i][0],t.slice(r+1),n)}e[o]&&"object"==typeof e[o]||(e[o]={}),e=e[o]}const o=t[t.length-1],i=e[o];if(void 0!==i){if(!n||"object"==typeof n&&0===Object.keys(n).length)return;if(n===i)return;if("object"!=typeof i||"object"!=typeof n||null===i||null===n)throw new Error(`Cannot set value for an existing key. Key: ${o}`);Object.assign(i,n)}else"_self"!==o||"object"!=typeof n||null===n||Array.isArray(n)?e[o]=n:Object.assign(e,n)}function Me(e,t,n=void 0){try{if(1===t.length&&"_self"===t[0])return e;for(let o=0;o<t.length;o++){if("object"!=typeof e||null===e)return n;const i=t[o];if(i.endsWith("[]")){const r=i.slice(0,-2);if(r in e){const i=e[r];return Array.isArray(i)?i.map(e=>Me(e,t.slice(o+1),n)):n}return n}e=e[i]}return e}catch(o){if(o instanceof TypeError)return n;throw o}}function Ue(e,t,n,o,i){if(o>=t.length)return;if("object"!=typeof e||null===e)return;const r=t[o];if(r.endsWith("[]")){const s=r.slice(0,-2),l=e;if(s in l&&Array.isArray(l[s]))for(const e of l[s])Ue(e,t,n,o+1,i)}else if("*"===r){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const t=e,r=Object.keys(t).filter(e=>!e.startsWith("_")&&!i.has(e)),s={};for(const e of r)s[e]=t[e];for(const[e,i]of Object.entries(s)){const r=[];for(const t of n.slice(o))"*"===t?r.push(e):r.push(t);De(t,r,i)}for(const e of r)delete t[e]}}else r in e&&Ue(e[r],t,n,o+1,i)}function Ge(e){if("string"!=typeof e)throw new Error("fromImageBytes must be a string");return e}function xe(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["name"],n);const o=Me(e,["metadata"]);null!=o&&De(t,["metadata"],o);const i=Me(e,["done"]);null!=i&&De(t,["done"],i);const r=Me(e,["error"]);null!=r&&De(t,["error"],r);const s=Me(e,["response"]);return null!=s&&De(t,["response"],function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["parent"]);null!=o&&De(t,["parent"],o);const i=Me(e,["documentName"]);return null!=i&&De(t,["documentName"],i),t}(s)),t}!function(e){e.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",e.PYTHON="PYTHON"}(f||(f={})),function(e){e.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",e.OUTCOME_OK="OUTCOME_OK",e.OUTCOME_FAILED="OUTCOME_FAILED",e.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"}(m||(m={})),function(e){e.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",e.SILENT="SILENT",e.WHEN_IDLE="WHEN_IDLE",e.INTERRUPT="INTERRUPT"}(g||(g={})),function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.STRING="STRING",e.NUMBER="NUMBER",e.INTEGER="INTEGER",e.BOOLEAN="BOOLEAN",e.ARRAY="ARRAY",e.OBJECT="OBJECT",e.NULL="NULL"}(E||(E={})),function(e){e.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",e.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"}(y||(y={})),function(e){e.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",e.NO_AUTH="NO_AUTH",e.API_KEY_AUTH="API_KEY_AUTH",e.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",e.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",e.OAUTH="OAUTH",e.OIDC_AUTH="OIDC_AUTH"}(v||(v={})),function(e){e.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",e.HTTP_IN_QUERY="HTTP_IN_QUERY",e.HTTP_IN_HEADER="HTTP_IN_HEADER",e.HTTP_IN_PATH="HTTP_IN_PATH",e.HTTP_IN_BODY="HTTP_IN_BODY",e.HTTP_IN_COOKIE="HTTP_IN_COOKIE"}(I||(I={})),function(e){e.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",e.SIMPLE_SEARCH="SIMPLE_SEARCH",e.ELASTIC_SEARCH="ELASTIC_SEARCH"}(_||(_={})),function(e){e.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",e.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",e.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",e.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"}(T||(T={})),function(e){e.UNSPECIFIED="UNSPECIFIED",e.BLOCKING="BLOCKING",e.NON_BLOCKING="NON_BLOCKING"}(A||(A={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"}(C||(C={})),function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE",e.VALIDATED="VALIDATED"}(O||(O={})),function(e){e.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",e.MINIMAL="MINIMAL",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(S||(S={})),function(e){e.DONT_ALLOW="DONT_ALLOW",e.ALLOW_ADULT="ALLOW_ADULT",e.ALLOW_ALL="ALLOW_ALL"}(b||(b={})),function(e){e.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",e.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",e.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"}(w||(w={})),function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",e.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",e.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",e.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",e.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"}(R||(R={})),function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"}(N||(N={})),function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE",e.OFF="OFF"}(P||(P={})),function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.IMAGE_SAFETY="IMAGE_SAFETY",e.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",e.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",e.NO_IMAGE="NO_IMAGE",e.IMAGE_RECITATION="IMAGE_RECITATION",e.IMAGE_OTHER="IMAGE_OTHER"}(D||(D={})),function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"}(M||(M={})),function(e){e.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"}(U||(U={})),function(e){e.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",e.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",e.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",e.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",e.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"}(G||(G={})),function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.IMAGE_SAFETY="IMAGE_SAFETY",e.MODEL_ARMOR="MODEL_ARMOR",e.JAILBREAK="JAILBREAK"}(x||(x={})),function(e){e.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",e.ON_DEMAND="ON_DEMAND",e.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",e.ON_DEMAND_FLEX="ON_DEMAND_FLEX",e.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"}(L||(L={})),function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.AUDIO="AUDIO",e.VIDEO="VIDEO"}(k||(k={})),function(e){e.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",e.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",e.EXPERIMENTAL="EXPERIMENTAL",e.PREVIEW="PREVIEW",e.STABLE="STABLE",e.LEGACY="LEGACY",e.DEPRECATED="DEPRECATED",e.RETIRED="RETIRED"}(q||(q={})),function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"}(H||(H={})),function(e){e.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",e.TUNING_MODE_FULL="TUNING_MODE_FULL",e.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"}(F||(F={})),function(e){e.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",e.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",e.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",e.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",e.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",e.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",e.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"}(V||(V={})),function(e){e.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",e.JOB_STATE_QUEUED="JOB_STATE_QUEUED",e.JOB_STATE_PENDING="JOB_STATE_PENDING",e.JOB_STATE_RUNNING="JOB_STATE_RUNNING",e.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",e.JOB_STATE_FAILED="JOB_STATE_FAILED",e.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",e.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",e.JOB_STATE_PAUSED="JOB_STATE_PAUSED",e.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",e.JOB_STATE_UPDATING="JOB_STATE_UPDATING",e.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"}(j||(j={})),function(e){e.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",e.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",e.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",e.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",e.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",e.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"}(B||(B={})),function(e){e.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",e.AVERAGE="AVERAGE",e.MODE="MODE",e.STANDARD_DEVIATION="STANDARD_DEVIATION",e.VARIANCE="VARIANCE",e.MINIMUM="MINIMUM",e.MAXIMUM="MAXIMUM",e.MEDIAN="MEDIAN",e.PERCENTILE_P90="PERCENTILE_P90",e.PERCENTILE_P95="PERCENTILE_P95",e.PERCENTILE_P99="PERCENTILE_P99"}(J||(J={})),function(e){e.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",e.BASELINE="BASELINE",e.CANDIDATE="CANDIDATE",e.TIE="TIE"}(Y||(Y={})),function(e){e.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",e.TUNING_TASK_I2V="TUNING_TASK_I2V",e.TUNING_TASK_T2V="TUNING_TASK_T2V",e.TUNING_TASK_R2V="TUNING_TASK_R2V"}($||($={})),function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.STATE_PENDING="STATE_PENDING",e.STATE_ACTIVE="STATE_ACTIVE",e.STATE_FAILED="STATE_FAILED"}(K||(K={})),function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",e.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"}(W||(W={})),function(e){e.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",e.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",e.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",e.URL_CONTEXT="URL_CONTEXT",e.GOOGLE_MAPS="GOOGLE_MAPS",e.FILE_SEARCH="FILE_SEARCH"}(z||(z={})),function(e){e.COLLECTION="COLLECTION"}(X||(X={})),function(e){e.UNSPECIFIED="unspecified",e.FLEX="flex",e.STANDARD="standard",e.PRIORITY="priority"}(Q||(Q={})),function(e){e.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",e.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",e.BALANCED="BALANCED",e.PRIORITIZE_COST="PRIORITIZE_COST"}(Z||(Z={})),function(e){e.PREDICT="PREDICT",e.EMBED_CONTENT="EMBED_CONTENT"}(ee||(ee={})),function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"}(te||(te={})),function(e){e.auto="auto",e.en="en",e.ja="ja",e.ko="ko",e.hi="hi",e.zh="zh",e.pt="pt",e.es="es"}(ne||(ne={})),function(e){e.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",e.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",e.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",e.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",e.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"}(oe||(oe={})),function(e){e.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",e.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",e.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",e.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"}(ie||(ie={})),function(e){e.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",e.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",e.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",e.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"}(re||(re={})),function(e){e.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",e.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",e.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",e.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",e.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",e.EDIT_MODE_STYLE="EDIT_MODE_STYLE",e.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",e.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"}(se||(se={})),function(e){e.FOREGROUND="FOREGROUND",e.BACKGROUND="BACKGROUND",e.PROMPT="PROMPT",e.SEMANTIC="SEMANTIC",e.INTERACTIVE="INTERACTIVE"}(le||(le={})),function(e){e.ASSET="ASSET",e.STYLE="STYLE"}(ae||(ae={})),function(e){e.INSERT="INSERT",e.REMOVE="REMOVE",e.REMOVE_STATIC="REMOVE_STATIC",e.OUTPAINT="OUTPAINT"}(ue||(ue={})),function(e){e.OPTIMIZED="OPTIMIZED",e.LOSSLESS="LOSSLESS"}(ce||(ce={})),function(e){e.CROP="CROP",e.PAD="PAD"}(pe||(pe={})),function(e){e.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",e.PREFERENCE_TUNING="PREFERENCE_TUNING",e.DISTILLATION="DISTILLATION"}(de||(de={})),function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.PROCESSING="PROCESSING",e.ACTIVE="ACTIVE",e.FAILED="FAILED"}(he||(he={})),function(e){e.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",e.UPLOADED="UPLOADED",e.GENERATED="GENERATED",e.REGISTERED="REGISTERED"}(fe||(fe={})),function(e){e.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.RESPONSE_REJECTED="RESPONSE_REJECTED",e.NEED_MORE_INPUT="NEED_MORE_INPUT",e.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",e.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",e.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",e.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",e.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",e.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",e.INPUT_OTHER="INPUT_OTHER",e.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",e.BLOCKLIST="BLOCKLIST",e.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",e.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",e.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",e.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",e.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",e.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",e.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",e.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",e.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",e.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",e.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",e.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",e.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",e.GENERATED_OTHER="GENERATED_OTHER",e.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"}(me||(me={})),function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"}(ge||(ge={})),function(e){e.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",e.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",e.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"}(Ee||(Ee={})),function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.ACTIVITY_START="ACTIVITY_START",e.ACTIVITY_END="ACTIVITY_END"}(ye||(ye={})),function(e){e.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",e.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",e.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"}(ve||(ve={})),function(e){e.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",e.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",e.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"}(Ie||(Ie={})),function(e){e.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",e.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",e.NO_INTERRUPTION="NO_INTERRUPTION"}(_e||(_e={})),function(e){e.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",e.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",e.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",e.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"}(Te||(Te={})),function(e){e.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",e.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",e.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",e.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",e.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",e.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",e.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",e.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",e.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",e.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",e.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",e.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",e.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"}(Ae||(Ae={})),function(e){e.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",e.QUALITY="QUALITY",e.DIVERSITY="DIVERSITY",e.VOCALIZATION="VOCALIZATION"}(Ce||(Ce={})),function(e){e.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",e.PLAY="PLAY",e.PAUSE="PAUSE",e.STOP="STOP",e.RESET_CONTEXT="RESET_CONTEXT"}(Oe||(Oe={}));var Le,ke=class{constructor(e){const t={};for(const n of e.headers.entries())t[n[0]]=n[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}},qe=class{get text(){var e,t,n,o,i,r,s,l;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;let a="",u=!1;const c=[];for(const p of null!==(l=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)&&void 0!==l?l:[]){for(const[e,t]of Object.entries(p))"text"===e||"thought"===e||"thoughtSignature"===e||null===t&&void 0===t||c.push(e);if("string"==typeof p.text){if("boolean"==typeof p.thought&&p.thought)continue;u=!0,a+=p.text}}return c.length,u?a:void 0}get data(){var e,t,n,o,i,r,s,l;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;let a="";const u=[];for(const c of null!==(l=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)&&void 0!==l?l:[]){for(const[e,t]of Object.entries(c))"inlineData"===e||null===t&&void 0===t||u.push(e);c.inlineData&&"string"==typeof c.inlineData.data&&(a+=atob(c.inlineData.data))}return u.length,a.length>0?btoa(a):void 0}get functionCalls(){var e,t,n,o,i,r,s,l;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;const a=null===(l=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)||void 0===l?void 0:l.filter(e=>e.functionCall).map(e=>e.functionCall).filter(e=>void 0!==e);return 0!==(null==a?void 0:a.length)?a:void 0}get executableCode(){var e,t,n,o,i,r,s,l,a;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;const u=null===(l=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)||void 0===l?void 0:l.filter(e=>e.executableCode).map(e=>e.executableCode).filter(e=>void 0!==e);return 0!==(null==u?void 0:u.length)?null===(a=null==u?void 0:u[0])||void 0===a?void 0:a.code:void 0}get codeExecutionResult(){var e,t,n,o,i,r,s,l,a;if(0===(null===(o=null===(n=null===(t=null===(e=this.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content)||void 0===n?void 0:n.parts)||void 0===o?void 0:o.length))return;this.candidates&&this.candidates.length;const u=null===(l=null===(s=null===(r=null===(i=this.candidates)||void 0===i?void 0:i[0])||void 0===r?void 0:r.content)||void 0===s?void 0:s.parts)||void 0===l?void 0:l.filter(e=>e.codeExecutionResult).map(e=>e.codeExecutionResult).filter(e=>void 0!==e);return 0!==(null==u?void 0:u.length)?null===(a=null==u?void 0:u[0])||void 0===a?void 0:a.output:void 0}},He=class{},Fe=class{},Ve=class{},je=class{},Be=class{},Je=class{},Ye=class{},$e=class{},Ke=class{},We=class{},ze=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const o=new e;let i;const r=t;return i=n?function(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["name"],n);const o=Me(e,["metadata"]);null!=o&&De(t,["metadata"],o);const i=Me(e,["done"]);null!=i&&De(t,["done"],i);const r=Me(e,["error"]);null!=r&&De(t,["error"],r);const s=Me(e,["response"]);return null!=s&&De(t,["response"],function(e){const t={},n=Me(e,["videos"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["_self"]);return null!=n&&De(t,["video"],function(e){const t={},n=Me(e,["gcsUri"]);null!=n&&De(t,["uri"],n);const o=Me(e,["bytesBase64Encoded"]);null!=o&&De(t,["videoBytes"],Ge(o));const i=Me(e,["mimeType"]);return null!=i&&De(t,["mimeType"],i),t}(n)),t}(e))),De(t,["generatedVideos"],e)}const o=Me(e,["raiMediaFilteredCount"]);null!=o&&De(t,["raiMediaFilteredCount"],o);const i=Me(e,["raiMediaFilteredReasons"]);return null!=i&&De(t,["raiMediaFilteredReasons"],i),t}(s)),t}(r):function(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["name"],n);const o=Me(e,["metadata"]);null!=o&&De(t,["metadata"],o);const i=Me(e,["done"]);null!=i&&De(t,["done"],i);const r=Me(e,["error"]);null!=r&&De(t,["error"],r);const s=Me(e,["response","generateVideoResponse"]);return null!=s&&De(t,["response"],function(e){const t={},n=Me(e,["generatedSamples"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["video"]);return null!=n&&De(t,["video"],function(e){const t={},n=Me(e,["uri"]);null!=n&&De(t,["uri"],n);const o=Me(e,["encodedVideo"]);null!=o&&De(t,["videoBytes"],Ge(o));const i=Me(e,["encoding"]);return null!=i&&De(t,["mimeType"],i),t}(n)),t}(e))),De(t,["generatedVideos"],e)}const o=Me(e,["raiMediaFilteredCount"]);null!=o&&De(t,["raiMediaFilteredCount"],o);const i=Me(e,["raiMediaFilteredReasons"]);return null!=i&&De(t,["raiMediaFilteredReasons"],i),t}(s)),t}(r),Object.assign(o,i),o}},Xe=class{},Qe=class{},Ze=class{},et=class{},tt=class{},nt=class{},ot=class{},it=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const o=new e,i=function(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["name"],n);const o=Me(e,["metadata"]);null!=o&&De(t,["metadata"],o);const i=Me(e,["done"]);null!=i&&De(t,["done"],i);const r=Me(e,["error"]);null!=r&&De(t,["error"],r);const s=Me(e,["response"]);return null!=s&&De(t,["response"],function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["parent"]);null!=o&&De(t,["parent"],o);const i=Me(e,["documentName"]);return null!=i&&De(t,["documentName"],i),t}(s)),t}(t);return Object.assign(o,i),o}},rt=class{},st=class{},lt=class{},at=class{},ut=class{},ct=class{get text(){var e,t,n;let o="",i=!1;const r=[];for(const s of null!==(n=null===(t=null===(e=this.serverContent)||void 0===e?void 0:e.modelTurn)||void 0===t?void 0:t.parts)&&void 0!==n?n:[]){for(const[e,t]of Object.entries(s))"text"!==e&&"thought"!==e&&null!==t&&r.push(e);if("string"==typeof s.text){if("boolean"==typeof s.thought&&s.thought)continue;i=!0,o+=s.text}}return r.length,i?o:void 0}get data(){var e,t,n;let o="";const i=[];for(const r of null!==(n=null===(t=null===(e=this.serverContent)||void 0===e?void 0:e.modelTurn)||void 0===t?void 0:t.parts)&&void 0!==n?n:[]){for(const[e,t]of Object.entries(r))"inlineData"!==e&&null!==t&&i.push(e);r.inlineData&&"string"==typeof r.inlineData.data&&(o+=atob(r.inlineData.data))}return i.length,o.length>0?btoa(o):void 0}},pt=class{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}},dt=class e{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const o=new e,i=xe(t);return Object.assign(o,i),o}};function ht(e,t){if(!t||"string"!=typeof t)throw new Error("model is required and must be a string");if(t.includes("..")||t.includes("?")||t.includes("&"))throw new Error("invalid model parameter");if(e.isVertexAI()){if(t.startsWith("publishers/")||t.startsWith("projects/")||t.startsWith("models/"))return t;if(t.indexOf("/")>=0){const e=t.split("/",2);return`publishers/${e[0]}/models/${e[1]}`}return`publishers/google/models/${t}`}return t.startsWith("models/")||t.startsWith("tunedModels/")?t:`models/${t}`}function ft(e,t){const n=ht(e,t);return n?n.startsWith("publishers/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/${n}`:n.startsWith("models/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${n}`:n:""}function mt(e){return Array.isArray(e)?e.map(e=>gt(e)):[gt(e)]}function gt(e){if("object"==typeof e&&null!==e)return e;throw new Error("Could not parse input as Blob. Unsupported blob type: "+typeof e)}function Et(e){const t=gt(e);if(t.mimeType&&t.mimeType.startsWith("image/"))return t;throw new Error(`Unsupported mime type: ${t.mimeType}`)}function yt(e){const t=gt(e);if(t.mimeType&&t.mimeType.startsWith("audio/"))return t;throw new Error(`Unsupported mime type: ${t.mimeType}`)}function vt(e){if(null==e)throw new Error("PartUnion is required");if("object"==typeof e)return e;if("string"==typeof e)return{text:e};throw new Error("Unsupported part type: "+typeof e)}function It(e){if(null==e||Array.isArray(e)&&0===e.length)throw new Error("PartListUnion is required");return Array.isArray(e)?e.map(e=>vt(e)):[vt(e)]}function _t(e){return null!=e&&"object"==typeof e&&"parts"in e&&Array.isArray(e.parts)}function Tt(e){return null!=e&&"object"==typeof e&&"functionCall"in e}function At(e){return null!=e&&"object"==typeof e&&"functionResponse"in e}function Ct(e){if(null==e)throw new Error("ContentUnion is required");return _t(e)?e:{role:"user",parts:It(e)}}function Ot(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap(e=>{const t=Ct(e);return t.parts&&t.parts.length>0&&void 0!==t.parts[0].text?[t.parts[0].text]:[]});if(e.isVertexAI()){const e=Ct(t);return e.parts&&e.parts.length>0&&void 0!==e.parts[0].text?[e.parts[0].text]:[]}return Array.isArray(t)?t.map(e=>Ct(e)):[Ct(t)]}function St(e){if(null==e||Array.isArray(e)&&0===e.length)throw new Error("contents are required");if(!Array.isArray(e)){if(Tt(e)||At(e))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[Ct(e)]}const t=[],n=[],o=_t(e[0]);for(const i of e){const e=_t(i);if(e!=o)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(e)t.push(i);else{if(Tt(i)||At(i))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");n.push(i)}}return o||t.push({role:"user",parts:It(n)}),t}function bt(e){const t={},n=["items"],o=["anyOf"],i=["properties"];if(e.type&&e.anyOf)throw new Error("type and anyOf cannot be both populated.");const r=e.anyOf;null!=r&&2==r.length&&("null"===r[0].type?(t.nullable=!0,e=r[1]):"null"===r[1].type&&(t.nullable=!0,e=r[0])),e.type instanceof Array&&function(e,t){e.includes("null")&&(t.nullable=!0);const n=e.filter(e=>"null"!==e);if(1===n.length)t.type=Object.values(E).includes(n[0].toUpperCase())?n[0].toUpperCase():E.TYPE_UNSPECIFIED;else{t.anyOf=[];for(const e of n)t.anyOf.push({type:Object.values(E).includes(e.toUpperCase())?e.toUpperCase():E.TYPE_UNSPECIFIED})}}(e.type,t);for(const[s,l]of Object.entries(e))if(null!=l)if("type"==s){if("null"===l)throw new Error("type: null can not be the only possible type for the field.");if(l instanceof Array)continue;t.type=Object.values(E).includes(l.toUpperCase())?l.toUpperCase():E.TYPE_UNSPECIFIED}else if(n.includes(s))t[s]=bt(l);else if(o.includes(s)){const e=[];for(const n of l)"null"!=n.type?e.push(bt(n)):t.nullable=!0;t[s]=e}else if(i.includes(s)){const e={};for(const[t,n]of Object.entries(l))e[t]=bt(n);t[s]=e}else{if("additionalProperties"===s)continue;t[s]=l}return t}function wt(e){return bt(e)}function Rt(e){if("object"==typeof e)return e;if("string"==typeof e)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};throw new Error("Unsupported speechConfig type: "+typeof e)}function Nt(e){if("multiSpeakerVoiceConfig"in e)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return e}function Pt(e){if(e.functionDeclarations)for(const t of e.functionDeclarations)t.parameters&&(Object.keys(t.parameters).includes("$schema")?t.parametersJsonSchema||(t.parametersJsonSchema=t.parameters,delete t.parameters):t.parameters=bt(t.parameters)),t.response&&(Object.keys(t.response).includes("$schema")?t.responseJsonSchema||(t.responseJsonSchema=t.response,delete t.response):t.response=bt(t.response));return e}function Dt(e){if(null==e)throw new Error("tools is required");if(!Array.isArray(e))throw new Error("tools is required and must be an array of Tools");const t=[];for(const n of e)t.push(n);return t}function Mt(e,t){if("string"!=typeof t)throw new Error("name must be a string");return function(e,t,n,o=1){const i=!t.startsWith(`${n}/`)&&t.split("/").length===o;return e.isVertexAI()?t.startsWith("projects/")?t:t.startsWith("locations/")?`projects/${e.getProject()}/${t}`:t.startsWith(`${n}/`)?`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`:i?`projects/${e.getProject()}/locations/${e.getLocation()}/${n}/${t}`:t:i?`${n}/${t}`:t}(e,t,"cachedContents")}function Ut(e){switch(e){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return e}}function Gt(e){return Ge(e)}function xt(e){var t;let n;var o;if(null!=(o=e)&&"object"==typeof o&&"name"in o&&(n=e.name),!(function(e){return null!=e&&"object"==typeof e&&"uri"in e}(e)&&(n=e.uri,void 0===n)||function(e){return null!=e&&"object"==typeof e&&"video"in e}(e)&&(n=null===(t=e.video)||void 0===t?void 0:t.uri,void 0===n))){if("string"==typeof e&&(n=e),void 0===n)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){const e=n.split("files/")[1].match(/[a-z0-9]+/);if(null===e)throw new Error(`Could not extract file name from URI ${n}`);n=e[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function Lt(e,t){let n;return n=e.isVertexAI()?t?"publishers/google/models":"models":t?"models":"tunedModels",n}function kt(e){for(const t of["models","tunedModels","publisherModels"])if(qt(e,t))return e[t];return[]}function qt(e,t){return null!==e&&"object"==typeof e&&t in e}function Ht(e,t={}){const n=e,o={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(o.responseJsonSchema=n.outputSchema),t.behavior&&(o.behavior=t.behavior),{functionDeclarations:[o]}}function Ft(e,t){let n;if("string"==typeof t)if(e.isVertexAI())if(t.startsWith("gs://"))n={format:"jsonl",gcsUri:[t]};else if(t.startsWith("bq://"))n={format:"bigquery",bigqueryUri:t};else{if(!/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(t))throw new Error(`Unsupported string source for Vertex AI: ${t}`);n={format:"vertex-dataset",vertexDatasetName:t}}else{if(!t.startsWith("files/"))throw new Error(`Unsupported string source for Gemini API: ${t}`);n={fileName:t}}else if(Array.isArray(t)){if(e.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:t}}else n=t;const o=[n.gcsUri,n.bigqueryUri,n.vertexDatasetName].filter(Boolean).length,i=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(e.isVertexAI()){if(i>0||1!==o)throw new Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(o>0||1!==i)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function Vt(e){if("object"!=typeof e||null===e)return{};const t=e,n=t.inlinedResponses;if("object"!=typeof n||null===n)return e;const o=n.inlinedResponses;if(!Array.isArray(o)||0===o.length)return e;let i=!1;for(const r of o){if("object"!=typeof r||null===r)continue;const e=r.response;if("object"==typeof e&&null!==e&&void 0!==e.embedding){i=!0;break}}return i&&(t.inlinedEmbedContentResponses=t.inlinedResponses,delete t.inlinedResponses),e}function jt(e,t){const n=t;if(!e.isVertexAI()){if(/batches\/[^/]+$/.test(n))return n.split("/").pop();throw new Error(`Invalid batch job name: ${n}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();if(/^\d+$/.test(n))return n;throw new Error(`Invalid batch job name: ${n}.`)}function Bt(e){return"BATCH_STATE_UNSPECIFIED"===e?"JOB_STATE_UNSPECIFIED":"BATCH_STATE_PENDING"===e?"JOB_STATE_PENDING":"BATCH_STATE_RUNNING"===e?"JOB_STATE_RUNNING":"BATCH_STATE_SUCCEEDED"===e?"JOB_STATE_SUCCEEDED":"BATCH_STATE_FAILED"===e?"JOB_STATE_FAILED":"BATCH_STATE_CANCELLED"===e?"JOB_STATE_CANCELLED":"BATCH_STATE_EXPIRED"===e?"JOB_STATE_EXPIRED":e}function Jt(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["name"],n);const o=Me(e,["metadata","displayName"]);null!=o&&De(t,["displayName"],o);const i=Me(e,["metadata","state"]);null!=i&&De(t,["state"],Bt(i));const r=Me(e,["metadata","createTime"]);null!=r&&De(t,["createTime"],r);const s=Me(e,["metadata","endTime"]);null!=s&&De(t,["endTime"],s);const l=Me(e,["metadata","updateTime"]);null!=l&&De(t,["updateTime"],l);const a=Me(e,["metadata","model"]);null!=a&&De(t,["model"],a);const u=Me(e,["metadata","output"]);return null!=u&&De(t,["dest"],function(e){const t={},n=Me(e,["responsesFile"]);null!=n&&De(t,["fileName"],n);const o=Me(e,["inlinedResponses","inlinedResponses"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["response"]);null!=n&&De(t,["response"],function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["candidates"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["content"]);null!=n&&De(t,["content"],n);const o=Me(e,["citationMetadata"]);null!=o&&De(t,["citationMetadata"],function(e){const t={},n=Me(e,["citationSources"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["citations"],e)}return t}(o));const i=Me(e,["tokenCount"]);null!=i&&De(t,["tokenCount"],i);const r=Me(e,["finishReason"]);null!=r&&De(t,["finishReason"],r);const s=Me(e,["groundingMetadata"]);null!=s&&De(t,["groundingMetadata"],s);const l=Me(e,["avgLogprobs"]);null!=l&&De(t,["avgLogprobs"],l);const a=Me(e,["index"]);null!=a&&De(t,["index"],a);const u=Me(e,["logprobsResult"]);null!=u&&De(t,["logprobsResult"],u);const c=Me(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["safetyRatings"],e)}const p=Me(e,["urlContextMetadata"]);return null!=p&&De(t,["urlContextMetadata"],p),t}(e))),De(t,["candidates"],e)}const i=Me(e,["modelVersion"]);null!=i&&De(t,["modelVersion"],i);const r=Me(e,["promptFeedback"]);null!=r&&De(t,["promptFeedback"],r);const s=Me(e,["responseId"]);null!=s&&De(t,["responseId"],s);const l=Me(e,["usageMetadata"]);null!=l&&De(t,["usageMetadata"],l);const a=Me(e,["modelStatus"]);return null!=a&&De(t,["modelStatus"],a),t}(n));const o=Me(e,["metadata"]);null!=o&&De(t,["metadata"],o);const i=Me(e,["error"]);return null!=i&&De(t,["error"],i),t}(e))),De(t,["inlinedResponses"],e)}const i=Me(e,["inlinedEmbedContentResponses","inlinedResponses"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["inlinedEmbedContentResponses"],e)}return t}(Vt(u))),t}function Yt(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["name"],n);const o=Me(e,["displayName"]);null!=o&&De(t,["displayName"],o);const i=Me(e,["state"]);null!=i&&De(t,["state"],Bt(i));const r=Me(e,["error"]);null!=r&&De(t,["error"],r);const s=Me(e,["createTime"]);null!=s&&De(t,["createTime"],s);const l=Me(e,["startTime"]);null!=l&&De(t,["startTime"],l);const a=Me(e,["endTime"]);null!=a&&De(t,["endTime"],a);const u=Me(e,["updateTime"]);null!=u&&De(t,["updateTime"],u);const c=Me(e,["model"]);null!=c&&De(t,["model"],c);const p=Me(e,["inputConfig"]);null!=p&&De(t,["src"],function(e){const t={},n=Me(e,["instancesFormat"]);null!=n&&De(t,["format"],n);const o=Me(e,["gcsSource","uris"]);null!=o&&De(t,["gcsUri"],o);const i=Me(e,["bigquerySource","inputUri"]);null!=i&&De(t,["bigqueryUri"],i);const r=Me(e,["vertexMultimodalDatasetSource","datasetName"]);return null!=r&&De(t,["vertexDatasetName"],r),t}(p));const d=Me(e,["outputConfig"]);null!=d&&De(t,["dest"],function(e){const t={},n=Me(e,["predictionsFormat"]);null!=n&&De(t,["format"],n);const o=Me(e,["gcsDestination","outputUriPrefix"]);null!=o&&De(t,["gcsUri"],o);const i=Me(e,["bigqueryDestination","outputUri"]);null!=i&&De(t,["bigqueryUri"],i);const r=Me(e,["vertexMultimodalDatasetDestination"]);return null!=r&&De(t,["vertexDataset"],function(e){const t={},n=Me(e,["bigqueryDestination","outputUri"]);null!=n&&De(t,["bigqueryDestination"],n);const o=Me(e,["displayName"]);return null!=o&&De(t,["displayName"],o),t}(r)),t}(Vt(d)));const h=Me(e,["completionStats"]);null!=h&&De(t,["completionStats"],h);const f=Me(e,["outputInfo"]);return null!=f&&De(t,["outputInfo"],f),t}function $t(e){const t={},n=Me(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["mediaResolution"]);null!=n&&De(t,["mediaResolution"],n);const o=Me(e,["codeExecutionResult"]);null!=o&&De(t,["codeExecutionResult"],o);const i=Me(e,["executableCode"]);null!=i&&De(t,["executableCode"],i);const r=Me(e,["fileData"]);null!=r&&De(t,["fileData"],function(e){const t={};if(void 0!==Me(e,["displayName"]))throw new Error("displayName parameter is not supported in Gemini API.");const n=Me(e,["fileUri"]);null!=n&&De(t,["fileUri"],n);const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}(r));const s=Me(e,["functionCall"]);null!=s&&De(t,["functionCall"],function(e){const t={},n=Me(e,["id"]);null!=n&&De(t,["id"],n);const o=Me(e,["args"]);null!=o&&De(t,["args"],o);const i=Me(e,["name"]);if(null!=i&&De(t,["name"],i),void 0!==Me(e,["partialArgs"]))throw new Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==Me(e,["willContinue"]))throw new Error("willContinue parameter is not supported in Gemini API.");return t}(s));const l=Me(e,["functionResponse"]);null!=l&&De(t,["functionResponse"],l);const a=Me(e,["inlineData"]);null!=a&&De(t,["inlineData"],function(e){const t={},n=Me(e,["data"]);if(null!=n&&De(t,["data"],n),void 0!==Me(e,["displayName"]))throw new Error("displayName parameter is not supported in Gemini API.");const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}(a));const u=Me(e,["text"]);null!=u&&De(t,["text"],u);const c=Me(e,["thought"]);null!=c&&De(t,["thought"],c);const p=Me(e,["thoughtSignature"]);null!=p&&De(t,["thoughtSignature"],p);const d=Me(e,["videoMetadata"]);null!=d&&De(t,["videoMetadata"],d);const h=Me(e,["toolCall"]);null!=h&&De(t,["toolCall"],h);const f=Me(e,["toolResponse"]);null!=f&&De(t,["toolResponse"],f);const m=Me(e,["partMetadata"]);return null!=m&&De(t,["partMetadata"],m),t}(e))),De(t,["parts"],e)}const o=Me(e,["role"]);return null!=o&&De(t,["role"],o),t}function Kt(e,t){const n=Me(e,["displayName"]);void 0!==t&&null!=n&&De(t,["displayName"],n);const o=Me(e,["dest"]);if(void 0!==t&&null!=o&&De(t,["outputConfig"],function(e){const t={},n=Me(e,["format"]);null!=n&&De(t,["predictionsFormat"],n);const o=Me(e,["gcsUri"]);null!=o&&De(t,["gcsDestination","outputUriPrefix"],o);const i=Me(e,["bigqueryUri"]);if(null!=i&&De(t,["bigqueryDestination","outputUri"],i),void 0!==Me(e,["fileName"]))throw new Error("fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==Me(e,["inlinedResponses"]))throw new Error("inlinedResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==Me(e,["inlinedEmbedContentResponses"]))throw new Error("inlinedEmbedContentResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const r=Me(e,["vertexDataset"]);return null!=r&&De(t,["vertexMultimodalDatasetDestination"],function(e){const t={},n=Me(e,["bigqueryDestination"]);null!=n&&De(t,["bigqueryDestination","outputUri"],n);const o=Me(e,["displayName"]);return null!=o&&De(t,["displayName"],o),t}(r)),t}(function(e){if("string"!=typeof e)return e;const t=e;if(t.startsWith("gs://"))return{format:"jsonl",gcsUri:t};if(t.startsWith("bq://"))return{format:"bigquery",bigqueryUri:t};throw new Error(`Unsupported destination: ${t}`)}(o))),void 0!==Me(e,["webhookConfig"]))throw new Error("webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return{}}function Wt(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["src"]);null!=i&&De(n,["batch","inputConfig"],function(e,t){const n={};if(void 0!==Me(t,["format"]))throw new Error("format parameter is not supported in Gemini API.");if(void 0!==Me(t,["gcsUri"]))throw new Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==Me(t,["bigqueryUri"]))throw new Error("bigqueryUri parameter is not supported in Gemini API.");const o=Me(t,["fileName"]);null!=o&&De(n,["fileName"],o);const i=Me(t,["inlinedRequests"]);if(null!=i){let t=i;Array.isArray(t)&&(t=t.map(t=>function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["request","model"],ht(e,o));const i=Me(t,["contents"]);if(null!=i){let e=St(i);Array.isArray(e)&&(e=e.map(e=>$t(e))),De(n,["request","contents"],e)}const r=Me(t,["metadata"]);null!=r&&De(n,["metadata"],r);const s=Me(t,["config"]);return null!=s&&De(n,["request","generationConfig"],function(e,t,n){const o={},i=Me(t,["systemInstruction"]);void 0!==n&&null!=i&&De(n,["systemInstruction"],$t(Ct(i)));const r=Me(t,["temperature"]);null!=r&&De(o,["temperature"],r);const s=Me(t,["topP"]);null!=s&&De(o,["topP"],s);const l=Me(t,["topK"]);null!=l&&De(o,["topK"],l);const a=Me(t,["candidateCount"]);null!=a&&De(o,["candidateCount"],a);const u=Me(t,["maxOutputTokens"]);null!=u&&De(o,["maxOutputTokens"],u);const c=Me(t,["stopSequences"]);null!=c&&De(o,["stopSequences"],c);const p=Me(t,["responseLogprobs"]);null!=p&&De(o,["responseLogprobs"],p);const d=Me(t,["logprobs"]);null!=d&&De(o,["logprobs"],d);const h=Me(t,["presencePenalty"]);null!=h&&De(o,["presencePenalty"],h);const f=Me(t,["frequencyPenalty"]);null!=f&&De(o,["frequencyPenalty"],f);const m=Me(t,["seed"]);null!=m&&De(o,["seed"],m);const g=Me(t,["responseMimeType"]);null!=g&&De(o,["responseMimeType"],g);const E=Me(t,["responseSchema"]);null!=E&&De(o,["responseSchema"],wt(E));const y=Me(t,["responseJsonSchema"]);if(null!=y&&De(o,["responseJsonSchema"],y),void 0!==Me(t,["routingConfig"]))throw new Error("routingConfig parameter is not supported in Gemini API.");if(void 0!==Me(t,["modelSelectionConfig"]))throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");const v=Me(t,["safetySettings"]);if(void 0!==n&&null!=v){let e=v;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["category"]);if(null!=n&&De(t,["category"],n),void 0!==Me(e,["method"]))throw new Error("method parameter is not supported in Gemini API.");const o=Me(e,["threshold"]);return null!=o&&De(t,["threshold"],o),t}(e))),De(n,["safetySettings"],e)}const I=Me(t,["tools"]);if(void 0!==n&&null!=I){let e=Dt(I);Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==Me(e,["retrieval"]))throw new Error("retrieval parameter is not supported in Gemini API.");const n=Me(e,["computerUse"]);null!=n&&De(t,["computerUse"],n);const o=Me(e,["fileSearch"]);null!=o&&De(t,["fileSearch"],o);const i=Me(e,["googleSearch"]);null!=i&&De(t,["googleSearch"],function(e){const t={},n=Me(e,["searchTypes"]);if(null!=n&&De(t,["searchTypes"],n),void 0!==Me(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(void 0!==Me(e,["excludeDomains"]))throw new Error("excludeDomains parameter is not supported in Gemini API.");const o=Me(e,["timeRangeFilter"]);return null!=o&&De(t,["timeRangeFilter"],o),t}(i));const r=Me(e,["googleMaps"]);null!=r&&De(t,["googleMaps"],function(e){const t={},n=Me(e,["authConfig"]);null!=n&&De(t,["authConfig"],function(e){const t={},n=Me(e,["apiKey"]);if(null!=n&&De(t,["apiKey"],n),void 0!==Me(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["authType"]))throw new Error("authType parameter is not supported in Gemini API.");if(void 0!==Me(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["oauthConfig"]))throw new Error("oauthConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["oidcConfig"]))throw new Error("oidcConfig parameter is not supported in Gemini API.");return t}(n));const o=Me(e,["enableWidget"]);return null!=o&&De(t,["enableWidget"],o),t}(r));const s=Me(e,["codeExecution"]);if(null!=s&&De(t,["codeExecution"],s),void 0!==Me(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const l=Me(e,["functionDeclarations"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["functionDeclarations"],e)}const a=Me(e,["googleSearchRetrieval"]);if(null!=a&&De(t,["googleSearchRetrieval"],a),void 0!==Me(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is not supported in Gemini API.");const u=Me(e,["urlContext"]);null!=u&&De(t,["urlContext"],u);const c=Me(e,["mcpServers"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["mcpServers"],e)}return t}(Pt(e)))),De(n,["tools"],e)}const _=Me(t,["toolConfig"]);if(void 0!==n&&null!=_&&De(n,["toolConfig"],function(e){const t={},n=Me(e,["retrievalConfig"]);null!=n&&De(t,["retrievalConfig"],n);const o=Me(e,["functionCallingConfig"]);null!=o&&De(t,["functionCallingConfig"],function(e){const t={},n=Me(e,["allowedFunctionNames"]);null!=n&&De(t,["allowedFunctionNames"],n);const o=Me(e,["mode"]);if(null!=o&&De(t,["mode"],o),void 0!==Me(e,["streamFunctionCallArguments"]))throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(o));const i=Me(e,["includeServerSideToolInvocations"]);return null!=i&&De(t,["includeServerSideToolInvocations"],i),t}(_)),void 0!==Me(t,["labels"]))throw new Error("labels parameter is not supported in Gemini API.");const T=Me(t,["cachedContent"]);void 0!==n&&null!=T&&De(n,["cachedContent"],Mt(e,T));const A=Me(t,["responseModalities"]);null!=A&&De(o,["responseModalities"],A);const C=Me(t,["mediaResolution"]);null!=C&&De(o,["mediaResolution"],C);const O=Me(t,["speechConfig"]);if(null!=O&&De(o,["speechConfig"],Rt(O)),void 0!==Me(t,["audioTimestamp"]))throw new Error("audioTimestamp parameter is not supported in Gemini API.");const S=Me(t,["thinkingConfig"]);null!=S&&De(o,["thinkingConfig"],S);const b=Me(t,["imageConfig"]);null!=b&&De(o,["imageConfig"],function(e){const t={},n=Me(e,["aspectRatio"]);null!=n&&De(t,["aspectRatio"],n);const o=Me(e,["imageSize"]);if(null!=o&&De(t,["imageSize"],o),void 0!==Me(e,["personGeneration"]))throw new Error("personGeneration parameter is not supported in Gemini API.");if(void 0!==Me(e,["prominentPeople"]))throw new Error("prominentPeople parameter is not supported in Gemini API.");if(void 0!==Me(e,["outputMimeType"]))throw new Error("outputMimeType parameter is not supported in Gemini API.");if(void 0!==Me(e,["outputCompressionQuality"]))throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");if(void 0!==Me(e,["imageOutputOptions"]))throw new Error("imageOutputOptions parameter is not supported in Gemini API.");return t}(b));const w=Me(t,["enableEnhancedCivicAnswers"]);if(null!=w&&De(o,["enableEnhancedCivicAnswers"],w),void 0!==Me(t,["modelArmorConfig"]))throw new Error("modelArmorConfig parameter is not supported in Gemini API.");const R=Me(t,["serviceTier"]);return void 0!==n&&null!=R&&De(n,["serviceTier"],R),o}(e,s,Me(n,["request"],{}))),n}(e,t))),De(n,["requests","requests"],t)}if(void 0!==Me(t,["vertexDatasetName"]))throw new Error("vertexDatasetName parameter is not supported in Gemini API.");return n}(e,Ft(e,i)));const r=Me(t,["config"]);return null!=r&&function(e,t){const n=Me(e,["displayName"]);if(void 0!==t&&null!=n&&De(t,["batch","displayName"],n),void 0!==Me(e,["dest"]))throw new Error("dest parameter is not supported in Gemini API.");const o=Me(e,["webhookConfig"]);void 0!==t&&null!=o&&De(t,["batch","webhookConfig"],o)}(r,n),n}!function(e){e.PAGED_ITEM_BATCH_JOBS="batchJobs",e.PAGED_ITEM_MODELS="models",e.PAGED_ITEM_TUNING_JOBS="tuningJobs",e.PAGED_ITEM_FILES="files",e.PAGED_ITEM_CACHED_CONTENTS="cachedContents",e.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",e.PAGED_ITEM_DOCUMENTS="documents"}(Le||(Le={}));var zt=class{constructor(e,t,n,o){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,n,o)}init(e,t,n){var o,i;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=null==t?void 0:t.sdkHttpResponse,this.idxInternal=0;let r={config:{}};r=n&&0!==Object.keys(n).length?"object"==typeof n?Object.assign({},n):n:{config:{}},r.config&&(r.config.pageToken=t.nextPageToken),this.paramsInternal=r,this.pageInternalSize=null!==(i=null===(o=r.config)||void 0===o?void 0:o.pageSize)&&void 0!==i?i:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength){if(!this.hasNextPage())return{value:void 0,done:!0};await this.nextPage()}const e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");const e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return void 0!==(null===(e=this.params.config)||void 0===e?void 0:e.pageToken)}},Xt=class extends Ne{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new zt(Le.PAGED_ITEM_BATCH_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.create=async e=>(this.apiClient.isVertexAI()&&(e.config=this.formatDestination(e.src,e.config)),this.createInternal(e)),this.createEmbeddings=async e=>{if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(e)}}createInlinedGenerateContentRequest(e){const t=Wt(this.apiClient,e),n=Pe("{model}:batchGenerateContent",t._url),o=t.batch.inputConfig.requests,i=o.requests,r=[];for(const s of i){const e=Object.assign({},s);if(e.systemInstruction){const t=e.systemInstruction;delete e.systemInstruction;const n=e.request;n.systemInstruction=t,e.request=n}r.push(e)}return o.requests=r,delete t.config,delete t._url,delete t._query,{path:n,body:t}}getGcsUri(e){return"string"==typeof e?e.startsWith("gs://")?e:void 0:!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0?e.gcsUri[0]:void 0}getBigqueryUri(e){return"string"==typeof e?e.startsWith("bq://")?e:void 0:Array.isArray(e)?void 0:e.bigqueryUri}formatDestination(e,t){const n=t?Object.assign({},t):{},o=Date.now().toString();if(n.displayName||(n.displayName=`genaiBatchJob_${o}`),void 0===n.dest){const t=this.getGcsUri(e),i=this.getBigqueryUri(e);if(t)t.endsWith(".jsonl")?n.dest=`${t.slice(0,-6)}/dest`:n.dest=`${t}_dest_${o}`;else{if(!i)throw new Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.");n.dest=`${i}_dest_${o}`}}return n}async createInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["model"],ht(e,o));const i=Me(t,["src"]);null!=i&&De(n,["inputConfig"],function(e){const t={},n=Me(e,["format"]);null!=n&&De(t,["instancesFormat"],n);const o=Me(e,["gcsUri"]);null!=o&&De(t,["gcsSource","uris"],o);const i=Me(e,["bigqueryUri"]);if(null!=i&&De(t,["bigquerySource","inputUri"],i),void 0!==Me(e,["fileName"]))throw new Error("fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==Me(e,["inlinedRequests"]))throw new Error("inlinedRequests parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const r=Me(e,["vertexDatasetName"]);return null!=r&&De(t,["vertexMultimodalDatasetSource","datasetName"],r),t}(Ft(e,i)));const r=Me(t,["config"]);return null!=r&&Kt(r,n),n}(this.apiClient,e);return s=Pe("batchPredictionJobs",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>Yt(e))}{const t=Wt(this.apiClient,e);return s=Pe("{model}:batchGenerateContent",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Jt(e))}}async createEmbeddingsInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["src"]);null!=i&&De(n,["batch","inputConfig"],function(e,t){const n={},o=Me(t,["fileName"]);null!=o&&De(n,["file_name"],o);const i=Me(t,["inlinedRequests"]);return null!=i&&De(n,["requests"],function(e,t){const n={},o=Me(t,["contents"]);if(null!=o){let t=Ot(e,o);Array.isArray(t)&&(t=t.map(e=>e)),De(n,["requests[]","request","content"],t)}const i=Me(t,["config"]);return null!=i&&(De(n,["_self"],function(e,t){const n=Me(e,["taskType"]);void 0!==t&&null!=n&&De(t,["requests[]","taskType"],n);const o=Me(e,["title"]);void 0!==t&&null!=o&&De(t,["requests[]","title"],o);const i=Me(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&De(t,["requests[]","outputDimensionality"],i),void 0!==Me(e,["mimeType"]))throw new Error("mimeType parameter is not supported in Gemini API.");if(void 0!==Me(e,["autoTruncate"]))throw new Error("autoTruncate parameter is not supported in Gemini API.");if(void 0!==Me(e,["documentOcr"]))throw new Error("documentOcr parameter is not supported in Gemini API.");if(void 0!==Me(e,["audioTrackExtraction"]))throw new Error("audioTrackExtraction parameter is not supported in Gemini API.");return{}}(i,n)),function(e){for(const[t,n]of Object.entries({"requests[].*":"requests[].request.*"})){const o=t.split("."),i=n.split("."),r=/* @__PURE__ */new Set;let s=-1;for(let e=0;e<o.length;e++)if("*"===o[e]){s=e;break}if(-1!==s&&i.length>s)for(let e=s;e<i.length;e++){const t=i[e];"*"===t||t.endsWith("[]")||t.endsWith("[0]")||r.add(t)}Ue(e,o,i,0,r)}}(n)),n}(e,i)),n}(e,i));const r=Me(t,["config"]);return null!=r&&function(e,t){const n=Me(e,["displayName"]);void 0!==t&&null!=n&&De(t,["batch","displayName"],n)}(r,n),n}(this.apiClient,e);return i=Pe("{model}:asyncBatchEmbedContent",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>Jt(e))}}async get(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["name"]);return null!=o&&De(n,["_url","name"],jt(e,o)),n}(this.apiClient,e);return s=Pe("batchPredictionJobs/{name}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>Yt(e))}{const t=function(e,t){const n={},o=Me(t,["name"]);return null!=o&&De(n,["_url","name"],jt(e,o)),n}(this.apiClient,e);return s=Pe("batches/{name}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Jt(e))}}async cancel(e){var t,n,o,i;let r="",s={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["name"]);return null!=o&&De(n,["_url","name"],jt(e,o)),n}(this.apiClient,e);r=Pe("batchPredictionJobs/{name}:cancel",o._url),s=o._query,delete o._url,delete o._query,await this.apiClient.request({path:r,queryParams:s,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal})}else{const t=function(e,t){const n={},o=Me(t,["name"]);return null!=o&&De(n,["_url","name"],jt(e,o)),n}(this.apiClient,e);r=Pe("batches/{name}:cancel",t._url),s=t._query,delete t._url,delete t._query,await this.apiClient.request({path:r,queryParams:s,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal})}}async listInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=Me(e,["config"]);return null!=n&&function(e,t){const n=Me(e,["pageSize"]);void 0!==t&&null!=n&&De(t,["_query","pageSize"],n);const o=Me(e,["pageToken"]);void 0!==t&&null!=o&&De(t,["_query","pageToken"],o);const i=Me(e,["filter"]);void 0!==t&&null!=i&&De(t,["_query","filter"],i)}(n,t),t}(e);return s=Pe("batchPredictionJobs",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["nextPageToken"]);null!=o&&De(t,["nextPageToken"],o);const i=Me(e,["batchPredictionJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>Yt(e))),De(t,["batchJobs"],e)}return t}(e),n=new ut;return Object.assign(n,t),n})}{const t=function(e){const t={},n=Me(e,["config"]);return null!=n&&function(e,t){const n=Me(e,["pageSize"]);void 0!==t&&null!=n&&De(t,["_query","pageSize"],n);const o=Me(e,["pageToken"]);if(void 0!==t&&null!=o&&De(t,["_query","pageToken"],o),void 0!==Me(e,["filter"]))throw new Error("filter parameter is not supported in Gemini API.")}(n,t),t}(e);return s=Pe("batches",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["nextPageToken"]);null!=o&&De(t,["nextPageToken"],o);const i=Me(e,["operations"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>Jt(e))),De(t,["batchJobs"],e)}return t}(e),n=new ut;return Object.assign(n,t),n})}}async delete(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["name"]);return null!=o&&De(n,["_url","name"],jt(e,o)),n}(this.apiClient,e);return s=Pe("batchPredictionJobs/{name}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["name"]);null!=o&&De(t,["name"],o);const i=Me(e,["done"]);null!=i&&De(t,["done"],i);const r=Me(e,["error"]);return null!=r&&De(t,["error"],r),t}(e))}{const t=function(e,t){const n={},o=Me(t,["name"]);return null!=o&&De(n,["_url","name"],jt(e,o)),n}(this.apiClient,e);return s=Pe("batches/{name}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"DELETE",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["name"]);null!=o&&De(t,["name"],o);const i=Me(e,["done"]);null!=i&&De(t,["done"],i);const r=Me(e,["error"]);return null!=r&&De(t,["error"],r),t}(e))}}};function Qt(e){const t={},n=Me(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["mediaResolution"]);null!=n&&De(t,["mediaResolution"],n);const o=Me(e,["codeExecutionResult"]);null!=o&&De(t,["codeExecutionResult"],o);const i=Me(e,["executableCode"]);null!=i&&De(t,["executableCode"],i);const r=Me(e,["fileData"]);null!=r&&De(t,["fileData"],function(e){const t={};if(void 0!==Me(e,["displayName"]))throw new Error("displayName parameter is not supported in Gemini API.");const n=Me(e,["fileUri"]);null!=n&&De(t,["fileUri"],n);const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}(r));const s=Me(e,["functionCall"]);null!=s&&De(t,["functionCall"],function(e){const t={},n=Me(e,["id"]);null!=n&&De(t,["id"],n);const o=Me(e,["args"]);null!=o&&De(t,["args"],o);const i=Me(e,["name"]);if(null!=i&&De(t,["name"],i),void 0!==Me(e,["partialArgs"]))throw new Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==Me(e,["willContinue"]))throw new Error("willContinue parameter is not supported in Gemini API.");return t}(s));const l=Me(e,["functionResponse"]);null!=l&&De(t,["functionResponse"],l);const a=Me(e,["inlineData"]);null!=a&&De(t,["inlineData"],function(e){const t={},n=Me(e,["data"]);if(null!=n&&De(t,["data"],n),void 0!==Me(e,["displayName"]))throw new Error("displayName parameter is not supported in Gemini API.");const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}(a));const u=Me(e,["text"]);null!=u&&De(t,["text"],u);const c=Me(e,["thought"]);null!=c&&De(t,["thought"],c);const p=Me(e,["thoughtSignature"]);null!=p&&De(t,["thoughtSignature"],p);const d=Me(e,["videoMetadata"]);null!=d&&De(t,["videoMetadata"],d);const h=Me(e,["toolCall"]);null!=h&&De(t,["toolCall"],h);const f=Me(e,["toolResponse"]);null!=f&&De(t,["toolResponse"],f);const m=Me(e,["partMetadata"]);return null!=m&&De(t,["partMetadata"],m),t}(e))),De(t,["parts"],e)}const o=Me(e,["role"]);return null!=o&&De(t,["role"],o),t}function Zt(e){const t={},n=Me(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["mediaResolution"]);null!=n&&De(t,["mediaResolution"],n);const o=Me(e,["codeExecutionResult"]);null!=o&&De(t,["codeExecutionResult"],o);const i=Me(e,["executableCode"]);null!=i&&De(t,["executableCode"],i);const r=Me(e,["fileData"]);null!=r&&De(t,["fileData"],r);const s=Me(e,["functionCall"]);null!=s&&De(t,["functionCall"],s);const l=Me(e,["functionResponse"]);null!=l&&De(t,["functionResponse"],l);const a=Me(e,["inlineData"]);null!=a&&De(t,["inlineData"],a);const u=Me(e,["text"]);null!=u&&De(t,["text"],u);const c=Me(e,["thought"]);null!=c&&De(t,["thought"],c);const p=Me(e,["thoughtSignature"]);null!=p&&De(t,["thoughtSignature"],p);const d=Me(e,["videoMetadata"]);if(null!=d&&De(t,["videoMetadata"],d),void 0!==Me(e,["toolCall"]))throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==Me(e,["toolResponse"]))throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==Me(e,["partMetadata"]))throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(e))),De(t,["parts"],e)}const o=Me(e,["role"]);return null!=o&&De(t,["role"],o),t}var en=class extends Ne{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new zt(Le.PAGED_ITEM_CACHED_CONTENTS,e=>this.listInternal(e),await this.listInternal(e),e)}async create(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["model"],ft(e,o));const i=Me(t,["config"]);return null!=i&&function(e,t){const n=Me(e,["ttl"]);void 0!==t&&null!=n&&De(t,["ttl"],n);const o=Me(e,["expireTime"]);void 0!==t&&null!=o&&De(t,["expireTime"],o);const i=Me(e,["displayName"]);void 0!==t&&null!=i&&De(t,["displayName"],i);const r=Me(e,["contents"]);if(void 0!==t&&null!=r){let e=St(r);Array.isArray(e)&&(e=e.map(e=>Zt(e))),De(t,["contents"],e)}const s=Me(e,["systemInstruction"]);void 0!==t&&null!=s&&De(t,["systemInstruction"],Zt(Ct(s)));const l=Me(e,["tools"]);if(void 0!==t&&null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["retrieval"]);null!=n&&De(t,["retrieval"],n);const o=Me(e,["computerUse"]);if(null!=o&&De(t,["computerUse"],o),void 0!==Me(e,["fileSearch"]))throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const i=Me(e,["googleSearch"]);null!=i&&De(t,["googleSearch"],i);const r=Me(e,["googleMaps"]);null!=r&&De(t,["googleMaps"],r);const s=Me(e,["codeExecution"]);null!=s&&De(t,["codeExecution"],s);const l=Me(e,["enterpriseWebSearch"]);null!=l&&De(t,["enterpriseWebSearch"],l);const a=Me(e,["functionDeclarations"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["description"]);null!=n&&De(t,["description"],n);const o=Me(e,["name"]);null!=o&&De(t,["name"],o);const i=Me(e,["parameters"]);null!=i&&De(t,["parameters"],i);const r=Me(e,["parametersJsonSchema"]);null!=r&&De(t,["parametersJsonSchema"],r);const s=Me(e,["response"]);null!=s&&De(t,["response"],s);const l=Me(e,["responseJsonSchema"]);if(null!=l&&De(t,["responseJsonSchema"],l),void 0!==Me(e,["behavior"]))throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(e))),De(t,["functionDeclarations"],e)}const u=Me(e,["googleSearchRetrieval"]);null!=u&&De(t,["googleSearchRetrieval"],u);const c=Me(e,["parallelAiSearch"]);null!=c&&De(t,["parallelAiSearch"],c);const p=Me(e,["urlContext"]);if(null!=p&&De(t,["urlContext"],p),void 0!==Me(e,["mcpServers"]))throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(e))),De(t,["tools"],e)}const a=Me(e,["toolConfig"]);void 0!==t&&null!=a&&De(t,["toolConfig"],function(e){const t={},n=Me(e,["retrievalConfig"]);null!=n&&De(t,["retrievalConfig"],n);const o=Me(e,["functionCallingConfig"]);if(null!=o&&De(t,["functionCallingConfig"],o),void 0!==Me(e,["includeServerSideToolInvocations"]))throw new Error("includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(a));const u=Me(e,["kmsKeyName"]);void 0!==t&&null!=u&&De(t,["encryption_spec","kmsKeyName"],u)}(i,n),n}(this.apiClient,e);return s=Pe("cachedContents",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>e)}{const t=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["model"],ft(e,o));const i=Me(t,["config"]);return null!=i&&function(e,t){const n=Me(e,["ttl"]);void 0!==t&&null!=n&&De(t,["ttl"],n);const o=Me(e,["expireTime"]);void 0!==t&&null!=o&&De(t,["expireTime"],o);const i=Me(e,["displayName"]);void 0!==t&&null!=i&&De(t,["displayName"],i);const r=Me(e,["contents"]);if(void 0!==t&&null!=r){let e=St(r);Array.isArray(e)&&(e=e.map(e=>Qt(e))),De(t,["contents"],e)}const s=Me(e,["systemInstruction"]);void 0!==t&&null!=s&&De(t,["systemInstruction"],Qt(Ct(s)));const l=Me(e,["tools"]);if(void 0!==t&&null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==Me(e,["retrieval"]))throw new Error("retrieval parameter is not supported in Gemini API.");const n=Me(e,["computerUse"]);null!=n&&De(t,["computerUse"],n);const o=Me(e,["fileSearch"]);null!=o&&De(t,["fileSearch"],o);const i=Me(e,["googleSearch"]);null!=i&&De(t,["googleSearch"],function(e){const t={},n=Me(e,["searchTypes"]);if(null!=n&&De(t,["searchTypes"],n),void 0!==Me(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(void 0!==Me(e,["excludeDomains"]))throw new Error("excludeDomains parameter is not supported in Gemini API.");const o=Me(e,["timeRangeFilter"]);return null!=o&&De(t,["timeRangeFilter"],o),t}(i));const r=Me(e,["googleMaps"]);null!=r&&De(t,["googleMaps"],function(e){const t={},n=Me(e,["authConfig"]);null!=n&&De(t,["authConfig"],function(e){const t={},n=Me(e,["apiKey"]);if(null!=n&&De(t,["apiKey"],n),void 0!==Me(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["authType"]))throw new Error("authType parameter is not supported in Gemini API.");if(void 0!==Me(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["oauthConfig"]))throw new Error("oauthConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["oidcConfig"]))throw new Error("oidcConfig parameter is not supported in Gemini API.");return t}(n));const o=Me(e,["enableWidget"]);return null!=o&&De(t,["enableWidget"],o),t}(r));const s=Me(e,["codeExecution"]);if(null!=s&&De(t,["codeExecution"],s),void 0!==Me(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const l=Me(e,["functionDeclarations"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["functionDeclarations"],e)}const a=Me(e,["googleSearchRetrieval"]);if(null!=a&&De(t,["googleSearchRetrieval"],a),void 0!==Me(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is not supported in Gemini API.");const u=Me(e,["urlContext"]);null!=u&&De(t,["urlContext"],u);const c=Me(e,["mcpServers"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["mcpServers"],e)}return t}(e))),De(t,["tools"],e)}const a=Me(e,["toolConfig"]);if(void 0!==t&&null!=a&&De(t,["toolConfig"],function(e){const t={},n=Me(e,["retrievalConfig"]);null!=n&&De(t,["retrievalConfig"],n);const o=Me(e,["functionCallingConfig"]);null!=o&&De(t,["functionCallingConfig"],function(e){const t={},n=Me(e,["allowedFunctionNames"]);null!=n&&De(t,["allowedFunctionNames"],n);const o=Me(e,["mode"]);if(null!=o&&De(t,["mode"],o),void 0!==Me(e,["streamFunctionCallArguments"]))throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(o));const i=Me(e,["includeServerSideToolInvocations"]);return null!=i&&De(t,["includeServerSideToolInvocations"],i),t}(a)),void 0!==Me(e,["kmsKeyName"]))throw new Error("kmsKeyName parameter is not supported in Gemini API.")}(i,n),n}(this.apiClient,e);return s=Pe("cachedContents",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>e)}}async get(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["name"]);return null!=o&&De(n,["_url","name"],Mt(e,o)),n}(this.apiClient,e);return s=Pe("{name}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>e)}{const t=function(e,t){const n={},o=Me(t,["name"]);return null!=o&&De(n,["_url","name"],Mt(e,o)),n}(this.apiClient,e);return s=Pe("{name}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>e)}}async delete(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["name"]);return null!=o&&De(n,["_url","name"],Mt(e,o)),n}(this.apiClient,e);return s=Pe("{name}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);return null!=n&&De(t,["sdkHttpResponse"],n),t}(e),n=new Ze;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=Me(t,["name"]);return null!=o&&De(n,["_url","name"],Mt(e,o)),n}(this.apiClient,e);return s=Pe("{name}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"DELETE",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);return null!=n&&De(t,["sdkHttpResponse"],n),t}(e),n=new Ze;return Object.assign(n,t),n})}}async update(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["name"]);null!=o&&De(n,["_url","name"],Mt(e,o));const i=Me(t,["config"]);return null!=i&&function(e,t){const n=Me(e,["ttl"]);void 0!==t&&null!=n&&De(t,["ttl"],n);const o=Me(e,["expireTime"]);void 0!==t&&null!=o&&De(t,["expireTime"],o)}(i,n),n}(this.apiClient,e);return s=Pe("{name}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"PATCH",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>e)}{const t=function(e,t){const n={},o=Me(t,["name"]);null!=o&&De(n,["_url","name"],Mt(e,o));const i=Me(t,["config"]);return null!=i&&function(e,t){const n=Me(e,["ttl"]);void 0!==t&&null!=n&&De(t,["ttl"],n);const o=Me(e,["expireTime"]);void 0!==t&&null!=o&&De(t,["expireTime"],o)}(i,n),n}(this.apiClient,e);return s=Pe("{name}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"PATCH",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>e)}}async listInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=Me(e,["config"]);return null!=n&&function(e,t){const n=Me(e,["pageSize"]);void 0!==t&&null!=n&&De(t,["_query","pageSize"],n);const o=Me(e,["pageToken"]);void 0!==t&&null!=o&&De(t,["_query","pageToken"],o)}(n,t),t}(e);return s=Pe("cachedContents",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["nextPageToken"]);null!=o&&De(t,["nextPageToken"],o);const i=Me(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["cachedContents"],e)}return t}(e),n=new et;return Object.assign(n,t),n})}{const t=function(e){const t={},n=Me(e,["config"]);return null!=n&&function(e,t){const n=Me(e,["pageSize"]);void 0!==t&&null!=n&&De(t,["_query","pageSize"],n);const o=Me(e,["pageToken"]);void 0!==t&&null!=o&&De(t,["_query","pageToken"],o)}(n,t),t}(e);return s=Pe("cachedContents",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["nextPageToken"]);null!=o&&De(t,["nextPageToken"],o);const i=Me(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["cachedContents"],e)}return t}(e),n=new et;return Object.assign(n,t),n})}}};function tn(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(n[o[i]]=e[o[i]])}return n}function nn(e){return this instanceof nn?(this.v=e,this):new nn(e)}function on(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o,i=n.apply(e,t||[]),r=[];return o=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),o[Symbol.asyncIterator]=function(){return this},o;function s(e,t){i[e]&&(o[e]=function(t){return new Promise(function(n,o){r.push([e,t,n,o])>1||l(e,t)})},t&&(o[e]=t(o[e])))}function l(e,t){try{(n=i[e](t)).value instanceof nn?Promise.resolve(n.value.v).then(a,u):c(r[0][2],n)}catch(o){c(r[0][3],o)}var n}function a(e){l("next",e)}function u(e){l("throw",e)}function c(e,t){e(t),r.shift(),r.length&&l(r[0][0],r[0][1])}}function rn(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],o=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&o>=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},o("next"),o("throw"),o("return"),t[Symbol.asyncIterator]=function(){return this},t);function o(n){t[n]=e[n]&&function(t){return new Promise(function(o,i){!function(e,t,n,o){Promise.resolve(o).then(function(t){e({value:t,done:n})},t)}(o,i,(t=e[n](t)).done,t.value)})}}}function sn(e){var t;if(null==e.candidates||0===e.candidates.length)return!1;const n=null===(t=e.candidates[0])||void 0===t?void 0:t.content;return void 0!==n&&ln(n)}function ln(e){if(void 0===e.parts||0===e.parts.length)return!1;for(const t of e.parts)if(void 0===t||0===Object.keys(t).length)return!1;return!0}function an(e){if(void 0===e||0===e.length)return[];const t=[],n=e.length;let o=0;for(;o<n;)if("user"===e[o].role)t.push(e[o]),o++;else{const i=[];let r=!0;for(;o<n&&"model"===e[o].role;)i.push(e[o]),r&&!ln(e[o])&&(r=!1),o++;r?t.push(...i):t.pop()}return t}var un=class{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new cn(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},cn=class{constructor(e,t,n,o={},i=[]){this.apiClient=e,this.modelsModule=t,this.model=n,this.config=o,this.history=i,this.sendPromise=Promise.resolve(),function(e){if(0!==e.length)for(const t of e)if("user"!==t.role&&"model"!==t.role)throw new Error(`Role must be user or model, but got ${t.role}.`)}(i)}async sendMessage(e){var t;await this.sendPromise;const n=Ct(e.message),o=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(n),config:null!==(t=e.config)&&void 0!==t?t:this.config});return this.sendPromise=(async()=>{var e,t,i;const r=await o,s=null===(t=null===(e=r.candidates)||void 0===e?void 0:e[0])||void 0===t?void 0:t.content,l=r.automaticFunctionCallingHistory,a=this.getHistory(!0).length;let u=[];null!=l&&(u=null!==(i=l.slice(a))&&void 0!==i?i:[]);const c=s?[s]:[];this.recordHistory(n,c,u)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),o}async sendMessageStream(e){var t;await this.sendPromise;const n=Ct(e.message),o=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(n),config:null!==(t=e.config)&&void 0!==t?t:this.config});this.sendPromise=o.then(()=>{}).catch(()=>{});const i=await o;return this.processStreamResponse(i,n)}getHistory(e=!1){const t=e?an(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return on(this,arguments,function*(){var n,o,i,r,s,l;const a=[];try{for(var u,c=!0,p=rn(e);!(n=(u=yield nn(p.next())).done);c=!0){r=u.value,c=!1;const e=r;if(sn(e)){const t=null===(l=null===(s=e.candidates)||void 0===s?void 0:s[0])||void 0===l?void 0:l.content;void 0!==t&&a.push(t)}yield yield nn(e)}}catch(d){o={error:d}}finally{try{c||n||!(i=p.return)||(yield nn(i.call(p)))}finally{if(o)throw o.error}}this.recordHistory(t,a)})}recordHistory(e,t,n){let o=[];t.length>0&&t.every(e=>void 0!==e.role)?o=t:o.push({role:"model",parts:[]}),n&&n.length>0?this.history.push(...an(n)):this.history.push(e),this.history.push(...o)}},pn=class e extends Error{constructor(t){super(t.message),this.name="ApiError",this.status=t.status,Object.setPrototypeOf(this,e.prototype)}};var dn=class extends Ne{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new zt(Le.PAGED_ITEM_FILES,e=>this.listInternal(e),await this.listInternal(e),e)}async upload(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(e=>e)}async download(e){await this.apiClient.downloadFile(e)}async registerFiles(e){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["config"]);return null!=n&&function(e,t){const n=Me(e,["pageSize"]);void 0!==t&&null!=n&&De(t,["_query","pageSize"],n);const o=Me(e,["pageToken"]);void 0!==t&&null!=o&&De(t,["_query","pageToken"],o)}(n,t),t}(e);return i=Pe("files",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["nextPageToken"]);null!=o&&De(t,["nextPageToken"],o);const i=Me(e,["files"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["files"],e)}return t}(e),n=new rt;return Object.assign(n,t),n})}}async createInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["file"]);return null!=n&&De(t,["file"],n),t}(e);return i=Pe("upload/v1beta/files",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);return null!=n&&De(t,["sdkHttpResponse"],n),t}(e),n=new st;return Object.assign(n,t),n})}}async get(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["name"]);return null!=n&&De(t,["_url","file"],xt(n)),t}(e);return i=Pe("files/{file}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async delete(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["name"]);return null!=n&&De(t,["_url","file"],xt(n)),t}(e);return i=Pe("files/{file}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);return null!=n&&De(t,["sdkHttpResponse"],n),t}(e),n=new lt;return Object.assign(n,t),n})}}async registerFilesInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["uris"]);return null!=n&&De(t,["uris"],n),t}(e);return i=Pe("files:register",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["files"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["files"],e)}return t}(e),n=new at;return Object.assign(n,t),n})}}};function hn(e){if(void 0!==Me(e,["languageCodes"]))throw new Error("languageCodes parameter is not supported in Gemini API.");return{}}function fn(e){const t={},n=Me(e,["data"]);if(null!=n&&De(t,["data"],n),void 0!==Me(e,["displayName"]))throw new Error("displayName parameter is not supported in Gemini API.");const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}function mn(e,t){const n=Me(e,["generationConfig"]);void 0!==t&&null!=n&&De(t,["setup","generationConfig"],n);const o=Me(e,["responseModalities"]);void 0!==t&&null!=o&&De(t,["setup","generationConfig","responseModalities"],o);const i=Me(e,["temperature"]);void 0!==t&&null!=i&&De(t,["setup","generationConfig","temperature"],i);const r=Me(e,["topP"]);void 0!==t&&null!=r&&De(t,["setup","generationConfig","topP"],r);const s=Me(e,["topK"]);void 0!==t&&null!=s&&De(t,["setup","generationConfig","topK"],s);const l=Me(e,["maxOutputTokens"]);void 0!==t&&null!=l&&De(t,["setup","generationConfig","maxOutputTokens"],l);const a=Me(e,["mediaResolution"]);void 0!==t&&null!=a&&De(t,["setup","generationConfig","mediaResolution"],a);const u=Me(e,["seed"]);void 0!==t&&null!=u&&De(t,["setup","generationConfig","seed"],u);const c=Me(e,["speechConfig"]);void 0!==t&&null!=c&&De(t,["setup","generationConfig","speechConfig"],Nt(c));const p=Me(e,["thinkingConfig"]);void 0!==t&&null!=p&&De(t,["setup","generationConfig","thinkingConfig"],p);const d=Me(e,["enableAffectiveDialog"]);void 0!==t&&null!=d&&De(t,["setup","generationConfig","enableAffectiveDialog"],d);const h=Me(e,["systemInstruction"]);void 0!==t&&null!=h&&De(t,["setup","systemInstruction"],function(e){const t={},n=Me(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["mediaResolution"]);null!=n&&De(t,["mediaResolution"],n);const o=Me(e,["codeExecutionResult"]);null!=o&&De(t,["codeExecutionResult"],o);const i=Me(e,["executableCode"]);null!=i&&De(t,["executableCode"],i);const r=Me(e,["fileData"]);null!=r&&De(t,["fileData"],function(e){const t={};if(void 0!==Me(e,["displayName"]))throw new Error("displayName parameter is not supported in Gemini API.");const n=Me(e,["fileUri"]);null!=n&&De(t,["fileUri"],n);const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}(r));const s=Me(e,["functionCall"]);null!=s&&De(t,["functionCall"],function(e){const t={},n=Me(e,["id"]);null!=n&&De(t,["id"],n);const o=Me(e,["args"]);null!=o&&De(t,["args"],o);const i=Me(e,["name"]);if(null!=i&&De(t,["name"],i),void 0!==Me(e,["partialArgs"]))throw new Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==Me(e,["willContinue"]))throw new Error("willContinue parameter is not supported in Gemini API.");return t}(s));const l=Me(e,["functionResponse"]);null!=l&&De(t,["functionResponse"],l);const a=Me(e,["inlineData"]);null!=a&&De(t,["inlineData"],fn(a));const u=Me(e,["text"]);null!=u&&De(t,["text"],u);const c=Me(e,["thought"]);null!=c&&De(t,["thought"],c);const p=Me(e,["thoughtSignature"]);null!=p&&De(t,["thoughtSignature"],p);const d=Me(e,["videoMetadata"]);null!=d&&De(t,["videoMetadata"],d);const h=Me(e,["toolCall"]);null!=h&&De(t,["toolCall"],h);const f=Me(e,["toolResponse"]);null!=f&&De(t,["toolResponse"],f);const m=Me(e,["partMetadata"]);return null!=m&&De(t,["partMetadata"],m),t}(e))),De(t,["parts"],e)}const o=Me(e,["role"]);return null!=o&&De(t,["role"],o),t}(Ct(h)));const f=Me(e,["tools"]);if(void 0!==t&&null!=f){let e=Dt(f);Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==Me(e,["retrieval"]))throw new Error("retrieval parameter is not supported in Gemini API.");const n=Me(e,["computerUse"]);null!=n&&De(t,["computerUse"],n);const o=Me(e,["fileSearch"]);null!=o&&De(t,["fileSearch"],o);const i=Me(e,["googleSearch"]);null!=i&&De(t,["googleSearch"],function(e){const t={},n=Me(e,["searchTypes"]);if(null!=n&&De(t,["searchTypes"],n),void 0!==Me(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(void 0!==Me(e,["excludeDomains"]))throw new Error("excludeDomains parameter is not supported in Gemini API.");const o=Me(e,["timeRangeFilter"]);return null!=o&&De(t,["timeRangeFilter"],o),t}(i));const r=Me(e,["googleMaps"]);null!=r&&De(t,["googleMaps"],function(e){const t={},n=Me(e,["authConfig"]);null!=n&&De(t,["authConfig"],function(e){const t={},n=Me(e,["apiKey"]);if(null!=n&&De(t,["apiKey"],n),void 0!==Me(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["authType"]))throw new Error("authType parameter is not supported in Gemini API.");if(void 0!==Me(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["oauthConfig"]))throw new Error("oauthConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["oidcConfig"]))throw new Error("oidcConfig parameter is not supported in Gemini API.");return t}(n));const o=Me(e,["enableWidget"]);return null!=o&&De(t,["enableWidget"],o),t}(r));const s=Me(e,["codeExecution"]);if(null!=s&&De(t,["codeExecution"],s),void 0!==Me(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const l=Me(e,["functionDeclarations"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["functionDeclarations"],e)}const a=Me(e,["googleSearchRetrieval"]);if(null!=a&&De(t,["googleSearchRetrieval"],a),void 0!==Me(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is not supported in Gemini API.");const u=Me(e,["urlContext"]);null!=u&&De(t,["urlContext"],u);const c=Me(e,["mcpServers"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["mcpServers"],e)}return t}(Pt(e)))),De(t,["setup","tools"],e)}const m=Me(e,["sessionResumption"]);void 0!==t&&null!=m&&De(t,["setup","sessionResumption"],function(e){const t={},n=Me(e,["handle"]);if(null!=n&&De(t,["handle"],n),void 0!==Me(e,["transparent"]))throw new Error("transparent parameter is not supported in Gemini API.");return t}(m));const g=Me(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&De(t,["setup","inputAudioTranscription"],hn(g));const E=Me(e,["outputAudioTranscription"]);void 0!==t&&null!=E&&De(t,["setup","outputAudioTranscription"],hn(E));const y=Me(e,["realtimeInputConfig"]);void 0!==t&&null!=y&&De(t,["setup","realtimeInputConfig"],y);const v=Me(e,["contextWindowCompression"]);void 0!==t&&null!=v&&De(t,["setup","contextWindowCompression"],v);const I=Me(e,["proactivity"]);if(void 0!==t&&null!=I&&De(t,["setup","proactivity"],I),void 0!==Me(e,["explicitVadSignal"]))throw new Error("explicitVadSignal parameter is not supported in Gemini API.");const _=Me(e,["avatarConfig"]);void 0!==t&&null!=_&&De(t,["setup","avatarConfig"],_);const T=Me(e,["safetySettings"]);if(void 0!==t&&null!=T){let e=T;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["category"]);if(null!=n&&De(t,["category"],n),void 0!==Me(e,["method"]))throw new Error("method parameter is not supported in Gemini API.");const o=Me(e,["threshold"]);return null!=o&&De(t,["threshold"],o),t}(e))),De(t,["setup","safetySettings"],e)}return{}}function gn(e,t){const n=Me(e,["generationConfig"]);void 0!==t&&null!=n&&De(t,["setup","generationConfig"],function(e){const t={},n=Me(e,["modelSelectionConfig"]);null!=n&&De(t,["modelConfig"],n);const o=Me(e,["responseJsonSchema"]);null!=o&&De(t,["responseJsonSchema"],o);const i=Me(e,["audioTimestamp"]);null!=i&&De(t,["audioTimestamp"],i);const r=Me(e,["candidateCount"]);null!=r&&De(t,["candidateCount"],r);const s=Me(e,["enableAffectiveDialog"]);null!=s&&De(t,["enableAffectiveDialog"],s);const l=Me(e,["frequencyPenalty"]);null!=l&&De(t,["frequencyPenalty"],l);const a=Me(e,["logprobs"]);null!=a&&De(t,["logprobs"],a);const u=Me(e,["maxOutputTokens"]);null!=u&&De(t,["maxOutputTokens"],u);const c=Me(e,["mediaResolution"]);null!=c&&De(t,["mediaResolution"],c);const p=Me(e,["presencePenalty"]);null!=p&&De(t,["presencePenalty"],p);const d=Me(e,["responseLogprobs"]);null!=d&&De(t,["responseLogprobs"],d);const h=Me(e,["responseMimeType"]);null!=h&&De(t,["responseMimeType"],h);const f=Me(e,["responseModalities"]);null!=f&&De(t,["responseModalities"],f);const m=Me(e,["responseSchema"]);null!=m&&De(t,["responseSchema"],m);const g=Me(e,["routingConfig"]);null!=g&&De(t,["routingConfig"],g);const E=Me(e,["seed"]);null!=E&&De(t,["seed"],E);const y=Me(e,["speechConfig"]);null!=y&&De(t,["speechConfig"],y);const v=Me(e,["stopSequences"]);null!=v&&De(t,["stopSequences"],v);const I=Me(e,["temperature"]);null!=I&&De(t,["temperature"],I);const _=Me(e,["thinkingConfig"]);null!=_&&De(t,["thinkingConfig"],_);const T=Me(e,["topK"]);null!=T&&De(t,["topK"],T);const A=Me(e,["topP"]);if(null!=A&&De(t,["topP"],A),void 0!==Me(e,["enableEnhancedCivicAnswers"]))throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(n));const o=Me(e,["responseModalities"]);void 0!==t&&null!=o&&De(t,["setup","generationConfig","responseModalities"],o);const i=Me(e,["temperature"]);void 0!==t&&null!=i&&De(t,["setup","generationConfig","temperature"],i);const r=Me(e,["topP"]);void 0!==t&&null!=r&&De(t,["setup","generationConfig","topP"],r);const s=Me(e,["topK"]);void 0!==t&&null!=s&&De(t,["setup","generationConfig","topK"],s);const l=Me(e,["maxOutputTokens"]);void 0!==t&&null!=l&&De(t,["setup","generationConfig","maxOutputTokens"],l);const a=Me(e,["mediaResolution"]);void 0!==t&&null!=a&&De(t,["setup","generationConfig","mediaResolution"],a);const u=Me(e,["seed"]);void 0!==t&&null!=u&&De(t,["setup","generationConfig","seed"],u);const c=Me(e,["speechConfig"]);void 0!==t&&null!=c&&De(t,["setup","generationConfig","speechConfig"],Nt(c));const p=Me(e,["thinkingConfig"]);void 0!==t&&null!=p&&De(t,["setup","generationConfig","thinkingConfig"],p);const d=Me(e,["enableAffectiveDialog"]);void 0!==t&&null!=d&&De(t,["setup","generationConfig","enableAffectiveDialog"],d);const h=Me(e,["systemInstruction"]);void 0!==t&&null!=h&&De(t,["setup","systemInstruction"],function(e){const t={},n=Me(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["mediaResolution"]);null!=n&&De(t,["mediaResolution"],n);const o=Me(e,["codeExecutionResult"]);null!=o&&De(t,["codeExecutionResult"],o);const i=Me(e,["executableCode"]);null!=i&&De(t,["executableCode"],i);const r=Me(e,["fileData"]);null!=r&&De(t,["fileData"],r);const s=Me(e,["functionCall"]);null!=s&&De(t,["functionCall"],s);const l=Me(e,["functionResponse"]);null!=l&&De(t,["functionResponse"],l);const a=Me(e,["inlineData"]);null!=a&&De(t,["inlineData"],a);const u=Me(e,["text"]);null!=u&&De(t,["text"],u);const c=Me(e,["thought"]);null!=c&&De(t,["thought"],c);const p=Me(e,["thoughtSignature"]);null!=p&&De(t,["thoughtSignature"],p);const d=Me(e,["videoMetadata"]);if(null!=d&&De(t,["videoMetadata"],d),void 0!==Me(e,["toolCall"]))throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==Me(e,["toolResponse"]))throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==Me(e,["partMetadata"]))throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(e))),De(t,["parts"],e)}const o=Me(e,["role"]);return null!=o&&De(t,["role"],o),t}(Ct(h)));const f=Me(e,["tools"]);if(void 0!==t&&null!=f){let e=Dt(f);Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["retrieval"]);null!=n&&De(t,["retrieval"],n);const o=Me(e,["computerUse"]);if(null!=o&&De(t,["computerUse"],o),void 0!==Me(e,["fileSearch"]))throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const i=Me(e,["googleSearch"]);null!=i&&De(t,["googleSearch"],i);const r=Me(e,["googleMaps"]);null!=r&&De(t,["googleMaps"],r);const s=Me(e,["codeExecution"]);null!=s&&De(t,["codeExecution"],s);const l=Me(e,["enterpriseWebSearch"]);null!=l&&De(t,["enterpriseWebSearch"],l);const a=Me(e,["functionDeclarations"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["description"]);null!=n&&De(t,["description"],n);const o=Me(e,["name"]);null!=o&&De(t,["name"],o);const i=Me(e,["parameters"]);null!=i&&De(t,["parameters"],i);const r=Me(e,["parametersJsonSchema"]);null!=r&&De(t,["parametersJsonSchema"],r);const s=Me(e,["response"]);null!=s&&De(t,["response"],s);const l=Me(e,["responseJsonSchema"]);if(null!=l&&De(t,["responseJsonSchema"],l),void 0!==Me(e,["behavior"]))throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(e))),De(t,["functionDeclarations"],e)}const u=Me(e,["googleSearchRetrieval"]);null!=u&&De(t,["googleSearchRetrieval"],u);const c=Me(e,["parallelAiSearch"]);null!=c&&De(t,["parallelAiSearch"],c);const p=Me(e,["urlContext"]);if(null!=p&&De(t,["urlContext"],p),void 0!==Me(e,["mcpServers"]))throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(Pt(e)))),De(t,["setup","tools"],e)}const m=Me(e,["sessionResumption"]);void 0!==t&&null!=m&&De(t,["setup","sessionResumption"],m);const g=Me(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&De(t,["setup","inputAudioTranscription"],g);const E=Me(e,["outputAudioTranscription"]);void 0!==t&&null!=E&&De(t,["setup","outputAudioTranscription"],E);const y=Me(e,["realtimeInputConfig"]);void 0!==t&&null!=y&&De(t,["setup","realtimeInputConfig"],y);const v=Me(e,["contextWindowCompression"]);void 0!==t&&null!=v&&De(t,["setup","contextWindowCompression"],v);const I=Me(e,["proactivity"]);void 0!==t&&null!=I&&De(t,["setup","proactivity"],I);const _=Me(e,["explicitVadSignal"]);void 0!==t&&null!=_&&De(t,["setup","explicitVadSignal"],_);const T=Me(e,["avatarConfig"]);void 0!==t&&null!=T&&De(t,["setup","avatarConfig"],T);const A=Me(e,["safetySettings"]);if(void 0!==t&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["setup","safetySettings"],e)}return{}}function En(e){const t={},n=Me(e,["media"]);if(null!=n){let e=mt(n);Array.isArray(e)&&(e=e.map(e=>fn(e))),De(t,["mediaChunks"],e)}const o=Me(e,["audio"]);null!=o&&De(t,["audio"],fn(yt(o)));const i=Me(e,["audioStreamEnd"]);null!=i&&De(t,["audioStreamEnd"],i);const r=Me(e,["video"]);null!=r&&De(t,["video"],fn(Et(r)));const s=Me(e,["text"]);null!=s&&De(t,["text"],s);const l=Me(e,["activityStart"]);null!=l&&De(t,["activityStart"],l);const a=Me(e,["activityEnd"]);return null!=a&&De(t,["activityEnd"],a),t}function yn(e){const t={},n=Me(e,["media"]);if(null!=n){let e=mt(n);Array.isArray(e)&&(e=e.map(e=>e)),De(t,["mediaChunks"],e)}const o=Me(e,["audio"]);null!=o&&De(t,["audio"],yt(o));const i=Me(e,["audioStreamEnd"]);null!=i&&De(t,["audioStreamEnd"],i);const r=Me(e,["video"]);null!=r&&De(t,["video"],Et(r));const s=Me(e,["text"]);null!=s&&De(t,["text"],s);const l=Me(e,["activityStart"]);null!=l&&De(t,["activityStart"],l);const a=Me(e,["activityEnd"]);return null!=a&&De(t,["activityEnd"],a),t}function vn(e,t){const n={},o=Me(e,["parts"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["mediaResolution"]);null!=n&&De(t,["mediaResolution"],n);const o=Me(e,["codeExecutionResult"]);null!=o&&De(t,["codeExecutionResult"],o);const i=Me(e,["executableCode"]);null!=i&&De(t,["executableCode"],i);const r=Me(e,["fileData"]);null!=r&&De(t,["fileData"],function(e){const t={};if(void 0!==Me(e,["displayName"]))throw new Error("displayName parameter is not supported in Gemini API.");const n=Me(e,["fileUri"]);null!=n&&De(t,["fileUri"],n);const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}(r));const s=Me(e,["functionCall"]);null!=s&&De(t,["functionCall"],function(e){const t={},n=Me(e,["id"]);null!=n&&De(t,["id"],n);const o=Me(e,["args"]);null!=o&&De(t,["args"],o);const i=Me(e,["name"]);if(null!=i&&De(t,["name"],i),void 0!==Me(e,["partialArgs"]))throw new Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==Me(e,["willContinue"]))throw new Error("willContinue parameter is not supported in Gemini API.");return t}(s));const l=Me(e,["functionResponse"]);null!=l&&De(t,["functionResponse"],l);const a=Me(e,["inlineData"]);null!=a&&De(t,["inlineData"],function(e){const t={},n=Me(e,["data"]);if(null!=n&&De(t,["data"],n),void 0!==Me(e,["displayName"]))throw new Error("displayName parameter is not supported in Gemini API.");const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}(a));const u=Me(e,["text"]);null!=u&&De(t,["text"],u);const c=Me(e,["thought"]);null!=c&&De(t,["thought"],c);const p=Me(e,["thoughtSignature"]);null!=p&&De(t,["thoughtSignature"],p);const d=Me(e,["videoMetadata"]);null!=d&&De(t,["videoMetadata"],d);const h=Me(e,["toolCall"]);null!=h&&De(t,["toolCall"],h);const f=Me(e,["toolResponse"]);null!=f&&De(t,["toolResponse"],f);const m=Me(e,["partMetadata"]);return null!=m&&De(t,["partMetadata"],m),t}(e))),De(n,["parts"],e)}const i=Me(e,["role"]);return null!=i&&De(n,["role"],i),n}function In(e,t){const n={},o=Me(e,["parts"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["mediaResolution"]);null!=n&&De(t,["mediaResolution"],n);const o=Me(e,["codeExecutionResult"]);null!=o&&De(t,["codeExecutionResult"],o);const i=Me(e,["executableCode"]);null!=i&&De(t,["executableCode"],i);const r=Me(e,["fileData"]);null!=r&&De(t,["fileData"],r);const s=Me(e,["functionCall"]);null!=s&&De(t,["functionCall"],s);const l=Me(e,["functionResponse"]);null!=l&&De(t,["functionResponse"],l);const a=Me(e,["inlineData"]);null!=a&&De(t,["inlineData"],a);const u=Me(e,["text"]);null!=u&&De(t,["text"],u);const c=Me(e,["thought"]);null!=c&&De(t,["thought"],c);const p=Me(e,["thoughtSignature"]);null!=p&&De(t,["thoughtSignature"],p);const d=Me(e,["videoMetadata"]);if(null!=d&&De(t,["videoMetadata"],d),void 0!==Me(e,["toolCall"]))throw new Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==Me(e,["toolResponse"]))throw new Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==Me(e,["partMetadata"]))throw new Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(e))),De(n,["parts"],e)}const i=Me(e,["role"]);return null!=i&&De(n,["role"],i),n}function _n(e,t,n){const o={},i=Me(t,["model"]);null!=i&&De(o,["_url","model"],ht(e,i));const r=Me(t,["contents"]);if(null!=r){let e=St(r);Array.isArray(e)&&(e=e.map(e=>vn(e))),De(o,["contents"],e)}const s=Me(t,["config"]);return null!=s&&De(o,["generationConfig"],function(e,t,n){const o={},i=Me(t,["systemInstruction"]);void 0!==n&&null!=i&&De(n,["systemInstruction"],vn(Ct(i)));const r=Me(t,["temperature"]);null!=r&&De(o,["temperature"],r);const s=Me(t,["topP"]);null!=s&&De(o,["topP"],s);const l=Me(t,["topK"]);null!=l&&De(o,["topK"],l);const a=Me(t,["candidateCount"]);null!=a&&De(o,["candidateCount"],a);const u=Me(t,["maxOutputTokens"]);null!=u&&De(o,["maxOutputTokens"],u);const c=Me(t,["stopSequences"]);null!=c&&De(o,["stopSequences"],c);const p=Me(t,["responseLogprobs"]);null!=p&&De(o,["responseLogprobs"],p);const d=Me(t,["logprobs"]);null!=d&&De(o,["logprobs"],d);const h=Me(t,["presencePenalty"]);null!=h&&De(o,["presencePenalty"],h);const f=Me(t,["frequencyPenalty"]);null!=f&&De(o,["frequencyPenalty"],f);const m=Me(t,["seed"]);null!=m&&De(o,["seed"],m);const g=Me(t,["responseMimeType"]);null!=g&&De(o,["responseMimeType"],g);const E=Me(t,["responseSchema"]);null!=E&&De(o,["responseSchema"],wt(E));const y=Me(t,["responseJsonSchema"]);if(null!=y&&De(o,["responseJsonSchema"],y),void 0!==Me(t,["routingConfig"]))throw new Error("routingConfig parameter is not supported in Gemini API.");if(void 0!==Me(t,["modelSelectionConfig"]))throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");const v=Me(t,["safetySettings"]);if(void 0!==n&&null!=v){let e=v;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["category"]);if(null!=n&&De(t,["category"],n),void 0!==Me(e,["method"]))throw new Error("method parameter is not supported in Gemini API.");const o=Me(e,["threshold"]);return null!=o&&De(t,["threshold"],o),t}(e))),De(n,["safetySettings"],e)}const I=Me(t,["tools"]);if(void 0!==n&&null!=I){let e=Dt(I);Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==Me(e,["retrieval"]))throw new Error("retrieval parameter is not supported in Gemini API.");const n=Me(e,["computerUse"]);null!=n&&De(t,["computerUse"],n);const o=Me(e,["fileSearch"]);null!=o&&De(t,["fileSearch"],o);const i=Me(e,["googleSearch"]);null!=i&&De(t,["googleSearch"],function(e){const t={},n=Me(e,["searchTypes"]);if(null!=n&&De(t,["searchTypes"],n),void 0!==Me(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(void 0!==Me(e,["excludeDomains"]))throw new Error("excludeDomains parameter is not supported in Gemini API.");const o=Me(e,["timeRangeFilter"]);return null!=o&&De(t,["timeRangeFilter"],o),t}(i));const r=Me(e,["googleMaps"]);null!=r&&De(t,["googleMaps"],function(e){const t={},n=Me(e,["authConfig"]);null!=n&&De(t,["authConfig"],function(e){const t={},n=Me(e,["apiKey"]);if(null!=n&&De(t,["apiKey"],n),void 0!==Me(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["authType"]))throw new Error("authType parameter is not supported in Gemini API.");if(void 0!==Me(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["oauthConfig"]))throw new Error("oauthConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["oidcConfig"]))throw new Error("oidcConfig parameter is not supported in Gemini API.");return t}(n));const o=Me(e,["enableWidget"]);return null!=o&&De(t,["enableWidget"],o),t}(r));const s=Me(e,["codeExecution"]);if(null!=s&&De(t,["codeExecution"],s),void 0!==Me(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const l=Me(e,["functionDeclarations"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["functionDeclarations"],e)}const a=Me(e,["googleSearchRetrieval"]);if(null!=a&&De(t,["googleSearchRetrieval"],a),void 0!==Me(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is not supported in Gemini API.");const u=Me(e,["urlContext"]);null!=u&&De(t,["urlContext"],u);const c=Me(e,["mcpServers"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["mcpServers"],e)}return t}(Pt(e)))),De(n,["tools"],e)}const _=Me(t,["toolConfig"]);if(void 0!==n&&null!=_&&De(n,["toolConfig"],function(e){const t={},n=Me(e,["retrievalConfig"]);null!=n&&De(t,["retrievalConfig"],n);const o=Me(e,["functionCallingConfig"]);null!=o&&De(t,["functionCallingConfig"],function(e){const t={},n=Me(e,["allowedFunctionNames"]);null!=n&&De(t,["allowedFunctionNames"],n);const o=Me(e,["mode"]);if(null!=o&&De(t,["mode"],o),void 0!==Me(e,["streamFunctionCallArguments"]))throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(o));const i=Me(e,["includeServerSideToolInvocations"]);return null!=i&&De(t,["includeServerSideToolInvocations"],i),t}(_)),void 0!==Me(t,["labels"]))throw new Error("labels parameter is not supported in Gemini API.");const T=Me(t,["cachedContent"]);void 0!==n&&null!=T&&De(n,["cachedContent"],Mt(e,T));const A=Me(t,["responseModalities"]);null!=A&&De(o,["responseModalities"],A);const C=Me(t,["mediaResolution"]);null!=C&&De(o,["mediaResolution"],C);const O=Me(t,["speechConfig"]);if(null!=O&&De(o,["speechConfig"],Rt(O)),void 0!==Me(t,["audioTimestamp"]))throw new Error("audioTimestamp parameter is not supported in Gemini API.");const S=Me(t,["thinkingConfig"]);null!=S&&De(o,["thinkingConfig"],S);const b=Me(t,["imageConfig"]);null!=b&&De(o,["imageConfig"],function(e){const t={},n=Me(e,["aspectRatio"]);null!=n&&De(t,["aspectRatio"],n);const o=Me(e,["imageSize"]);if(null!=o&&De(t,["imageSize"],o),void 0!==Me(e,["personGeneration"]))throw new Error("personGeneration parameter is not supported in Gemini API.");if(void 0!==Me(e,["prominentPeople"]))throw new Error("prominentPeople parameter is not supported in Gemini API.");if(void 0!==Me(e,["outputMimeType"]))throw new Error("outputMimeType parameter is not supported in Gemini API.");if(void 0!==Me(e,["outputCompressionQuality"]))throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");if(void 0!==Me(e,["imageOutputOptions"]))throw new Error("imageOutputOptions parameter is not supported in Gemini API.");return t}(b));const w=Me(t,["enableEnhancedCivicAnswers"]);if(null!=w&&De(o,["enableEnhancedCivicAnswers"],w),void 0!==Me(t,["modelArmorConfig"]))throw new Error("modelArmorConfig parameter is not supported in Gemini API.");const R=Me(t,["serviceTier"]);return void 0!==n&&null!=R&&De(n,["serviceTier"],R),o}(e,s,o)),o}function Tn(e,t,n){const o={},i=Me(t,["model"]);null!=i&&De(o,["_url","model"],ht(e,i));const r=Me(t,["contents"]);if(null!=r){let e=St(r);Array.isArray(e)&&(e=e.map(e=>In(e))),De(o,["contents"],e)}const s=Me(t,["config"]);return null!=s&&De(o,["generationConfig"],function(e,t,n){const o={},i=Me(t,["systemInstruction"]);void 0!==n&&null!=i&&De(n,["systemInstruction"],In(Ct(i)));const r=Me(t,["temperature"]);null!=r&&De(o,["temperature"],r);const s=Me(t,["topP"]);null!=s&&De(o,["topP"],s);const l=Me(t,["topK"]);null!=l&&De(o,["topK"],l);const a=Me(t,["candidateCount"]);null!=a&&De(o,["candidateCount"],a);const u=Me(t,["maxOutputTokens"]);null!=u&&De(o,["maxOutputTokens"],u);const c=Me(t,["stopSequences"]);null!=c&&De(o,["stopSequences"],c);const p=Me(t,["responseLogprobs"]);null!=p&&De(o,["responseLogprobs"],p);const d=Me(t,["logprobs"]);null!=d&&De(o,["logprobs"],d);const h=Me(t,["presencePenalty"]);null!=h&&De(o,["presencePenalty"],h);const f=Me(t,["frequencyPenalty"]);null!=f&&De(o,["frequencyPenalty"],f);const m=Me(t,["seed"]);null!=m&&De(o,["seed"],m);const g=Me(t,["responseMimeType"]);null!=g&&De(o,["responseMimeType"],g);const E=Me(t,["responseSchema"]);null!=E&&De(o,["responseSchema"],wt(E));const y=Me(t,["responseJsonSchema"]);null!=y&&De(o,["responseJsonSchema"],y);const v=Me(t,["routingConfig"]);null!=v&&De(o,["routingConfig"],v);const I=Me(t,["modelSelectionConfig"]);null!=I&&De(o,["modelConfig"],I);const _=Me(t,["safetySettings"]);if(void 0!==n&&null!=_){let e=_;Array.isArray(e)&&(e=e.map(e=>e)),De(n,["safetySettings"],e)}const T=Me(t,["tools"]);if(void 0!==n&&null!=T){let e=Dt(T);Array.isArray(e)&&(e=e.map(e=>Gn(Pt(e)))),De(n,["tools"],e)}const A=Me(t,["toolConfig"]);void 0!==n&&null!=A&&De(n,["toolConfig"],function(e){const t={},n=Me(e,["retrievalConfig"]);null!=n&&De(t,["retrievalConfig"],n);const o=Me(e,["functionCallingConfig"]);if(null!=o&&De(t,["functionCallingConfig"],o),void 0!==Me(e,["includeServerSideToolInvocations"]))throw new Error("includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(A));const C=Me(t,["labels"]);void 0!==n&&null!=C&&De(n,["labels"],C);const O=Me(t,["cachedContent"]);void 0!==n&&null!=O&&De(n,["cachedContent"],Mt(e,O));const S=Me(t,["responseModalities"]);null!=S&&De(o,["responseModalities"],S);const b=Me(t,["mediaResolution"]);null!=b&&De(o,["mediaResolution"],b);const w=Me(t,["speechConfig"]);null!=w&&De(o,["speechConfig"],Rt(w));const R=Me(t,["audioTimestamp"]);null!=R&&De(o,["audioTimestamp"],R);const N=Me(t,["thinkingConfig"]);null!=N&&De(o,["thinkingConfig"],N);const P=Me(t,["imageConfig"]);if(null!=P&&De(o,["imageConfig"],function(e){const t={},n=Me(e,["aspectRatio"]);null!=n&&De(t,["aspectRatio"],n);const o=Me(e,["imageSize"]);null!=o&&De(t,["imageSize"],o);const i=Me(e,["personGeneration"]);null!=i&&De(t,["personGeneration"],i);const r=Me(e,["prominentPeople"]);null!=r&&De(t,["prominentPeople"],r);const s=Me(e,["outputMimeType"]);null!=s&&De(t,["imageOutputOptions","mimeType"],s);const l=Me(e,["outputCompressionQuality"]);null!=l&&De(t,["imageOutputOptions","compressionQuality"],l);const a=Me(e,["imageOutputOptions"]);return null!=a&&De(t,["imageOutputOptions"],a),t}(P)),void 0!==Me(t,["enableEnhancedCivicAnswers"]))throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const D=Me(t,["modelArmorConfig"]);void 0!==n&&null!=D&&De(n,["modelArmorConfig"],D);const M=Me(t,["serviceTier"]);return void 0!==n&&null!=M&&De(n,["serviceTier"],M),o}(e,s,o)),o}function An(e,t){const n={},o=Me(e,["sdkHttpResponse"]);null!=o&&De(n,["sdkHttpResponse"],o);const i=Me(e,["candidates"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["content"]);null!=n&&De(t,["content"],n);const o=Me(e,["citationMetadata"]);null!=o&&De(t,["citationMetadata"],function(e){const t={},n=Me(e,["citationSources"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["citations"],e)}return t}(o));const i=Me(e,["tokenCount"]);null!=i&&De(t,["tokenCount"],i);const r=Me(e,["finishReason"]);null!=r&&De(t,["finishReason"],r);const s=Me(e,["groundingMetadata"]);null!=s&&De(t,["groundingMetadata"],s);const l=Me(e,["avgLogprobs"]);null!=l&&De(t,["avgLogprobs"],l);const a=Me(e,["index"]);null!=a&&De(t,["index"],a);const u=Me(e,["logprobsResult"]);null!=u&&De(t,["logprobsResult"],u);const c=Me(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["safetyRatings"],e)}const p=Me(e,["urlContextMetadata"]);return null!=p&&De(t,["urlContextMetadata"],p),t}(e))),De(n,["candidates"],e)}const r=Me(e,["modelVersion"]);null!=r&&De(n,["modelVersion"],r);const s=Me(e,["promptFeedback"]);null!=s&&De(n,["promptFeedback"],s);const l=Me(e,["responseId"]);null!=l&&De(n,["responseId"],l);const a=Me(e,["usageMetadata"]);null!=a&&De(n,["usageMetadata"],a);const u=Me(e,["modelStatus"]);return null!=u&&De(n,["modelStatus"],u),n}function Cn(e,t){const n={},o=Me(e,["sdkHttpResponse"]);null!=o&&De(n,["sdkHttpResponse"],o);const i=Me(e,["candidates"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),De(n,["candidates"],e)}const r=Me(e,["createTime"]);null!=r&&De(n,["createTime"],r);const s=Me(e,["modelVersion"]);null!=s&&De(n,["modelVersion"],s);const l=Me(e,["promptFeedback"]);null!=l&&De(n,["promptFeedback"],l);const a=Me(e,["responseId"]);null!=a&&De(n,["responseId"],a);const u=Me(e,["usageMetadata"]);return null!=u&&De(n,["usageMetadata"],u),n}function On(e,t,n){const o={},i=Me(t,["model"]);null!=i&&De(o,["_url","model"],ht(e,i));const r=Me(t,["prompt"]);null!=r&&De(o,["instances[0]","prompt"],r);const s=Me(t,["image"]);null!=s&&De(o,["instances[0]","image"],Rn(s));const l=Me(t,["video"]);null!=l&&De(o,["instances[0]","video"],xn(l));const a=Me(t,["source"]);null!=a&&function(e,t){const n=Me(e,["prompt"]);void 0!==t&&null!=n&&De(t,["instances[0]","prompt"],n);const o=Me(e,["image"]);void 0!==t&&null!=o&&De(t,["instances[0]","image"],Rn(o));const i=Me(e,["video"]);void 0!==t&&null!=i&&De(t,["instances[0]","video"],xn(i))}(a,o);const u=Me(t,["config"]);return null!=u&&function(e,t){const n=Me(e,["numberOfVideos"]);if(void 0!==t&&null!=n&&De(t,["parameters","sampleCount"],n),void 0!==Me(e,["outputGcsUri"]))throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(void 0!==Me(e,["fps"]))throw new Error("fps parameter is not supported in Gemini API.");const o=Me(e,["durationSeconds"]);if(void 0!==t&&null!=o&&De(t,["parameters","durationSeconds"],o),void 0!==Me(e,["seed"]))throw new Error("seed parameter is not supported in Gemini API.");const i=Me(e,["aspectRatio"]);void 0!==t&&null!=i&&De(t,["parameters","aspectRatio"],i);const r=Me(e,["resolution"]);void 0!==t&&null!=r&&De(t,["parameters","resolution"],r);const s=Me(e,["personGeneration"]);if(void 0!==t&&null!=s&&De(t,["parameters","personGeneration"],s),void 0!==Me(e,["pubsubTopic"]))throw new Error("pubsubTopic parameter is not supported in Gemini API.");const l=Me(e,["negativePrompt"]);void 0!==t&&null!=l&&De(t,["parameters","negativePrompt"],l);const a=Me(e,["enhancePrompt"]);if(void 0!==t&&null!=a&&De(t,["parameters","enhancePrompt"],a),void 0!==Me(e,["generateAudio"]))throw new Error("generateAudio parameter is not supported in Gemini API.");const u=Me(e,["lastFrame"]);void 0!==t&&null!=u&&De(t,["instances[0]","lastFrame"],Rn(u));const c=Me(e,["referenceImages"]);if(void 0!==t&&null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["image"]);null!=n&&De(t,["image"],Rn(n));const o=Me(e,["referenceType"]);return null!=o&&De(t,["referenceType"],o),t}(e))),De(t,["instances[0]","referenceImages"],e)}if(void 0!==Me(e,["mask"]))throw new Error("mask parameter is not supported in Gemini API.");if(void 0!==Me(e,["compressionQuality"]))throw new Error("compressionQuality parameter is not supported in Gemini API.");if(void 0!==Me(e,["labels"]))throw new Error("labels parameter is not supported in Gemini API.");const p=Me(e,["webhookConfig"]);if(void 0!==t&&null!=p&&De(t,["webhookConfig"],p),void 0!==Me(e,["resizeMode"]))throw new Error("resizeMode parameter is not supported in Gemini API.")}(u,o),o}function Sn(e,t,n){const o={},i=Me(t,["model"]);null!=i&&De(o,["_url","model"],ht(e,i));const r=Me(t,["prompt"]);null!=r&&De(o,["instances[0]","prompt"],r);const s=Me(t,["image"]);null!=s&&De(o,["instances[0]","image"],Nn(s));const l=Me(t,["video"]);null!=l&&De(o,["instances[0]","video"],Ln(l));const a=Me(t,["source"]);null!=a&&function(e,t){const n=Me(e,["prompt"]);void 0!==t&&null!=n&&De(t,["instances[0]","prompt"],n);const o=Me(e,["image"]);void 0!==t&&null!=o&&De(t,["instances[0]","image"],Nn(o));const i=Me(e,["video"]);void 0!==t&&null!=i&&De(t,["instances[0]","video"],Ln(i))}(a,o);const u=Me(t,["config"]);return null!=u&&function(e,t){const n=Me(e,["numberOfVideos"]);void 0!==t&&null!=n&&De(t,["parameters","sampleCount"],n);const o=Me(e,["outputGcsUri"]);void 0!==t&&null!=o&&De(t,["parameters","storageUri"],o);const i=Me(e,["fps"]);void 0!==t&&null!=i&&De(t,["parameters","fps"],i);const r=Me(e,["durationSeconds"]);void 0!==t&&null!=r&&De(t,["parameters","durationSeconds"],r);const s=Me(e,["seed"]);void 0!==t&&null!=s&&De(t,["parameters","seed"],s);const l=Me(e,["aspectRatio"]);void 0!==t&&null!=l&&De(t,["parameters","aspectRatio"],l);const a=Me(e,["resolution"]);void 0!==t&&null!=a&&De(t,["parameters","resolution"],a);const u=Me(e,["personGeneration"]);void 0!==t&&null!=u&&De(t,["parameters","personGeneration"],u);const c=Me(e,["pubsubTopic"]);void 0!==t&&null!=c&&De(t,["parameters","pubsubTopic"],c);const p=Me(e,["negativePrompt"]);void 0!==t&&null!=p&&De(t,["parameters","negativePrompt"],p);const d=Me(e,["enhancePrompt"]);void 0!==t&&null!=d&&De(t,["parameters","enhancePrompt"],d);const h=Me(e,["generateAudio"]);void 0!==t&&null!=h&&De(t,["parameters","generateAudio"],h);const f=Me(e,["lastFrame"]);void 0!==t&&null!=f&&De(t,["instances[0]","lastFrame"],Nn(f));const m=Me(e,["referenceImages"]);if(void 0!==t&&null!=m){let e=m;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["image"]);null!=n&&De(t,["image"],Nn(n));const o=Me(e,["referenceType"]);return null!=o&&De(t,["referenceType"],o),t}(e))),De(t,["instances[0]","referenceImages"],e)}const g=Me(e,["mask"]);void 0!==t&&null!=g&&De(t,["instances[0]","mask"],function(e){const t={},n=Me(e,["image"]);null!=n&&De(t,["_self"],Nn(n));const o=Me(e,["maskMode"]);return null!=o&&De(t,["maskMode"],o),t}(g));const E=Me(e,["compressionQuality"]);void 0!==t&&null!=E&&De(t,["parameters","compressionQuality"],E);const y=Me(e,["labels"]);if(void 0!==t&&null!=y&&De(t,["labels"],y),void 0!==Me(e,["webhookConfig"]))throw new Error("webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const v=Me(e,["resizeMode"]);void 0!==t&&null!=v&&De(t,["parameters","resizeMode"],v)}(u,o),o}function bn(e,t){const n={},o=Me(e,["_self"]);null!=o&&De(n,["image"],wn(o));const i=Me(e,["raiFilteredReason"]);null!=i&&De(n,["raiFilteredReason"],i);const r=Me(e,["_self"]);null!=r&&De(n,["safetyAttributes"],Un(r));const s=Me(e,["prompt"]);return null!=s&&De(n,["enhancedPrompt"],s),n}function wn(e,t){const n={},o=Me(e,["gcsUri"]);null!=o&&De(n,["gcsUri"],o);const i=Me(e,["bytesBase64Encoded"]);null!=i&&De(n,["imageBytes"],Gt(i));const r=Me(e,["mimeType"]);return null!=r&&De(n,["mimeType"],r),n}function Rn(e,t){const n={};if(void 0!==Me(e,["gcsUri"]))throw new Error("gcsUri parameter is not supported in Gemini API.");const o=Me(e,["imageBytes"]);null!=o&&De(n,["bytesBase64Encoded"],Gt(o));const i=Me(e,["mimeType"]);return null!=i&&De(n,["mimeType"],i),n}function Nn(e,t){const n={},o=Me(e,["gcsUri"]);null!=o&&De(n,["gcsUri"],o);const i=Me(e,["imageBytes"]);null!=i&&De(n,["bytesBase64Encoded"],Gt(i));const r=Me(e,["mimeType"]);return null!=r&&De(n,["mimeType"],r),n}function Pn(e,t){const n={},o=Me(e,["name"]);null!=o&&De(n,["name"],o);const i=Me(e,["displayName"]);null!=i&&De(n,["displayName"],i);const r=Me(e,["description"]);null!=r&&De(n,["description"],r);const s=Me(e,["version"]);null!=s&&De(n,["version"],s);const l=Me(e,["_self"]);null!=l&&De(n,["tunedModelInfo"],function(e){const t={},n=Me(e,["baseModel"]);null!=n&&De(t,["baseModel"],n);const o=Me(e,["createTime"]);null!=o&&De(t,["createTime"],o);const i=Me(e,["updateTime"]);return null!=i&&De(t,["updateTime"],i),t}(l));const a=Me(e,["inputTokenLimit"]);null!=a&&De(n,["inputTokenLimit"],a);const u=Me(e,["outputTokenLimit"]);null!=u&&De(n,["outputTokenLimit"],u);const c=Me(e,["supportedGenerationMethods"]);null!=c&&De(n,["supportedActions"],c);const p=Me(e,["temperature"]);null!=p&&De(n,["temperature"],p);const d=Me(e,["maxTemperature"]);null!=d&&De(n,["maxTemperature"],d);const h=Me(e,["topP"]);null!=h&&De(n,["topP"],h);const f=Me(e,["topK"]);null!=f&&De(n,["topK"],f);const m=Me(e,["thinking"]);return null!=m&&De(n,["thinking"],m),n}function Dn(e,t){const n={},o=Me(e,["name"]);null!=o&&De(n,["name"],o);const i=Me(e,["displayName"]);null!=i&&De(n,["displayName"],i);const r=Me(e,["description"]);null!=r&&De(n,["description"],r);const s=Me(e,["versionId"]);null!=s&&De(n,["version"],s);const l=Me(e,["deployedModels"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["endpoint"]);null!=n&&De(t,["name"],n);const o=Me(e,["deployedModelId"]);return null!=o&&De(t,["deployedModelId"],o),t}(e))),De(n,["endpoints"],e)}const a=Me(e,["labels"]);null!=a&&De(n,["labels"],a);const u=Me(e,["_self"]);null!=u&&De(n,["tunedModelInfo"],function(e){const t={},n=Me(e,["labels","google-vertex-llm-tuning-base-model-id"]);null!=n&&De(t,["baseModel"],n);const o=Me(e,["createTime"]);null!=o&&De(t,["createTime"],o);const i=Me(e,["updateTime"]);return null!=i&&De(t,["updateTime"],i),t}(u));const c=Me(e,["defaultCheckpointId"]);null!=c&&De(n,["defaultCheckpointId"],c);const p=Me(e,["checkpoints"]);if(null!=p){let e=p;Array.isArray(e)&&(e=e.map(e=>e)),De(n,["checkpoints"],e)}return n}function Mn(e,t){const n={},o=Me(e,["safetyAttributes","categories"]);null!=o&&De(n,["categories"],o);const i=Me(e,["safetyAttributes","scores"]);null!=i&&De(n,["scores"],i);const r=Me(e,["contentType"]);return null!=r&&De(n,["contentType"],r),n}function Un(e,t){const n={},o=Me(e,["safetyAttributes","categories"]);null!=o&&De(n,["categories"],o);const i=Me(e,["safetyAttributes","scores"]);null!=i&&De(n,["scores"],i);const r=Me(e,["contentType"]);return null!=r&&De(n,["contentType"],r),n}function Gn(e,t){const n={},o=Me(e,["retrieval"]);null!=o&&De(n,["retrieval"],o);const i=Me(e,["computerUse"]);if(null!=i&&De(n,["computerUse"],i),void 0!==Me(e,["fileSearch"]))throw new Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");const r=Me(e,["googleSearch"]);null!=r&&De(n,["googleSearch"],r);const s=Me(e,["googleMaps"]);null!=s&&De(n,["googleMaps"],s);const l=Me(e,["codeExecution"]);null!=l&&De(n,["codeExecution"],l);const a=Me(e,["enterpriseWebSearch"]);null!=a&&De(n,["enterpriseWebSearch"],a);const u=Me(e,["functionDeclarations"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["description"]);null!=n&&De(t,["description"],n);const o=Me(e,["name"]);null!=o&&De(t,["name"],o);const i=Me(e,["parameters"]);null!=i&&De(t,["parameters"],i);const r=Me(e,["parametersJsonSchema"]);null!=r&&De(t,["parametersJsonSchema"],r);const s=Me(e,["response"]);null!=s&&De(t,["response"],s);const l=Me(e,["responseJsonSchema"]);if(null!=l&&De(t,["responseJsonSchema"],l),void 0!==Me(e,["behavior"]))throw new Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(e))),De(n,["functionDeclarations"],e)}const c=Me(e,["googleSearchRetrieval"]);null!=c&&De(n,["googleSearchRetrieval"],c);const p=Me(e,["parallelAiSearch"]);null!=p&&De(n,["parallelAiSearch"],p);const d=Me(e,["urlContext"]);if(null!=d&&De(n,["urlContext"],d),void 0!==Me(e,["mcpServers"]))throw new Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return n}function xn(e,t){const n={},o=Me(e,["uri"]);null!=o&&De(n,["uri"],o);const i=Me(e,["videoBytes"]);null!=i&&De(n,["encodedVideo"],Gt(i));const r=Me(e,["mimeType"]);return null!=r&&De(n,["encoding"],r),n}function Ln(e,t){const n={},o=Me(e,["uri"]);null!=o&&De(n,["gcsUri"],o);const i=Me(e,["videoBytes"]);null!=i&&De(n,["bytesBase64Encoded"],Gt(i));const r=Me(e,["mimeType"]);return null!=r&&De(n,["mimeType"],r),n}function kn(e,t){const n=Me(e,["mimeType"]);void 0!==t&&null!=n&&De(t,["mimeType"],n);const o=Me(e,["displayName"]);void 0!==t&&null!=o&&De(t,["displayName"],o);const i=Me(e,["customMetadata"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["customMetadata"],e)}const r=Me(e,["chunkingConfig"]);return void 0!==t&&null!=r&&De(t,["chunkingConfig"],r),{}}var qn="x-goog-api-client",Hn=/* @__PURE__ */new Set(["us","eu"]),Fn=[408,429,500,502,503,504],Vn=class{constructor(e){var t,n,o;this.clientOptions=Object.assign({},e),this.customBaseUrl=null===(t=e.httpOptions)||void 0===t?void 0:t.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 i={};if(this.clientOptions.vertexai){if(this.clientOptions.location||this.clientOptions.apiKey||this.customBaseUrl||(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey||this.customBaseUrl))throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");const t=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!t?(i.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey||"global"===this.clientOptions.location?i.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&Hn.has(this.clientOptions.location)?i.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(i.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),i.apiVersion=null!==(n=this.clientOptions.apiVersion)&&void 0!==n?n:"v1beta1"}else this.clientOptions.apiKey,i.apiVersion=null!==(o=this.clientOptions.apiVersion)&&void 0!==o?o:"v1beta",i.baseUrl="https://generativelanguage.googleapis.com/";i.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=i,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(i,e.httpOptions))}isVertexAI(){var e;return null!==(e=this.clientOptions.vertexai)&&void 0!==e&&e}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){const e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.apiVersion)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.baseUrl)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.headers)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||void 0===e.baseUrl||void 0===e.apiVersion)throw new Error("HTTP options are not correctly set.");const t=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&""!==e.apiVersion&&t.push(e.apiVersion),t.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const e=this.getBaseUrl(),t=new URL(e);return t.protocol="http:"==t.protocol?"ws":"wss",t.toString()}setBaseUrl(e){if(!this.clientOptions.httpOptions)throw new Error("HTTP options are not correctly set.");this.clientOptions.httpOptions.baseUrl=e}constructUrl(e,t,n){const o=[this.getRequestUrlInternal(t)];return n&&o.push(this.getBaseResourcePath()),""!==e&&o.push(e),new URL(`${o.join("/")}`)}shouldPrependVertexProjectPath(e,t){return!(t.baseUrl&&t.baseUrlResourceScope===X.COLLECTION||this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||"GET"===e.httpMethod&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const n=this.shouldPrependVertexProjectPath(e,t),o=this.constructUrl(e.path,t,n);if(e.queryParams)for(const[r,s]of Object.entries(e.queryParams))o.searchParams.append(r,String(s));let i={};if("GET"===e.httpMethod){if(e.body&&"{}"!==e.body)throw new Error("Request body should be empty for GET request, but got non empty request body")}else i.body=e.body;return i=await this.includeExtraHttpOptionsToRequestInit(i,t,o.toString(),e.abortSignal),this.unaryApiCall(o,i,e.httpMethod)}patchHttpOptions(e,t){const n=JSON.parse(JSON.stringify(e));for(const[o,i]of Object.entries(t))"object"==typeof i?n[o]=Object.assign(Object.assign({},n[o]),i):void 0!==i&&(n[o]=i);return n}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));const n=this.shouldPrependVertexProjectPath(e,t),o=this.constructUrl(e.path,t,n);o.searchParams.has("alt")&&"sse"===o.searchParams.get("alt")||o.searchParams.set("alt","sse");let i={};return i.body=e.body,i=await this.includeExtraHttpOptionsToRequestInit(i,t,o.toString(),e.abortSignal),this.streamApiCall(o,i,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,t,n,o){if(t&&t.timeout||o){const n=new AbortController,i=n.signal;if(t.timeout&&(null==t?void 0:t.timeout)>0){const e=setTimeout(()=>n.abort(),t.timeout);e&&"function"==typeof e.unref&&e.unref()}o&&o.addEventListener("abort",()=>{n.abort()}),e.signal=i}return t&&null!==t.extraBody&&function(e,t){if(!t||0===Object.keys(t).length)return;if(e.body instanceof Blob)return;let n={};if("string"==typeof e.body&&e.body.length>0)try{const t=JSON.parse(e.body);if("object"!=typeof t||null===t||Array.isArray(t))return;n=t}catch(i){return}const o=function e(t,n){const o=Object.assign({},t);for(const i in n)if(Object.prototype.hasOwnProperty.call(n,i)){const t=n[i],r=o[i];t&&"object"==typeof t&&!Array.isArray(t)&&r&&"object"==typeof r&&!Array.isArray(r)?o[i]=e(r,t):o[i]=t}return o}(n,t);e.body=JSON.stringify(o)}(e,t.extraBody),e.headers=await this.getHeadersInternal(t,n),e}async unaryApiCall(e,t,n){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n})).then(async e=>(await jn(e),new ke(e))).catch(e=>{throw e instanceof Error?e:new Error(JSON.stringify(e))})}async streamApiCall(e,t,n){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:n})).then(async e=>(await jn(e),this.processStreamResponse(e))).catch(e=>{throw e instanceof Error?e:new Error(JSON.stringify(e))})}processStreamResponse(e){return on(this,arguments,function*(){var t;const n=null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.getReader(),o=new TextDecoder("utf-8");if(!n)throw new Error("Response body is empty");try{let t="";const r="data:",s=["\n\n","\r\r","\r\n\r\n"];for(;;){const{done:l,value:a}=yield nn(n.read());if(l){if(t.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}const u=o.decode(a,{stream:!0});try{const e=JSON.parse(u);if("error"in e){const t=JSON.parse(JSON.stringify(e.error)),n=t.status,o=t.code,i=`got status: ${n}. ${JSON.stringify(e)}`;if(o>=400&&o<600)throw new pn({message:i,status:o})}}catch(i){if("ApiError"===i.name)throw i}t+=u;let c=-1,p=0;for(;;){c=-1,p=0;for(const e of s){const n=t.indexOf(e);-1!==n&&(-1===c||n<c)&&(c=n,p=e.length)}if(-1===c)break;const n=t.substring(0,c);t=t.substring(c+p);const o=n.trim();if(o.startsWith(r)){const t=o.substring(5).trim();try{const n=new Response(t,{headers:null==e?void 0:e.headers,status:null==e?void 0:e.status,statusText:null==e?void 0:e.statusText});yield yield nn(new ke(n))}catch(i){throw new Error(`exception parsing stream chunk ${t}. ${i}`)}}}}}finally{n.releaseLock()}})}async apiCall(e,t){var n;if(!this.clientOptions.httpOptions||!this.clientOptions.httpOptions.retryOptions)return fetch(e,t);const o=this.clientOptions.httpOptions.retryOptions;return(0,Re.default)(async()=>{const n=await fetch(e,t);if(n.ok)return n;if(Fn.includes(n.status))throw new Error(`Retryable HTTP Error: ${n.statusText}`);throw new Re.AbortError(`Non-retryable exception ${n.statusText} sending request`)},{retries:(null!==(n=o.attempts)&&void 0!==n?n:5)-1})}getDefaultHeaders(){const e={},t="google-genai-sdk/1.52.0 "+this.clientOptions.userAgentExtra;return e["User-Agent"]=t,e[qn]=t,e["Content-Type"]="application/json",e}async getHeadersInternal(e,t){const n=new Headers;if(e&&e.headers){for(const[t,o]of Object.entries(e.headers))n.append(t,o);e.timeout&&e.timeout>0&&n.append("X-Server-Timeout",String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(n,t),n}getFileName(e){var t;let n="";return"string"==typeof e&&(n=e.replace(/[/\\]+$/,""),n=null!==(t=n.split(/[/\\]/).pop())&&void 0!==t?t:""),n}async uploadFile(e,t){var n;const o={};null!=t&&(o.mimeType=t.mimeType,o.name=t.name,o.displayName=t.displayName),o.name&&!o.name.startsWith("files/")&&(o.name=`files/${o.name}`);const i=this.clientOptions.uploader,r=await i.stat(e);o.sizeBytes=String(r.size);const s=null!==(n=null==t?void 0:t.mimeType)&&void 0!==n?n:r.type;if(void 0===s||""===s)throw new Error("Can not determine mimeType. Please provide mimeType in the config.");o.mimeType=s;const l={file:o},a=this.getFileName(e),u=Pe("upload/v1beta/files",l._url),c=await this.fetchUploadUrl(u,o.sizeBytes,o.mimeType,a,l,null==t?void 0:t.httpOptions);return i.upload(e,c,this)}async uploadFileToFileSearchStore(e,t,n){var o;const i=this.clientOptions.uploader,r=await i.stat(t),s=String(r.size),l=null!==(o=null==n?void 0:n.mimeType)&&void 0!==o?o:r.type;if(void 0===l||""===l)throw new Error("Can not determine mimeType. Please provide mimeType in the config.");const a=`upload/v1beta/${e}:uploadToFileSearchStore`,u=this.getFileName(t),c={};null!=n&&kn(n,c);const p=await this.fetchUploadUrl(a,s,l,u,c,null==n?void 0:n.httpOptions);return i.uploadToFileSearchStore(t,p,this)}async downloadFile(e){await this.clientOptions.downloader.download(e,this)}async fetchUploadUrl(e,t,n,o,i,r){var s;let l={};l=r||{apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${n}`},o?{"X-Goog-Upload-File-Name":o}:{})};const a=await this.request({path:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:l});if(!a||!(null==a?void 0:a.headers))throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");const u=null===(s=null==a?void 0:a.headers)||void 0===s?void 0:s["x-goog-upload-url"];if(void 0===u)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return u}};async function jn(e){var t;if(void 0===e)throw new Error("response is undefined");if(!e.ok){const n=e.status;let o;o=(null===(t=e.headers.get("content-type"))||void 0===t?void 0:t.includes("application/json"))?await e.json():{error:{message:await e.text(),code:e.status,status:e.statusText}};const i=JSON.stringify(o);if(n>=400&&n<600)throw new pn({message:i,status:n});throw new Error(i)}}function Bn(e){for(const t of e){if(Yn(t))return!0;if("object"==typeof t&&"inputSchema"in t)return!0}return!1}function Jn(e){var t;const n=null!==(t=e[qn])&&void 0!==t?t:"";e[qn]=(n+" mcp_used/unknown").trimStart()}function Yn(e){return null!==e&&"object"==typeof e&&e instanceof Kn}function $n(e){return on(this,arguments,function*(e,t=100){let n,o=0;for(;o<t;){const t=yield nn(e.listTools({cursor:n}));for(const e of t.tools)yield yield nn(e),o++;if(!t.nextCursor)break;n=t.nextCursor}})}var Kn=class e{constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(t,n){return new e(t,n)}async initialize(){var e,t,n,o;if(this.mcpTools.length>0)return;const i={},r=[];for(const c of this.mcpClients)try{for(var s,l=!0,a=(t=void 0,rn($n(c)));!(e=(s=await a.next()).done);l=!0){o=s.value,l=!1;const e=o;r.push(e);const t=e.name;if(i[t])throw new Error(`Duplicate function name ${t} found in MCP tools. Please ensure function names are unique.`);i[t]=c}}catch(u){t={error:u}}finally{try{l||e||!(n=a.return)||await n.call(a)}finally{if(t)throw t.error}}this.mcpTools=r,this.functionNameToMcpClient=i}async tool(){return await this.initialize(),function(e,t={}){const n=[],o=/* @__PURE__ */new Set;for(const i of e){const e=i.name;if(o.has(e))throw new Error(`Duplicate function name ${e} found in MCP tools. Please ensure function names are unique.`);o.add(e);const r=Ht(i,t);r.functionDeclarations&&n.push(...r.functionDeclarations)}return{functionDeclarations:n}}(this.mcpTools,this.config)}async callTool(e){await this.initialize();const t=[];for(const n of e)if(n.name in this.functionNameToMcpClient){const e=this.functionNameToMcpClient[n.name];let o;this.config.timeout&&(o={timeout:this.config.timeout});const i=await e.callTool({name:n.name,arguments:n.args},void 0,o);t.push({functionResponse:{name:n.name,response:i.isError?{error:i}:i}})}return t}},Wn=class{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n}async connect(e){var t,n;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");const o=this.apiClient.getWebsocketBaseUrl(),i=this.apiClient.getApiVersion(),r=function(e){const t=new Headers;for(const[n,o]of Object.entries(e))t.append(n,o);return t}(this.apiClient.getDefaultHeaders()),s=`${o}/ws/google.ai.generativelanguage.${i}.GenerativeService.BidiGenerateMusic?key=${this.apiClient.getApiKey()}`;let l=()=>{};const a=new Promise(e=>{l=e}),u=e.callbacks,c=(this.apiClient,{onopen:function(){l({})},onmessage:e=>{!async function(e,t,n){const o=new pt;let i;i=n.data instanceof Blob?JSON.parse(await n.data.text()):JSON.parse(n.data),Object.assign(o,i),t(o)}(0,u.onmessage,e)},onerror:null!==(t=null==u?void 0:u.onerror)&&void 0!==t?t:function(e){},onclose:null!==(n=null==u?void 0:u.onclose)&&void 0!==n?n:function(e){}}),p=this.webSocketFactory.create(s,function(e){const t={};return e.forEach((e,n)=>{t[n]=e}),t}(r),c);p.connect(),await a;const d={setup:{model:ht(this.apiClient,e.model)}};return p.send(JSON.stringify(d)),new zn(p,this.apiClient)}},zn=class{constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||0===Object.keys(e.weightedPrompts).length)throw new Error("Weighted prompts must be set and contain at least one entry.");const t=function(e){const t={},n=Me(e,["weightedPrompts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["weightedPrompts"],e)}return t}(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});const t=function(e){const t={},n=Me(e,["musicGenerationConfig"]);return null!=n&&De(t,["musicGenerationConfig"],n),t}(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){const t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(Oe.PLAY)}pause(){this.sendPlaybackControl(Oe.PAUSE)}stop(){this.sendPlaybackControl(Oe.STOP)}resetContext(){this.sendPlaybackControl(Oe.RESET_CONTEXT)}close(){this.conn.close()}},Xn=class{constructor(e,t,n){this.apiClient=e,this.auth=t,this.webSocketFactory=n,this.music=new Wn(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,n,o,i,r,s;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 l=this.apiClient.getWebsocketBaseUrl(),a=this.apiClient.getApiVersion();let u;const c=this.apiClient.getHeaders();e.config&&e.config.tools&&Bn(e.config.tools)&&Jn(c);const p=function(e){const t=new Headers;for(const[n,o]of Object.entries(e))t.append(n,o);return t}(c);if(this.apiClient.isVertexAI()){const e=this.apiClient.getProject(),t=this.apiClient.getLocation(),n=this.apiClient.getApiKey(),o=!!e&&!!t||!!n;this.apiClient.getCustomBaseUrl()&&!o?u=l:(u=`${l}/ws/google.cloud.aiplatform.${a}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(p,u))}else{const e=this.apiClient.getApiKey();let t="BidiGenerateContent",n="key";(null==e?void 0:e.startsWith("auth_tokens/"))&&(t="BidiGenerateContentConstrained",n="access_token"),u=`${l}/ws/google.ai.generativelanguage.${a}.GenerativeService.${t}?${n}=${e}`}let d=()=>{};const h=new Promise(e=>{d=e}),f=e.callbacks,m=this.apiClient,g={onopen:function(){var e;null===(e=null==f?void 0:f.onopen)||void 0===e||e.call(f),d({})},onmessage:e=>{!async function(e,t,n){const o=new ct;let i;i=n.data instanceof Blob?await n.data.text():n.data instanceof ArrayBuffer?(new TextDecoder).decode(n.data):n.data;const r=JSON.parse(i);if(e.isVertexAI()){const e=function(e){const t={},n=Me(e,["setupComplete"]);null!=n&&De(t,["setupComplete"],n);const o=Me(e,["serverContent"]);null!=o&&De(t,["serverContent"],o);const i=Me(e,["toolCall"]);null!=i&&De(t,["toolCall"],i);const r=Me(e,["toolCallCancellation"]);null!=r&&De(t,["toolCallCancellation"],r);const s=Me(e,["usageMetadata"]);null!=s&&De(t,["usageMetadata"],function(e){const t={},n=Me(e,["promptTokenCount"]);null!=n&&De(t,["promptTokenCount"],n);const o=Me(e,["cachedContentTokenCount"]);null!=o&&De(t,["cachedContentTokenCount"],o);const i=Me(e,["candidatesTokenCount"]);null!=i&&De(t,["responseTokenCount"],i);const r=Me(e,["toolUsePromptTokenCount"]);null!=r&&De(t,["toolUsePromptTokenCount"],r);const s=Me(e,["thoughtsTokenCount"]);null!=s&&De(t,["thoughtsTokenCount"],s);const l=Me(e,["totalTokenCount"]);null!=l&&De(t,["totalTokenCount"],l);const a=Me(e,["promptTokensDetails"]);if(null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["promptTokensDetails"],e)}const u=Me(e,["cacheTokensDetails"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["cacheTokensDetails"],e)}const c=Me(e,["candidatesTokensDetails"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["responseTokensDetails"],e)}const p=Me(e,["toolUsePromptTokensDetails"]);if(null!=p){let e=p;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["toolUsePromptTokensDetails"],e)}const d=Me(e,["trafficType"]);return null!=d&&De(t,["trafficType"],d),t}(s));const l=Me(e,["goAway"]);null!=l&&De(t,["goAway"],l);const a=Me(e,["sessionResumptionUpdate"]);null!=a&&De(t,["sessionResumptionUpdate"],a);const u=Me(e,["voiceActivityDetectionSignal"]);null!=u&&De(t,["voiceActivityDetectionSignal"],u);const c=Me(e,["voiceActivity"]);return null!=c&&De(t,["voiceActivity"],function(e){const t={},n=Me(e,["type"]);return null!=n&&De(t,["voiceActivityType"],n),t}(c)),t}(r);Object.assign(o,e)}else Object.assign(o,r);t(o)}(m,f.onmessage,e)},onerror:null!==(t=null==f?void 0:f.onerror)&&void 0!==t?t:function(e){},onclose:null!==(n=null==f?void 0:f.onclose)&&void 0!==n?n:function(e){}},E=this.webSocketFactory.create(u,function(e){const t={};return e.forEach((e,n)=>{t[n]=e}),t}(p),g);E.connect(),await h;let y=ht(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&y.startsWith("publishers/")){const e=this.apiClient.getProject(),t=this.apiClient.getLocation();e&&t&&(y=`projects/${e}/locations/${t}/`+y)}let v={};this.apiClient.isVertexAI()&&void 0===(null===(o=e.config)||void 0===o?void 0:o.responseModalities)&&(void 0===e.config?e.config={responseModalities:[k.AUDIO]}:e.config.responseModalities=[k.AUDIO]),null===(i=e.config)||void 0===i||i.generationConfig;const I=null!==(s=null===(r=e.config)||void 0===r?void 0:r.tools)&&void 0!==s?s:[],_=[];for(const A of I)if(this.isCallableTool(A)){const e=A;_.push(await e.tool())}else _.push(A);_.length>0&&(e.config.tools=_);const T={model:y,config:e.config,callbacks:e.callbacks};return v=this.apiClient.isVertexAI()?function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["setup","model"],ht(e,o));const i=Me(t,["config"]);return null!=i&&De(n,["config"],gn(i,n)),n}(this.apiClient,T):function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["setup","model"],ht(e,o));const i=Me(t,["config"]);return null!=i&&De(n,["config"],mn(i,n)),n}(this.apiClient,T),delete v.config,E.send(JSON.stringify(v)),new Zn(E,this.apiClient)}isCallableTool(e){return"callTool"in e&&"function"==typeof e.callTool}},Qn={turnComplete:!0},Zn=class{constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(null!==t.turns&&void 0!==t.turns){let n=[];try{n=St(t.turns),e.isVertexAI()||(n=n.map(e=>vn(e)))}catch(mi){throw new Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:n,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let n=[];if(null==t.functionResponses)throw new Error("functionResponses is required.");if(n=Array.isArray(t.functionResponses)?t.functionResponses:[t.functionResponses],0===n.length)throw new Error("functionResponses is required.");for(const o of n){if("object"!=typeof o||null===o||!("name"in o)||!("response"in o))throw new Error(`Could not parse function response, type '${typeof o}'.`);if(!e.isVertexAI()&&!("id"in o))throw new Error("FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.")}return{toolResponse:{functionResponses:n}}}sendClientContent(e){e=Object.assign(Object.assign({},Qn),e);const t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};t=this.apiClient.isVertexAI()?{realtimeInput:yn(e)}:{realtimeInput:En(e)},this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(null==e.functionResponses)throw new Error("Tool response parameters are required.");const t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}close(){this.conn.close()}};function eo(e){var t,n,o;if(null===(t=null==e?void 0:e.automaticFunctionCalling)||void 0===t?void 0:t.disable)return!0;let i=!1;for(const s of null!==(n=null==e?void 0:e.tools)&&void 0!==n?n:[])if(to(s)){i=!0;break}if(!i)return!0;const r=null===(o=null==e?void 0:e.automaticFunctionCalling)||void 0===o?void 0:o.maximumRemoteCalls;return!!(r&&(r<0||!Number.isInteger(r))||0==r)}function to(e){return"callTool"in e&&"function"==typeof e.callTool}function no(e){var t;const n=[];return(null===(t=null==e?void 0:e.config)||void 0===t?void 0:t.tools)?(e.config.tools.forEach((e,t)=>{if(to(e))return;const o=e;o.functionDeclarations&&o.functionDeclarations.length>0&&n.push(t)}),n):n}function oo(e){var t;return!(null===(t=null==e?void 0:e.automaticFunctionCalling)||void 0===t?void 0:t.ignoreCallHistory)}var io=class extends Ne{constructor(e){super(),this.apiClient=e,this.embedContent=async e=>{if(!this.apiClient.isVertexAI())return e.model.includes("gemini-embedding-2")&&(e.contents=St(e.contents)),await this.embedContentInternal(e);if(e.model.includes("gemini")&&"gemini-embedding-001"!==e.model||e.model.includes("maas")){const t=St(e.contents);if(t.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");const n=Object.assign(Object.assign({},e),{content:t[0],embeddingApiType:ee.EMBED_CONTENT});return await this.embedContentInternal(n)}{const t=Object.assign(Object.assign({},e),{embeddingApiType:ee.PREDICT});return await this.embedContentInternal(t)}},this.generateContent=async e=>{var t,n,o,i,r;const s=await this.processParamsMaybeAddMcpUsage(e);if(this.maybeMoveToResponseJsonSchem(e),!function(e){var t,n,o;return null!==(o=null===(n=null===(t=e.config)||void 0===t?void 0:t.tools)||void 0===n?void 0:n.some(e=>to(e)))&&void 0!==o&&o}(e)||eo(e.config))return await this.generateContentInternal(s);const l=no(e);if(l.length>0){const e=l.map(e=>`tools[${e}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${e}.`)}let a,u;const c=St(s.contents),p=null!==(o=null===(n=null===(t=s.config)||void 0===t?void 0:t.automaticFunctionCalling)||void 0===n?void 0:n.maximumRemoteCalls)&&void 0!==o?o:10;let d=0;for(;d<p&&(a=await this.generateContentInternal(s),a.functionCalls&&0!==a.functionCalls.length);){const t=a.candidates[0].content,n=[];for(const o of null!==(r=null===(i=e.config)||void 0===i?void 0:i.tools)&&void 0!==r?r:[])if(to(o)){const e=await o.callTool(a.functionCalls);n.push(...e)}d++,u={role:"user",parts:n},s.contents=St(s.contents),s.contents.push(t),s.contents.push(u),oo(s.config)&&(c.push(t),c.push(u))}return oo(s.config)&&(a.automaticFunctionCallingHistory=c),a},this.generateContentStream=async e=>{var t,n,o,i,r;if(this.maybeMoveToResponseJsonSchem(e),eo(e.config)){const t=await this.processParamsMaybeAddMcpUsage(e);return await this.generateContentStreamInternal(t)}const s=no(e);if(s.length>0){const e=s.map(e=>`tools[${e}]`).join(", ");throw new Error(`Incompatible tools found at ${e}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}const l=null===(o=null===(n=null===(t=null==e?void 0:e.config)||void 0===t?void 0:t.toolConfig)||void 0===n?void 0:n.functionCallingConfig)||void 0===o?void 0:o.streamFunctionCallArguments,a=null===(r=null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.automaticFunctionCalling)||void 0===r?void 0:r.disable;if(l&&!a)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(e)},this.generateImages=async e=>await this.generateImagesInternal(e).then(e=>{var t;let n;const o=[];if(null==e?void 0:e.generatedImages)for(const r of e.generatedImages)r&&(null==r?void 0:r.safetyAttributes)&&"Positive Prompt"===(null===(t=null==r?void 0:r.safetyAttributes)||void 0===t?void 0:t.contentType)?n=null==r?void 0:r.safetyAttributes:o.push(r);let i;return i=n?{generatedImages:o,positivePromptSafetyAttributes:n,sdkHttpResponse:e.sdkHttpResponse}:{generatedImages:o,sdkHttpResponse:e.sdkHttpResponse},i}),this.list=async e=>{var t;const n={config:Object.assign(Object.assign({},{queryBase:!0}),null==e?void 0:e.config)};if(this.apiClient.isVertexAI()&&!n.config.queryBase){if(null===(t=n.config)||void 0===t?void 0:t.filter)throw new Error("Filtering tuned models list for Gemini Enterprise Agent Platform (previously known as Vertex AI) is not currently supported");n.config.filter="labels.tune-type:*"}return new zt(Le.PAGED_ITEM_MODELS,e=>this.listInternal(e),await this.listInternal(n),n)},this.editImage=async e=>{const t={model:e.model,prompt:e.prompt,referenceImages:[],config:e.config};return e.referenceImages&&e.referenceImages&&(t.referenceImages=e.referenceImages.map(e=>e.toReferenceImageAPI())),await this.editImageInternal(t)},this.upscaleImage=async e=>{let t={numberOfImages:1,mode:"upscale"};e.config&&(t=Object.assign(Object.assign({},t),e.config));const n={model:e.model,image:e.image,upscaleFactor:e.upscaleFactor,config:t};return await this.upscaleImageInternal(n)},this.generateVideos=async e=>{var t,n,o,i,r,s;if((e.prompt||e.image||e.video)&&e.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return this.apiClient.isVertexAI()||((null===(t=e.video)||void 0===t?void 0:t.uri)&&(null===(n=e.video)||void 0===n?void 0:n.videoBytes)?e.video={uri:e.video.uri,mimeType:e.video.mimeType}:(null===(i=null===(o=e.source)||void 0===o?void 0:o.video)||void 0===i?void 0:i.uri)&&(null===(s=null===(r=e.source)||void 0===r?void 0:r.video)||void 0===s?void 0:s.videoBytes)&&(e.source.video={uri:e.source.video.uri,mimeType:e.source.video.mimeType})),await this.generateVideosInternal(e)}}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 t,n,o;const i=null===(t=e.config)||void 0===t?void 0:t.tools;if(!i)return e;const r=await Promise.all(i.map(async e=>to(e)?await e.tool():e)),s={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:r})};if(s.config.tools=r,e.config&&e.config.tools&&Bn(e.config.tools)){const t=null!==(o=null===(n=e.config.httpOptions)||void 0===n?void 0:n.headers)&&void 0!==o?o:{};let i=Object.assign({},t);0===Object.keys(i).length&&(i=this.apiClient.getDefaultHeaders()),Jn(i),s.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:i})}return s}async initAfcToolsMap(e){var t,n,o;const i=/* @__PURE__ */new Map;for(const r of null!==(n=null===(t=e.config)||void 0===t?void 0:t.tools)&&void 0!==n?n:[])if(to(r)){const e=r,t=await e.tool();for(const n of null!==(o=t.functionDeclarations)&&void 0!==o?o:[]){if(!n.name)throw new Error("Function declaration name is required.");if(i.has(n.name))throw new Error(`Duplicate tool declaration name: ${n.name}`);i.set(n.name,e)}}return i}async processAfcStream(e){var t,n,o;const i=null!==(o=null===(n=null===(t=e.config)||void 0===t?void 0:t.automaticFunctionCalling)||void 0===n?void 0:n.maximumRemoteCalls)&&void 0!==o?o:10;let r=!1,s=0;return function(e,t,n){return on(this,arguments,function*(){for(var o,l,a,u,c,p;s<i;){r&&(s++,r=!1);const g=yield nn(e.processParamsMaybeAddMcpUsage(n)),E=yield nn(e.generateContentStreamInternal(g)),y=[],v=[];try{for(var d,h=!0,f=(l=void 0,rn(E));!(o=(d=yield nn(f.next())).done);h=!0){u=d.value,h=!1;const e=u;if(yield yield nn(e),e.candidates&&(null===(c=e.candidates[0])||void 0===c?void 0:c.content)){v.push(e.candidates[0].content);for(const n of null!==(p=e.candidates[0].content.parts)&&void 0!==p?p:[])if(s<i&&n.functionCall){if(!n.functionCall.name)throw new Error("Function call name was not returned by the model.");if(!t.has(n.functionCall.name))throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${t.keys()}, mising tool: ${n.functionCall.name}`);{const e=yield nn(t.get(n.functionCall.name).callTool([n.functionCall]));y.push(...e)}}}}}catch(m){l={error:m}}finally{try{h||o||!(a=f.return)||(yield nn(a.call(f)))}finally{if(l)throw l.error}}if(!(y.length>0))break;{r=!0;const e=new qe;e.candidates=[{content:{role:"user",parts:y}}],yield yield nn(e);const t=[];t.push(...v),t.push({role:"user",parts:y}),n.contents=St(n.contents).concat(t)}}})}(this,await this.initAfcToolsMap(e),e)}async generateContentInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=Tn(this.apiClient,e);return s=Pe("{model}:generateContent",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=Cn(e),n=new qe;return Object.assign(n,t),n})}{const t=_n(this.apiClient,e);return s=Pe("{model}:generateContent",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=An(e),n=new qe;return Object.assign(n,t),n})}}async generateContentStreamInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=Tn(this.apiClient,e);return s=Pe("{model}:streamGenerateContent?alt=sse",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.requestStream({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}),r.then(function(e){return on(this,arguments,function*(){var t,n,o,i;try{for(var r,s=!0,l=rn(e);!(t=(r=yield nn(l.next())).done);s=!0){i=r.value,s=!1;const e=i,t=Cn(yield nn(e.json()));t.sdkHttpResponse={headers:e.headers};const n=new qe;Object.assign(n,t),yield yield nn(n)}}catch(a){n={error:a}}finally{try{s||t||!(o=l.return)||(yield nn(o.call(l)))}finally{if(n)throw n.error}}})})}{const t=_n(this.apiClient,e);return s=Pe("{model}:streamGenerateContent?alt=sse",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.requestStream({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}),r.then(function(e){return on(this,arguments,function*(){var t,n,o,i;try{for(var r,s=!0,l=rn(e);!(t=(r=yield nn(l.next())).done);s=!0){i=r.value,s=!1;const e=i,t=An(yield nn(e.json()));t.sdkHttpResponse={headers:e.headers};const n=new qe;Object.assign(n,t),yield yield nn(n)}}catch(a){n={error:a}}finally{try{s||t||!(o=l.return)||(yield nn(o.call(l)))}finally{if(n)throw n.error}}})})}}async embedContentInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t,n){const o={},i=Me(t,["model"]);null!=i&&De(o,["_url","model"],ht(e,i));let r=Me(n,["embeddingApiType"]);if(void 0===r&&(r="PREDICT"),"PREDICT"===r){const n=Me(t,["contents"]);if(null!=n){let t=Ot(e,n);Array.isArray(t)&&(t=t.map(e=>e)),De(o,["instances[]","content"],t)}}let s=Me(n,["embeddingApiType"]);if(void 0===s&&(s="PREDICT"),"EMBED_CONTENT"===s){const e=Me(t,["content"]);null!=e&&De(o,["content"],In(Ct(e)))}const l=Me(t,["config"]);return null!=l&&function(e,t,n){let o=Me(n,["embeddingApiType"]);if(void 0===o&&(o="PREDICT"),"PREDICT"===o){const n=Me(e,["taskType"]);void 0!==t&&null!=n&&De(t,["instances[]","task_type"],n)}else if("EMBED_CONTENT"===o){const n=Me(e,["taskType"]);void 0!==t&&null!=n&&De(t,["embedContentConfig","taskType"],n)}let i=Me(n,["embeddingApiType"]);if(void 0===i&&(i="PREDICT"),"PREDICT"===i){const n=Me(e,["title"]);void 0!==t&&null!=n&&De(t,["instances[]","title"],n)}else if("EMBED_CONTENT"===i){const n=Me(e,["title"]);void 0!==t&&null!=n&&De(t,["embedContentConfig","title"],n)}let r=Me(n,["embeddingApiType"]);if(void 0===r&&(r="PREDICT"),"PREDICT"===r){const n=Me(e,["outputDimensionality"]);void 0!==t&&null!=n&&De(t,["parameters","outputDimensionality"],n)}else if("EMBED_CONTENT"===r){const n=Me(e,["outputDimensionality"]);void 0!==t&&null!=n&&De(t,["embedContentConfig","outputDimensionality"],n)}let s=Me(n,["embeddingApiType"]);if(void 0===s&&(s="PREDICT"),"PREDICT"===s){const n=Me(e,["mimeType"]);void 0!==t&&null!=n&&De(t,["instances[]","mimeType"],n)}let l=Me(n,["embeddingApiType"]);if(void 0===l&&(l="PREDICT"),"PREDICT"===l){const n=Me(e,["autoTruncate"]);void 0!==t&&null!=n&&De(t,["parameters","autoTruncate"],n)}else if("EMBED_CONTENT"===l){const n=Me(e,["autoTruncate"]);void 0!==t&&null!=n&&De(t,["embedContentConfig","autoTruncate"],n)}let a=Me(n,["embeddingApiType"]);if(void 0===a&&(a="PREDICT"),"EMBED_CONTENT"===a){const n=Me(e,["documentOcr"]);void 0!==t&&null!=n&&De(t,["embedContentConfig","documentOcr"],n)}let u=Me(n,["embeddingApiType"]);if(void 0===u&&(u="PREDICT"),"EMBED_CONTENT"===u){const n=Me(e,["audioTrackExtraction"]);void 0!==t&&null!=n&&De(t,["embedContentConfig","audioTrackExtraction"],n)}}(l,o,n),o}(this.apiClient,e,e);return s=Pe((a=e.model).includes("gemini")&&"gemini-embedding-001"!==a||a.includes("maas")?"{model}:embedContent":"{model}:predict",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(t=>{const n=function(e,t){const n={},o=Me(e,["sdkHttpResponse"]);null!=o&&De(n,["sdkHttpResponse"],o);const i=Me(e,["predictions[]","embeddings"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["values"]);null!=n&&De(t,["values"],n);const o=Me(e,["statistics"]);return null!=o&&De(t,["statistics"],function(e){const t={},n=Me(e,["truncated"]);null!=n&&De(t,["truncated"],n);const o=Me(e,["token_count"]);return null!=o&&De(t,["tokenCount"],o),t}(o)),t}(e))),De(n,["embeddings"],e)}const r=Me(e,["metadata"]);if(null!=r&&De(n,["metadata"],r),t&&"EMBED_CONTENT"===Me(t,["embeddingApiType"])){const t=Me(e,["embedding"]),o=Me(e,["usageMetadata"]),i=Me(e,["truncated"]);if(t){const e={};o&&o.promptTokenCount&&(e.tokenCount=o.promptTokenCount),i&&(e.truncated=i),t.statistics=e,De(n,["embeddings"],[t])}}return n}(t,e),o=new He;return Object.assign(o,n),o})}{const t=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["contents"]);if(null!=i){let t=Ot(e,i);Array.isArray(t)&&(t=t.map(e=>e)),De(n,["requests[]","content"],t)}const r=Me(t,["content"]);null!=r&&vn(Ct(r));const s=Me(t,["config"]);null!=s&&function(e,t){const n=Me(e,["taskType"]);void 0!==t&&null!=n&&De(t,["requests[]","taskType"],n);const o=Me(e,["title"]);void 0!==t&&null!=o&&De(t,["requests[]","title"],o);const i=Me(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&De(t,["requests[]","outputDimensionality"],i),void 0!==Me(e,["mimeType"]))throw new Error("mimeType parameter is not supported in Gemini API.");if(void 0!==Me(e,["autoTruncate"]))throw new Error("autoTruncate parameter is not supported in Gemini API.");if(void 0!==Me(e,["documentOcr"]))throw new Error("documentOcr parameter is not supported in Gemini API.");if(void 0!==Me(e,["audioTrackExtraction"]))throw new Error("audioTrackExtraction parameter is not supported in Gemini API.")}(s,n);const l=Me(t,["model"]);return void 0!==l&&De(n,["requests[]","model"],ht(e,l)),n}(this.apiClient,e);return s=Pe("{model}:batchEmbedContents",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["embeddings"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["embeddings"],e)}const i=Me(e,["metadata"]);return null!=i&&De(t,["metadata"],i),t}(e),n=new He;return Object.assign(n,t),n})}var a}async generateImagesInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["prompt"]);null!=i&&De(n,["instances[0]","prompt"],i);const r=Me(t,["config"]);return null!=r&&function(e,t){const n=Me(e,["outputGcsUri"]);void 0!==t&&null!=n&&De(t,["parameters","storageUri"],n);const o=Me(e,["negativePrompt"]);void 0!==t&&null!=o&&De(t,["parameters","negativePrompt"],o);const i=Me(e,["numberOfImages"]);void 0!==t&&null!=i&&De(t,["parameters","sampleCount"],i);const r=Me(e,["aspectRatio"]);void 0!==t&&null!=r&&De(t,["parameters","aspectRatio"],r);const s=Me(e,["guidanceScale"]);void 0!==t&&null!=s&&De(t,["parameters","guidanceScale"],s);const l=Me(e,["seed"]);void 0!==t&&null!=l&&De(t,["parameters","seed"],l);const a=Me(e,["safetyFilterLevel"]);void 0!==t&&null!=a&&De(t,["parameters","safetySetting"],a);const u=Me(e,["personGeneration"]);void 0!==t&&null!=u&&De(t,["parameters","personGeneration"],u);const c=Me(e,["includeSafetyAttributes"]);void 0!==t&&null!=c&&De(t,["parameters","includeSafetyAttributes"],c);const p=Me(e,["includeRaiReason"]);void 0!==t&&null!=p&&De(t,["parameters","includeRaiReason"],p);const d=Me(e,["language"]);void 0!==t&&null!=d&&De(t,["parameters","language"],d);const h=Me(e,["outputMimeType"]);void 0!==t&&null!=h&&De(t,["parameters","outputOptions","mimeType"],h);const f=Me(e,["outputCompressionQuality"]);void 0!==t&&null!=f&&De(t,["parameters","outputOptions","compressionQuality"],f);const m=Me(e,["addWatermark"]);void 0!==t&&null!=m&&De(t,["parameters","addWatermark"],m);const g=Me(e,["labels"]);void 0!==t&&null!=g&&De(t,["labels"],g);const E=Me(e,["imageSize"]);void 0!==t&&null!=E&&De(t,["parameters","sampleImageSize"],E);const y=Me(e,["enhancePrompt"]);void 0!==t&&null!=y&&De(t,["parameters","enhancePrompt"],y)}(r,n),n}(this.apiClient,e);return s=Pe("{model}:predict",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["predictions"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>bn(e))),De(t,["generatedImages"],e)}const i=Me(e,["positivePromptSafetyAttributes"]);return null!=i&&De(t,["positivePromptSafetyAttributes"],Un(i)),t}(e),n=new Fe;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["prompt"]);null!=i&&De(n,["instances[0]","prompt"],i);const r=Me(t,["config"]);return null!=r&&function(e,t){if(void 0!==Me(e,["outputGcsUri"]))throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(void 0!==Me(e,["negativePrompt"]))throw new Error("negativePrompt parameter is not supported in Gemini API.");const n=Me(e,["numberOfImages"]);void 0!==t&&null!=n&&De(t,["parameters","sampleCount"],n);const o=Me(e,["aspectRatio"]);void 0!==t&&null!=o&&De(t,["parameters","aspectRatio"],o);const i=Me(e,["guidanceScale"]);if(void 0!==t&&null!=i&&De(t,["parameters","guidanceScale"],i),void 0!==Me(e,["seed"]))throw new Error("seed parameter is not supported in Gemini API.");const r=Me(e,["safetyFilterLevel"]);void 0!==t&&null!=r&&De(t,["parameters","safetySetting"],r);const s=Me(e,["personGeneration"]);void 0!==t&&null!=s&&De(t,["parameters","personGeneration"],s);const l=Me(e,["includeSafetyAttributes"]);void 0!==t&&null!=l&&De(t,["parameters","includeSafetyAttributes"],l);const a=Me(e,["includeRaiReason"]);void 0!==t&&null!=a&&De(t,["parameters","includeRaiReason"],a);const u=Me(e,["language"]);void 0!==t&&null!=u&&De(t,["parameters","language"],u);const c=Me(e,["outputMimeType"]);void 0!==t&&null!=c&&De(t,["parameters","outputOptions","mimeType"],c);const p=Me(e,["outputCompressionQuality"]);if(void 0!==t&&null!=p&&De(t,["parameters","outputOptions","compressionQuality"],p),void 0!==Me(e,["addWatermark"]))throw new Error("addWatermark parameter is not supported in Gemini API.");if(void 0!==Me(e,["labels"]))throw new Error("labels parameter is not supported in Gemini API.");const d=Me(e,["imageSize"]);if(void 0!==t&&null!=d&&De(t,["parameters","sampleImageSize"],d),void 0!==Me(e,["enhancePrompt"]))throw new Error("enhancePrompt parameter is not supported in Gemini API.")}(r,n),n}(this.apiClient,e);return s=Pe("{model}:predict",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["predictions"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["_self"]);null!=n&&De(t,["image"],function(e){const t={},n=Me(e,["bytesBase64Encoded"]);null!=n&&De(t,["imageBytes"],Gt(n));const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}(n));const o=Me(e,["raiFilteredReason"]);null!=o&&De(t,["raiFilteredReason"],o);const i=Me(e,["_self"]);return null!=i&&De(t,["safetyAttributes"],Mn(i)),t}(e))),De(t,["generatedImages"],e)}const i=Me(e,["positivePromptSafetyAttributes"]);return null!=i&&De(t,["positivePromptSafetyAttributes"],Mn(i)),t}(e),n=new Fe;return Object.assign(n,t),n})}}async editImageInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["prompt"]);null!=i&&De(n,["instances[0]","prompt"],i);const r=Me(t,["referenceImages"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["referenceImage"]);null!=n&&De(t,["referenceImage"],Nn(n));const o=Me(e,["referenceId"]);null!=o&&De(t,["referenceId"],o);const i=Me(e,["referenceType"]);null!=i&&De(t,["referenceType"],i);const r=Me(e,["maskImageConfig"]);null!=r&&De(t,["maskImageConfig"],function(e){const t={},n=Me(e,["maskMode"]);null!=n&&De(t,["maskMode"],n);const o=Me(e,["segmentationClasses"]);null!=o&&De(t,["maskClasses"],o);const i=Me(e,["maskDilation"]);return null!=i&&De(t,["dilation"],i),t}(r));const s=Me(e,["controlImageConfig"]);null!=s&&De(t,["controlImageConfig"],function(e){const t={},n=Me(e,["controlType"]);null!=n&&De(t,["controlType"],n);const o=Me(e,["enableControlImageComputation"]);return null!=o&&De(t,["computeControl"],o),t}(s));const l=Me(e,["styleImageConfig"]);null!=l&&De(t,["styleImageConfig"],l);const a=Me(e,["subjectImageConfig"]);return null!=a&&De(t,["subjectImageConfig"],a),t}(e))),De(n,["instances[0]","referenceImages"],e)}const s=Me(t,["config"]);return null!=s&&function(e,t){const n=Me(e,["outputGcsUri"]);void 0!==t&&null!=n&&De(t,["parameters","storageUri"],n);const o=Me(e,["negativePrompt"]);void 0!==t&&null!=o&&De(t,["parameters","negativePrompt"],o);const i=Me(e,["numberOfImages"]);void 0!==t&&null!=i&&De(t,["parameters","sampleCount"],i);const r=Me(e,["aspectRatio"]);void 0!==t&&null!=r&&De(t,["parameters","aspectRatio"],r);const s=Me(e,["guidanceScale"]);void 0!==t&&null!=s&&De(t,["parameters","guidanceScale"],s);const l=Me(e,["seed"]);void 0!==t&&null!=l&&De(t,["parameters","seed"],l);const a=Me(e,["safetyFilterLevel"]);void 0!==t&&null!=a&&De(t,["parameters","safetySetting"],a);const u=Me(e,["personGeneration"]);void 0!==t&&null!=u&&De(t,["parameters","personGeneration"],u);const c=Me(e,["includeSafetyAttributes"]);void 0!==t&&null!=c&&De(t,["parameters","includeSafetyAttributes"],c);const p=Me(e,["includeRaiReason"]);void 0!==t&&null!=p&&De(t,["parameters","includeRaiReason"],p);const d=Me(e,["language"]);void 0!==t&&null!=d&&De(t,["parameters","language"],d);const h=Me(e,["outputMimeType"]);void 0!==t&&null!=h&&De(t,["parameters","outputOptions","mimeType"],h);const f=Me(e,["outputCompressionQuality"]);void 0!==t&&null!=f&&De(t,["parameters","outputOptions","compressionQuality"],f);const m=Me(e,["addWatermark"]);void 0!==t&&null!=m&&De(t,["parameters","addWatermark"],m);const g=Me(e,["labels"]);void 0!==t&&null!=g&&De(t,["labels"],g);const E=Me(e,["editMode"]);void 0!==t&&null!=E&&De(t,["parameters","editMode"],E);const y=Me(e,["baseSteps"]);void 0!==t&&null!=y&&De(t,["parameters","editConfig","baseSteps"],y)}(s,n),n}(this.apiClient,e);return i=Pe("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["predictions"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>bn(e))),De(t,["generatedImages"],e)}return t}(e),n=new Ve;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["image"]);null!=i&&De(n,["instances[0]","image"],Nn(i));const r=Me(t,["upscaleFactor"]);null!=r&&De(n,["parameters","upscaleConfig","upscaleFactor"],r);const s=Me(t,["config"]);return null!=s&&function(e,t){const n=Me(e,["outputGcsUri"]);void 0!==t&&null!=n&&De(t,["parameters","storageUri"],n);const o=Me(e,["safetyFilterLevel"]);void 0!==t&&null!=o&&De(t,["parameters","safetySetting"],o);const i=Me(e,["personGeneration"]);void 0!==t&&null!=i&&De(t,["parameters","personGeneration"],i);const r=Me(e,["includeRaiReason"]);void 0!==t&&null!=r&&De(t,["parameters","includeRaiReason"],r);const s=Me(e,["outputMimeType"]);void 0!==t&&null!=s&&De(t,["parameters","outputOptions","mimeType"],s);const l=Me(e,["outputCompressionQuality"]);void 0!==t&&null!=l&&De(t,["parameters","outputOptions","compressionQuality"],l);const a=Me(e,["enhanceInputImage"]);void 0!==t&&null!=a&&De(t,["parameters","upscaleConfig","enhanceInputImage"],a);const u=Me(e,["imagePreservationFactor"]);void 0!==t&&null!=u&&De(t,["parameters","upscaleConfig","imagePreservationFactor"],u);const c=Me(e,["labels"]);void 0!==t&&null!=c&&De(t,["labels"],c);const p=Me(e,["numberOfImages"]);void 0!==t&&null!=p&&De(t,["parameters","sampleCount"],p);const d=Me(e,["mode"]);void 0!==t&&null!=d&&De(t,["parameters","mode"],d)}(s,n),n}(this.apiClient,e);return i=Pe("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["predictions"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>bn(e))),De(t,["generatedImages"],e)}return t}(e),n=new je;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["source"]);null!=i&&function(e,t){const n=Me(e,["prompt"]);void 0!==t&&null!=n&&De(t,["instances[0]","prompt"],n);const o=Me(e,["personImage"]);void 0!==t&&null!=o&&De(t,["instances[0]","personImage","image"],Nn(o));const i=Me(e,["productImages"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["productImage"]);return null!=n&&De(t,["image"],Nn(n)),t}(e))),De(t,["instances[0]","productImages"],e)}}(i,n);const r=Me(t,["config"]);return null!=r&&function(e,t){const n=Me(e,["numberOfImages"]);void 0!==t&&null!=n&&De(t,["parameters","sampleCount"],n);const o=Me(e,["baseSteps"]);void 0!==t&&null!=o&&De(t,["parameters","baseSteps"],o);const i=Me(e,["outputGcsUri"]);void 0!==t&&null!=i&&De(t,["parameters","storageUri"],i);const r=Me(e,["seed"]);void 0!==t&&null!=r&&De(t,["parameters","seed"],r);const s=Me(e,["safetyFilterLevel"]);void 0!==t&&null!=s&&De(t,["parameters","safetySetting"],s);const l=Me(e,["personGeneration"]);void 0!==t&&null!=l&&De(t,["parameters","personGeneration"],l);const a=Me(e,["addWatermark"]);void 0!==t&&null!=a&&De(t,["parameters","addWatermark"],a);const u=Me(e,["outputMimeType"]);void 0!==t&&null!=u&&De(t,["parameters","outputOptions","mimeType"],u);const c=Me(e,["outputCompressionQuality"]);void 0!==t&&null!=c&&De(t,["parameters","outputOptions","compressionQuality"],c);const p=Me(e,["enhancePrompt"]);void 0!==t&&null!=p&&De(t,["parameters","enhancePrompt"],p);const d=Me(e,["labels"]);void 0!==t&&null!=d&&De(t,["labels"],d)}(r,n),n}(this.apiClient,e);return i=Pe("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=Me(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>bn(e))),De(t,["generatedImages"],e)}return t}(e),n=new Be;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["source"]);null!=i&&function(e,t){const n=Me(e,["prompt"]);void 0!==t&&null!=n&&De(t,["instances[0]","prompt"],n);const o=Me(e,["image"]);void 0!==t&&null!=o&&De(t,["instances[0]","image"],Nn(o));const i=Me(e,["scribbleImage"]);void 0!==t&&null!=i&&De(t,["instances[0]","scribble"],function(e){const t={},n=Me(e,["image"]);return null!=n&&De(t,["image"],Nn(n)),t}(i))}(i,n);const r=Me(t,["config"]);return null!=r&&function(e,t){const n=Me(e,["mode"]);void 0!==t&&null!=n&&De(t,["parameters","mode"],n);const o=Me(e,["maxPredictions"]);void 0!==t&&null!=o&&De(t,["parameters","maxPredictions"],o);const i=Me(e,["confidenceThreshold"]);void 0!==t&&null!=i&&De(t,["parameters","confidenceThreshold"],i);const r=Me(e,["maskDilation"]);void 0!==t&&null!=r&&De(t,["parameters","maskDilation"],r);const s=Me(e,["binaryColorThreshold"]);void 0!==t&&null!=s&&De(t,["parameters","binaryColorThreshold"],s);const l=Me(e,["labels"]);void 0!==t&&null!=l&&De(t,["labels"],l)}(r,n),n}(this.apiClient,e);return i=Pe("{model}:predict",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=Me(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["_self"]);null!=n&&De(t,["mask"],wn(n));const o=Me(e,["labels"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["labels"],e)}return t}(e))),De(t,["generatedMasks"],e)}return t}(e),n=new Je;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["model"]);return null!=o&&De(n,["_url","name"],ht(e,o)),n}(this.apiClient,e);return s=Pe("{name}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>Dn(e))}{const t=function(e,t){const n={},o=Me(t,["model"]);return null!=o&&De(n,["_url","name"],ht(e,o)),n}(this.apiClient,e);return s=Pe("{name}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Pn(e))}}async listInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["config"]);return null!=o&&function(e,t,n){const o=Me(t,["pageSize"]);void 0!==n&&null!=o&&De(n,["_query","pageSize"],o);const i=Me(t,["pageToken"]);void 0!==n&&null!=i&&De(n,["_query","pageToken"],i);const r=Me(t,["filter"]);void 0!==n&&null!=r&&De(n,["_query","filter"],r);const s=Me(t,["queryBase"]);void 0!==n&&null!=s&&De(n,["_url","models_url"],Lt(e,s))}(e,o,n),n}(this.apiClient,e);return s=Pe("{models_url}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["nextPageToken"]);null!=o&&De(t,["nextPageToken"],o);const i=Me(e,["_self"]);if(null!=i){let e=kt(i);Array.isArray(e)&&(e=e.map(e=>Dn(e))),De(t,["models"],e)}return t}(e),n=new Ye;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=Me(t,["config"]);return null!=o&&function(e,t,n){const o=Me(t,["pageSize"]);void 0!==n&&null!=o&&De(n,["_query","pageSize"],o);const i=Me(t,["pageToken"]);void 0!==n&&null!=i&&De(n,["_query","pageToken"],i);const r=Me(t,["filter"]);void 0!==n&&null!=r&&De(n,["_query","filter"],r);const s=Me(t,["queryBase"]);void 0!==n&&null!=s&&De(n,["_url","models_url"],Lt(e,s))}(e,o,n),n}(this.apiClient,e);return s=Pe("{models_url}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["nextPageToken"]);null!=o&&De(t,["nextPageToken"],o);const i=Me(e,["_self"]);if(null!=i){let e=kt(i);Array.isArray(e)&&(e=e.map(e=>Pn(e))),De(t,["models"],e)}return t}(e),n=new Ye;return Object.assign(n,t),n})}}async update(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["config"]);return null!=i&&function(e,t){const n=Me(e,["displayName"]);void 0!==t&&null!=n&&De(t,["displayName"],n);const o=Me(e,["description"]);void 0!==t&&null!=o&&De(t,["description"],o);const i=Me(e,["defaultCheckpointId"]);void 0!==t&&null!=i&&De(t,["defaultCheckpointId"],i)}(i,n),n}(this.apiClient,e);return s=Pe("{model}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"PATCH",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>Dn(e))}{const t=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","name"],ht(e,o));const i=Me(t,["config"]);return null!=i&&function(e,t){const n=Me(e,["displayName"]);void 0!==t&&null!=n&&De(t,["displayName"],n);const o=Me(e,["description"]);void 0!==t&&null!=o&&De(t,["description"],o);const i=Me(e,["defaultCheckpointId"]);void 0!==t&&null!=i&&De(t,["defaultCheckpointId"],i)}(i,n),n}(this.apiClient,e);return s=Pe("{name}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"PATCH",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>Pn(e))}}async delete(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["model"]);return null!=o&&De(n,["_url","name"],ht(e,o)),n}(this.apiClient,e);return s=Pe("{name}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);return null!=n&&De(t,["sdkHttpResponse"],n),t}(e),n=new $e;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=Me(t,["model"]);return null!=o&&De(n,["_url","name"],ht(e,o)),n}(this.apiClient,e);return s=Pe("{name}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"DELETE",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);return null!=n&&De(t,["sdkHttpResponse"],n),t}(e),n=new $e;return Object.assign(n,t),n})}}async countTokens(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["contents"]);if(null!=i){let e=St(i);Array.isArray(e)&&(e=e.map(e=>In(e))),De(n,["contents"],e)}const r=Me(t,["config"]);return null!=r&&function(e,t){const n=Me(e,["systemInstruction"]);void 0!==t&&null!=n&&De(t,["systemInstruction"],In(Ct(n)));const o=Me(e,["tools"]);if(void 0!==t&&null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>Gn(e))),De(t,["tools"],e)}const i=Me(e,["generationConfig"]);void 0!==t&&null!=i&&De(t,["generationConfig"],function(e){const t={},n=Me(e,["modelSelectionConfig"]);null!=n&&De(t,["modelConfig"],n);const o=Me(e,["responseJsonSchema"]);null!=o&&De(t,["responseJsonSchema"],o);const i=Me(e,["audioTimestamp"]);null!=i&&De(t,["audioTimestamp"],i);const r=Me(e,["candidateCount"]);null!=r&&De(t,["candidateCount"],r);const s=Me(e,["enableAffectiveDialog"]);null!=s&&De(t,["enableAffectiveDialog"],s);const l=Me(e,["frequencyPenalty"]);null!=l&&De(t,["frequencyPenalty"],l);const a=Me(e,["logprobs"]);null!=a&&De(t,["logprobs"],a);const u=Me(e,["maxOutputTokens"]);null!=u&&De(t,["maxOutputTokens"],u);const c=Me(e,["mediaResolution"]);null!=c&&De(t,["mediaResolution"],c);const p=Me(e,["presencePenalty"]);null!=p&&De(t,["presencePenalty"],p);const d=Me(e,["responseLogprobs"]);null!=d&&De(t,["responseLogprobs"],d);const h=Me(e,["responseMimeType"]);null!=h&&De(t,["responseMimeType"],h);const f=Me(e,["responseModalities"]);null!=f&&De(t,["responseModalities"],f);const m=Me(e,["responseSchema"]);null!=m&&De(t,["responseSchema"],m);const g=Me(e,["routingConfig"]);null!=g&&De(t,["routingConfig"],g);const E=Me(e,["seed"]);null!=E&&De(t,["seed"],E);const y=Me(e,["speechConfig"]);null!=y&&De(t,["speechConfig"],y);const v=Me(e,["stopSequences"]);null!=v&&De(t,["stopSequences"],v);const I=Me(e,["temperature"]);null!=I&&De(t,["temperature"],I);const _=Me(e,["thinkingConfig"]);null!=_&&De(t,["thinkingConfig"],_);const T=Me(e,["topK"]);null!=T&&De(t,["topK"],T);const A=Me(e,["topP"]);if(null!=A&&De(t,["topP"],A),void 0!==Me(e,["enableEnhancedCivicAnswers"]))throw new Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(i))}(r,n),n}(this.apiClient,e);return s=Pe("{model}:countTokens",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["totalTokens"]);return null!=o&&De(t,["totalTokens"],o),t}(e),n=new Ke;return Object.assign(n,t),n})}{const t=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["contents"]);if(null!=i){let e=St(i);Array.isArray(e)&&(e=e.map(e=>vn(e))),De(n,["contents"],e)}const r=Me(t,["config"]);return null!=r&&function(e){if(void 0!==Me(e,["systemInstruction"]))throw new Error("systemInstruction parameter is not supported in Gemini API.");if(void 0!==Me(e,["tools"]))throw new Error("tools parameter is not supported in Gemini API.");if(void 0!==Me(e,["generationConfig"]))throw new Error("generationConfig parameter is not supported in Gemini API.")}(r),n}(this.apiClient,e);return s=Pe("{model}:countTokens",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["totalTokens"]);null!=o&&De(t,["totalTokens"],o);const i=Me(e,["cachedContentTokenCount"]);return null!=i&&De(t,["cachedContentTokenCount"],i),t}(e),n=new Ke;return Object.assign(n,t),n})}}async computeTokens(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["_url","model"],ht(e,o));const i=Me(t,["contents"]);if(null!=i){let e=St(i);Array.isArray(e)&&(e=e.map(e=>In(e))),De(n,["contents"],e)}return n}(this.apiClient,e);return i=Pe("{model}:computeTokens",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["tokensInfo"]);if(null!=o){let e=o;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["tokensInfo"],e)}return t}(e),n=new We;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=Sn(this.apiClient,e);return s=Pe("{model}:predictLongRunning",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r.then(e=>{const t=function(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["name"],n);const o=Me(e,["metadata"]);null!=o&&De(t,["metadata"],o);const i=Me(e,["done"]);null!=i&&De(t,["done"],i);const r=Me(e,["error"]);null!=r&&De(t,["error"],r);const s=Me(e,["response"]);return null!=s&&De(t,["response"],function(e){const t={},n=Me(e,["videos"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["_self"]);return null!=n&&De(t,["video"],function(e){const t={},n=Me(e,["gcsUri"]);null!=n&&De(t,["uri"],n);const o=Me(e,["bytesBase64Encoded"]);null!=o&&De(t,["videoBytes"],Gt(o));const i=Me(e,["mimeType"]);return null!=i&&De(t,["mimeType"],i),t}(n)),t}(e))),De(t,["generatedVideos"],e)}const o=Me(e,["raiMediaFilteredCount"]);null!=o&&De(t,["raiMediaFilteredCount"],o);const i=Me(e,["raiMediaFilteredReasons"]);return null!=i&&De(t,["raiMediaFilteredReasons"],i),t}(s)),t}(e),n=new ze;return Object.assign(n,t),n})}{const t=On(this.apiClient,e);return s=Pe("{model}:predictLongRunning",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r.then(e=>{const t=function(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["name"],n);const o=Me(e,["metadata"]);null!=o&&De(t,["metadata"],o);const i=Me(e,["done"]);null!=i&&De(t,["done"],i);const r=Me(e,["error"]);null!=r&&De(t,["error"],r);const s=Me(e,["response","generateVideoResponse"]);return null!=s&&De(t,["response"],function(e){const t={},n=Me(e,["generatedSamples"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["video"]);return null!=n&&De(t,["video"],function(e){const t={},n=Me(e,["uri"]);null!=n&&De(t,["uri"],n);const o=Me(e,["encodedVideo"]);null!=o&&De(t,["videoBytes"],Gt(o));const i=Me(e,["encoding"]);return null!=i&&De(t,["mimeType"],i),t}(n)),t}(e))),De(t,["generatedVideos"],e)}const o=Me(e,["raiMediaFilteredCount"]);null!=o&&De(t,["raiMediaFilteredCount"],o);const i=Me(e,["raiMediaFilteredReasons"]);return null!=i&&De(t,["raiMediaFilteredReasons"],i),t}(s)),t}(e),n=new ze;return Object.assign(n,t),n})}}},ro=class extends Ne{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){const t=e.operation,n=e.config;if(void 0===t.name||""===t.name)throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const e=t.name.split("/operations/")[0];let o;n&&"httpOptions"in n&&(o=n.httpOptions);const i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:e,config:{httpOptions:o}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{const e=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async get(e){const t=e.operation,n=e.config;if(void 0===t.name||""===t.name)throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const e=t.name.split("/operations/")[0];let o;n&&"httpOptions"in n&&(o=n.httpOptions);const i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:e,config:{httpOptions:o}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{const e=await this.getVideosOperationInternal({operationName:t.name,config:n});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=Me(e,["operationName"]);return null!=n&&De(t,["_url","operationName"],n),t}(e);return s=Pe("{operationName}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),r}{const t=function(e){const t={},n=Me(e,["operationName"]);return null!=n&&De(t,["_url","operationName"],n),t}(e);return s=Pe("{operationName}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json()),r}}async fetchPredictVideosOperationInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e){const t={},n=Me(e,["operationName"]);null!=n&&De(t,["operationName"],n);const o=Me(e,["resourceName"]);return null!=o&&De(t,["_url","resourceName"],o),t}(e);return i=Pe("{resourceName}:fetchPredictOperation",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function so(e){if(void 0!==Me(e,["languageCodes"]))throw new Error("languageCodes parameter is not supported in Gemini API.");return{}}function lo(e,t,n){const o=Me(t,["expireTime"]);void 0!==n&&null!=o&&De(n,["expireTime"],o);const i=Me(t,["newSessionExpireTime"]);void 0!==n&&null!=i&&De(n,["newSessionExpireTime"],i);const r=Me(t,["uses"]);void 0!==n&&null!=r&&De(n,["uses"],r);const s=Me(t,["liveConnectConstraints"]);void 0!==n&&null!=s&&De(n,["bidiGenerateContentSetup"],function(e,t){const n={},o=Me(t,["model"]);null!=o&&De(n,["setup","model"],ht(e,o));const i=Me(t,["config"]);return null!=i&&De(n,["config"],function(e,t){const n=Me(e,["generationConfig"]);void 0!==t&&null!=n&&De(t,["setup","generationConfig"],n);const o=Me(e,["responseModalities"]);void 0!==t&&null!=o&&De(t,["setup","generationConfig","responseModalities"],o);const i=Me(e,["temperature"]);void 0!==t&&null!=i&&De(t,["setup","generationConfig","temperature"],i);const r=Me(e,["topP"]);void 0!==t&&null!=r&&De(t,["setup","generationConfig","topP"],r);const s=Me(e,["topK"]);void 0!==t&&null!=s&&De(t,["setup","generationConfig","topK"],s);const l=Me(e,["maxOutputTokens"]);void 0!==t&&null!=l&&De(t,["setup","generationConfig","maxOutputTokens"],l);const a=Me(e,["mediaResolution"]);void 0!==t&&null!=a&&De(t,["setup","generationConfig","mediaResolution"],a);const u=Me(e,["seed"]);void 0!==t&&null!=u&&De(t,["setup","generationConfig","seed"],u);const c=Me(e,["speechConfig"]);void 0!==t&&null!=c&&De(t,["setup","generationConfig","speechConfig"],Nt(c));const p=Me(e,["thinkingConfig"]);void 0!==t&&null!=p&&De(t,["setup","generationConfig","thinkingConfig"],p);const d=Me(e,["enableAffectiveDialog"]);void 0!==t&&null!=d&&De(t,["setup","generationConfig","enableAffectiveDialog"],d);const h=Me(e,["systemInstruction"]);void 0!==t&&null!=h&&De(t,["setup","systemInstruction"],function(e){const t={},n=Me(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["mediaResolution"]);null!=n&&De(t,["mediaResolution"],n);const o=Me(e,["codeExecutionResult"]);null!=o&&De(t,["codeExecutionResult"],o);const i=Me(e,["executableCode"]);null!=i&&De(t,["executableCode"],i);const r=Me(e,["fileData"]);null!=r&&De(t,["fileData"],function(e){const t={};if(void 0!==Me(e,["displayName"]))throw new Error("displayName parameter is not supported in Gemini API.");const n=Me(e,["fileUri"]);null!=n&&De(t,["fileUri"],n);const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}(r));const s=Me(e,["functionCall"]);null!=s&&De(t,["functionCall"],function(e){const t={},n=Me(e,["id"]);null!=n&&De(t,["id"],n);const o=Me(e,["args"]);null!=o&&De(t,["args"],o);const i=Me(e,["name"]);if(null!=i&&De(t,["name"],i),void 0!==Me(e,["partialArgs"]))throw new Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==Me(e,["willContinue"]))throw new Error("willContinue parameter is not supported in Gemini API.");return t}(s));const l=Me(e,["functionResponse"]);null!=l&&De(t,["functionResponse"],l);const a=Me(e,["inlineData"]);null!=a&&De(t,["inlineData"],function(e){const t={},n=Me(e,["data"]);if(null!=n&&De(t,["data"],n),void 0!==Me(e,["displayName"]))throw new Error("displayName parameter is not supported in Gemini API.");const o=Me(e,["mimeType"]);return null!=o&&De(t,["mimeType"],o),t}(a));const u=Me(e,["text"]);null!=u&&De(t,["text"],u);const c=Me(e,["thought"]);null!=c&&De(t,["thought"],c);const p=Me(e,["thoughtSignature"]);null!=p&&De(t,["thoughtSignature"],p);const d=Me(e,["videoMetadata"]);null!=d&&De(t,["videoMetadata"],d);const h=Me(e,["toolCall"]);null!=h&&De(t,["toolCall"],h);const f=Me(e,["toolResponse"]);null!=f&&De(t,["toolResponse"],f);const m=Me(e,["partMetadata"]);return null!=m&&De(t,["partMetadata"],m),t}(e))),De(t,["parts"],e)}const o=Me(e,["role"]);return null!=o&&De(t,["role"],o),t}(Ct(h)));const f=Me(e,["tools"]);if(void 0!==t&&null!=f){let e=Dt(f);Array.isArray(e)&&(e=e.map(e=>function(e){const t={};if(void 0!==Me(e,["retrieval"]))throw new Error("retrieval parameter is not supported in Gemini API.");const n=Me(e,["computerUse"]);null!=n&&De(t,["computerUse"],n);const o=Me(e,["fileSearch"]);null!=o&&De(t,["fileSearch"],o);const i=Me(e,["googleSearch"]);null!=i&&De(t,["googleSearch"],function(e){const t={},n=Me(e,["searchTypes"]);if(null!=n&&De(t,["searchTypes"],n),void 0!==Me(e,["blockingConfidence"]))throw new Error("blockingConfidence parameter is not supported in Gemini API.");if(void 0!==Me(e,["excludeDomains"]))throw new Error("excludeDomains parameter is not supported in Gemini API.");const o=Me(e,["timeRangeFilter"]);return null!=o&&De(t,["timeRangeFilter"],o),t}(i));const r=Me(e,["googleMaps"]);null!=r&&De(t,["googleMaps"],function(e){const t={},n=Me(e,["authConfig"]);null!=n&&De(t,["authConfig"],function(e){const t={},n=Me(e,["apiKey"]);if(null!=n&&De(t,["apiKey"],n),void 0!==Me(e,["apiKeyConfig"]))throw new Error("apiKeyConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["authType"]))throw new Error("authType parameter is not supported in Gemini API.");if(void 0!==Me(e,["googleServiceAccountConfig"]))throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["httpBasicAuthConfig"]))throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["oauthConfig"]))throw new Error("oauthConfig parameter is not supported in Gemini API.");if(void 0!==Me(e,["oidcConfig"]))throw new Error("oidcConfig parameter is not supported in Gemini API.");return t}(n));const o=Me(e,["enableWidget"]);return null!=o&&De(t,["enableWidget"],o),t}(r));const s=Me(e,["codeExecution"]);if(null!=s&&De(t,["codeExecution"],s),void 0!==Me(e,["enterpriseWebSearch"]))throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const l=Me(e,["functionDeclarations"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["functionDeclarations"],e)}const a=Me(e,["googleSearchRetrieval"]);if(null!=a&&De(t,["googleSearchRetrieval"],a),void 0!==Me(e,["parallelAiSearch"]))throw new Error("parallelAiSearch parameter is not supported in Gemini API.");const u=Me(e,["urlContext"]);null!=u&&De(t,["urlContext"],u);const c=Me(e,["mcpServers"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["mcpServers"],e)}return t}(Pt(e)))),De(t,["setup","tools"],e)}const m=Me(e,["sessionResumption"]);void 0!==t&&null!=m&&De(t,["setup","sessionResumption"],function(e){const t={},n=Me(e,["handle"]);if(null!=n&&De(t,["handle"],n),void 0!==Me(e,["transparent"]))throw new Error("transparent parameter is not supported in Gemini API.");return t}(m));const g=Me(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&De(t,["setup","inputAudioTranscription"],so(g));const E=Me(e,["outputAudioTranscription"]);void 0!==t&&null!=E&&De(t,["setup","outputAudioTranscription"],so(E));const y=Me(e,["realtimeInputConfig"]);void 0!==t&&null!=y&&De(t,["setup","realtimeInputConfig"],y);const v=Me(e,["contextWindowCompression"]);void 0!==t&&null!=v&&De(t,["setup","contextWindowCompression"],v);const I=Me(e,["proactivity"]);if(void 0!==t&&null!=I&&De(t,["setup","proactivity"],I),void 0!==Me(e,["explicitVadSignal"]))throw new Error("explicitVadSignal parameter is not supported in Gemini API.");const _=Me(e,["avatarConfig"]);void 0!==t&&null!=_&&De(t,["setup","avatarConfig"],_);const T=Me(e,["safetySettings"]);if(void 0!==t&&null!=T){let e=T;Array.isArray(e)&&(e=e.map(e=>function(e){const t={},n=Me(e,["category"]);if(null!=n&&De(t,["category"],n),void 0!==Me(e,["method"]))throw new Error("method parameter is not supported in Gemini API.");const o=Me(e,["threshold"]);return null!=o&&De(t,["threshold"],o),t}(e))),De(t,["setup","safetySettings"],e)}return{}}(i,n)),n}(e,s));const l=Me(t,["lockAdditionalFields"]);return void 0!==n&&null!=l&&De(n,["fieldMask"],l),{}}var ao=class extends Ne{constructor(e){super(),this.apiClient=e}async create(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{const s=function(e,t){const n={},o=Me(t,["config"]);return null!=o&&De(n,["config"],lo(e,o,n)),n}(this.apiClient,e);i=Pe("auth_tokens",s._url),r=s._query,delete s.config,delete s._url,delete s._query;const l=function(e,t){let n=null;const o=e.bidiGenerateContentSetup;if("object"==typeof o&&null!==o&&"setup"in o){const t=o.setup;"object"==typeof t&&null!==t?(e.bidiGenerateContentSetup=t,n=t):delete e.bidiGenerateContentSetup}else void 0!==o&&delete e.bidiGenerateContentSetup;const i=e.fieldMask;if(n){const o=function(e){const t=[];for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const o=e[n];if("object"==typeof o&&null!=o&&Object.keys(o).length>0){const e=Object.keys(o).map(e=>`${n}.${e}`);t.push(...e)}else t.push(n)}return t.join(",")}(n);if(Array.isArray(null==t?void 0:t.lockAdditionalFields)&&0===(null==t?void 0:t.lockAdditionalFields.length))o?e.fieldMask=o:delete e.fieldMask;else if((null==t?void 0:t.lockAdditionalFields)&&t.lockAdditionalFields.length>0&&null!==i&&Array.isArray(i)&&i.length>0){const t=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let n=[];i.length>0&&(n=i.map(e=>t.includes(e)?`generationConfig.${e}`:e));const r=[];o&&r.push(o),n.length>0&&r.push(...n),r.length>0?e.fieldMask=r.join(","):delete e.fieldMask}else delete e.fieldMask}else null!==i&&Array.isArray(i)&&i.length>0?e.fieldMask=i.join(","):delete e.fieldMask;return e}(s,e.config);return o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}};var uo=class extends Ne{constructor(e){super(),this.apiClient=e,this.list=async e=>new zt(Le.PAGED_ITEM_DOCUMENTS,t=>this.listInternal({parent:e.parent,config:t.config}),await this.listInternal(e),e)}async get(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["name"]);return null!=n&&De(t,["_url","name"],n),t}(e);return i=Pe("{name}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async delete(e){var t,n;let o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const r=function(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["_url","name"],n);const o=Me(e,["config"]);return null!=o&&function(e,t){const n=Me(e,["force"]);void 0!==t&&null!=n&&De(t,["_query","force"],n)}(o,t),t}(e);o=Pe("{name}",r._url),i=r._query,delete r._url,delete r._query,await this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(r),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal})}}async listInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["parent"]);null!=n&&De(t,["_url","parent"],n);const o=Me(e,["config"]);return null!=o&&function(e,t){const n=Me(e,["pageSize"]);void 0!==t&&null!=n&&De(t,["_query","pageSize"],n);const o=Me(e,["pageToken"]);void 0!==t&&null!=o&&De(t,["_query","pageToken"],o)}(o,t),t}(e);return i=Pe("{parent}/documents",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["nextPageToken"]);null!=o&&De(t,["nextPageToken"],o);const i=Me(e,["documents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["documents"],e)}return t}(e),n=new tt;return Object.assign(n,t),n})}}},co=class extends Ne{constructor(e,t=new uo(e)){super(),this.apiClient=e,this.documents=t,this.list=async(e={})=>new zt(Le.PAGED_ITEM_FILE_SEARCH_STORES,e=>this.listInternal(e),await this.listInternal(e),e)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async downloadMedia(e,t){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");const n=new URL(e,"http://dummy.com");let o=n.pathname;if(o.startsWith("/")&&(o=o.slice(1)),!o.includes("/media/"))throw new Error(`Invalid uri format: ${e}. Expected to contain /media/`);const i={};n.searchParams.forEach((e,t)=>{i[t]=e}),i.alt="media";const r=Object.assign({},null==t?void 0:t.httpOptions),s=await this.apiClient.request({path:o,httpMethod:"GET",queryParams:i,httpOptions:r});if(s instanceof ke){const e=await s.responseInternal.arrayBuffer();return new Uint8Array(e)}throw new Error("Unexpected response type from downloadMedia")}async create(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e,t){const n={},o=Me(t,["config"]);return null!=o&&function(e,t,n){const o=Me(t,["displayName"]);void 0!==n&&null!=o&&De(n,["displayName"],o);const i=Me(t,["embeddingModel"]);void 0!==n&&null!=i&&De(n,["embeddingModel"],ht(e,i))}(e,o,n),n}(this.apiClient,e);return i=Pe("fileSearchStores",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async get(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["name"]);return null!=n&&De(t,["_url","name"],n),t}(e);return i=Pe("{name}",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>e)}}async delete(e){var t,n;let o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const r=function(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["_url","name"],n);const o=Me(e,["config"]);return null!=o&&function(e,t){const n=Me(e,["force"]);void 0!==t&&null!=n&&De(t,["_query","force"],n)}(o,t),t}(e);o=Pe("{name}",r._url),i=r._query,delete r._url,delete r._query,await this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(r),httpMethod:"DELETE",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal})}}async listInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["config"]);return null!=n&&function(e,t){const n=Me(e,["pageSize"]);void 0!==t&&null!=n&&De(t,["_query","pageSize"],n);const o=Me(e,["pageToken"]);void 0!==t&&null!=o&&De(t,["_query","pageToken"],o)}(n,t),t}(e);return i=Pe("fileSearchStores",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["nextPageToken"]);null!=o&&De(t,["nextPageToken"],o);const i=Me(e,["fileSearchStores"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["fileSearchStores"],e)}return t}(e),n=new nt;return Object.assign(n,t),n})}}async uploadToFileSearchStoreInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["fileSearchStoreName"]);null!=n&&De(t,["_url","file_search_store_name"],n);const o=Me(e,["config"]);return null!=o&&kn(o,t),t}(e);return i=Pe("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);return null!=n&&De(t,["sdkHttpResponse"],n),t}(e),n=new ot;return Object.assign(n,t),n})}}async importFile(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["fileSearchStoreName"]);null!=n&&De(t,["_url","file_search_store_name"],n);const o=Me(e,["fileName"]);null!=o&&De(t,["fileName"],o);const i=Me(e,["config"]);return null!=i&&function(e,t){const n=Me(e,["customMetadata"]);if(void 0!==t&&null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["customMetadata"],e)}const o=Me(e,["chunkingConfig"]);void 0!==t&&null!=o&&De(t,["chunkingConfig"],o)}(i,t),t}(e);return i=Pe("{file_search_store_name}:importFile",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json()),o.then(e=>{const t=function(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["name"],n);const o=Me(e,["metadata"]);null!=o&&De(t,["metadata"],o);const i=Me(e,["done"]);null!=i&&De(t,["done"],i);const r=Me(e,["error"]);null!=r&&De(t,["error"],r);const s=Me(e,["response"]);return null!=s&&De(t,["response"],function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["parent"]);null!=o&&De(t,["parent"],o);const i=Me(e,["documentName"]);return null!=i&&De(t,["documentName"],i),t}(s)),t}(e),n=new it;return Object.assign(n,t),n})}}},po=function(){const{crypto:e}=globalThis;if(null==e?void 0:e.randomUUID)return po=e.randomUUID.bind(e),e.randomUUID();const t=/* @__PURE__ */new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^n()&15>>+e/4).toString(16))};function ho(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var fo=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch(mi){}try{return new Error(JSON.stringify(e))}catch(t){}}return new Error(e)},mo=class extends Error{},go=class e extends mo{constructor(t,n,o,i){super(`${e.makeMessage(t,n,o)}`),this.status=t,this.headers=i,this.error=n}static makeMessage(e,t,n){const o=(null==t?void 0:t.message)?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(t,n,o,i){if(!t||!i)return new yo({message:o,cause:fo(n)});const r=n;return 400===t?new Io(t,r,o,i):401===t?new _o(t,r,o,i):403===t?new To(t,r,o,i):404===t?new Ao(t,r,o,i):409===t?new Co(t,r,o,i):422===t?new Oo(t,r,o,i):429===t?new So(t,r,o,i):t>=500?new bo(t,r,o,i):new e(t,r,o,i)}},Eo=class extends go{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},yo=class extends go{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},vo=class extends yo{constructor({message:e}={}){super({message:null!=e?e:"Request timed out."})}},Io=class extends go{},_o=class extends go{},To=class extends go{},Ao=class extends go{},Co=class extends go{},Oo=class extends go{},So=class extends go{},bo=class extends go{},wo=/^[a-z][a-z0-9+.-]*:/i,Ro=e=>(Ro=Array.isArray)(e),No=Ro;function Po(e){if(!e)return!0;for(const t in e)return!1;return!0}function Do(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Mo(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Do({start(){},async pull(e){const{done:n,value:o}=await t.next();n?e.close():e.enqueue(o)},async cancel(){var e;await(null===(e=t.return)||void 0===e?void 0:e.call(t))}})}function Uo(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return(null==e?void 0:e.done)&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var Go=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),xo=()=>{var e;if("undefined"==typeof File){const{process:t}=globalThis,n="string"==typeof(null===(e=null==t?void 0:t.versions)||void 0===e?void 0:e.node)&&parseInt(t.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 Lo(e,t,n){return xo(),new File(e,null!=t?t:"unknown_file",n)}var ko=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function qo(e){var t,n,o,i,r;let s=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)s.push(e);else if(ko(e))s.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!(e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator])(e)){const t=null===(r=null==e?void 0:e.constructor)||void 0===r?void 0:r.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){return"object"!=typeof e||null===e?"":`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(", ")}]`}(e)}`)}try{for(var l,a=!0,u=rn(e);!(t=(l=await u.next()).done);a=!0){i=l.value,a=!1;const e=i;s.push(...await qo(e))}}catch(c){n={error:c}}finally{try{a||t||!(o=u.return)||await o.call(u)}finally{if(n)throw n.error}}}return s}var Ho=class{constructor(e){this._client=e}};function Fo(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}Ho._key=[];var Vo=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.create(null)),jo=(e=Fo)=>function(t,...n){if(1===t.length)return t[0];let o=!1;const i=[],r=t.reduce((t,r,s)=>{var l,a,u;/[?#]/.test(r)&&(o=!0);const c=n[s];let p=(o?encodeURIComponent:e)(""+c);return s!==n.length&&(null==c||"object"==typeof c&&c.toString===(null===(u=Object.getPrototypeOf(null!==(a=Object.getPrototypeOf(null!==(l=c.hasOwnProperty)&&void 0!==l?l:Vo))&&void 0!==a?a:Vo))||void 0===u?void 0:u.toString))&&(p=c+"",i.push({start:t.length+r.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),t+r+(s===n.length?"":p)},""),s=r.split(/[?#]/,1)[0],l=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let a;for(;null!==(a=l.exec(s));){const e=a[0].startsWith("/"),t=e?1:0,n=e?a[0].slice(1):a[0];i.push({start:a.index+t,length:n.length,error:`Value "${n}" can't be safely passed as a path parameter`})}if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0;const t=i.reduce((t,n)=>{const o=" ".repeat(n.start-e),i="^".repeat(n.length);return e=n.start+n.length,t+o+i},"");throw new mo(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join("\n")}\n${r}\n${t}`)}return r},Bo=/* @__PURE__ */jo(Fo),Jo=class extends Ho{create(e,t){var n;const{api_version:o=this._client.apiVersion}=e,i=tn(e,["api_version"]);if("model"in i&&"agent_config"in i)throw new mo("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in i&&"generation_config"in i)throw new mo("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(Bo`/${o}/interactions`,Object.assign(Object.assign({body:i},t),{stream:null!==(n=e.stream)&&void 0!==n&&n}))}delete(e,t={},n){const{api_version:o=this._client.apiVersion}=null!=t?t:{};return this._client.delete(Bo`/${o}/interactions/${e}`,n)}cancel(e,t={},n){const{api_version:o=this._client.apiVersion}=null!=t?t:{};return this._client.post(Bo`/${o}/interactions/${e}/cancel`,n)}get(e,t={},n){var o;const i=null!=t?t:{},{api_version:r=this._client.apiVersion}=i,s=tn(i,["api_version"]);return this._client.get(Bo`/${r}/interactions/${e}`,Object.assign(Object.assign({query:s},n),{stream:null!==(o=null==t?void 0:t.stream)&&void 0!==o&&o}))}};Jo._key=Object.freeze(["interactions"]);var Yo=class extends Jo{},$o=class extends Ho{create(e,t){const{api_version:n=this._client.apiVersion}=e,o=tn(e,["api_version"]);return this._client.post(Bo`/${n}/webhooks`,Object.assign({body:o},t))}update(e,t={},n){const o=null!=t?t:{},{api_version:i=this._client.apiVersion,update_mask:r}=o,s=tn(o,["api_version","update_mask"]);return this._client.patch(Bo`/${i}/webhooks/${e}`,Object.assign({query:{update_mask:r},body:s},n))}list(e={},t){const n=null!=e?e:{},{api_version:o=this._client.apiVersion}=n,i=tn(n,["api_version"]);return this._client.get(Bo`/${o}/webhooks`,Object.assign({query:i},t))}delete(e,t={},n){const{api_version:o=this._client.apiVersion}=null!=t?t:{};return this._client.delete(Bo`/${o}/webhooks/${e}`,n)}get(e,t={},n){const{api_version:o=this._client.apiVersion}=null!=t?t:{};return this._client.get(Bo`/${o}/webhooks/${e}`,n)}ping(e,t=void 0,n){const{api_version:o=this._client.apiVersion,body:i}=null!=t?t:{};return this._client.post(Bo`/${o}/webhooks/${e}:ping`,Object.assign({body:i},n))}rotateSigningSecret(e,t={},n){const o=null!=t?t:{},{api_version:i=this._client.apiVersion}=o,r=tn(o,["api_version"]);return this._client.post(Bo`/${i}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:r},n))}};$o._key=Object.freeze(["webhooks"]);var Ko,Wo,zo=class extends $o{};function Xo(e){let t;return(null!=Ko?Ko:(t=new globalThis.TextEncoder,Ko=t.encode.bind(t)))(e)}function Qo(e){let t;return(null!=Wo?Wo:(t=new globalThis.TextDecoder,Wo=t.decode.bind(t)))(e)}var Zo=class{constructor(){this.buffer=/* @__PURE__ */new Uint8Array,this.carriageReturnIndex=null,this.searchIndex=0}decode(e){var t;if(null==e)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?Xo(e):e;this.buffer=function(e){let t=0;for(const i of e)t+=i.length;const n=new Uint8Array(t);let o=0;for(const i of e)n.set(i,o),o+=i.length;return n}([this.buffer,n]);const o=[];let i;for(;null!=(i=ei(this.buffer,null!==(t=this.carriageReturnIndex)&&void 0!==t?t:this.searchIndex));){if(i.carriage&&null==this.carriageReturnIndex){this.carriageReturnIndex=i.index;continue}if(null!=this.carriageReturnIndex&&(i.index!==this.carriageReturnIndex+1||i.carriage)){o.push(Qo(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null,this.searchIndex=0;continue}const e=null!==this.carriageReturnIndex?i.preceding-1:i.preceding,t=Qo(this.buffer.subarray(0,e));o.push(t),this.buffer=this.buffer.subarray(i.index),this.carriageReturnIndex=null,this.searchIndex=0}return this.searchIndex=Math.max(0,this.buffer.length-1),o}flush(){return this.buffer.length?this.decode("\n"):[]}};function ei(e,t){const n=null!=t?t:0,o=e.indexOf(10,n),i=e.indexOf(13,n);if(-1===o&&-1===i)return null;let r;return r=-1!==o&&-1!==i?Math.min(o,i):-1!==o?o:i,10===e[r]?{preceding:r,index:r+1,carriage:!1}:{preceding:r,index:r+1,carriage:!0}}Zo.NEWLINE_CHARS=/* @__PURE__ */new Set(["\n","\r"]),Zo.NEWLINE_REGEXP=/\r\n|[\n\r]/g;var ti={off:0,error:200,warn:300,info:400,debug:500},ni=(e,t,n)=>{var o,i;if(e)return o=ti,i=e,Object.prototype.hasOwnProperty.call(o,i)?e:void li(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(ti))}`)};function oi(){}function ii(e,t,n){return!t||ti[e]>ti[n]?oi:t[e].bind(t)}var ri={error:oi,warn:oi,info:oi,debug:oi},si=/* @__PURE__ */new WeakMap;function li(e){var t;const n=e.logger,o=null!==(t=e.logLevel)&&void 0!==t?t:"off";if(!n)return ri;const i=si.get(n);if(i&&i[0]===o)return i[1];const r={error:ii("error",n,o),warn:ii("warn",n,o),info:ii("info",n,o),debug:ii("debug",n,o)};return si.set(n,[o,r]),r}var ai=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"x-goog-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),ui=class e{constructor(e,t,n){this.iterator=e,this.controller=t,this.client=n}static fromSSEResponse(t,n,o){let i=!1;const r=o?li(o):console;return new e(function(){return on(this,arguments,function*(){var e,o,s,l;if(i)throw new mo("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let a=!1;try{try{for(var u,c=!0,p=rn(function(e,t){return on(this,arguments,function*(){var n,o,i,r;if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new mo("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new mo("Attempted to iterate over a response with no body")}const s=new ci,l=new Zo,a=Uo(e.body);try{for(var u,c=!0,p=rn(function(e){return on(this,arguments,function*(){var t,n,o,i;try{for(var r,s=!0,l=rn(e);!(t=(r=yield nn(l.next())).done);s=!0){i=r.value,s=!1;const e=i;null!=e&&(yield yield nn(e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?Xo(e):e))}}catch(a){n={error:a}}finally{try{s||t||!(o=l.return)||(yield nn(o.call(l)))}finally{if(n)throw n.error}}})}(a));!(n=(u=yield nn(p.next())).done);c=!0){r=u.value,c=!1;const e=r;for(const t of l.decode(e)){const e=s.decode(t);e&&(yield yield nn(e))}}}catch(d){o={error:d}}finally{try{c||n||!(i=p.return)||(yield nn(i.call(p)))}finally{if(o)throw o.error}}for(const e of l.flush()){const t=s.decode(e);t&&(yield yield nn(t))}})}(t,n));!(e=(u=yield nn(p.next())).done);c=!0){l=u.value,c=!1;const e=l;if(!a)if(e.data.startsWith("[DONE]"))a=!0;else try{yield yield nn(JSON.parse(e.data))}catch(d){throw r.error("Could not parse message into JSON:",e.data),r.error("From chunk:",e.raw),d}}}catch(h){o={error:h}}finally{try{c||e||!(s=p.return)||(yield nn(s.call(p)))}finally{if(o)throw o.error}}a=!0}catch(d){if(ho(d))return yield nn(void 0);throw d}finally{a||n.abort()}})},n,o)}static fromReadableStream(t,n,o){let i=!1;return new e(function(){return on(this,arguments,function*(){var e,o,r,s;if(i)throw new mo("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let l=!1;try{try{for(var a,u=!0,c=rn(function(){return on(this,arguments,function*(){var e,n,o,i;const r=new Zo,s=Uo(t);try{for(var l,a=!0,u=rn(s);!(e=(l=yield nn(u.next())).done);a=!0){i=l.value,a=!1;const e=i;for(const t of r.decode(e))yield yield nn(t)}}catch(c){n={error:c}}finally{try{a||e||!(o=u.return)||(yield nn(o.call(u)))}finally{if(n)throw n.error}}for(const t of r.flush())yield yield nn(t)})}());!(e=(a=yield nn(c.next())).done);u=!0){s=a.value,u=!1;const e=s;l||e&&(yield yield nn(JSON.parse(e)))}}catch(p){o={error:p}}finally{try{u||e||!(r=c.return)||(yield nn(r.call(c)))}finally{if(o)throw o.error}}l=!0}catch(d){if(ho(d))return yield nn(void 0);throw d}finally{l||n.abort()}})},n,o)}[Symbol.asyncIterator](){return this.iterator()}tee(){const t=[],n=[],o=this.iterator(),i=e=>({next:()=>{if(0===e.length){const e=o.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,this.client),new e(()=>i(n),this.controller,this.client)]}toReadableStream(){const e=this;let t;return Do({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:o}=await t.next();if(o)return e.close();const i=Xo(JSON.stringify(n)+"\n");e.enqueue(i)}catch(n){e.error(n)}},async cancel(){var e;await(null===(e=t.return)||void 0===e?void 0:e.call(t))}})}},ci=class{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 e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,o]=function(e){const t=e.indexOf(":");return-1!==t?[e.substring(0,t),":",e.substring(t+1)]:[e,"",""]}(e);return o.startsWith(" ")&&(o=o.substring(1)),"event"===t?this.event=o:"data"===t&&this.data.push(o),null}};async function pi(e,t){const{response:n,requestLogID:o,retryOfRequestLogID:i,startTime:r}=t,s=await(async()=>{var o;if(t.options.stream)return li(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):ui.fromSSEResponse(n,t.controller,e);if(204===n.status)return null;if(t.options.__binaryResponse)return n;const i=n.headers.get("content-type"),r=null===(o=null==i?void 0:i.split(";")[0])||void 0===o?void 0:o.trim();if((null==r?void 0:r.includes("application/json"))||(null==r?void 0:r.endsWith("+json"))){if("0"===n.headers.get("content-length"))return;return await n.json()}return await n.text()})();return li(e).debug(`[${o}] response parsed`,ai({retryOfRequestLogID:i,url:n.url,status:n.status,body:s,durationMs:Date.now()-r})),s}var di=class e extends Promise{constructor(e,t,n=pi){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,this.client=e}_thenUnwrap(t){return new e(this.client,this.responsePromise,async(e,n)=>t(await this.parseResponse(e,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},hi=/* @__PURE__ */Symbol("brand.privateNullableHeaders");function*fi(e){if(!e)return;if(hi in e){const{values:t,nulls:n}=e;yield*t.entries();for(const e of n)yield[e,null];return}let t,n=!1;e instanceof Headers?t=e.entries():No(e)?t=e:(n=!0,t=Object.entries(null!=e?e:{}));for(let o of t){const e=o[0];if("string"!=typeof e)throw new TypeError("expected header name to be a string");const t=No(o[1])?o[1]:[o[1]];let i=!1;for(const o of t)void 0!==o&&(n&&!i&&(i=!0,yield[e,null]),yield[e,o])}}var mi,gi=e=>{const t=new Headers,n=/* @__PURE__ */new Set;for(const o of e){const e=/* @__PURE__ */new Set;for(const[i,r]of fi(o)){const o=i.toLowerCase();e.has(o)||(t.delete(i),e.add(o)),null===r?(t.delete(i),n.add(o)):(t.append(i,r),n.delete(o))}}return{[hi]:!0,values:t,nulls:n}},Ei=e=>{var t,n,o,i,r;return void 0!==globalThis.process?(null===(n=null===(t=globalThis.process.env)||void 0===t?void 0:t[e])||void 0===n?void 0:n.trim())||void 0:void 0!==globalThis.Deno&&(null===(r=null===(i=null===(o=globalThis.Deno.env)||void 0===o?void 0:o.get)||void 0===i?void 0:i.call(o,e))||void 0===r?void 0:r.trim())||void 0},yi=class e{constructor(t){var n,o,i,r,s,l,a,{baseURL:u=Ei("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:c=(null!==(n=Ei("GEMINI_API_KEY"))&&void 0!==n?n:null),apiVersion:p="v1beta"}=t,d=tn(t,["baseURL","apiKey","apiVersion"]);const h=Object.assign(Object.assign({apiKey:c,apiVersion:p},d),{baseURL:u||"https://generativelanguage.googleapis.com"});this.baseURL=h.baseURL,this.timeout=null!==(o=h.timeout)&&void 0!==o?o:e.DEFAULT_TIMEOUT,this.logger=null!==(i=h.logger)&&void 0!==i?i:console;const f="warn";this.logLevel=f,this.logLevel=null!==(s=null!==(r=ni(h.logLevel,"ClientOptions.logLevel",this))&&void 0!==r?r:ni(Ei("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))&&void 0!==s?s:f,this.fetchOptions=h.fetchOptions,this.maxRetries=null!==(l=h.maxRetries)&&void 0!==l?l:2,this.fetch=null!==(a=h.fetch)&&void 0!==a?a:function(){if("undefined"!=typeof fetch)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`")}(),this.encoder=Go,this._options=h,this.apiKey=c,this.apiVersion=p,this.clientAdapter=h.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"https://generativelanguage.googleapis.com"!==this.baseURL}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!e.has("authorization")&&!e.has("x-goog-api-key")&&!(this.apiKey&&e.get("x-goog-api-key")||t.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 t=gi([e.headers]);if(!t.values.has("authorization")&&!t.values.has("x-goog-api-key"))return this.apiKey?gi([{"x-goog-api-key":this.apiKey}]):this.clientAdapter&&this.clientAdapter.isVertexAI()?gi([await this.clientAdapter.getAuthHeaders()]):void 0}stringifyQuery(e){return function(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new mo(`Cannot stringify type ${typeof t}; 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("&")}(e)}getUserAgent(){return`${this.constructor.name}/JS 0.0.1`}defaultIdempotencyKey(){return`stainless-node-retry-${po()}`}makeStatusError(e,t,n,o){return go.generate(e,t,n,o)}buildURL(e,t,n){const o=!this.baseURLOverridden()&&n||this.baseURL,i=(e=>wo.test(e))(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),r=this.defaultQuery(),s=Object.fromEntries(i.searchParams);return Po(r)&&Po(s)||(t=Object.assign(Object.assign(Object.assign({},s),r),t)),"object"==typeof t&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){const t=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${t}`}}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>Object.assign({method:e,path:t},n)))}request(e,t=null){return new di(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){var o,i,r;const s=await e,l=null!==(o=s.maxRetries)&&void 0!==o?o:this.maxRetries;null==t&&(t=l),await this.prepareOptions(s);const{req:a,url:u,timeout:c}=await this.buildRequest(s,{retryCount:l-t});await this.prepareRequest(a,{url:u,options:s});const p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=void 0===n?"":`, retryOf: ${n}`,h=Date.now();if(li(this).debug(`[${p}] sending request`,ai({retryOfRequestLogID:n,method:s.method,url:u,options:s,headers:a.headers})),null===(i=s.signal)||void 0===i?void 0:i.aborted)throw new Eo;const f=new AbortController,m=await this.fetchWithTimeout(u,a,c,f).catch(fo),g=Date.now();if(m instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(null===(r=s.signal)||void 0===r?void 0:r.aborted)throw new Eo;const o=ho(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return li(this).info(`[${p}] connection ${o?"timed out":"failed"} - ${e}`),li(this).debug(`[${p}] connection ${o?"timed out":"failed"} (${e})`,ai({retryOfRequestLogID:n,url:u,durationMs:g-h,message:m.message})),this.retryRequest(s,t,null!=n?n:p);if(li(this).info(`[${p}] connection ${o?"timed out":"failed"} - error; no more retries left`),li(this).debug(`[${p}] connection ${o?"timed out":"failed"} (error; no more retries left)`,ai({retryOfRequestLogID:n,url:u,durationMs:g-h,message:m.message})),o)throw new vo;throw new yo({cause:m})}const E=`[${p}${d}] ${a.method} ${u} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${g-h}ms`;if(!m.ok){const e=await this.shouldRetry(m);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){var t,n;if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void(await(null===(n=(t=e[Symbol.asyncIterator]()).return)||void 0===n?void 0:n.call(t)));const o=e.getReader(),i=o.cancel();o.releaseLock(),await i}(m.body),li(this).info(`${E} - ${e}`),li(this).debug(`[${p}] response error (${e})`,ai({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,durationMs:g-h})),this.retryRequest(s,t,null!=n?n:p,m.headers)}const o=e?"error; no more retries left":"error; not retryable";li(this).info(`${E} - ${o}`);const i=await m.text().catch(e=>fo(e).message),r=(e=>{try{return JSON.parse(e)}catch(t){return}})(i),l=r?void 0:i;throw li(this).debug(`[${p}] response error (${o})`,ai({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,message:l,durationMs:Date.now()-h})),this.makeStatusError(m.status,r,l,m.headers)}return li(this).info(E),li(this).debug(`[${p}] response start`,ai({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,durationMs:g-h})),{response:m,options:s,controller:f,requestLogID:p,retryOfRequestLogID:n,startTime:h}}async fetchWithTimeout(e,t,n,o){const i=t||{},{signal:r,method:s}=i,l=tn(i,["signal","method"]),a=this._makeAbort(o);r&&r.addEventListener("abort",a,{once:!0});const u=setTimeout(a,n),c=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||"object"==typeof l.body&&null!==l.body&&Symbol.asyncIterator in l.body,p=Object.assign(Object.assign(Object.assign({signal:o.signal},c?{duplex:"half"}:{}),{method:"GET"}),l);s&&(p.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(u)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||e.status>=500)}async retryRequest(e,t,n,o){var i;let r;const s=null==o?void 0:o.get("retry-after-ms");if(s){const e=parseFloat(s);Number.isNaN(e)||(r=e)}const l=null==o?void 0:o.get("retry-after");if(l&&!r){const e=parseFloat(l);r=Number.isNaN(e)?Date.parse(l)-Date.now():1e3*e}if(void 0===r){const n=null!==(i=e.maxRetries)&&void 0!==i?i:this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,n)}var a;return await(a=r,new Promise(e=>setTimeout(e,a))),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){var n,o,i;const r=Object.assign({},e),{method:s,path:l,query:a,defaultBaseURL:u}=r,c=this.buildURL(l,a,u);"timeout"in r&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new mo(`${e} must be an integer`);if(t<0)throw new mo(`${e} must be a positive integer`)})("timeout",r.timeout),r.timeout=null!==(n=r.timeout)&&void 0!==n?n:this.timeout;const{bodyHeaders:p,body:d}=this.buildBody({options:r}),h=await this.buildHeaders({options:e,method:s,bodyHeaders:p,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:s,headers:h},r.signal&&{signal:r.signal}),globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"}),d&&{body:d}),null!==(o=this.fetchOptions)&&void 0!==o?o:{}),null!==(i=r.fetchOptions)&&void 0!==i?i:{}),url:c,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:o}){let i={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const r=await this.authHeaders(e);let s=gi([i,{Accept:"application/json","User-Agent":this.getUserAgent()},this._options.defaultHeaders,n,e.headers,r]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=gi([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&n.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}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:Mo(e)}:"object"==typeof e&&"application/x-www-form-urlencoded"===n.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:n})}};yi.DEFAULT_TIMEOUT=6e4;var vi=class extends yi{constructor(){super(...arguments),this.interactions=new Yo(this),this.webhooks=new zo(this)}};function Ii(e,t){const n={},o=Me(e,["sdkHttpResponse"]);null!=o&&De(n,["sdkHttpResponse"],o);const i=Me(e,["name"]);null!=i&&De(n,["name"],i);const r=Me(e,["state"]);null!=r&&De(n,["state"],Ut(r));const s=Me(e,["createTime"]);null!=s&&De(n,["createTime"],s);const l=Me(e,["startTime"]);null!=l&&De(n,["startTime"],l);const a=Me(e,["endTime"]);null!=a&&De(n,["endTime"],a);const u=Me(e,["updateTime"]);null!=u&&De(n,["updateTime"],u);const c=Me(e,["error"]);null!=c&&De(n,["error"],c);const p=Me(e,["description"]);null!=p&&De(n,["description"],p);const d=Me(e,["baseModel"]);null!=d&&De(n,["baseModel"],d);const h=Me(e,["tunedModel"]);null!=h&&De(n,["tunedModel"],h);const f=Me(e,["preTunedModel"]);null!=f&&De(n,["preTunedModel"],f);const m=Me(e,["supervisedTuningSpec"]);null!=m&&De(n,["supervisedTuningSpec"],m);const g=Me(e,["preferenceOptimizationSpec"]);null!=g&&De(n,["preferenceOptimizationSpec"],g);const E=Me(e,["distillationSpec"]);null!=E&&De(n,["distillationSpec"],E);const y=Me(e,["tuningDataStats"]);null!=y&&De(n,["tuningDataStats"],y);const v=Me(e,["encryptionSpec"]);null!=v&&De(n,["encryptionSpec"],v);const I=Me(e,["partnerModelTuningSpec"]);null!=I&&De(n,["partnerModelTuningSpec"],I);const _=Me(e,["customBaseModel"]);null!=_&&De(n,["customBaseModel"],_);const T=Me(e,["evaluateDatasetRuns"]);if(null!=T){let e=T;Array.isArray(e)&&(e=e.map(e=>e)),De(n,["evaluateDatasetRuns"],e)}const A=Me(e,["experiment"]);null!=A&&De(n,["experiment"],A);const C=Me(e,["fullFineTuningSpec"]);null!=C&&De(n,["fullFineTuningSpec"],C);const O=Me(e,["labels"]);null!=O&&De(n,["labels"],O);const S=Me(e,["outputUri"]);null!=S&&De(n,["outputUri"],S);const b=Me(e,["pipelineJob"]);null!=b&&De(n,["pipelineJob"],b);const w=Me(e,["serviceAccount"]);null!=w&&De(n,["serviceAccount"],w);const R=Me(e,["tunedModelDisplayName"]);null!=R&&De(n,["tunedModelDisplayName"],R);const N=Me(e,["tuningJobState"]);null!=N&&De(n,["tuningJobState"],N);const P=Me(e,["veoTuningSpec"]);null!=P&&De(n,["veoTuningSpec"],P);const D=Me(e,["distillationSamplingSpec"]);null!=D&&De(n,["distillationSamplingSpec"],D);const M=Me(e,["tuningJobMetadata"]);return null!=M&&De(n,["tuningJobMetadata"],M),n}function _i(e,t){const n={},o=Me(e,["gcsUri"]);null!=o&&De(n,["validationDatasetUri"],o);const i=Me(e,["vertexDatasetResource"]);return null!=i&&De(n,["validationDatasetUri"],i),n}mi=vi,vi.GeminiNextGenAPIClient=mi,vi.GeminiNextGenAPIClientError=mo,vi.APIError=go,vi.APIConnectionError=yo,vi.APIConnectionTimeoutError=vo,vi.APIUserAbortError=Eo,vi.NotFoundError=Ao,vi.ConflictError=Co,vi.RateLimitError=So,vi.BadRequestError=Io,vi.AuthenticationError=_o,vi.InternalServerError=bo,vi.PermissionDeniedError=To,vi.UnprocessableEntityError=Oo,vi.toFile=async function(e,t,n){if(xo(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&ko(e))(e=await e))return e instanceof File?e:Lo([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const o=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Lo(await qo(o),t,n)}const o=await qo(e);if(t||(t=function(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}(e)),!(null==n?void 0:n.type)){const e=o.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(n=Object.assign(Object.assign({},n),{type:e}))}return Lo(o,t,n)},vi.Interactions=Yo,vi.Webhooks=zo;var Ti=class extends Ne{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new zt(Le.PAGED_ITEM_TUNING_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.get=async e=>await this.getInternal(e),this.tune=async e=>{var t;if(this.apiClient.isVertexAI()){if(e.baseModel.startsWith("projects/")){const n={tunedModelName:e.baseModel};(null===(t=e.config)||void 0===t?void 0:t.preTunedModelCheckpointId)&&(n.checkpointId=e.config.preTunedModelCheckpointId);const o=Object.assign(Object.assign({},e),{preTunedModel:n});return o.baseModel=void 0,await this.tuneInternal(o)}{const t=Object.assign({},e);return await this.tuneInternal(t)}}{const t=Object.assign({},e),n=await this.tuneMldevInternal(t);let o="";return void 0!==n.metadata&&void 0!==n.metadata.tunedModel?o=n.metadata.tunedModel:void 0!==n.name&&n.name.includes("/operations/")&&(o=n.name.split("/operations/")[0]),{name:o,state:j.JOB_STATE_QUEUED}}}}async getInternal(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=Me(e,["name"]);return null!=n&&De(t,["_url","name"],n),t}(e);return s=Pe("{name}",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>Ii(e))}{const t=function(e){const t={},n=Me(e,["name"]);return null!=n&&De(t,["_url","name"],n),t}(e);return s=Pe("{name}",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"GET",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["name"]);null!=o&&De(t,["name"],o);const i=Me(e,["state"]);null!=i&&De(t,["state"],Ut(i));const r=Me(e,["createTime"]);null!=r&&De(t,["createTime"],r);const s=Me(e,["tuningTask","startTime"]);null!=s&&De(t,["startTime"],s);const l=Me(e,["tuningTask","completeTime"]);null!=l&&De(t,["endTime"],l);const a=Me(e,["updateTime"]);null!=a&&De(t,["updateTime"],a);const u=Me(e,["description"]);null!=u&&De(t,["description"],u);const c=Me(e,["baseModel"]);null!=c&&De(t,["baseModel"],c);const p=Me(e,["_self"]);return null!=p&&De(t,["tunedModel"],function(e){const t={},n=Me(e,["name"]);null!=n&&De(t,["model"],n);const o=Me(e,["name"]);return null!=o&&De(t,["endpoint"],o),t}(p)),t}(e))}}async listInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e){const t={},n=Me(e,["config"]);return null!=n&&function(e,t){const n=Me(e,["pageSize"]);void 0!==t&&null!=n&&De(t,["_query","pageSize"],n);const o=Me(e,["pageToken"]);void 0!==t&&null!=o&&De(t,["_query","pageToken"],o);const i=Me(e,["filter"]);void 0!==t&&null!=i&&De(t,["_query","filter"],i)}(n,t),t}(e);return i=Pe("tuningJobs",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["nextPageToken"]);null!=o&&De(t,["nextPageToken"],o);const i=Me(e,["tuningJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>Ii(e))),De(t,["tuningJobs"],e)}return t}(e),n=new Xe;return Object.assign(n,t),n})}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var t,n,o,i;let r,s="",l={};if(this.apiClient.isVertexAI()){const o=function(e){const t={},n=Me(e,["name"]);return null!=n&&De(t,["_url","name"],n),t}(e);return s=Pe("{name}:cancel",o._url),l=o._query,delete o._url,delete o._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);return null!=n&&De(t,["sdkHttpResponse"],n),t}(e),n=new Qe;return Object.assign(n,t),n})}{const t=function(e){const t={},n=Me(e,["name"]);return null!=n&&De(t,["_url","name"],n),t}(e);return s=Pe("{name}:cancel",t._url),l=t._query,delete t._url,delete t._query,r=this.apiClient.request({path:s,queryParams:l,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null===(o=e.config)||void 0===o?void 0:o.httpOptions,abortSignal:null===(i=e.config)||void 0===i?void 0:i.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),r.then(e=>{const t=function(e){const t={},n=Me(e,["sdkHttpResponse"]);return null!=n&&De(t,["sdkHttpResponse"],n),t}(e),n=new Qe;return Object.assign(n,t),n})}}async tuneInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI()){const s=function(e,t){const n={},o=Me(e,["baseModel"]);null!=o&&De(n,["baseModel"],o);const i=Me(e,["preTunedModel"]);null!=i&&De(n,["preTunedModel"],i);const r=Me(e,["trainingDataset"]);null!=r&&function(e,t,n){let o=Me(n,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){const n=Me(e,["gcsUri"]);void 0!==t&&null!=n&&De(t,["supervisedTuningSpec","trainingDatasetUri"],n)}else if("PREFERENCE_TUNING"===o){const n=Me(e,["gcsUri"]);void 0!==t&&null!=n&&De(t,["preferenceOptimizationSpec","trainingDatasetUri"],n)}else if("DISTILLATION"===o){const n=Me(e,["gcsUri"]);void 0!==t&&null!=n&&De(t,["distillationSpec","promptDatasetUri"],n)}let i=Me(n,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){const n=Me(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&De(t,["supervisedTuningSpec","trainingDatasetUri"],n)}else if("PREFERENCE_TUNING"===i){const n=Me(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&De(t,["preferenceOptimizationSpec","trainingDatasetUri"],n)}else if("DISTILLATION"===i){const n=Me(e,["vertexDatasetResource"]);void 0!==t&&null!=n&&De(t,["distillationSpec","promptDatasetUri"],n)}if(void 0!==Me(e,["examples"]))throw new Error("examples parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}(r,n,t);const s=Me(e,["config"]);return null!=s&&function(e,t,n){let o=Me(n,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){const n=Me(e,["validationDataset"]);void 0!==t&&null!=n&&De(t,["supervisedTuningSpec"],_i(n))}else if("PREFERENCE_TUNING"===o){const n=Me(e,["validationDataset"]);void 0!==t&&null!=n&&De(t,["preferenceOptimizationSpec"],_i(n))}else if("DISTILLATION"===o){const n=Me(e,["validationDataset"]);void 0!==t&&null!=n&&De(t,["distillationSpec"],_i(n))}const i=Me(e,["tunedModelDisplayName"]);void 0!==t&&null!=i&&De(t,["tunedModelDisplayName"],i);const r=Me(e,["description"]);void 0!==t&&null!=r&&De(t,["description"],r);let s=Me(n,["config","method"]);if(void 0===s&&(s="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===s){const n=Me(e,["epochCount"]);void 0!==t&&null!=n&&De(t,["supervisedTuningSpec","hyperParameters","epochCount"],n)}else if("PREFERENCE_TUNING"===s){const n=Me(e,["epochCount"]);void 0!==t&&null!=n&&De(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],n)}else if("DISTILLATION"===s){const n=Me(e,["epochCount"]);void 0!==t&&null!=n&&De(t,["distillationSpec","hyperParameters","epochCount"],n)}let l=Me(n,["config","method"]);if(void 0===l&&(l="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===l){const n=Me(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&De(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],n)}else if("PREFERENCE_TUNING"===l){const n=Me(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&De(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],n)}else if("DISTILLATION"===l){const n=Me(e,["learningRateMultiplier"]);void 0!==t&&null!=n&&De(t,["distillationSpec","hyperParameters","learningRateMultiplier"],n)}let a=Me(n,["config","method"]);if(void 0===a&&(a="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===a){const n=Me(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=n&&De(t,["supervisedTuningSpec","exportLastCheckpointOnly"],n)}else if("PREFERENCE_TUNING"===a){const n=Me(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=n&&De(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],n)}else if("DISTILLATION"===a){const n=Me(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=n&&De(t,["distillationSpec","exportLastCheckpointOnly"],n)}let u=Me(n,["config","method"]);if(void 0===u&&(u="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===u){const n=Me(e,["adapterSize"]);void 0!==t&&null!=n&&De(t,["supervisedTuningSpec","hyperParameters","adapterSize"],n)}else if("PREFERENCE_TUNING"===u){const n=Me(e,["adapterSize"]);void 0!==t&&null!=n&&De(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],n)}else if("DISTILLATION"===u){const n=Me(e,["adapterSize"]);void 0!==t&&null!=n&&De(t,["distillationSpec","hyperParameters","adapterSize"],n)}let c=Me(n,["config","method"]);if(void 0===c&&(c="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===c){const n=Me(e,["tuningMode"]);void 0!==t&&null!=n&&De(t,["supervisedTuningSpec","tuningMode"],n)}else if("DISTILLATION"===c){const n=Me(e,["tuningMode"]);void 0!==t&&null!=n&&De(t,["distillationSpec","tuningMode"],n)}const p=Me(e,["customBaseModel"]);void 0!==t&&null!=p&&De(t,["customBaseModel"],p);let d=Me(n,["config","method"]);if(void 0===d&&(d="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===d){const n=Me(e,["batchSize"]);void 0!==t&&null!=n&&De(t,["supervisedTuningSpec","hyperParameters","batchSize"],n)}else if("DISTILLATION"===d){const n=Me(e,["batchSize"]);void 0!==t&&null!=n&&De(t,["distillationSpec","hyperParameters","batchSize"],n)}let h=Me(n,["config","method"]);if(void 0===h&&(h="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===h){const n=Me(e,["learningRate"]);void 0!==t&&null!=n&&De(t,["supervisedTuningSpec","hyperParameters","learningRate"],n)}else if("DISTILLATION"===h){const n=Me(e,["learningRate"]);void 0!==t&&null!=n&&De(t,["distillationSpec","hyperParameters","learningRate"],n)}const f=Me(e,["labels"]);void 0!==t&&null!=f&&De(t,["labels"],f);const m=Me(e,["beta"]);void 0!==t&&null!=m&&De(t,["preferenceOptimizationSpec","hyperParameters","beta"],m);const g=Me(e,["baseTeacherModel"]);void 0!==t&&null!=g&&De(t,["distillationSpec","baseTeacherModel"],g);const E=Me(e,["tunedTeacherModelSource"]);void 0!==t&&null!=E&&De(t,["distillationSpec","tunedTeacherModelSource"],E);const y=Me(e,["sftLossWeightMultiplier"]);void 0!==t&&null!=y&&De(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],y);const v=Me(e,["outputUri"]);void 0!==t&&null!=v&&De(t,["outputUri"],v);const I=Me(e,["encryptionSpec"]);void 0!==t&&null!=I&&De(t,["encryptionSpec"],I)}(s,n,t),n}(e,e);return i=Pe("tuningJobs",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>Ii(e))}throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var t,n;let o,i="",r={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const s=function(e){const t={},n=Me(e,["baseModel"]);null!=n&&De(t,["baseModel"],n);const o=Me(e,["preTunedModel"]);null!=o&&De(t,["preTunedModel"],o);const i=Me(e,["trainingDataset"]);null!=i&&function(e){const t={};if(void 0!==Me(e,["gcsUri"]))throw new Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==Me(e,["vertexDatasetResource"]))throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");const n=Me(e,["examples"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),De(t,["examples","examples"],e)}}(i);const r=Me(e,["config"]);return null!=r&&function(e,t){if(void 0!==Me(e,["validationDataset"]))throw new Error("validationDataset parameter is not supported in Gemini API.");const n=Me(e,["tunedModelDisplayName"]);if(void 0!==t&&null!=n&&De(t,["displayName"],n),void 0!==Me(e,["description"]))throw new Error("description parameter is not supported in Gemini API.");const o=Me(e,["epochCount"]);void 0!==t&&null!=o&&De(t,["tuningTask","hyperparameters","epochCount"],o);const i=Me(e,["learningRateMultiplier"]);if(null!=i&&De({},["tuningTask","hyperparameters","learningRateMultiplier"],i),void 0!==Me(e,["exportLastCheckpointOnly"]))throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(void 0!==Me(e,["preTunedModelCheckpointId"]))throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(void 0!==Me(e,["adapterSize"]))throw new Error("adapterSize parameter is not supported in Gemini API.");if(void 0!==Me(e,["tuningMode"]))throw new Error("tuningMode parameter is not supported in Gemini API.");if(void 0!==Me(e,["customBaseModel"]))throw new Error("customBaseModel parameter is not supported in Gemini API.");const r=Me(e,["batchSize"]);void 0!==t&&null!=r&&De(t,["tuningTask","hyperparameters","batchSize"],r);const s=Me(e,["learningRate"]);if(void 0!==t&&null!=s&&De(t,["tuningTask","hyperparameters","learningRate"],s),void 0!==Me(e,["labels"]))throw new Error("labels parameter is not supported in Gemini API.");if(void 0!==Me(e,["beta"]))throw new Error("beta parameter is not supported in Gemini API.");if(void 0!==Me(e,["baseTeacherModel"]))throw new Error("baseTeacherModel parameter is not supported in Gemini API.");if(void 0!==Me(e,["tunedTeacherModelSource"]))throw new Error("tunedTeacherModelSource parameter is not supported in Gemini API.");if(void 0!==Me(e,["sftLossWeightMultiplier"]))throw new Error("sftLossWeightMultiplier parameter is not supported in Gemini API.");if(void 0!==Me(e,["outputUri"]))throw new Error("outputUri parameter is not supported in Gemini API.");if(void 0!==Me(e,["encryptionSpec"]))throw new Error("encryptionSpec parameter is not supported in Gemini API.")}(r,t),t}(e);return i=Pe("tunedModels",s._url),r=s._query,delete s._url,delete s._query,o=this.apiClient.request({path:i,queryParams:r,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null===(t=e.config)||void 0===t?void 0:t.httpOptions,abortSignal:null===(n=e.config)||void 0===n?void 0:n.abortSignal}).then(e=>e.json().then(t=>{const n=t;return n.sdkHttpResponse={headers:e.headers},n})),o.then(e=>function(e){const t={},n=Me(e,["sdkHttpResponse"]);null!=n&&De(t,["sdkHttpResponse"],n);const o=Me(e,["name"]);null!=o&&De(t,["name"],o);const i=Me(e,["metadata"]);null!=i&&De(t,["metadata"],i);const r=Me(e,["done"]);null!=r&&De(t,["done"],r);const s=Me(e,["error"]);return null!=s&&De(t,["error"],s),t}(e))}}},Ai=class{async download(e,t){throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.")}},Ci="x-goog-upload-status";async function Oi(e,t,n,o){var i,r,s;let l=t;const a=(null==o?void 0:o.baseUrl)||(null===(i=n.clientOptions.httpOptions)||void 0===i?void 0:i.baseUrl);if(a){const e=new URL(a),n=new URL(t);n.protocol=e.protocol,n.host=e.host,n.port=e.port,l=n.toString()}let u=0,c=0,p=new ke(new Response),d="upload";for(u=e.size;c<u;){const t=Math.min(8388608,u-c),i=e.slice(c,c+t);c+t>=u&&(d+=", finalize");let a=0,h=1e3;for(;a<3;){const e=Object.assign(Object.assign({},(null==o?void 0:o.headers)||{}),{"X-Goog-Upload-Command":d,"X-Goog-Upload-Offset":String(c),"Content-Length":String(t)});if(p=await n.request({path:"",body:i,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},o),{apiVersion:"",baseUrl:l,headers:e})}),null===(r=null==p?void 0:p.headers)||void 0===r?void 0:r[Ci])break;a++,await Si(h),h*=2}if(c+=t,"active"!==(null===(s=null==p?void 0:p.headers)||void 0===s?void 0:s[Ci]))break;if(u<=c)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return p}function Si(e){return new Promise(t=>setTimeout(t,e))}var bi=class{async upload(e,t,n,o){if("string"==typeof e)throw new Error("File path is not supported in browser uploader.");return await async function(e,t,n,o){var i;const r=await Oi(e,t,n,o),s=await(null==r?void 0:r.json());if("final"!==(null===(i=null==r?void 0:r.headers)||void 0===i?void 0:i[Ci]))throw new Error("Failed to upload file: Upload status is not finalized.");return s.file}(e,t,n,o)}async uploadToFileSearchStore(e,t,n,o){if("string"==typeof e)throw new Error("File path is not supported in browser uploader.");return await async function(e,t,n,o){var i;const r=await Oi(e,t,n,o),s=await(null==r?void 0:r.json());if("final"!==(null===(i=null==r?void 0:r.headers)||void 0===i?void 0:i[Ci]))throw new Error("Failed to upload file: Upload status is not finalized.");const l=xe(s),a=new dt;return Object.assign(a,l),a}(e,t,n,o)}async stat(e){if("string"==typeof e)throw new Error("File path is not supported in browser uploader.");return await async function(e){return{size:e.size,type:e.type}}(e)}},wi=class{create(e,t,n){return new Ri(e,t,n)}},Ri=class{constructor(e,t,n){this.url=e,this.headers=t,this.callbacks=n}connect(){this.ws=new WebSocket(this.url),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(void 0===this.ws)throw new Error("WebSocket is not connected");this.ws.send(e)}close(){if(void 0===this.ws)throw new Error("WebSocket is not connected");this.ws.close()}},Ni="x-goog-api-key",Pi=class{constructor(e){this.apiKey=e}async addAuthHeaders(e,t){if(null===e.get(Ni)){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(Ni,this.apiKey)}}},Di=class{getNextGenClient(){var e;const t=this.httpOptions;if(void 0===this._nextGenClient){const t=this.httpOptions;this._nextGenClient=new vi({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:null==t?void 0:t.timeout,maxRetries:null===(e=null==t?void 0:t.retryOptions)||void 0===e?void 0:e.attempts})}return null==t||t.extraBody,this._nextGenClient}get interactions(){return void 0!==this._interactions||(this._interactions=this.getNextGenClient().interactions),this._interactions}get webhooks(){return void 0!==this._webhooks||(this._webhooks=this.getNextGenClient().webhooks),this._webhooks}constructor(e){var t;if(null==e.apiKey)throw new Error("An API Key must be set when running in a browser");if(e.project||e.location)throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.");this.vertexai=null!==(t=e.vertexai)&&void 0!==t&&t,this.apiKey=e.apiKey;const n=function(e,t){var n,o;if(!(null==e?void 0:e.baseUrl)){const e={geminiUrl:void 0,vertexUrl:void 0};return t?null!==(n=e.vertexUrl)&&void 0!==n?n:void 0:null!==(o=e.geminiUrl)&&void 0!==o?o:void 0}return e.baseUrl}(e.httpOptions,e.vertexai);n&&(e.httpOptions?e.httpOptions.baseUrl=n:e.httpOptions={baseUrl:n}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;const o=new Pi(this.apiKey);this.apiClient=new Vn({auth:o,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:"gl-node/web",uploader:new bi,downloader:new Ai}),this.models=new io(this.apiClient),this.live=new Xn(this.apiClient,o,new wi),this.batches=new Xt(this.apiClient),this.chats=new un(this.models,this.apiClient),this.caches=new en(this.apiClient),this.files=new dn(this.apiClient),this.operations=new ro(this.apiClient),this.authTokens=new ao(this.apiClient),this.tunings=new Ti(this.apiClient),this.fileSearchStores=new co(this.apiClient)}};function Mi(e){return!0===e.thought}function Ui(e,t){return"string"==typeof t&&t.length>0?t:e}var Gi=/^[A-Za-z0-9+/]+={0,2}$/;function xi(e,t){return e&&function(e){return!!e&&e.length%4==0&&Gi.test(e)}(t)?t:void 0}function Li(e){const t=ki(e);return e.startsWith("claude-")||e.startsWith("gpt-oss-")||void 0!==t&&t>=3}function ki(e){const t=e.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(t)return Number.parseInt(t[1],10)}function qi(e){const t=ki(e);return void 0===t||t>=3}var Hi=/* @__PURE__ */new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function Fi(e){if("object"!=typeof e||null===e||Array.isArray(e))return e;const t={};for(const[n,o]of Object.entries(e))Hi.has(n)||(t[n]=Fi(o));return t}function Vi(e,t=!1,n=!0){if(0!==e.length)return[{functionDeclarations:e.map(e=>{const o=r(e,n),i=p(e,o);return{name:e.name,description:e.description,...t?{parameters:Fi(i)}:{parametersJsonSchema:i}}})}]}function ji(e){switch(e){case"auto":default:return O.AUTO;case"none":return O.NONE;case"any":return O.ANY}}function Bi(e){switch(e){case D.STOP:return"stop";case D.MAX_TOKENS:return"length";case D.BLOCKLIST:case D.PROHIBITED_CONTENT:case D.SPII:case D.SAFETY:case D.IMAGE_SAFETY:case D.IMAGE_PROHIBITED_CONTENT:case D.IMAGE_RECITATION:case D.IMAGE_OTHER:case D.RECITATION:case D.FINISH_REASON_UNSPECIFIED:case D.OTHER:case D.LANGUAGE:case D.MALFORMED_FUNCTION_CALL:case D.UNEXPECTED_TOOL_CALL:case D.NO_IMAGE:return"error";default:throw new Error(`Unhandled stop reason: ${e}`)}}var Ji=0,Yi=(e,t,o)=>{const l=new n;return(async()=>{const n={role:"assistant",content:[],api:"google-generative-ai",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(o?.fetch&&o.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");const p=o?.apiKey;if(!p)throw new Error(`No API key for provider: ${e.provider}`);const d=function(e,t,n){const o={};e.baseUrl&&(o.baseUrl=e.baseUrl,o.apiVersion="");const i=s({...e.headers,...n});return i&&(o.headers=i),new Di({apiKey:t,httpOptions:Object.keys(o).length>0?o:void 0})}(e,p,o?.headers);let h=function(e,t,n={}){const o=function(e,t){const n=[],o=c(t.messages,e,t=>Li(e.id)?t.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):t);for(const i of o)if("user"===i.role)if("string"==typeof i.content)n.push({role:"user",parts:[{text:u(i.content)}]});else{const e=i.content.map(e=>"text"===e.type?{text:u(e.text)}:{inlineData:{mimeType:e.mimeType,data:e.data}});if(0===e.length)continue;n.push({role:"user",parts:e})}else if("assistant"===i.role){const t=[],o=i.provider===e.provider&&i.model===e.id;for(const n of i.content)if("text"===n.type){const e=xi(o,n.textSignature);if(!(n.text&&""!==n.text.trim()||e))continue;t.push({text:u(n.text),...e&&{thoughtSignature:e}})}else if("thinking"===n.type)if(o){const e=xi(o,n.thinkingSignature);if(!(n.thinking&&""!==n.thinking.trim()||e))continue;t.push({thought:!0,text:u(n.thinking),...e&&{thoughtSignature:e}})}else{if(!n.thinking||""===n.thinking.trim())continue;t.push({text:u(n.thinking)})}else if("toolCall"===n.type){const i=xi(o,n.thoughtSignature),r={functionCall:{name:n.name,args:n.arguments??{},...Li(e.id)?{id:n.id}:{}},...i&&{thoughtSignature:i}};t.push(r)}if(0===t.length)continue;n.push({role:"model",parts:t})}else if("toolResult"===i.role){const t=i.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),o=e.input.includes("image")?i.content.filter(e=>"image"===e.type):[],r=t.length>0,s=o.length>0,l=qi(e.id),a=r?u(t):s?"(see attached image)":"",c=o.map(e=>({inlineData:{mimeType:e.mimeType,data:e.data}})),p=Li(e.id),d={functionResponse:{name:i.toolName,response:i.isError?{error:a}:{output:a},...s&&l&&{parts:c},...p?{id:i.toolCallId}:{}}},h=n[n.length-1];"user"===h?.role&&h.parts?.some(e=>e.functionResponse)?h.parts.push(d):n.push({role:"user",parts:[d]}),s&&!l&&n.push({role:"user",parts:[{text:"Tool result image:"},...c]})}return n}(e,t),i={};void 0!==n.temperature&&(i.temperature=n.temperature),void 0!==n.maxTokens&&(i.maxOutputTokens=n.maxTokens);const s=function(e){const t=ki(e);return void 0!==t&&t>=3}(e.id),l=t.tools?.length?function(e,t,n){const o=e.some(e=>!0===r(e,n));return"none"===t||"any"===t?ji(t):o?O.VALIDATED:t?ji(t):void 0}(t.tools,n.toolChoice,s):void 0,a={...Object.keys(i).length>0&&i,...t.systemPrompt&&{systemInstruction:u(t.systemPrompt)},...t.tools&&t.tools.length>0&&{tools:Vi(t.tools,!1,s)},...void 0!==l&&{toolConfig:{functionCallingConfig:{mode:l}}}};if(n.thinking?.enabled&&e.reasoning){const e={includeThoughts:!0};void 0!==n.thinking.level?e.thinkingLevel=n.thinking.level:void 0!==n.thinking.budgetTokens&&(e.thinkingBudget=n.thinking.budgetTokens),a.thinkingConfig=e}else e.reasoning&&n.thinking&&!n.thinking.enabled&&(a.thinkingConfig=function(e){return Wi(e)?{thinkingLevel:"LOW"}:zi(e)||Ki(e)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}(e));if(n.signal){if(n.signal.aborted)throw new Error("Request aborted");a.abortSignal=n.signal}return{model:e.id,contents:o,config:a}}(e,t,o);const f=await(o?.onPayload?.(h,e));void 0!==f&&(h=f);const m=await function(e,t){return a(async()=>{try{return await d.models.generateContentStream(h)}catch(e){throw e instanceof Error&&"status"in e&&!("headers"in e)&&(e.headers=void 0),e}},{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal})}(0,o);l.push({type:"start",partial:n});let g=null;const E=n.content,y=()=>E.length-1;for await(const t of m){n.responseId||=t.responseId;const o=t.candidates?.[0];if(o?.content?.parts)for(const e of o.content.parts){if(void 0!==e.text){const t=Mi(e);(!g||t&&"thinking"!==g.type||!t&&"text"!==g.type)&&(g&&("text"===g.type?l.push({type:"text_end",contentIndex:E.length-1,content:g.text,partial:n}):l.push({type:"thinking_end",contentIndex:y(),content:g.thinking,partial:n})),t?(g={type:"thinking",thinking:"",thinkingSignature:void 0},n.content.push(g),l.push({type:"thinking_start",contentIndex:y(),partial:n})):(g={type:"text",text:""},n.content.push(g),l.push({type:"text_start",contentIndex:y(),partial:n}))),"thinking"===g.type?(g.thinking+=e.text,g.thinkingSignature=Ui(g.thinkingSignature,e.thoughtSignature),l.push({type:"thinking_delta",contentIndex:y(),delta:e.text,partial:n})):(g.text+=e.text,g.textSignature=Ui(g.textSignature,e.thoughtSignature),l.push({type:"text_delta",contentIndex:y(),delta:e.text,partial:n}))}if(e.functionCall){g&&("text"===g.type?l.push({type:"text_end",contentIndex:y(),content:g.text,partial:n}):l.push({type:"thinking_end",contentIndex:y(),content:g.thinking,partial:n}),g=null);const t=e.functionCall.id,o={type:"toolCall",id:!t||n.content.some(e=>"toolCall"===e.type&&e.id===t)?`${e.functionCall.name}_${Date.now()}_${++Ji}`:t,name:e.functionCall.name||"",arguments:e.functionCall.args??{},...e.thoughtSignature&&{thoughtSignature:e.thoughtSignature}};n.content.push(o),l.push({type:"toolcall_start",contentIndex:y(),partial:n}),l.push({type:"toolcall_delta",contentIndex:y(),delta:JSON.stringify(o.arguments),partial:n}),l.push({type:"toolcall_end",contentIndex:y(),toolCall:o,partial:n})}}o?.finishReason&&(n.rawStopReason=o.finishReason,n.stopReason=Bi(o.finishReason),n.content.some(e=>"toolCall"===e.type)&&"stop"===n.stopReason&&(n.stopReason="toolUse")),t.usageMetadata&&(n.usage={input:(t.usageMetadata.promptTokenCount||0)-(t.usageMetadata.cachedContentTokenCount||0),output:(t.usageMetadata.candidatesTokenCount||0)+(t.usageMetadata.thoughtsTokenCount||0),cacheRead:t.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:t.usageMetadata.thoughtsTokenCount||0,totalTokens:t.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},i(e,n.usage))}if(g&&("text"===g.type?l.push({type:"text_end",contentIndex:y(),content:g.text,partial:n}):l.push({type:"thinking_end",contentIndex:y(),content:g.thinking,partial:n})),o?.signal?.aborted)throw new Error("Request was aborted");if("pending"===n.stopReason)throw new Error("Google stream ended without a finish reason");if("aborted"===n.stopReason||"error"===n.stopReason){const e=n.rawStopReason?`Provider stopped with: ${n.rawStopReason}`:"An unknown error occurred";throw new Error(e)}l.push({type:"done",reason:n.stopReason,message:n}),l.end()}catch(p){for(const e of n.content)"index"in e&&delete e.index;n.stopReason=o?.signal?.aborted?"aborted":"error",n.errorMessage=h(d(p)),l.push({type:"error",reason:n.stopReason,error:n}),l.end()}})(),l},$i=(e,t,n)=>{const i=n?.apiKey;if(!i)throw new Error(`No API key for provider: ${e.provider}`);const r=l(e,t,n,i);if(!n?.reasoning)return Yi(e,t,{...r,thinking:{enabled:!1}});const s=o(e,n.reasoning),a="off"===s?"high":s,u=e;return Wi(u)||zi(u)||Ki(u)?Yi(e,t,{...r,thinking:{enabled:!0,level:Xi(a,u)}}):Yi(e,t,{...r,thinking:{enabled:!0,budgetTokens:Qi(u,a,n.thinkingBudgets)}})};function Ki(e){return/gemma-?4/.test(e.id.toLowerCase())}function Wi(e){return/gemini-3(?:\.\d+)?-pro/.test(e.id.toLowerCase())}function zi(e){const t=e.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(t)||"gemini-flash-latest"===t||"gemini-flash-lite-latest"===t}function Xi(e,t){if(Wi(t))switch(e){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(Ki(t))switch(e){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function Qi(e,t,n){return void 0!==n?.[t]?n[t]:e.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[t]:e.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[t]:e.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[t]:-1}export{Yi as stream,$i as streamSimple};