hummin-cli 1.0.2 → 1.0.4

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 (67) hide show
  1. package/CHANGELOG.md +5778 -0
  2. package/LICENSE +21 -0
  3. package/README.md +718 -0
  4. package/dist/bundle/chunks/anthropic-messages-MYU5ZMRF.js +6 -0
  5. package/dist/bundle/chunks/azure-openai-responses-HUSQ3GP2.js +2 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +7 -2
  7. package/dist/bundle/chunks/{chunk-YMF7ELEJ.js → chunk-LNNEJ7WT.js} +46 -75
  8. package/dist/bundle/chunks/{chunk-WG5HGQZU.js → chunk-MFD3YQEX.js} +3 -3
  9. package/dist/bundle/chunks/{chunk-GTBU4EAF.js → chunk-RCZIEVGO.js} +10 -1
  10. package/dist/bundle/chunks/chunk-S7SZN6Z3.js +2 -0
  11. package/dist/bundle/chunks/chunk-WIUZI2CJ.js +11 -0
  12. package/dist/bundle/chunks/github-copilot.js +1 -1
  13. package/dist/bundle/chunks/google-generative-ai-DS3DOLEI.js +2 -0
  14. package/dist/bundle/chunks/google-vertex-TWD5HIQW.js +2 -0
  15. package/dist/bundle/chunks/mistral-conversations-NOSQHBEY.js +5 -0
  16. package/dist/bundle/chunks/openai-codex-responses-C4DRL6BB.js +10 -0
  17. package/dist/bundle/chunks/openai-completions-KQPOPEVM.js +7 -0
  18. package/dist/bundle/chunks/openai-responses-HWEUZ6WZ.js +2 -0
  19. package/dist/bundle/cli.js +1 -1
  20. package/dist/bundle/index.js +1 -1
  21. package/dist/bundle/rpc-entry.js +1 -1
  22. package/dist/core/export-html/ansi-to-html.d.ts +22 -0
  23. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
  24. package/dist/core/export-html/ansi-to-html.js +249 -0
  25. package/dist/core/export-html/ansi-to-html.js.map +1 -0
  26. package/dist/core/export-html/index.d.ts +37 -0
  27. package/dist/core/export-html/index.d.ts.map +1 -0
  28. package/dist/core/export-html/index.js +226 -0
  29. package/dist/core/export-html/index.js.map +1 -0
  30. package/dist/core/export-html/template.css +1066 -0
  31. package/dist/core/export-html/template.html +55 -0
  32. package/dist/core/export-html/template.js +1864 -0
  33. package/dist/core/export-html/tool-renderer.d.ts +34 -0
  34. package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
  35. package/dist/core/export-html/tool-renderer.js +108 -0
  36. package/dist/core/export-html/tool-renderer.js.map +1 -0
  37. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  38. package/dist/core/export-html/vendor/marked.min.js +78 -0
  39. package/dist/modes/interactive/assets/clankolas.png +0 -0
  40. package/dist/modes/interactive/theme/dark.json +91 -0
  41. package/dist/modes/interactive/theme/hummin-dark.json +93 -0
  42. package/dist/modes/interactive/theme/light.json +90 -0
  43. package/dist/modes/interactive/theme/theme-controller.d.ts +41 -0
  44. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -0
  45. package/dist/modes/interactive/theme/theme-controller.js +130 -0
  46. package/dist/modes/interactive/theme/theme-controller.js.map +1 -0
  47. package/dist/modes/interactive/theme/theme-json.d.ts +84 -0
  48. package/dist/modes/interactive/theme/theme-json.d.ts.map +1 -0
  49. package/dist/modes/interactive/theme/theme-json.js +130 -0
  50. package/dist/modes/interactive/theme/theme-json.js.map +1 -0
  51. package/dist/modes/interactive/theme/theme-schema.json +356 -0
  52. package/dist/modes/interactive/theme/theme.d.ts +131 -0
  53. package/dist/modes/interactive/theme/theme.d.ts.map +1 -0
  54. package/dist/modes/interactive/theme/theme.js +993 -0
  55. package/dist/modes/interactive/theme/theme.js.map +1 -0
  56. package/package.json +61 -38
  57. package/dist/bundle/chunks/anthropic-messages-RS73YAAL.js +0 -6
  58. package/dist/bundle/chunks/azure-openai-responses-WDUJVP6K.js +0 -2
  59. package/dist/bundle/chunks/chunk-AXIIZGTV.js +0 -2
  60. package/dist/bundle/chunks/chunk-GMWCTUPB.js +0 -2
  61. package/dist/bundle/chunks/chunk-NV6PWB3O.js +0 -11
  62. package/dist/bundle/chunks/google-generative-ai-BZMAU2ZY.js +0 -2
  63. package/dist/bundle/chunks/google-vertex-PW4J25VW.js +0 -2
  64. package/dist/bundle/chunks/mistral-conversations-KKK7YQAI.js +0 -5
  65. package/dist/bundle/chunks/openai-codex-responses-Y5ODP57V.js +0 -10
  66. package/dist/bundle/chunks/openai-completions-EIF77N53.js +0 -7
  67. package/dist/bundle/chunks/openai-responses-3W4DADHO.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{retryProviderRequest}from"./chunk-XNGRGP62.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-AXIIZGTV.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{__commonJS,__require,__toESM}from"./chunk-4L3WN2XY.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&&copy&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
2
+ import{retryProviderRequest}from"./chunk-XNGRGP62.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-S7SZN6Z3.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{clampThinkingLevel,collapseSystemMessages,withoutInitialSystemMessage}from"./chunk-RCZIEVGO.js";import{__commonJS,__require,__toESM}from"./chunk-4L3WN2XY.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&&copy&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
3
3
  `)||message,code,status},res.data.error)}return Object.assign({message,code,status},res.data.error)}}return{message,code:res.status,status:res.statusText}}};exports.GaxiosError=GaxiosError;function translateData(responseType,data){switch(responseType){case"stream":return data;case"json":return JSON.parse(JSON.stringify(data));case"arraybuffer":return JSON.parse(Buffer.from(data).toString("utf8"));case"blob":return JSON.parse(data.text());default:return data}}function defaultErrorRedactor(data){let REDACT="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function redactHeaders(headers){headers&&headers.forEach((_,key)=>{(/^authentication$/i.test(key)||/^authorization$/i.test(key)||/secret/i.test(key))&&headers.set(key,REDACT)})}function redactString(obj,key){if(typeof obj=="object"&&obj!==null&&typeof obj[key]=="string"){let text=obj[key];(/grant_type=/i.test(text)||/assertion=/i.test(text)||/secret/i.test(text))&&(obj[key]=REDACT)}}function redactObject(obj){!obj||typeof obj!="object"||(obj instanceof FormData||obj instanceof URLSearchParams||"forEach"in obj&&"set"in obj?obj.forEach((_,key)=>{(["grant_type","assertion"].includes(key)||/secret/.test(key))&&obj.set(key,REDACT)}):("grant_type"in obj&&(obj.grant_type=REDACT),"assertion"in obj&&(obj.assertion=REDACT),"client_secret"in obj&&(obj.client_secret=REDACT)))}return data.config&&(redactHeaders(data.config.headers),redactString(data.config,"data"),redactObject(data.config.data),redactString(data.config,"body"),redactObject(data.config.body),data.config.url.searchParams.has("token")&&data.config.url.searchParams.set("token",REDACT),data.config.url.searchParams.has("client_secret")&&data.config.url.searchParams.set("client_secret",REDACT)),data.response&&(defaultErrorRedactor({config:data.response.config}),redactHeaders(data.response.headers),data.response.bodyUsed&&(redactString(data.response,"data"),redactObject(data.response.data))),data}}});var require_retry3=__commonJS({"node_modules/gaxios/build/cjs/src/retry.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getRetryConfig=getRetryConfig;async function getRetryConfig(err){let config=getConfig(err);if(!err||!err.config||!config&&!err.config.retry)return{shouldRetry:!1};config=config||{},config.currentRetryAttempt=config.currentRetryAttempt||0,config.retry=config.retry===void 0||config.retry===null?3:config.retry,config.httpMethodsToRetry=config.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],config.noResponseRetries=config.noResponseRetries===void 0||config.noResponseRetries===null?2:config.noResponseRetries,config.retryDelayMultiplier=config.retryDelayMultiplier?config.retryDelayMultiplier:2,config.timeOfFirstRequest=config.timeOfFirstRequest?config.timeOfFirstRequest:Date.now(),config.totalTimeout=config.totalTimeout?config.totalTimeout:Number.MAX_SAFE_INTEGER,config.maxRetryDelay=config.maxRetryDelay?config.maxRetryDelay:Number.MAX_SAFE_INTEGER;let retryRanges=[[100,199],[408,408],[429,429],[500,599]];if(config.statusCodesToRetry=config.statusCodesToRetry||retryRanges,err.config.retryConfig=config,!await(config.shouldRetry||shouldRetryRequest)(err))return{shouldRetry:!1,config:err.config};let delay2=getNextRetryDelay(config);err.config.retryConfig.currentRetryAttempt+=1;let backoff=config.retryBackoff?config.retryBackoff(err,delay2):new Promise(resolve=>{setTimeout(resolve,delay2)});return config.onRetryAttempt&&await config.onRetryAttempt(err),await backoff,{shouldRetry:!0,config:err.config}}function shouldRetryRequest(err){let config=getConfig(err);if(err.config.signal?.aborted&&err.code!=="TimeoutError"||err.code==="AbortError"||!config||config.retry===0||!err.response&&(config.currentRetryAttempt||0)>=config.noResponseRetries||!config.httpMethodsToRetry||!config.httpMethodsToRetry.includes(err.config.method?.toUpperCase()||"GET"))return!1;if(err.response&&err.response.status){let isInRange=!1;for(let[min,max]of config.statusCodesToRetry){let status=err.response.status;if(status>=min&&status<=max){isInRange=!0;break}}if(!isInRange)return!1}return config.currentRetryAttempt=config.currentRetryAttempt||0,!(config.currentRetryAttempt>=config.retry)}function getConfig(err){if(err&&err.config&&err.config.retryConfig)return err.config.retryConfig}function getNextRetryDelay(config){let calculatedDelay=(config.currentRetryAttempt?0:config.retryDelay??100)+(Math.pow(config.retryDelayMultiplier,config.currentRetryAttempt)-1)/2*1e3,maxAllowableDelay=config.totalTimeout-(Date.now()-config.timeOfFirstRequest);return Math.min(calculatedDelay,maxAllowableDelay,config.maxRetryDelay)}}});var require_interceptor=__commonJS({"node_modules/gaxios/build/cjs/src/interceptor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosInterceptorManager=void 0;var GaxiosInterceptorManager=class extends Set{};exports.GaxiosInterceptorManager=GaxiosInterceptorManager}});var require_gaxios=__commonJS({"node_modules/gaxios/build/cjs/src/gaxios.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}},_a2;Object.defineProperty(exports,"__esModule",{value:!0});exports.Gaxios=void 0;var extend_1=__importDefault(require_extend()),https_1=__require("https"),common_js_1=require_common(),retry_js_1=require_retry3(),stream_1=__require("stream"),interceptor_js_1=require_interceptor(),randomUUID=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),HTTP_STATUS_NO_CONTENT=204,Gaxios=class{agentCache=new Map;defaults;interceptors;constructor(defaults){this.defaults=defaults||{},this.interceptors={request:new interceptor_js_1.GaxiosInterceptorManager,response:new interceptor_js_1.GaxiosInterceptorManager}}fetch(...args){let input=args[0],init=args[1],url,headers=new Headers;return typeof input=="string"?url=new URL(input):input instanceof URL?url=input:input&&input.url&&(url=new URL(input.url)),input&&typeof input=="object"&&"headers"in input&&_a2.mergeHeaders(headers,input.headers),init&&_a2.mergeHeaders(headers,new Headers(init.headers)),typeof input=="object"&&!(input instanceof URL)?this.request({...init,...input,headers,url}):this.request({...init,headers,url})}async request(opts={}){let prepared=await this.#prepareRequest(opts);return prepared=await this.#applyRequestInterceptors(prepared),this.#applyResponseInterceptors(this._request(prepared))}async _defaultAdapter(config){let fetchImpl=config.fetchImplementation||this.defaults.fetchImplementation||await _a2.#getFetch(),preparedOpts={...config};delete preparedOpts.data;let res=await fetchImpl(config.url,preparedOpts),data=await this.getResponseData(config,res);return Object.getOwnPropertyDescriptor(res,"data")?.configurable||Object.defineProperties(res,{data:{configurable:!0,writable:!0,enumerable:!0,value:data}}),Object.assign(res,{config,data})}async _request(opts){try{let translatedResponse;if(opts.adapter?translatedResponse=await opts.adapter(opts,this._defaultAdapter.bind(this)):translatedResponse=await this._defaultAdapter(opts),!opts.validateStatus(translatedResponse.status)){if(opts.responseType==="stream"){let response=[];for await(let chunk of translatedResponse.data)response.push(chunk);translatedResponse.data=response.toString()}let errorInfo=common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse,`Request failed with status code ${translatedResponse.status}`);throw new common_js_1.GaxiosError(errorInfo?.message,opts,translatedResponse,errorInfo)}return translatedResponse}catch(e){let err;e instanceof common_js_1.GaxiosError?err=e:e instanceof Error?err=new common_js_1.GaxiosError(e.message,opts,void 0,e):err=new common_js_1.GaxiosError("Unexpected Gaxios Error",opts,void 0,e);let{shouldRetry,config}=await(0,retry_js_1.getRetryConfig)(err);if(shouldRetry&&config)return err.config.retryConfig.currentRetryAttempt=config.retryConfig.currentRetryAttempt,opts.retryConfig=err.config?.retryConfig,this.#appendTimeoutToSignal(opts),this._request(opts);throw opts.errorRedactor&&opts.errorRedactor(err),err}}async getResponseData(opts,res){if(res.status===HTTP_STATUS_NO_CONTENT)return"";if(opts.maxContentLength&&res.headers.has("content-length")&&opts.maxContentLength<Number.parseInt(res.headers?.get("content-length")||""))throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.",opts,Object.assign(res,{config:opts}));switch(opts.responseType){case"stream":return res.body;case"json":{let data=await res.text();try{return JSON.parse(data)}catch{return data}}case"arraybuffer":return res.arrayBuffer();case"blob":return res.blob();case"text":return res.text();default:return this.getResponseDataFromContentType(res)}}#urlMayUseProxy(url,noProxy=[]){let candidate=new URL(url),noProxyList=[...noProxy],noProxyEnvList=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let rule of noProxyEnvList)noProxyList.push(rule.trim());for(let rule of noProxyList)if(rule instanceof RegExp){if(rule.test(candidate.toString()))return!1}else if(rule instanceof URL){if(rule.origin===candidate.origin)return!1}else if(rule.startsWith("*.")||rule.startsWith(".")){let cleanedRule=rule.replace(/^\*\./,".");if(candidate.hostname.endsWith(cleanedRule))return!1}else if(rule===candidate.origin||rule===candidate.hostname||rule===candidate.href)return!1;return!0}async#applyRequestInterceptors(options){let promiseChain=Promise.resolve(options);for(let interceptor of this.interceptors.request.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#applyResponseInterceptors(response){let promiseChain=Promise.resolve(response);for(let interceptor of this.interceptors.response.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#prepareRequest(options){let preparedHeaders=new Headers(this.defaults.headers);_a2.mergeHeaders(preparedHeaders,options.headers);let opts=(0,extend_1.default)(!0,{},this.defaults,options);if(!opts.url)throw new Error("URL is required.");if(opts.baseURL&&(opts.url=new URL(opts.url,opts.baseURL)),opts.url=new URL(opts.url),opts.params)if(opts.paramsSerializer){let additionalQueryParams=opts.paramsSerializer(opts.params);additionalQueryParams.startsWith("?")&&(additionalQueryParams=additionalQueryParams.slice(1));let prefix=opts.url.toString().includes("?")?"&":"?";opts.url=opts.url+prefix+additionalQueryParams}else{let url=opts.url instanceof URL?opts.url:new URL(opts.url);for(let[key,value]of new URLSearchParams(opts.params))url.searchParams.append(key,value);opts.url=url}typeof options.maxContentLength=="number"&&(opts.size=options.maxContentLength),typeof options.maxRedirects=="number"&&(opts.follow=options.maxRedirects);let shouldDirectlyPassData=typeof opts.data=="string"||opts.data instanceof ArrayBuffer||opts.data instanceof Blob||globalThis.File&&opts.data instanceof File||opts.data instanceof FormData||opts.data instanceof stream_1.Readable||opts.data instanceof ReadableStream||opts.data instanceof String||opts.data instanceof URLSearchParams||ArrayBuffer.isView(opts.data)||["Blob","File","FormData"].includes(opts.data?.constructor?.name||"");if(opts.multipart?.length){let boundary=await randomUUID();preparedHeaders.set("content-type",`multipart/related; boundary=${boundary}`),opts.body=stream_1.Readable.from(this.getMultipartRequest(opts.multipart,boundary))}else shouldDirectlyPassData?opts.body=opts.data:typeof opts.data=="object"?preparedHeaders.get("Content-Type")==="application/x-www-form-urlencoded"?opts.body=opts.paramsSerializer?opts.paramsSerializer(opts.data):new URLSearchParams(opts.data):(preparedHeaders.has("content-type")||preparedHeaders.set("content-type","application/json"),opts.body=JSON.stringify(opts.data)):opts.data&&(opts.body=opts.data);opts.validateStatus=opts.validateStatus||this.validateStatus,opts.responseType=opts.responseType||"unknown",!preparedHeaders.has("accept")&&opts.responseType==="json"&&preparedHeaders.set("accept","application/json");let proxy=opts.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!opts.agent)if(proxy&&this.#urlMayUseProxy(opts.url,opts.noProxy)){let HttpsProxyAgent=await _a2.#getProxyAgent();this.agentCache.has(proxy)?opts.agent=this.agentCache.get(proxy):(opts.agent=new HttpsProxyAgent(proxy,{cert:opts.cert,key:opts.key}),this.agentCache.set(proxy,opts.agent))}else opts.cert&&opts.key&&(this.agentCache.has(opts.key)?opts.agent=this.agentCache.get(opts.key):(opts.agent=new https_1.Agent({cert:opts.cert,key:opts.key}),this.agentCache.set(opts.key,opts.agent)));return typeof opts.errorRedactor!="function"&&opts.errorRedactor!==!1&&(opts.errorRedactor=common_js_1.defaultErrorRedactor),opts.body&&!("duplex"in opts)&&(opts.duplex="half"),this.#appendTimeoutToSignal(opts),Object.assign(opts,{headers:preparedHeaders,url:opts.url instanceof URL?opts.url:new URL(opts.url)})}#appendTimeoutToSignal(opts){if(opts.timeout){let timeoutSignal=AbortSignal.timeout(opts.timeout);opts.signal&&!opts.signal.aborted?opts.signal=AbortSignal.any([opts.signal,timeoutSignal]):opts.signal=timeoutSignal}}validateStatus(status){return status>=200&&status<300}async getResponseDataFromContentType(response){let contentType=response.headers.get("Content-Type");if(contentType===null)return response.text();if(contentType=contentType.toLowerCase(),contentType.includes("application/json")){let data=await response.text();try{data=JSON.parse(data)}catch{}return data}else return contentType.match(/^text\//)?response.text():response.blob()}async*getMultipartRequest(multipartOptions,boundary){let finale=`--${boundary}--`;for(let currentPart of multipartOptions){let partContentType=currentPart.headers.get("Content-Type")||"application/octet-stream";yield`--${boundary}\r
4
4
  Content-Type: ${partContentType}\r
5
5
  \r
@@ -40,5 +40,5 @@ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Go
40
40
  \r
41
41
  `];for(;;){let{done,value}=yield __await(reader.read());if(done){if(buffer.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}let chunkString=decoder.decode(value,{stream:!0});try{let chunkJson=JSON.parse(chunkString);if("error"in chunkJson){let errorJson=JSON.parse(JSON.stringify(chunkJson.error)),status=errorJson.status,code=errorJson.code,errorMessage=`got status: ${status}. ${JSON.stringify(chunkJson)}`;if(code>=400&&code<600)throw new ApiError({message:errorMessage,status:code})}}catch(e){if(e.name==="ApiError")throw e}buffer+=chunkString;let delimiterIndex=-1,delimiterLength=0;for(;;){delimiterIndex=-1,delimiterLength=0;for(let delimiter of delimiters){let index=buffer.indexOf(delimiter);index!==-1&&(delimiterIndex===-1||index<delimiterIndex)&&(delimiterIndex=index,delimiterLength=delimiter.length)}if(delimiterIndex===-1)break;let eventString=buffer.substring(0,delimiterIndex);buffer=buffer.substring(delimiterIndex+delimiterLength);let trimmedEvent=eventString.trim();if(trimmedEvent.startsWith(dataPrefix)){let processedChunkString=trimmedEvent.substring(dataPrefix.length).trim();try{let partialResponse=new Response(processedChunkString,{headers:response?.headers,status:response?.status,statusText:response?.statusText});yield yield __await(new HttpResponse(partialResponse))}catch(e){throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`)}}}}}finally{reader.releaseLock()}})}async apiCall(url,requestInit,retryOptions,timeout,abortSignal){var _a2,_b,_c,_d,_e,_f;let retryableStatusCodes=(_a2=retryOptions?.httpStatusCodes)!==null&&_a2!==void 0?_a2:DEFAULT_RETRY_HTTP_STATUS_CODES,runFetch=async()=>{let attempt=createAttemptSignal(timeout,abortSignal),response;try{response=await fetch(url,Object.assign(Object.assign({},requestInit),{signal:attempt.signal}))}catch(e){throw attempt.dispose(),e}if(!retryOptions||response.ok||!retryableStatusCodes.includes(response.status))return response;try{await throwErrorIfNotOK(response)}finally{attempt.dispose()}return response};if(!retryOptions)return runFetch();let attempts=Math.max(1,(_b=retryOptions.attempts)!==null&&_b!==void 0?_b:DEFAULT_RETRY_ATTEMPTS),minTimeout=Math.round(((_c=retryOptions.initialDelay)!==null&&_c!==void 0?_c:DEFAULT_RETRY_INITIAL_DELAY)*1e3),maxTimeout=Math.max(minTimeout,Math.round(((_d=retryOptions.maxDelay)!==null&&_d!==void 0?_d:DEFAULT_RETRY_MAX_DELAY)*1e3));return(0,import_p_retry.default)(runFetch,{retries:attempts-1,factor:(_e=retryOptions.expBase)!==null&&_e!==void 0?_e:DEFAULT_RETRY_EXP_BASE,minTimeout,maxTimeout,randomize:((_f=retryOptions.jitter)!==null&&_f!==void 0?_f:DEFAULT_RETRY_JITTER)>0,onFailedAttempt:info=>{var _a3;if(abortSignal?.aborted)throw(_a3=info.error)!==null&&_a3!==void 0?_a3:info}})}getDefaultHeaders(){let headers={},versionHeaderValue=LIBRARY_LABEL+" "+this.clientOptions.userAgentExtra;return headers[USER_AGENT_HEADER]=versionHeaderValue,headers[GOOGLE_API_CLIENT_HEADER]=versionHeaderValue,headers[CONTENT_TYPE_HEADER]="application/json",headers}async getHeadersInternal(httpOptions,url){let headers=new Headers;if(httpOptions&&httpOptions.headers)for(let[key,value]of Object.entries(httpOptions.headers))headers.append(key,value);return httpOptions?.timeout&&httpOptions.timeout>0&&headers.append(SERVER_TIMEOUT_HEADER,String(Math.ceil(httpOptions.timeout/1e3))),await this.clientOptions.auth.addAuthHeaders(headers,url),headers}getFileName(file){var _a2;let fileName="";return typeof file=="string"&&(fileName=file.replace(/[/\\]+$/,""),fileName=(_a2=fileName.split(/[/\\]/).pop())!==null&&_a2!==void 0?_a2:""),fileName}async uploadFile(file,config){var _a2;let fileToUpload={};config!=null&&(fileToUpload.mimeType=config.mimeType,fileToUpload.name=config.name,fileToUpload.displayName=config.displayName),fileToUpload.name&&!fileToUpload.name.startsWith("files/")&&(fileToUpload.name=`files/${fileToUpload.name}`);let uploader=this.clientOptions.uploader,fileStat=await uploader.stat(file);fileToUpload.sizeBytes=String(fileStat.size);let mimeType=(_a2=config?.mimeType)!==null&&_a2!==void 0?_a2:fileStat.type;if(mimeType===void 0||mimeType==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");fileToUpload.mimeType=mimeType;let body={file:fileToUpload},fileName=this.getFileName(file),path2=formatMap("upload/v1beta/files",body._url),uploadUrl=await this.fetchUploadUrl(path2,fileToUpload.sizeBytes,fileToUpload.mimeType,fileName,body,config?.httpOptions);return uploader.upload(file,uploadUrl,this)}async uploadFileToFileSearchStore(fileSearchStoreName,file,config){var _a2;let uploader=this.clientOptions.uploader,fileStat=await uploader.stat(file),sizeBytes=String(fileStat.size),mimeType=(_a2=config?.mimeType)!==null&&_a2!==void 0?_a2:fileStat.type;if(mimeType===void 0||mimeType==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let path2=`upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`,fileName=this.getFileName(file),body={};config!=null&&uploadToFileSearchStoreConfigToMldev(config,body);let uploadUrl=await this.fetchUploadUrl(path2,sizeBytes,mimeType,fileName,body,config?.httpOptions);return uploader.uploadToFileSearchStore(file,uploadUrl,this)}async downloadFile(params){await this.clientOptions.downloader.download(params,this)}async fetchUploadUrl(path2,sizeBytes,mimeType,fileName,body,configHttpOptions){var _a2;let httpOptions={};configHttpOptions?httpOptions=configHttpOptions:httpOptions={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${sizeBytes}`,"X-Goog-Upload-Header-Content-Type":`${mimeType}`},fileName?{"X-Goog-Upload-File-Name":fileName}:{})};let httpResponse=await this.request({path:path2,body:JSON.stringify(body),httpMethod:"POST",httpOptions});if(!httpResponse||!httpResponse?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let uploadUrl=(_a2=httpResponse?.headers)===null||_a2===void 0?void 0:_a2["x-goog-upload-url"];if(uploadUrl===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return uploadUrl}};async function throwErrorIfNotOK(response){var _a2;if(response===void 0)throw new Error("response is undefined");if(!response.ok){let status=response.status,errorBody;!((_a2=response.headers.get("content-type"))===null||_a2===void 0)&&_a2.includes("application/json")?errorBody=await response.json():errorBody={error:{message:await response.text(),code:response.status,status:response.statusText}};let errorMessage=JSON.stringify(errorBody);throw status>=400&&status<600?new ApiError({message:errorMessage,status}):new Error(errorMessage)}}function includeExtraBodyToRequestInit(requestInit,extraBody){if(!extraBody||Object.keys(extraBody).length===0)return;if(requestInit.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let currentBodyObject={};if(typeof requestInit.body=="string"&&requestInit.body.length>0)try{let parsedBody=JSON.parse(requestInit.body);if(typeof parsedBody=="object"&&parsedBody!==null&&!Array.isArray(parsedBody))currentBodyObject=parsedBody;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function deepMerge(target,source){let output=Object.assign({},target);for(let key in source)if(Object.prototype.hasOwnProperty.call(source,key)){let sourceValue=source[key],targetValue=output[key];sourceValue&&typeof sourceValue=="object"&&!Array.isArray(sourceValue)&&targetValue&&typeof targetValue=="object"&&!Array.isArray(targetValue)?output[key]=deepMerge(targetValue,sourceValue):(targetValue&&sourceValue&&typeof targetValue!=typeof sourceValue&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`),output[key]=sourceValue)}return output}let mergedBody=deepMerge(currentBodyObject,extraBody);requestInit.body=JSON.stringify(mergedBody)}var MCP_LABEL="mcp_used/unknown",hasMcpToolUsageFromMcpToTool=!1;function hasMcpToolUsage(tools){for(let tool of tools)if(isMcpCallableTool(tool)||typeof tool=="object"&&"inputSchema"in tool)return!0;return hasMcpToolUsageFromMcpToTool}function setMcpUsageHeader(headers){var _a2;let existingHeader=(_a2=headers[GOOGLE_API_CLIENT_HEADER])!==null&&_a2!==void 0?_a2:"";headers[GOOGLE_API_CLIENT_HEADER]=(existingHeader+` ${MCP_LABEL}`).trimStart()}function isMcpCallableTool(object){return object!==null&&typeof object=="object"&&object instanceof McpCallableTool}function listAllTools(mcpClient_1){return __asyncGenerator(this,arguments,function*(mcpClient,maxTools=100){let cursor,numTools=0;for(;numTools<maxTools;){let t=yield __await(mcpClient.listTools({cursor}));for(let tool of t.tools)yield yield __await(tool),numTools++;if(!t.nextCursor)break;cursor=t.nextCursor}})}var McpCallableTool=class _McpCallableTool{constructor(mcpClients=[],config){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=mcpClients,this.config=config}static create(mcpClients,config){return new _McpCallableTool(mcpClients,config)}async initialize(){var _a2,e_1,_b,_c;if(this.mcpTools.length>0)return;let functionMap={},mcpTools=[];for(let mcpClient of this.mcpClients)try{for(var _d=!0,_e=(e_1=void 0,__asyncValues(listAllTools(mcpClient))),_f;_f=await _e.next(),_a2=_f.done,!_a2;_d=!0){_c=_f.value,_d=!1;let mcpTool=_c;mcpTools.push(mcpTool);let mcpToolName=mcpTool.name;if(functionMap[mcpToolName])throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);functionMap[mcpToolName]=mcpClient}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_d&&!_a2&&(_b=_e.return)&&await _b.call(_e)}finally{if(e_1)throw e_1.error}}this.mcpTools=mcpTools,this.functionNameToMcpClient=functionMap}async tool(){return await this.initialize(),mcpToolsToGeminiTool(this.mcpTools,this.config)}async callTool(functionCalls){await this.initialize();let functionCallResponseParts=[];for(let functionCall of functionCalls)if(functionCall.name in this.functionNameToMcpClient){let mcpClient=this.functionNameToMcpClient[functionCall.name],requestOptions;this.config.timeout&&(requestOptions={timeout:this.config.timeout});let callToolResponse=await mcpClient.callTool({name:functionCall.name,arguments:functionCall.args},void 0,requestOptions);functionCallResponseParts.push({functionResponse:{name:functionCall.name,response:callToolResponse.isError?{error:callToolResponse}:callToolResponse}})}return functionCallResponseParts}};async function handleWebSocketMessage$1(apiClient,onmessage,event){let serverMessage=new LiveMusicServerMessage,data;event.data instanceof Blob?data=JSON.parse(await event.data.text()):data=JSON.parse(event.data),Object.assign(serverMessage,data),onmessage(serverMessage)}var LiveMusic=class{constructor(apiClient,auth,webSocketFactory){this.apiClient=apiClient,this.auth=auth,this.webSocketFactory=webSocketFactory}async connect(params){var _a2,_b;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let websocketBaseUrl=this.apiClient.getWebsocketBaseUrl(),apiVersion=this.apiClient.getApiVersion(),headers=mapToHeaders$1(this.apiClient.getDefaultHeaders()),apiKey=this.apiClient.getApiKey(),url=`${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`,onopenResolve=()=>{},onopenPromise=new Promise(resolve=>{onopenResolve=resolve}),callbacks=params.callbacks,onopenAwaitedCallback=function(){onopenResolve({})},apiClient=this.apiClient,websocketCallbacks={onopen:onopenAwaitedCallback,onmessage:event=>{handleWebSocketMessage$1(apiClient,callbacks.onmessage,event)},onerror:(_a2=callbacks?.onerror)!==null&&_a2!==void 0?_a2:function(e){},onclose:(_b=callbacks?.onclose)!==null&&_b!==void 0?_b:function(e){}},conn=this.webSocketFactory.create(url,headersToMap$1(headers),websocketCallbacks);conn.connect(),await onopenPromise;let clientMessage={setup:{model:tModel(this.apiClient,params.model)}};return conn.send(JSON.stringify(clientMessage)),new LiveMusicSession(conn,this.apiClient)}},LiveMusicSession=class{constructor(conn,apiClient){this.conn=conn,this.apiClient=apiClient}async setWeightedPrompts(params){if(!params.weightedPrompts||Object.keys(params.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");let clientContent=liveMusicSetWeightedPromptsParametersToMldev(params);this.conn.send(JSON.stringify({clientContent}))}async setMusicGenerationConfig(params){params.musicGenerationConfig||(params.musicGenerationConfig={});let setConfigParameters=liveMusicSetConfigParametersToMldev(params);this.conn.send(JSON.stringify(setConfigParameters))}sendPlaybackControl(playbackControl){let clientMessage={playbackControl};this.conn.send(JSON.stringify(clientMessage))}play(){this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY)}pause(){this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE)}stop(){this.sendPlaybackControl(LiveMusicPlaybackControl.STOP)}resetContext(){this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT)}close(){this.conn.close()}};function headersToMap$1(headers){let headerMap={};return headers.forEach((value,key)=>{headerMap[key]=value}),headerMap}function mapToHeaders$1(map){let headers=new Headers;for(let[key,value]of Object.entries(map))headers.append(key,value);return headers}var FUNCTION_RESPONSE_REQUIRES_ID="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function handleWebSocketMessage(apiClient,onmessage,event){let serverMessage=new LiveServerMessage,jsonData;event.data instanceof Blob?jsonData=await event.data.text():event.data instanceof ArrayBuffer?jsonData=new TextDecoder().decode(event.data):jsonData=event.data;let data=JSON.parse(jsonData);if(apiClient.isVertexAI()){let resp=liveServerMessageFromVertex(data);Object.assign(serverMessage,resp)}else Object.assign(serverMessage,data);onmessage(serverMessage)}var Live=class{constructor(apiClient,auth,webSocketFactory){this.apiClient=apiClient,this.auth=auth,this.webSocketFactory=webSocketFactory,this.music=new LiveMusic(this.apiClient,this.auth,this.webSocketFactory)}async connect(params){var _a2,_b,_c,_d,_e,_f;if(params.config&&params.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let websocketBaseUrl=this.apiClient.getWebsocketBaseUrl(),apiVersion=this.apiClient.getApiVersion(),url,clientHeaders=this.apiClient.getHeaders();params.config&&params.config.tools&&hasMcpToolUsage(params.config.tools)&&setMcpUsageHeader(clientHeaders);let headers=mapToHeaders(clientHeaders);if(this.apiClient.isVertexAI()){let project=this.apiClient.getProject(),location=this.apiClient.getLocation(),apiKey=this.apiClient.getApiKey(),hasStandardAuth=!!project&&!!location||!!apiKey;this.apiClient.getCustomBaseUrl()&&!hasStandardAuth?url=websocketBaseUrl:(url=`${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(headers,url))}else{let apiKey=this.apiClient.getApiKey(),method="BidiGenerateContent",keyName="key";apiKey?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),apiVersion!=="v1alpha"&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),method="BidiGenerateContentConstrained",keyName="access_token"),url=`${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`}let onopenResolve=()=>{},onopenPromise=new Promise(resolve=>{onopenResolve=resolve}),callbacks=params.callbacks,onopenAwaitedCallback=function(){var _a3;(_a3=callbacks?.onopen)===null||_a3===void 0||_a3.call(callbacks),onopenResolve({})},apiClient=this.apiClient,sessionResolved=!1,messageQueue=[],setupCompleteResolve=()=>{},setupCompletePromise=new Promise(resolve=>{setupCompleteResolve=resolve}),websocketCallbacks={onopen:onopenAwaitedCallback,onmessage:event=>{handleWebSocketMessage(apiClient,msg=>{msg.setupComplete&&!session.setupComplete&&(session.setupComplete=msg.setupComplete,setupCompleteResolve({})),sessionResolved?callbacks.onmessage(msg):messageQueue.push(msg)},event)},onerror:(_a2=callbacks?.onerror)!==null&&_a2!==void 0?_a2:function(e){},onclose:(_b=callbacks?.onclose)!==null&&_b!==void 0?_b:function(e){}},conn=this.webSocketFactory.create(url,headersToMap(headers),websocketCallbacks);conn.connect(),await onopenPromise;let transformedModel=tModel(this.apiClient,params.model);if(this.apiClient.isVertexAI()&&transformedModel.startsWith("publishers/")){let project=this.apiClient.getProject(),location=this.apiClient.getLocation();project&&location&&(transformedModel=`projects/${project}/locations/${location}/`+transformedModel)}let clientMessage={};this.apiClient.isVertexAI()&&((_c=params.config)===null||_c===void 0?void 0:_c.responseModalities)===void 0&&(params.config===void 0?params.config={responseModalities:[Modality.AUDIO]}:params.config.responseModalities=[Modality.AUDIO]),!((_d=params.config)===null||_d===void 0)&&_d.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. It will be removed in the next major version (not before 7/31/2026).");let inputTools=(_f=(_e=params.config)===null||_e===void 0?void 0:_e.tools)!==null&&_f!==void 0?_f:[],convertedTools=[];for(let tool of inputTools)if(this.isCallableTool(tool)){let callableTool=tool;convertedTools.push(await callableTool.tool())}else convertedTools.push(tool);convertedTools.length>0&&(params.config.tools=convertedTools);let liveConnectParameters={model:transformedModel,config:params.config,callbacks:params.callbacks};this.apiClient.isVertexAI()?clientMessage=liveConnectParametersToVertex(this.apiClient,liveConnectParameters):clientMessage=liveConnectParametersToMldev(this.apiClient,liveConnectParameters),delete clientMessage.config;let session=new Session(conn,this.apiClient);conn.send(JSON.stringify(clientMessage)),await setupCompletePromise,sessionResolved=!0;for(let msg of messageQueue)callbacks.onmessage(msg);return session}isCallableTool(tool){return"callTool"in tool&&typeof tool.callTool=="function"}},defaultLiveSendClientContentParamerters={turnComplete:!0},Session=class{constructor(conn,apiClient){this.conn=conn,this.apiClient=apiClient}tLiveClientContent(apiClient,params){if(params.turns!==null&&params.turns!==void 0){let contents=[];try{contents=tContents(params.turns),apiClient.isVertexAI()||(contents=contents.map(item=>contentToMldev$1(item)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`)}return{clientContent:{turns:contents,turnComplete:params.turnComplete}}}return{clientContent:{turnComplete:params.turnComplete}}}tLiveClienttToolResponse(apiClient,params){let functionResponses=[];if(params.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(params.functionResponses)?functionResponses=params.functionResponses:functionResponses=[params.functionResponses],functionResponses.length===0)throw new Error("functionResponses is required.");for(let functionResponse of functionResponses){if(typeof functionResponse!="object"||functionResponse===null||!("name"in functionResponse)||!("response"in functionResponse))throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`);if(!apiClient.isVertexAI()&&!("id"in functionResponse))throw new Error(FUNCTION_RESPONSE_REQUIRES_ID)}return{toolResponse:{functionResponses}}}sendClientContent(params){params=Object.assign(Object.assign({},defaultLiveSendClientContentParamerters),params);let clientMessage=this.tLiveClientContent(this.apiClient,params);this.conn.send(JSON.stringify(clientMessage))}sendRealtimeInput(params){let clientMessage={};this.apiClient.isVertexAI()?clientMessage={realtimeInput:liveSendRealtimeInputParametersToVertex(params)}:clientMessage={realtimeInput:liveSendRealtimeInputParametersToMldev(params)},this.conn.send(JSON.stringify(clientMessage))}sendToolResponse(params){if(params.functionResponses==null)throw new Error("Tool response parameters are required.");let clientMessage=this.tLiveClienttToolResponse(this.apiClient,params);this.conn.send(JSON.stringify(clientMessage))}close(){this.conn.close()}};function headersToMap(headers){let headerMap={};return headers.forEach((value,key)=>{headerMap[key]=value}),headerMap}function mapToHeaders(map){let headers=new Headers;for(let[key,value]of Object.entries(map))headers.append(key,value);return headers}var DEFAULT_MAX_REMOTE_CALLS=10;function shouldDisableAfc(config){var _a2,_b,_c;if(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.disable)return!0;let callableToolsPresent=!1;for(let tool of(_b=config?.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){callableToolsPresent=!0;break}if(!callableToolsPresent)return!0;let maxCalls=(_c=config?.automaticFunctionCalling)===null||_c===void 0?void 0:_c.maximumRemoteCalls;return maxCalls&&(maxCalls<0||!Number.isInteger(maxCalls))||maxCalls==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",maxCalls),!0):!1}function isCallableTool(tool){return"callTool"in tool&&typeof tool.callTool=="function"}function hasCallableTools(params){var _a2,_b,_c;return(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)===null||_b===void 0?void 0:_b.some(tool=>isCallableTool(tool)))!==null&&_c!==void 0?_c:!1}function findAfcIncompatibleToolIndexes(params){var _a2;let afcIncompatibleToolIndexes=[];return!((_a2=params?.config)===null||_a2===void 0)&&_a2.tools&&params.config.tools.forEach((tool,index)=>{if(isCallableTool(tool))return;let geminiTool=tool;geminiTool.functionDeclarations&&geminiTool.functionDeclarations.length>0&&afcIncompatibleToolIndexes.push(index)}),afcIncompatibleToolIndexes}function shouldAppendAfcHistory(config){var _a2;return!(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.ignoreCallHistory)}var Models=class _Models extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.embedContent=async params=>{if(!this.apiClient.isVertexAI())return params.model.includes("gemini-embedding-2")&&(params.contents=tContents(params.contents)),await this.embedContentInternal(params);if(params.model.includes("gemini")&&params.model!=="gemini-embedding-001"||params.model.includes("maas")){let contents=tContents(params.contents);if(contents.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let paramsPrivate=Object.assign(Object.assign({},params),{content:contents[0],embeddingApiType:EmbeddingApiType.EMBED_CONTENT});return await this.embedContentInternal(paramsPrivate)}else{let paramsPrivate=Object.assign(Object.assign({},params),{embeddingApiType:EmbeddingApiType.PREDICT});return await this.embedContentInternal(paramsPrivate)}},this.generateContent=async params=>{var _a2,_b,_c,_d,_e;let transformedParams=await this.processParamsMaybeAddMcpUsage(params);if(this.maybeMoveToResponseJsonSchema(params),!hasCallableTools(params)||shouldDisableAfc(params.config))return await this.generateContentInternal(transformedParams);let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`)}let response,functionResponseContent,automaticFunctionCallingHistory=tContents(transformedParams.contents),maxRemoteCalls=(_c=(_b=(_a2=transformedParams.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,remoteCalls=0;for(;remoteCalls<maxRemoteCalls&&(response=await this.generateContentInternal(transformedParams),!(!response.functionCalls||response.functionCalls.length===0));){let responseContent=response.candidates[0].content,functionResponseParts=[];for(let tool of(_e=(_d=params.config)===null||_d===void 0?void 0:_d.tools)!==null&&_e!==void 0?_e:[])if(isCallableTool(tool)){let parts=await tool.callTool(response.functionCalls);functionResponseParts.push(...parts)}remoteCalls++,functionResponseContent={role:"user",parts:functionResponseParts},transformedParams.contents=tContents(transformedParams.contents),transformedParams.contents.push(responseContent),transformedParams.contents.push(functionResponseContent),shouldAppendAfcHistory(transformedParams.config)&&(automaticFunctionCallingHistory.push(responseContent),automaticFunctionCallingHistory.push(functionResponseContent))}return shouldAppendAfcHistory(transformedParams.config)&&(response.automaticFunctionCallingHistory=automaticFunctionCallingHistory),response},this.generateContentStream=async params=>{var _a2,_b,_c,_d,_e;if(this.maybeMoveToResponseJsonSchema(params),shouldDisableAfc(params.config)){let transformedParams=await this.processParamsMaybeAddMcpUsage(params);return await this.generateContentStreamInternal(transformedParams)}let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let streamFunctionCall=(_c=(_b=(_a2=params?.config)===null||_a2===void 0?void 0:_a2.toolConfig)===null||_b===void 0?void 0:_b.functionCallingConfig)===null||_c===void 0?void 0:_c.streamFunctionCallArguments,disableAfc=(_e=(_d=params?.config)===null||_d===void 0?void 0:_d.automaticFunctionCalling)===null||_e===void 0?void 0:_e.disable;if(streamFunctionCall&&!disableAfc)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(params)},this.generateImages=async params=>(_Models.loggedGenerateImagesWarning||(_Models.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(params).then(apiResponse=>{var _a2;let positivePromptSafetyAttributes,generatedImages=[];if(apiResponse?.generatedImages)for(let generatedImage of apiResponse.generatedImages)generatedImage&&generatedImage?.safetyAttributes&&((_a2=generatedImage?.safetyAttributes)===null||_a2===void 0?void 0:_a2.contentType)==="Positive Prompt"?positivePromptSafetyAttributes=generatedImage?.safetyAttributes:generatedImages.push(generatedImage);let response;return positivePromptSafetyAttributes?response={generatedImages,positivePromptSafetyAttributes,sdkHttpResponse:apiResponse.sdkHttpResponse}:response={generatedImages,sdkHttpResponse:apiResponse.sdkHttpResponse},response})),this.list=async params=>{var _a2;let actualParams={config:Object.assign(Object.assign({},{queryBase:!0}),params?.config)};if(this.apiClient.isVertexAI()&&!actualParams.config.queryBase){if(!((_a2=actualParams.config)===null||_a2===void 0)&&_a2.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");actualParams.config.filter="labels.tune-type:*"}return new Pager(PagedItem.PAGED_ITEM_MODELS,x=>this.listInternal(x),await this.listInternal(actualParams),actualParams)},this.editImage=async params=>{_Models.loggedEditImageWarning||(_Models.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let paramsInternal={model:params.model,prompt:params.prompt,referenceImages:[],config:params.config};return params.referenceImages&&params.referenceImages&&(paramsInternal.referenceImages=params.referenceImages.map(img=>img.toReferenceImageAPI())),await this.editImageInternal(paramsInternal)},this.upscaleImage=async params=>{let apiConfig={numberOfImages:1,mode:"upscale"};params.config&&(apiConfig=Object.assign(Object.assign({},apiConfig),params.config));let apiParams={model:params.model,image:params.image,upscaleFactor:params.upscaleFactor,config:apiConfig};return await this.upscaleImageInternal(apiParams)},this.generateVideos=async params=>{var _a2,_b,_c,_d,_e,_f;if((params.prompt||params.image||params.video)&&params.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(params.prompt||params.image||params.video)&&(_Models.loggedGenerateVideosWarning||(_Models.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((_a2=params.video)===null||_a2===void 0)&&_a2.uri&&(!((_b=params.video)===null||_b===void 0)&&_b.videoBytes)?params.video={uri:params.video.uri,mimeType:params.video.mimeType}:!((_d=(_c=params.source)===null||_c===void 0?void 0:_c.video)===null||_d===void 0)&&_d.uri&&(!((_f=(_e=params.source)===null||_e===void 0?void 0:_e.video)===null||_f===void 0)&&_f.videoBytes)&&(params.source.video={uri:params.source.video.uri,mimeType:params.source.video.mimeType})),await this.generateVideosInternal(params)}}maybeMoveToResponseJsonSchema(params){params.config&&params.config.responseSchema&&(params.config.responseJsonSchema||Object.keys(params.config.responseSchema).includes("$schema")&&(params.config.responseJsonSchema=params.config.responseSchema,delete params.config.responseSchema))}async processParamsMaybeAddMcpUsage(params){var _a2,_b,_c;let tools=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools;if(!tools)return params;let transformedTools=await Promise.all(tools.map(async tool=>isCallableTool(tool)?await tool.tool():tool)),newParams={model:params.model,contents:params.contents,config:Object.assign(Object.assign({},params.config),{tools:transformedTools})};if(newParams.config.tools=transformedTools,params.config&&params.config.tools&&hasMcpToolUsage(params.config.tools)){let headers=(_c=(_b=params.config.httpOptions)===null||_b===void 0?void 0:_b.headers)!==null&&_c!==void 0?_c:{},newHeaders=Object.assign({},headers);Object.keys(newHeaders).length===0&&(newHeaders=this.apiClient.getDefaultHeaders()),setMcpUsageHeader(newHeaders),newParams.config.httpOptions=Object.assign(Object.assign({},params.config.httpOptions),{headers:newHeaders})}return newParams}async initAfcToolsMap(params){var _a2,_b,_c;let afcTools=new Map;for(let tool of(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){let callableTool=tool,toolDeclaration=await callableTool.tool();for(let declaration of(_c=toolDeclaration.functionDeclarations)!==null&&_c!==void 0?_c:[]){if(!declaration.name)throw new Error("Function declaration name is required.");if(afcTools.has(declaration.name))throw new Error(`Duplicate tool declaration name: ${declaration.name}`);afcTools.set(declaration.name,callableTool)}}return afcTools}async processAfcStream(params){var _a2,_b,_c;let maxRemoteCalls=(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,wereFunctionsCalled=!1,remoteCallCount=0,afcToolsMap=await this.initAfcToolsMap(params);return(function(models,afcTools,params2){return __asyncGenerator(this,arguments,function*(){for(var _a3,e_1,_b2,_c2,_d,_e;remoteCallCount<maxRemoteCalls;){wereFunctionsCalled&&(remoteCallCount++,wereFunctionsCalled=!1);let transformedParams=yield __await(models.processParamsMaybeAddMcpUsage(params2)),response=yield __await(models.generateContentStreamInternal(transformedParams)),functionResponses=[],responseContents=[];try{for(var _f=!0,response_1=(e_1=void 0,__asyncValues(response)),response_1_1;response_1_1=yield __await(response_1.next()),_a3=response_1_1.done,!_a3;_f=!0){_c2=response_1_1.value,_f=!1;let chunk=_c2;if(yield yield __await(chunk),chunk.candidates&&(!((_d=chunk.candidates[0])===null||_d===void 0)&&_d.content)){responseContents.push(chunk.candidates[0].content);for(let part of(_e=chunk.candidates[0].content.parts)!==null&&_e!==void 0?_e:[])if(remoteCallCount<maxRemoteCalls&&part.functionCall){if(!part.functionCall.name)throw new Error("Function call name was not returned by the model.");if(afcTools.has(part.functionCall.name)){let responseParts=yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall]));functionResponses.push(...responseParts)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, missing tool: ${part.functionCall.name}`)}}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_f&&!_a3&&(_b2=response_1.return)&&(yield __await(_b2.call(response_1)))}finally{if(e_1)throw e_1.error}}if(functionResponses.length>0){wereFunctionsCalled=!0;let typedResponseChunk=new GenerateContentResponse;typedResponseChunk.candidates=[{content:{role:"user",parts:functionResponses}}],yield yield __await(typedResponseChunk);let newContents=[];newContents.push(...responseContents),newContents.push({role:"user",parts:functionResponses});let updatedContents=tContents(params2.contents).concat(newContents);params2.contents=updatedContents}else break}})})(this,afcToolsMap,params)}async generateContentInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateContentResponseFromVertex(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateContentResponseFromMldev(apiResponse),typedResp=new GenerateContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateContentStreamInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}),response.then(function(apiResponse){return __asyncGenerator(this,arguments,function*(){var _a3,e_2,_b2,_c2;try{for(var _d2=!0,apiResponse_1=__asyncValues(apiResponse),apiResponse_1_1;apiResponse_1_1=yield __await(apiResponse_1.next()),_a3=apiResponse_1_1.done,!_a3;_d2=!0){_c2=apiResponse_1_1.value,_d2=!1;let chunk=_c2,resp=generateContentResponseFromVertex(yield __await(chunk.json()),params);resp.sdkHttpResponse={headers:chunk.headers};let typedResp=new GenerateContentResponse;Object.assign(typedResp,resp),yield yield __await(typedResp)}}catch(e_2_1){e_2={error:e_2_1}}finally{try{!_d2&&!_a3&&(_b2=apiResponse_1.return)&&(yield __await(_b2.call(apiResponse_1)))}finally{if(e_2)throw e_2.error}}})})}else{let body=generateContentParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}),response.then(function(apiResponse){return __asyncGenerator(this,arguments,function*(){var _a3,e_3,_b2,_c2;try{for(var _d2=!0,apiResponse_2=__asyncValues(apiResponse),apiResponse_2_1;apiResponse_2_1=yield __await(apiResponse_2.next()),_a3=apiResponse_2_1.done,!_a3;_d2=!0){_c2=apiResponse_2_1.value,_d2=!1;let chunk=_c2,resp=generateContentResponseFromMldev(yield __await(chunk.json()),params);resp.sdkHttpResponse={headers:chunk.headers};let typedResp=new GenerateContentResponse;Object.assign(typedResp,resp),yield yield __await(typedResp)}}catch(e_3_1){e_3={error:e_3_1}}finally{try{!_d2&&!_a3&&(_b2=apiResponse_2.return)&&(yield __await(_b2.call(apiResponse_2)))}finally{if(e_3)throw e_3.error}}})})}}async embedContentInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=embedContentParametersPrivateToVertex(this.apiClient,params,params),endpointUrl=tIsVertexEmbedContentModel(params.model)?"{model}:embedContent":"{model}:predict";return path2=formatMap(endpointUrl,body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=embedContentResponseFromVertex(apiResponse,params),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=embedContentParametersPrivateToMldev(this.apiClient,params);return path2=formatMap("{model}:batchEmbedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=embedContentResponseFromMldev(apiResponse),typedResp=new EmbedContentResponse;return Object.assign(typedResp,resp),typedResp})}}async generateImagesInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateImagesParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=generateImagesResponseFromVertex(apiResponse),typedResp=new GenerateImagesResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async editImageInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=editImageParametersInternalToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=editImageResponseFromVertex(apiResponse),typedResp=new EditImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=upscaleImageAPIParametersInternalToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=upscaleImageResponseFromVertex(apiResponse),typedResp=new UpscaleImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=recontextImageParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=recontextImageResponseFromVertex(apiResponse),typedResp=new RecontextImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=segmentImageParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=segmentImageResponseFromVertex(apiResponse),typedResp=new SegmentImageResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getModelParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromVertex(apiResponse))}else{let body=getModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromMldev(apiResponse))}}async listInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listModelsParametersToVertex(this.apiClient,params);return path2=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listModelsResponseFromVertex(apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=listModelsParametersToMldev(this.apiClient,params);return path2=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listModelsResponseFromMldev(apiResponse),typedResp=new ListModelsResponse;return Object.assign(typedResp,resp),typedResp})}}async update(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateModelParametersToVertex(this.apiClient,params);return path2=formatMap("{model}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromVertex(apiResponse))}else{let body=updateModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"PATCH",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>modelFromMldev(apiResponse))}}async delete(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteModelParametersToVertex(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteModelResponseFromVertex(apiResponse),typedResp=new DeleteModelResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=deleteModelParametersToMldev(this.apiClient,params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=deleteModelResponseFromMldev(apiResponse),typedResp=new DeleteModelResponse;return Object.assign(typedResp,resp),typedResp})}}async countTokens(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=countTokensParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=countTokensResponseFromVertex(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=countTokensParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=countTokensResponseFromMldev(apiResponse),typedResp=new CountTokensResponse;return Object.assign(typedResp,resp),typedResp})}}async computeTokens(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=computeTokensParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:computeTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=computeTokensResponseFromVertex(apiResponse),typedResp=new ComputeTokensResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateVideosParametersToVertex(this.apiClient,params);return path2=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=generateVideosOperationFromVertex(apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}else{let body=generateVideosParametersToMldev(this.apiClient,params);return path2=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=generateVideosOperationFromMldev(apiResponse),typedResp=new GenerateVideosOperation;return Object.assign(typedResp,resp),typedResp})}}};Models.loggedGenerateImagesWarning=!1;Models.loggedEditImageWarning=!1;Models.loggedGenerateVideosWarning=!1;var Operations=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient}async getVideosOperation(parameters){let operation=parameters.operation,config=parameters.config;if(operation.name===void 0||operation.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let resourceName2=operation.name.split("/operations/")[0],httpOptions;config&&"httpOptions"in config&&(httpOptions=config.httpOptions);let rawOperation=await this.fetchPredictVideosOperationInternal({operationName:operation.name,resourceName:resourceName2,config:{httpOptions}});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!0})}else{let rawOperation=await this.getVideosOperationInternal({operationName:operation.name,config});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!1})}}async get(parameters){let operation=parameters.operation,config=parameters.config;if(operation.name===void 0||operation.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){let resourceName2=operation.name.split("/operations/")[0],httpOptions;config&&"httpOptions"in config&&(httpOptions=config.httpOptions);let rawOperation=await this.fetchPredictVideosOperationInternal({operationName:operation.name,resourceName:resourceName2,config:{httpOptions}});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!0})}else{let rawOperation=await this.getVideosOperationInternal({operationName:operation.name,config});return operation._fromAPIResponse({apiResponse:rawOperation,_isVertexAI:!1})}}async getVideosOperationInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getOperationParametersToVertex(params);return path2=formatMap("{operationName}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response}else{let body=getOperationParametersToMldev(params);return path2=formatMap("{operationName}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json()),response}}async fetchPredictVideosOperationInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=fetchPredictOperationParametersToVertex(params);return path2=formatMap("{resourceName}:fetchPredictOperation",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}};function authConfigToMldev(fromObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev(fromObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function contentToMldev(fromObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createAuthTokenConfigToMldev(apiClient,fromObject,parentObject){let toObject={},fromExpireTime=getValueByPath(fromObject,["expireTime"]);parentObject!==void 0&&fromExpireTime!=null&&setValueByPath(parentObject,["expireTime"],fromExpireTime);let fromNewSessionExpireTime=getValueByPath(fromObject,["newSessionExpireTime"]);parentObject!==void 0&&fromNewSessionExpireTime!=null&&setValueByPath(parentObject,["newSessionExpireTime"],fromNewSessionExpireTime);let fromUses=getValueByPath(fromObject,["uses"]);parentObject!==void 0&&fromUses!=null&&setValueByPath(parentObject,["uses"],fromUses);let fromLiveConnectConstraints=getValueByPath(fromObject,["liveConnectConstraints"]);parentObject!==void 0&&fromLiveConnectConstraints!=null&&setValueByPath(parentObject,["bidiGenerateContentSetup"],liveConnectConstraintsToMldev(apiClient,fromLiveConnectConstraints));let fromLockAdditionalFields=getValueByPath(fromObject,["lockAdditionalFields"]);return parentObject!==void 0&&fromLockAdditionalFields!=null&&setValueByPath(parentObject,["fieldMask"],fromLockAdditionalFields),toObject}function createAuthTokenParametersToMldev(apiClient,fromObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],createAuthTokenConfigToMldev(apiClient,fromConfig,toObject)),toObject}function fileDataToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev(fromObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleMapsToMldev(fromObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function liveConnectConfigToMldev(fromObject,parentObject){let toObject={},fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig"],fromGenerationConfig);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);parentObject!==void 0&&fromResponseModalities!=null&&setValueByPath(parentObject,["setup","generationConfig","responseModalities"],fromResponseModalities);let fromTemperature=getValueByPath(fromObject,["temperature"]);parentObject!==void 0&&fromTemperature!=null&&setValueByPath(parentObject,["setup","generationConfig","temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);parentObject!==void 0&&fromTopP!=null&&setValueByPath(parentObject,["setup","generationConfig","topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);parentObject!==void 0&&fromTopK!=null&&setValueByPath(parentObject,["setup","generationConfig","topK"],fromTopK);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["setup","generationConfig","maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);parentObject!==void 0&&fromMediaResolution!=null&&setValueByPath(parentObject,["setup","generationConfig","mediaResolution"],fromMediaResolution);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["setup","generationConfig","seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);parentObject!==void 0&&fromSpeechConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","speechConfig"],tLiveSpeechConfig(fromSpeechConfig));let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);parentObject!==void 0&&fromThinkingConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","thinkingConfig"],fromThinkingConfig);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);parentObject!==void 0&&fromEnableAffectiveDialog!=null&&setValueByPath(parentObject,["setup","generationConfig","enableAffectiveDialog"],fromEnableAffectiveDialog);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["setup","systemInstruction"],contentToMldev(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev(tTool(item)))),setValueByPath(parentObject,["setup","tools"],transformedList)}let fromSessionResumption=getValueByPath(fromObject,["sessionResumption"]);parentObject!==void 0&&fromSessionResumption!=null&&setValueByPath(parentObject,["setup","sessionResumption"],sessionResumptionConfigToMldev(fromSessionResumption));let fromInputAudioTranscription=getValueByPath(fromObject,["inputAudioTranscription"]);parentObject!==void 0&&fromInputAudioTranscription!=null&&setValueByPath(parentObject,["setup","inputAudioTranscription"],fromInputAudioTranscription);let fromOutputAudioTranscription=getValueByPath(fromObject,["outputAudioTranscription"]);parentObject!==void 0&&fromOutputAudioTranscription!=null&&setValueByPath(parentObject,["setup","outputAudioTranscription"],fromOutputAudioTranscription);let fromRealtimeInputConfig=getValueByPath(fromObject,["realtimeInputConfig"]);parentObject!==void 0&&fromRealtimeInputConfig!=null&&setValueByPath(parentObject,["setup","realtimeInputConfig"],fromRealtimeInputConfig);let fromContextWindowCompression=getValueByPath(fromObject,["contextWindowCompression"]);parentObject!==void 0&&fromContextWindowCompression!=null&&setValueByPath(parentObject,["setup","contextWindowCompression"],fromContextWindowCompression);let fromProactivity=getValueByPath(fromObject,["proactivity"]);if(parentObject!==void 0&&fromProactivity!=null&&setValueByPath(parentObject,["setup","proactivity"],fromProactivity),getValueByPath(fromObject,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAvatarConfig=getValueByPath(fromObject,["avatarConfig"]);parentObject!==void 0&&fromAvatarConfig!=null&&setValueByPath(parentObject,["setup","avatarConfig"],fromAvatarConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev(item))),setValueByPath(parentObject,["setup","safetySettings"],transformedList)}let fromTranslationConfig=getValueByPath(fromObject,["translationConfig"]);return parentObject!==void 0&&fromTranslationConfig!=null&&setValueByPath(parentObject,["setup","generationConfig","translationConfig"],fromTranslationConfig),toObject}function liveConnectConstraintsToMldev(apiClient,fromObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["setup","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["config"],liveConnectConfigToMldev(fromConfig,toObject)),toObject}function partToMldev(fromObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function safetySettingToMldev(fromObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function sessionResumptionConfigToMldev(fromObject){let toObject={},fromHandle=getValueByPath(fromObject,["handle"]);if(fromHandle!=null&&setValueByPath(toObject,["handle"],fromHandle),getValueByPath(fromObject,["transparent"])!==void 0)throw new Error("transparent parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function toolToMldev(fromObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function getFieldMasks(setup){let fields=[];for(let key in setup)if(Object.prototype.hasOwnProperty.call(setup,key)){let value=setup[key];if(typeof value=="object"&&value!=null&&Object.keys(value).length>0){let field=Object.keys(value).map(kk=>`${key}.${kk}`);fields.push(...field)}else fields.push(key)}return fields.join(",")}function convertBidiSetupToTokenSetup(requestDict,config){let setupForMaskGeneration=null,bidiGenerateContentSetupValue=requestDict.bidiGenerateContentSetup;if(typeof bidiGenerateContentSetupValue=="object"&&bidiGenerateContentSetupValue!==null&&"setup"in bidiGenerateContentSetupValue){let innerSetup=bidiGenerateContentSetupValue.setup;typeof innerSetup=="object"&&innerSetup!==null?(requestDict.bidiGenerateContentSetup=innerSetup,setupForMaskGeneration=innerSetup):delete requestDict.bidiGenerateContentSetup}else bidiGenerateContentSetupValue!==void 0&&delete requestDict.bidiGenerateContentSetup;let preExistingFieldMask=requestDict.fieldMask;if(setupForMaskGeneration){let generatedMaskFromBidi=getFieldMasks(setupForMaskGeneration);if(Array.isArray(config?.lockAdditionalFields)&&config?.lockAdditionalFields.length===0)generatedMaskFromBidi?requestDict.fieldMask=generatedMaskFromBidi:delete requestDict.fieldMask;else if(config?.lockAdditionalFields&&config.lockAdditionalFields.length>0&&preExistingFieldMask!==null&&Array.isArray(preExistingFieldMask)&&preExistingFieldMask.length>0){let generationConfigFields=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],mappedFieldsFromPreExisting=[];preExistingFieldMask.length>0&&(mappedFieldsFromPreExisting=preExistingFieldMask.map(field=>generationConfigFields.includes(field)?`generationConfig.${field}`:field));let finalMaskParts=[];generatedMaskFromBidi&&finalMaskParts.push(generatedMaskFromBidi),mappedFieldsFromPreExisting.length>0&&finalMaskParts.push(...mappedFieldsFromPreExisting),finalMaskParts.length>0?requestDict.fieldMask=finalMaskParts.join(","):delete requestDict.fieldMask}else delete requestDict.fieldMask}else preExistingFieldMask!==null&&Array.isArray(preExistingFieldMask)&&preExistingFieldMask.length>0?requestDict.fieldMask=preExistingFieldMask.join(","):delete requestDict.fieldMask;return requestDict}var Tokens=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient}async create(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let body=createAuthTokenParametersToMldev(this.apiClient,params);path2=formatMap("auth_tokens",body._url),queryParams=body._query,delete body.config,delete body._url,delete body._query;let transformedBody=convertBidiSetupToTokenSetup(body,params.config);return response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(transformedBody),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}};function deleteDocumentConfigToMldev(fromObject,parentObject){let toObject={},fromForce=getValueByPath(fromObject,["force"]);return parentObject!==void 0&&fromForce!=null&&setValueByPath(parentObject,["_query","force"],fromForce),toObject}function deleteDocumentParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["_url","name"],fromName);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&deleteDocumentConfigToMldev(fromConfig,toObject),toObject}function getDocumentParametersToMldev(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function listDocumentsConfigToMldev(fromObject,parentObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);return parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken),toObject}function listDocumentsParametersToMldev(fromObject){let toObject={},fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["_url","parent"],fromParent);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listDocumentsConfigToMldev(fromConfig,toObject),toObject}function listDocumentsResponseFromMldev(fromObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromDocuments=getValueByPath(fromObject,["documents"]);if(fromDocuments!=null){let transformedList=fromDocuments;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["documents"],transformedList)}return toObject}var Documents=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async params=>new Pager(PagedItem.PAGED_ITEM_DOCUMENTS,x=>this.listInternal({parent:params.parent,config:x.config}),await this.listInternal(params),params)}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getDocumentParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteDocumentParametersToMldev(params);path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listDocumentsParametersToMldev(params);return path2=formatMap("{parent}/documents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=listDocumentsResponseFromMldev(apiResponse),typedResp=new ListDocumentsResponse;return Object.assign(typedResp,resp),typedResp})}}};var FileSearchStores=class extends BaseModule{constructor(apiClient,documents=new Documents(apiClient)){super(),this.apiClient=apiClient,this.documents=documents,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_FILE_SEARCH_STORES,x=>this.listInternal(x),await this.listInternal(params),params)}async uploadToFileSearchStore(params){if(this.apiClient.isVertexAI())throw new Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName,params.file,params.config)}async downloadMedia(uri,config){if(this.apiClient.isVertexAI())throw new Error("This method is only supported in the Gemini Developer client.");let parsedUri=new URL(uri,"http://dummy.com"),pathname=parsedUri.pathname;if(pathname.startsWith("/")&&(pathname=pathname.slice(1)),!pathname.includes("/media/"))throw new Error(`Invalid uri format: ${uri}. Expected to contain /media/`);let queryParams={};parsedUri.searchParams.forEach((value,key)=>{queryParams[key]=value}),queryParams.alt="media";let httpOptions=Object.assign({},config?.httpOptions),response=await this.apiClient.request({path:pathname,httpMethod:"GET",queryParams,httpOptions});if(response instanceof HttpResponse){let arrayBuffer=await response.responseInternal.arrayBuffer();return new Uint8Array(arrayBuffer)}else throw new Error("Unexpected response type from downloadMedia")}async create(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createFileSearchStoreParametersToMldev(this.apiClient,params);return path2=formatMap("fileSearchStores",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async get(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=getFileSearchStoreParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(resp=>resp)}}async delete(params){var _a2,_b;let path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=deleteFileSearchStoreParametersToMldev(params);path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,await this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"DELETE",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal})}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=listFileSearchStoresParametersToMldev(params);return path2=formatMap("fileSearchStores",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=listFileSearchStoresResponseFromMldev(apiResponse),typedResp=new ListFileSearchStoresResponse;return Object.assign(typedResp,resp),typedResp})}}async uploadToFileSearchStoreInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=uploadToFileSearchStoreParametersToMldev(params);return path2=formatMap("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=uploadToFileSearchStoreResumableResponseFromMldev(apiResponse),typedResp=new UploadToFileSearchStoreResumableResponse;return Object.assign(typedResp,resp),typedResp})}}async importFile(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=importFileParametersToMldev(params);return path2=formatMap("{file_search_store_name}:importFile",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json()),response.then(apiResponse=>{let resp=importFileOperationFromMldev(apiResponse),typedResp=new ImportFileOperation;return Object.assign(typedResp,resp),typedResp})}}};function isDeno(){return"Deno"in globalThis}var envMemo;function env(){var _a2,_b,_c,_d,_e,_f;if(envMemo)return envMemo;let globals=globalThis,envObject={};return isDeno()?envObject=(_d=(_c=(_b=(_a2=globals.Deno)===null||_a2===void 0?void 0:_a2.env)===null||_b===void 0?void 0:_b.toObject)===null||_c===void 0?void 0:_c.call(_b))!==null&&_d!==void 0?_d:{}:envObject=(_f=(_e=globals.process)===null||_e===void 0?void 0:_e.env)!==null&&_f!==void 0?_f:{},envMemo=envObject,envMemo}function fillGlobals(options){var _a2,_b;let clone=Object.assign({},options),envVars=env();return typeof envVars.GOOGLE_GENAI_API_VERSION<"u"&&((_a2=clone.api_version)!==null&&_a2!==void 0||(clone.api_version=envVars.GOOGLE_GENAI_API_VERSION)),typeof envVars.GOOGLE_GENAI_USER_PROJECT<"u"&&((_b=clone.user_project)!==null&&_b!==void 0||(clone.user_project=envVars.GOOGLE_GENAI_USER_PROJECT)),clone}var GoogleGenAISecurityProvider=class{constructor(options){this.options=options}getDefaultHeaders(){return this.options.defaultHeaders}async resolveGoogleGenAISecurity(url){return securityFromHeaders(await this.options.getAuthHeaders(url))}},GoogleGenAIAuthHook=class{beforeCreateRequest(_hookCtx,input){return Object.assign(Object.assign({},input),{url:decodeSDKLevelAPIVersionPath(input.url)})}async beforeRequest(hookCtx,request){if(applyDefaultHeaders(request.headers,getStaticDefaultHeaders(hookCtx.security_source)),applyUserProject(hookCtx,request.headers),hasAuthHeaders(request.headers))return request;let security=await resolveSecurity$1(hookCtx.security_source,request.url);return applyDefaultHeaders(request.headers,security?.default_headers),applyAuth(request.headers,security),request}};function decodeSDKLevelAPIVersionPath(url){let[,apiVersion,...rest]=url.pathname.split("/");if(!apiVersion)return url;let decodedAPIVersion=decodeURIComponent(apiVersion);if(!decodedAPIVersion.includes("/"))return url;let nextURL=new URL(url);return nextURL.pathname=`/${decodedAPIVersion}/${rest.join("/")}`,nextURL}async function resolveSecurity$1(securitySource,requestURL){if(isSecurityResolver(securitySource))return securitySource.resolveGoogleGenAISecurity(requestURL);let security=typeof securitySource=="function"?await securitySource():securitySource;return isSecurity(security)?withEnvSecurity(security):withEnvSecurity(void 0)}function getStaticDefaultHeaders(securitySource){var _a2,_b;if(isSecurityResolver(securitySource))return(_b=(_a2=securitySource.getDefaultHeaders)===null||_a2===void 0?void 0:_a2.call(securitySource))!==null&&_b!==void 0?_b:securitySource.defaultHeaders;if(isSecurity(securitySource))return securitySource.default_headers}function withEnvSecurity(security){var _a2,_b;let envVars=env(),nextSecurity=Object.assign(Object.assign({},security),{api_key:(_a2=security?.api_key)!==null&&_a2!==void 0?_a2:envVars.GOOGLE_GENAI_API_KEY,access_token:(_b=security?.access_token)!==null&&_b!==void 0?_b:envVars.GOOGLE_GENAI_ACCESS_TOKEN});return hasSecurityValue(nextSecurity)?nextSecurity:void 0}function securityFromHeaders(headers){var _a2,_b;let defaultHeaders={};for(let[key,value]of headers){let lowerKey=key.toLowerCase();lowerKey!=="authorization"&&lowerKey!=="x-goog-api-key"&&(defaultHeaders[key]=value)}let security={access_token:(_a2=headers.get("authorization"))!==null&&_a2!==void 0?_a2:void 0,api_key:(_b=headers.get("x-goog-api-key"))!==null&&_b!==void 0?_b:void 0,default_headers:Object.keys(defaultHeaders).length?defaultHeaders:void 0};return hasSecurityValue(security)?security:void 0}function applyDefaultHeaders(target,source){if(source)for(let[key,value]of new Headers(source))target.get(key)===null&&target.set(key,value)}function applyUserProject(hookCtx,headers){hookCtx.options.user_project!==void 0&&headers.get("x-goog-user-project")===null&&headers.set("x-goog-user-project",hookCtx.options.user_project)}function applyAuth(headers,security){if(security){if(security.api_key){headers.set("x-goog-api-key",security.api_key);return}security.access_token&&headers.set("Authorization",bearer(security.access_token))}}function hasAuthHeaders(headers){return headers.get("authorization")!==null||headers.get("x-goog-api-key")!==null}function bearer(token){return token.slice(0,7).toLowerCase()==="bearer "?token:`Bearer ${token}`}function isSecurity(value){return typeof value=="object"&&value!==null}function isSecurityResolver(value){return typeof value=="object"&&value!==null&&"resolveGoogleGenAISecurity"in value&&typeof value.resolveGoogleGenAISecurity=="function"}function hasSecurityValue(security){return security.api_key!==void 0||security.access_token!==void 0||security.default_headers!==void 0}var HTTPClientError=class extends Error{constructor(message,opts){let msg=message;opts?.cause&&(msg+=`: ${opts.cause}`),super(msg,opts),this.name="HTTPClientError",typeof this.cause>"u"&&(this.cause=opts?.cause)}},UnexpectedClientError=class extends HTTPClientError{constructor(){super(...arguments),this.name="UnexpectedClientError"}},InvalidRequestError=class extends HTTPClientError{constructor(){super(...arguments),this.name="InvalidRequestError"}},RequestAbortedError=class extends HTTPClientError{constructor(){super(...arguments),this.name="RequestAbortedError"}},RequestTimeoutError=class extends HTTPClientError{constructor(){super(...arguments),this.name="RequestTimeoutError"}},ConnectionError=class extends HTTPClientError{constructor(){super(...arguments),this.name="ConnectionError"}};var GoogleGenAiError=class extends Error{constructor(message,httpMeta){var _a2,_b,_c,_d;super(message),this.statusCode=(_a2=httpMeta?.response)===null||_a2===void 0?void 0:_a2.status,this.body=(_b=httpMeta?.body)!==null&&_b!==void 0?_b:"",this.headers=(_c=httpMeta?.response)===null||_c===void 0?void 0:_c.headers,this.contentType=((_d=httpMeta?.response)===null||_d===void 0?void 0:_d.headers.get("content-type"))||"",this.rawResponse=httpMeta?.response,this.name="GoogleGenAiError"}};var GeminiNextGenAPIClientError=class extends Error{},APIError=class _APIError extends GeminiNextGenAPIClientError{constructor(status,error,message,headers){super(_APIError.makeMessage(status,error,message)),this.status=status,this.headers=headers,this.error=error,this.statusCode=status,this.body=stringifyErrorBody(error),this.contentType=headers?.get("content-type")||"",this.rawResponse=void 0,this.cause=void 0,this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}static makeMessage(status,error,message){var _a2;let errorMessage=error&&isPlainObject$2(error)&&typeof error.message=="string"?error.message:void 0,errorBody=stringifyErrorBody(error),msg=(_a2=errorMessage??message)!==null&&_a2!==void 0?_a2:errorBody||"An error occurred";return`${status?`${status} `:""}${msg}`}static generate(status,errorResponse,message,headers){return!status||!headers?new APIConnectionError({message,cause:errorResponse instanceof Error?errorResponse:void 0}):status===400?new BadRequestError(status,errorResponse,message,headers):status===401?new AuthenticationError(status,errorResponse,message,headers):status===403?new PermissionDeniedError(status,errorResponse,message,headers):status===404?new NotFoundError(status,errorResponse,message,headers):status===409?new ConflictError(status,errorResponse,message,headers):status===422?new UnprocessableEntityError(status,errorResponse,message,headers):status===429?new RateLimitError(status,errorResponse,message,headers):status>=500?new InternalServerError(status,errorResponse,message,headers):new _APIError(status,errorResponse,message,headers)}},APIUserAbortError=class extends APIError{constructor({message}={}){super(void 0,void 0,message||"Request was aborted.",void 0)}},APIConnectionError=class extends APIError{constructor({message,cause}){super(void 0,void 0,message||"Connection error.",void 0),this.cause=cause}},APIConnectionTimeoutError=class extends APIConnectionError{constructor({message}={}){super({message:message||"Request timed out. This is a client-side timeout. You can increase the timeout by setting the `timeout` argument in your request or client http options."})}},BadRequestError=class extends APIError{},AuthenticationError=class extends APIError{},PermissionDeniedError=class extends APIError{},NotFoundError=class extends APIError{},ConflictError=class extends APIError{},UnprocessableEntityError=class extends APIError{},RateLimitError=class extends APIError{},InternalServerError=class extends APIError{};function wrapSDKError(error){return isCompatAPIErrorInstance(error)?error:error instanceof GoogleGenAiError?wrapAPIError(error):error instanceof HTTPClientError?wrapHTTPClientError(error):error}function wrapAPIError(error){let errorPayload=getErrorPayload(error),wrapped=APIError.generate(error.statusCode,errorPayload,error.message,error.headers);return defineReadonly(wrapped,"body",error.body),defineReadonly(wrapped,"contentType",error.contentType),defineReadonly(wrapped,"rawResponse",error.rawResponse),defineReadonly(wrapped,"statusCode",error.statusCode),defineReadonly(wrapped,"cause",error),wrapped}function wrapHTTPClientError(error){return error instanceof RequestTimeoutError?new APIConnectionTimeoutError({message:error.message}):error instanceof RequestAbortedError?new APIUserAbortError({message:error.message}):error instanceof ConnectionError?new APIConnectionError({message:error.message,cause:error}):new APIConnectionError({message:error.message,cause:error})}function getErrorPayload(error){let data=getObjectProperty(error,"data$");if(data&&typeof data=="object")return data;try{let parsed=JSON.parse(error.body);if(parsed&&typeof parsed=="object")return parsed}catch{}let dataError=getObjectProperty(error,"error");return dataError&&typeof dataError=="object"?dataError:void 0}function getObjectProperty(value,key){return value&&typeof value=="object"?value[key]:void 0}function stringifyErrorBody(error){if(!error)return"";try{return JSON.stringify(error)}catch{return String(error)}}function isPlainObject$2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function isCompatAPIErrorInstance(value){return typeof value=="object"&&value!==null?APIError.prototype.isPrototypeOf(value):!1}function defineReadonly(target,key,value){Object.defineProperty(target,key,{configurable:!0,enumerable:!0,value,writable:!1})}function initHooks(hooks){let googleGenAIAuthHook=new GoogleGenAIAuthHook;hooks.registerBeforeCreateRequestHook(googleGenAIAuthHook),hooks.registerBeforeRequestHook(googleGenAIAuthHook)}var SDKHooks=class{constructor(){this.sdkInitHooks=[],this.beforeCreateRequestHooks=[],this.beforeRequestHooks=[],this.afterSuccessHooks=[],this.afterErrorHooks=[];let presetHooks=[];for(let hook of presetHooks)"sdkInit"in hook&&this.registerSDKInitHook(hook),"beforeCreateRequest"in hook&&this.registerBeforeCreateRequestHook(hook),"beforeRequest"in hook&&this.registerBeforeRequestHook(hook),"afterSuccess"in hook&&this.registerAfterSuccessHook(hook),"afterError"in hook&&this.registerAfterErrorHook(hook);initHooks(this)}registerSDKInitHook(hook){this.sdkInitHooks.push(hook)}registerBeforeCreateRequestHook(hook){this.beforeCreateRequestHooks.push(hook)}registerBeforeRequestHook(hook){this.beforeRequestHooks.push(hook)}registerAfterSuccessHook(hook){this.afterSuccessHooks.push(hook)}registerAfterErrorHook(hook){this.afterErrorHooks.push(hook)}sdkInit(opts){return this.sdkInitHooks.reduce((opts2,hook)=>hook.sdkInit(opts2),opts)}beforeCreateRequest(hookCtx,input){let inp=input;for(let hook of this.beforeCreateRequestHooks)inp=hook.beforeCreateRequest(hookCtx,inp);return inp}async beforeRequest(hookCtx,request){let req=request;for(let hook of this.beforeRequestHooks)req=await hook.beforeRequest(hookCtx,req);return req}async afterSuccess(hookCtx,response){let res=response;for(let hook of this.afterSuccessHooks)res=await hook.afterSuccess(hookCtx,res);return res}async afterError(hookCtx,response,error){let res=response,err=error;for(let hook of this.afterErrorHooks){let result=await hook.afterError(hookCtx,res,err);res=result.response,err=result.error}return{response:res,error:err}}};function OK(value){return{ok:!0,value}}function ERR(error){return{ok:!1,error}}function bytesToBase64(u8arr){return btoa(String.fromCodePoint(...u8arr))}function stringToBytes(str){return new TextEncoder().encode(str)}function stringToBase64(str){return bytesToBase64(stringToBytes(str))}var hasOwn=Object.prototype.hasOwnProperty;function pathToFunc(pathPattern,options){let paramRE=/\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;return function(params={}){return pathPattern.replace(paramRE,function(_,placeholder){if(!hasOwn.call(params,placeholder))throw new Error(`Parameter '${placeholder}' is required`);let value=params[placeholder];if(typeof value!="string"&&typeof value!="number")throw new Error(`Parameter '${placeholder}' must be a string or number`);return`${value}`}).replace(/^\/+/,"")}}var ServerList=["https://generativelanguage.googleapis.com"];function serverURLFromOptions(options){var _a2;let serverURL=options.server_url,params={};if(!serverURL){let serverIdx=(_a2=options.server_idx)!==null&&_a2!==void 0?_a2:0;if(serverIdx<0||serverIdx>=ServerList.length)throw new Error(`Invalid server index ${serverIdx}`);serverURL=ServerList[serverIdx]||""}let u=pathToFunc(serverURL)(params);return new URL(u)}var SDK_METADATA={userAgent:"speakeasy-sdk/typescript 2.4.1-preview.4 internal v1beta @google/genai"};function combineSignals(...signals){let filtered=[];for(let signal of signals)signal&&filtered.push(signal);switch(filtered.length){case 0:case 1:return filtered[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(filtered):abortSignalAny(filtered)}}function abortSignalAny(signals){let controller=new AbortController,result=controller.signal;if(!signals.length)return controller.signal;if(signals.length===1)return signals[0]||controller.signal;for(let signal of signals)if(signal.aborted)return signal;function abort(){controller.abort(this.reason),clean()}let signalRefs=[];function clean(){for(let signalRef of signalRefs){let signal=signalRef.deref();signal&&signal.removeEventListener("abort",abort)}}for(let signal of signals)signalRefs.push(new WeakRef(signal)),signal.addEventListener("abort",abort);return result}function compactMap(values){let out={};for(let[k,v]of Object.entries(values))typeof v<"u"&&(out[k]=v);return out}function isPlainObject$1(value){if(value===null||typeof value!="object"||Object.prototype.toString.call(value)!=="[object Object]")return!1;let proto=Object.getPrototypeOf(value);if(proto===null||proto===Object.prototype)return!0;try{return Object.getPrototypeOf(proto)===null}catch{return!1}}function formEncoder(sep){return(key,value,options)=>{let out="",pairs=options?.explode?explode(key,value):[[key,value]];if(pairs.every(([_,v])=>v==null))return;let encodeString=v=>options?.charEncoding==="percent"?encodeURIComponent(v):v,encodeValue=v=>encodeString(serializeValue(v)),encodedSep=encodeString(sep);return pairs.forEach(([pk,pv])=>{var _a2,_b;let tmp="",encValue=null;pv!=null&&(Array.isArray(pv)?encValue=(_a2=mapDefined(pv,v=>`${encodeValue(v)}`))===null||_a2===void 0?void 0:_a2.join(encodedSep):isPlainObject$1(pv)?encValue=(_b=mapDefinedEntries(Object.entries(pv),([k,v])=>`${encodeString(k)}${encodedSep}${encodeValue(v)}`))===null||_b===void 0?void 0:_b.join(encodedSep):encValue=`${encodeValue(pv)}`,encValue!=null&&(tmp=`${encodeString(pk)}=${encValue}`,!(!tmp||tmp==="=")&&(out+=`&${tmp}`)))}),out.slice(1)}}var encodeForm=formEncoder(",");function encodeJSON(key,value,options){if(typeof value>"u")return;let encodeString=v=>options?.charEncoding==="percent"?encodeURIComponent(v):v,encVal=encodeString(JSON.stringify(value,jsonReplacer));return options?.explode?encVal:`${encodeString(key)}=${encVal}`}var encodeSimple=(key,value,options)=>{let out="",pairs=options?.explode?explode(key,value):[[key,value]];if(pairs.every(([_,v])=>v==null))return;let encodeString=v=>options?.charEncoding==="percent"?encodeURIComponent(v):v,encodeValue=v=>encodeString(serializeValue(v));return pairs.forEach(([pk,pv])=>{var _a2;let tmp="";if(pv!=null){if(Array.isArray(pv))tmp=(_a2=mapDefined(pv,v=>`${encodeValue(v)}`))===null||_a2===void 0?void 0:_a2.join(",");else if(isPlainObject$1(pv)){let mapped=mapDefinedEntries(Object.entries(pv),([k,v])=>`,${encodeString(k)},${encodeValue(v)}`);tmp=mapped?.join("").slice(1)}else tmp=`${options?.explode&&isPlainObject$1(value)?`${pk}=`:""}${encodeValue(pv)}`;out+=tmp?`,${tmp}`:""}}),out.slice(1)};function explode(key,value){return Array.isArray(value)?value.map(v=>[key,v]):isPlainObject$1(value)?Object.entries(value??{}).map(([k,v])=>[k,v]):[[key,value]]}function serializeValue(value){return value==null?"":value instanceof Date?value.toISOString():value instanceof Uint8Array?bytesToBase64(value):typeof value=="object"?JSON.stringify(value,jsonReplacer):`${value}`}function jsonReplacer(_,value){return value instanceof Uint8Array?bytesToBase64(value):value}function mapDefined(inp,mapper){let res=inp.reduce((acc,v)=>{if(v==null)return acc;let m=mapper(v);return m==null||acc.push(m),acc},[]);return res.length?res:null}function mapDefinedEntries(inp,mapper){let acc=[];for(let[k,v]of inp){if(v==null)continue;let m=mapper([k,v]);m!=null&&acc.push(m)}return acc.length?acc:null}function queryJoin(...args){return args.filter(Boolean).join("&")}function queryEncoder(f){return function(values,options){var _a2,_b,_c;let opts=Object.assign(Object.assign({},options),{explode:(_a2=options?.explode)!==null&&_a2!==void 0?_a2:!0,charEncoding:(_b=options?.charEncoding)!==null&&_b!==void 0?_b:"percent"}),allowEmptySet=new Set((_c=options?.allowEmptyValue)!==null&&_c!==void 0?_c:[]),encoded=Object.entries(values).map(([key,value])=>allowEmptySet.has(key)&&(value==null||value===""||Array.isArray(value)&&value.length===0)?`${encodeURIComponent(key)}=`:f(key,value,opts));return queryJoin(...encoded)}}var encodeFormQuery=queryEncoder(encodeForm);var DEFAULT_FETCHER=(input,init)=>init==null?fetch(input):fetch(input,init),HTTPClient=class _HTTPClient{constructor(options={}){this.requestHooks=[],this.requestErrorHooks=[],this.responseHooks=[],this.options=options,this.fetcher=options.fetcher||DEFAULT_FETCHER}async request(request){let req=request;for(let hook of this.requestHooks){let nextRequest=await hook(req);nextRequest&&(req=nextRequest)}try{let res=await this.fetcher(req);for(let hook of this.responseHooks)await hook(res,req);return res}catch(err){for(let hook of this.requestErrorHooks)await hook(err,req);throw err}}addHook(...args){if(args[0]==="beforeRequest")this.requestHooks.push(args[1]);else if(args[0]==="requestError")this.requestErrorHooks.push(args[1]);else if(args[0]==="response")this.responseHooks.push(args[1]);else throw new Error(`Invalid hook type: ${args[0]}`);return this}removeHook(...args){let target;if(args[0]==="beforeRequest")target=this.requestHooks;else if(args[0]==="requestError")target=this.requestErrorHooks;else if(args[0]==="response")target=this.responseHooks;else throw new Error(`Invalid hook type: ${args[0]}`);let index=target.findIndex(v=>v===args[1]);return index>=0&&target.splice(index,1),this}clone(){let child=new _HTTPClient(this.options);return child.requestHooks=this.requestHooks.slice(),child.requestErrorHooks=this.requestErrorHooks.slice(),child.responseHooks=this.responseHooks.slice(),child}},mediaParamSeparator=/\s*;\s*/g;function matchContentType(response,pattern){var _a2;if(pattern==="*")return!0;let contentType=((_a2=response.headers.get("content-type"))===null||_a2===void 0?void 0:_a2.trim())||"application/octet-stream";contentType=contentType.toLowerCase();let wantParts=pattern.toLowerCase().trim().split(mediaParamSeparator),[wantType="",...wantParams]=wantParts;if(wantType.split("/").length!==2)return!1;let gotParts=contentType.split(mediaParamSeparator),[gotType="",...gotParams]=gotParts,[type="",subtype=""]=gotType.split("/");if(!type||!subtype||wantType!=="*/*"&&gotType!==wantType&&`${type}/*`!==wantType&&`*/${subtype}`!==wantType||gotParams.length<wantParams.length)return!1;let params=new Set(gotParams);for(let wantParam of wantParams)if(!params.has(wantParam))return!1;return!0}var codeRangeRE$1=new RegExp("^[0-9]xx$","i");function matchStatusCode(response,codes){let actual=`${response.status}`,expectedCodes=Array.isArray(codes)?codes:[codes];return expectedCodes.length?expectedCodes.some(ec=>{let code=`${ec}`;if(code==="default")return!0;if(!codeRangeRE$1.test(`${code}`))return code===actual;let expectFamily=code.charAt(0);if(!expectFamily)throw new Error("Invalid status code range");let actualFamily=actual.charAt(0);if(!actualFamily)throw new Error(`Invalid response status code: ${actual}`);return actualFamily===expectFamily}):!1}function matchResponse(response,code,contentTypePattern){return matchStatusCode(response,code)&&matchContentType(response,contentTypePattern)}function isConnectionError(err){if(typeof err!="object"||err==null)return!1;let isBrowserErr=err instanceof TypeError&&err.message.toLowerCase().startsWith("failed to fetch"),isNodeErr=err instanceof TypeError&&err.message.toLowerCase().startsWith("fetch failed"),isBunErr="name"in err&&err.name==="ConnectionError",isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnreset";return isBrowserErr||isNodeErr||isGenericErr||isBunErr}function isTimeoutError(err){if(typeof err!="object"||err==null)return!1;let isNative="name"in err&&err.name==="TimeoutError",isLegacyNative="code"in err&&err.code===23,isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnaborted";return isNative||isLegacyNative||isGenericErr}function isAbortError(err){if(typeof err!="object"||err==null)return!1;let isNative="name"in err&&err.name==="AbortError",isLegacyNative="code"in err&&err.code===20,isGenericErr="code"in err&&typeof err.code=="string"&&err.code.toLowerCase()==="econnaborted";return isNative||isLegacyNative||isGenericErr}var defaultBackoff={initialInterval:500,maxInterval:6e4,exponent:1.5,maxElapsedTime:36e5},PermanentError=class _PermanentError extends Error{constructor(message,options){let msg=message;options?.cause&&(msg+=`: ${options.cause}`),super(msg,options),this.name="PermanentError",typeof this.cause>"u"&&(this.cause=options?.cause),Object.setPrototypeOf(this,_PermanentError.prototype)}},TemporaryError=class _TemporaryError extends Error{constructor(message,response){super(message),this.response=response,this.name="TemporaryError",Object.setPrototypeOf(this,_TemporaryError.prototype)}};async function retry(fetchFn,options){var _a2;switch(options.config.strategy){case"backoff":return retryBackoff(wrapFetcher(fetchFn,{statusCodes:options.statusCodes,retryConnectionErrors:!!options.config.retryConnectionErrors}),(_a2=options.config.backoff)!==null&&_a2!==void 0?_a2:defaultBackoff);case"attempt-count-backoff":return retryAttemptCountBackoff(wrapFetcher(fetchFn,{statusCodes:options.statusCodes,retryConnectionErrors:!!options.config.retryConnectionErrors}),Object.assign(Object.assign({},defaultBackoff),options.config.backoff),options.config);default:return await fetchFn(0)}}function wrapFetcher(fn,options){return async attempt=>{try{let res=await fn(attempt);if(isRetryableResponse(res,options.statusCodes))throw new TemporaryError("Response failed with retryable status code",res);return res}catch(err){throw err instanceof TemporaryError||options.retryConnectionErrors&&(isTimeoutError(err)||isConnectionError(err))?err:new PermanentError("Permanent error",{cause:err})}}}var codeRangeRE=new RegExp("^[0-9]xx$","i");function isRetryableResponse(res,statusCodes){let actual=`${res.status}`;return statusCodes.some(code=>{if(!codeRangeRE.test(code))return code===actual;let expectFamily=code.charAt(0);if(!expectFamily)throw new Error("Invalid status code range");let actualFamily=actual.charAt(0);if(!actualFamily)throw new Error(`Invalid response status code: ${actual}`);return actualFamily===expectFamily})}async function retryBackoff(fn,strategy){let{maxElapsedTime,initialInterval,exponent,maxInterval}=strategy,start=Date.now(),x=0;for(;;)try{return await fn(x)}catch(err){if(err instanceof PermanentError)throw err.cause;if(Date.now()-start>maxElapsedTime){if(err instanceof TemporaryError)return err.response;throw err}let retryInterval=0;err instanceof TemporaryError&&(retryInterval=retryIntervalFromResponse(err.response)),retryInterval<=0&&(retryInterval=initialInterval*Math.pow(x,exponent)+Math.random()*1e3);let d=Math.min(retryInterval,maxInterval);await delay(d),x++}}async function retryAttemptCountBackoff(fn,strategy,config){let attempt=0;for(;;)try{return await fn(attempt)}catch(err){if(err instanceof PermanentError)throw err.cause;if(attempt>=config.maxRetries){if(err instanceof TemporaryError)return err.response;throw err}let retryInterval=0;err instanceof TemporaryError&&(retryInterval=retryIntervalFromResponse(err.response)),retryInterval<=0&&(retryInterval=strategy.initialInterval*Math.pow(strategy.exponent,attempt)*(1-Math.random()*.25));let d=Math.min(retryInterval,strategy.maxInterval);await delay(d),attempt++}}function retryIntervalFromResponse(res){let retryAfterMsVal=res.headers.get("retry-after-ms");if(retryAfterMsVal){let parsedMs=Number(retryAfterMsVal);if(Number.isFinite(parsedMs)&&parsedMs>=0)return parsedMs}let retryVal=res.headers.get("retry-after")||"";if(!retryVal)return 0;let parsedNumber=Number(retryVal);if(Number.isInteger(parsedNumber))return parsedNumber*1e3;let parsedDate=Date.parse(retryVal);if(Number.isInteger(parsedDate)){let deltaMS=parsedDate-Date.now();return deltaMS>0?Math.ceil(deltaMS):0}return 0}async function delay(delay2){return new Promise(resolve=>setTimeout(resolve,delay2))}var gt=typeof globalThis>"u"?null:globalThis,webWorkerLike=typeof gt=="object"&&gt!=null&&"importScripts"in gt&&typeof gt.importScripts=="function",isBrowserLike=webWorkerLike||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u",ClientSDK=class{constructor(options={}){let opt=options;typeof opt=="object"&&opt!=null&&"hooks"in opt&&opt.hooks instanceof SDKHooks?this._hooks=opt.hooks:this._hooks=new SDKHooks;let defaultHttpClient=new HTTPClient;options.http_client=options.http_client||defaultHttpClient,options=this._hooks.sdkInit(options);let url=serverURLFromOptions(options);url&&(url.pathname=url.pathname.replace(/\/+$/,"")+"/"),this._baseURL=url,this._httpClient=options.http_client||defaultHttpClient,this._options=Object.assign(Object.assign({},fillGlobals(options)),{hooks:this._hooks}),this._logger=this._options.debug_logger,!this._logger&&env().GOOGLE_GENAI_DEBUG&&(this._logger=console)}_createRequest(context,conf,options){var _a2,_b,_c,_d,_e;let{method,path:path2,query,headers:opHeaders,security}=conf,base=(_a2=conf.baseURL)!==null&&_a2!==void 0?_a2:this._baseURL;if(!base)return ERR(new InvalidRequestError("No base URL provided for operation"));let baseURL=new URL(base),reqURL;path2?(baseURL.pathname=baseURL.pathname.replace(/\/+$/,"")+"/",reqURL=new URL(path2,baseURL),!reqURL.search&&baseURL.search&&(reqURL.search=baseURL.search)):reqURL=baseURL,reqURL.hash="";let mergeQuery=(current,additions)=>{if(!additions)return current;let additionKeys=new Set(additions.split("&").filter(pair=>pair!=="").map(pair=>{var _a3;return(_a3=pair.split("=")[0])!==null&&_a3!==void 0?_a3:""}));return[...current.split("&").filter(pair=>{var _a3;return pair!==""&&!additionKeys.has((_a3=pair.split("=")[0])!==null&&_a3!==void 0?_a3:"")}),additions].join("&")},encodeQueryRecord=record=>Object.entries(record).map(([k,v])=>{if(v==null)return;let value=isPlainObject$1(v)?JSON.stringify(v):v;return encodeForm(k,value,{explode:Array.isArray(value),charEncoding:"percent"})}).filter(pair=>typeof pair<"u").join("&"),finalQuery=[query||"",encodeQueryRecord(options?.extra_query||{}),encodeQueryRecord(security?.queryParams||{})].reduce(mergeQuery,reqURL.search.slice(1));finalQuery&&(reqURL.search=`?${finalQuery}`);let headers=new Headers(opHeaders),username=security?.basic.username,password=security?.basic.password;if(username!=null||password!=null){let encoded=stringToBase64([username||"",password||""].join(":"));headers.set("Authorization",`Basic ${encoded}`)}let securityHeaders=new Headers(security?.headers||{});for(let[k,v]of securityHeaders)headers.set(k,v);let cookie=headers.get("cookie")||"";for(let[k,v]of Object.entries(security?.cookies||{}))cookie+=`; ${k}=${v}`;cookie=cookie.startsWith("; ")?cookie.slice(2):cookie,headers.set("cookie",cookie);let userHeaders=new Headers((_b=options?.headers)!==null&&_b!==void 0?_b:(_c=options?.fetch_options)===null||_c===void 0?void 0:_c.headers);for(let[k,v]of userHeaders)headers.set(k,v);isBrowserLike||headers.set((_d=conf.uaHeader)!==null&&_d!==void 0?_d:"user-agent",(_e=conf.userAgent)!==null&&_e!==void 0?_e:SDK_METADATA.userAgent);let reqBody=conf.body,extraBody=Object.fromEntries(Object.entries(options?.extra_body||{}).filter(([,v])=>typeof v<"u"));if(Object.keys(extraBody).length>0){let contentType=new Headers(opHeaders).get("content-type")||"";if(!/^(application|text)\/([^+]+\+)*json/.test(contentType)||typeof reqBody!="string"&&reqBody!=null)return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies"));let parsedBody;try{parsedBody=reqBody?JSON.parse(reqBody):{}}catch(err){return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies",{cause:err}))}if(!isPlainObject$1(parsedBody))return ERR(new InvalidRequestError("extra_body can only be merged into JSON object request bodies"));reqBody=JSON.stringify(Object.assign(Object.assign({},parsedBody),extraBody)),headers.delete("content-length")}let fetchOptions=Object.assign(Object.assign({},options?.fetch_options),options);!fetchOptions?.signal&&conf.timeout_ms!=null&&conf.timeout_ms>0&&(context.timeout_ms=conf.timeout_ms),conf.body instanceof ReadableStream&&Object.assign(fetchOptions,{duplex:"half"});let input;try{input=this._hooks.beforeCreateRequest(context,{url:reqURL,options:Object.assign(Object.assign({},fetchOptions),{body:reqBody??null,headers,method})})}catch(err){return ERR(new UnexpectedClientError("Create request hook failed to execute",{cause:err}))}return OK(new Request(input.url,input.options))}async _do(request,options){let{context,isErrorStatusCode}=options,timeout_ms=context.timeout_ms;return retry(async()=>{var _a2;let cloned=request.clone(),attempt=cloned;if(timeout_ms!=null&&timeout_ms>0){let timeoutSignal=AbortSignal.timeout(timeout_ms),combined=(_a2=combineSignals(cloned.signal,timeoutSignal))!==null&&_a2!==void 0?_a2:timeoutSignal;attempt=new Request(cloned,{signal:combined})}let req=await this._hooks.beforeRequest(context,attempt);await logRequest(this._logger,req).catch(e=>{var _a3;return(_a3=this._logger)===null||_a3===void 0?void 0:_a3.log("Failed to log request:",e)});let response=await this._httpClient.request(req);try{if(isErrorStatusCode(response.status)){let result=await this._hooks.afterError(context,response,null);if(result.error)throw result.error;response=result.response||response}else response=await this._hooks.afterSuccess(context,response)}finally{await logResponse(this._logger,response,req).catch(e=>{var _a3;return(_a3=this._logger)===null||_a3===void 0?void 0:_a3.log("Failed to log response:",e)})}return response},{config:options.retryConfig,statusCodes:options.retryCodes}).then(r=>OK(r),err=>{switch(!0){case isAbortError(err):return ERR(new RequestAbortedError("Request aborted by client",{cause:err}));case isTimeoutError(err):return ERR(new RequestTimeoutError("Request timed out",{cause:err}));case isConnectionError(err):return ERR(new ConnectionError("Unable to make request",{cause:err}));default:return ERR(new UnexpectedClientError("Unexpected HTTP client error",{cause:err}))}})}},jsonLikeContentTypeRE=/^(application|text)\/([^+]+\+)*json.*/,jsonlLikeContentTypeRE=/^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/;async function logRequest(logger,req){if(!logger)return;let contentType=req.headers.get("content-type"),ct=contentType?.split(";")[0]||"";logger.group(`> Request: ${req.method} ${req.url}`),logger.group("Headers:");for(let[k,v]of req.headers.entries())logger.log(`${k}: ${v}`);switch(logger.groupEnd(),logger.group("Body:"),!0){case jsonLikeContentTypeRE.test(ct):logger.log(await req.clone().json());break;case ct.startsWith("text/"):logger.log(await req.clone().text());break;case ct==="multipart/form-data":{let body=await req.clone().formData();for(let[k,v]of body){let vlabel=v instanceof Blob?"<Blob>":v;logger.log(`${k}: ${vlabel}`)}break}default:logger.log(`<${contentType}>`);break}logger.groupEnd(),logger.groupEnd()}async function logResponse(logger,res,req){if(!logger)return;let contentType=res.headers.get("content-type"),ct=contentType?.split(";")[0]||"";logger.group(`< Response: ${req.method} ${req.url}`),logger.log("Status Code:",res.status,res.statusText),logger.group("Headers:");for(let[k,v]of res.headers.entries())logger.log(`${k}: ${v}`);switch(logger.groupEnd(),logger.group("Body:"),!0){case(matchContentType(res,"application/json")||jsonLikeContentTypeRE.test(ct)&&!jsonlLikeContentTypeRE.test(ct)):logger.log(await res.clone().json());break;case(matchContentType(res,"application/jsonl")||jsonlLikeContentTypeRE.test(ct)):case matchContentType(res,"text/event-stream"):logger.log(`<${contentType}>`);break;case matchContentType(res,"text/*"):logger.log(await res.clone().text());break;case matchContentType(res,"multipart/form-data"):{let body=await res.clone().formData();for(let[k,v]of body){let vlabel=v instanceof Blob?"<Blob>":v;logger.log(`${k}: ${vlabel}`)}break}default:logger.log(`<${contentType}>`);break}logger.groupEnd(),logger.groupEnd()}var GoogleGenAiDefaultError=class extends GoogleGenAiError{constructor(message,httpMeta){message&&(message+=": "),message+=`Status ${httpMeta.response.status}`;let contentType=httpMeta.response.headers.get("content-type")||'""';contentType!=="application/json"&&(message+=` Content-Type ${contentType.includes(" ")?`"${contentType}"`:contentType}`);let body=httpMeta.body||'""';message+=body.length>100?`
42
42
  `:". ";let bodyDisplay=body;if(body.length>1e4){let truncated=body.substring(0,1e4),remaining=body.length-1e4;bodyDisplay=`${truncated}...and ${remaining} more chars`}message+=`Body: ${bodyDisplay}`,message=message.trim(),super(message,httpMeta),this.name="GoogleGenAiDefaultError"}};function tryParseJson(s){try{return JSON.parse(s)}catch{return s}}function wrapEventStreamResponse(body,opts={}){var _a2,_b;let flattened=opts.flattened===!0,sentinel=(_a2=opts.sentinel)!==null&&_a2!==void 0?_a2:"";return new Stream(body,rawEvent=>sentinel!==""&&rawEvent.data===sentinel?{done:!0,value:void 0}:flattened?{done:!1,value:rawEvent.data==null?void 0:tryParseJson(rawEvent.data)}:{done:!1,value:Object.assign(Object.assign({},rawEvent),{data:rawEvent.data==null?rawEvent.data:tryParseJson(rawEvent.data)})},{dataRequired:(_b=opts.dataRequired)!==null&&_b!==void 0?_b:!0})}var Stream=class extends ReadableStream{constructor(responseBody,parse,opts){var _a2;let upstream=responseBody.getReader(),buffer=new Uint8Array(4096),bufferLen=0,searchStart=0,state={eventId:void 0},dataRequired=(_a2=opts?.dataRequired)!==null&&_a2!==void 0?_a2:!0;super({async pull(downstream){try{for(;;){let match2=findBoundary(buffer,bufferLen,searchStart);if(!match2){searchStart=Math.max(0,bufferLen-MAX_BOUNDARY_LEN+1);let chunk=await upstream.read();if(chunk.done)return downstream.close();if(bufferLen+chunk.value.length>buffer.length){let grown=new Uint8Array(Math.max(buffer.length*2,bufferLen+chunk.value.length));grown.set(buffer.subarray(0,bufferLen)),buffer=grown}buffer.set(chunk.value,bufferLen),bufferLen+=chunk.value.length;continue}let message=buffer.slice(0,match2.index);if(buffer.copyWithin(0,match2.index+match2.length,bufferLen),bufferLen-=match2.index+match2.length,buffer.length>4096&&bufferLen<=buffer.length>>2){let shrunk=new Uint8Array(Math.max(4096,bufferLen*2));shrunk.set(buffer.subarray(0,bufferLen)),buffer=shrunk}searchStart=0;let item=parseMessage(message,parse,state,dataRequired);if(item&&!item.done)return downstream.enqueue(item.value);if(item?.done)return await upstream.cancel("done"),downstream.close()}}catch(e){downstream.error(e),await upstream.cancel(e)}},cancel:reason=>upstream.cancel(reason)})}[Symbol.asyncIterator](options){let fn=ReadableStream.prototype[Symbol.asyncIterator];if(typeof fn=="function")return fn.call(this,options);let reader=this.getReader(),iterator={next:async()=>{let r=await reader.read();return r.done?(reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:r.value}},throw:async e=>(await reader.cancel(e),reader.releaseLock(),{done:!0,value:void 0}),return:async()=>(await reader.cancel("done"),reader.releaseLock(),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}},asyncDispose=Symbol.asyncDispose;return asyncDispose&&(iterator[asyncDispose]=async()=>{var _a2;await((_a2=iterator.return)===null||_a2===void 0?void 0:_a2.call(iterator))}),iterator}values(options){return this[Symbol.asyncIterator](options)}},CR=13,LF=10,BOUNDARIES=[[CR,LF,CR,LF],[CR,LF,CR],[CR,LF,LF],[CR,CR,LF],[LF,CR,LF],[CR,CR],[LF,CR],[LF,LF]],MAX_BOUNDARY_LEN=BOUNDARIES.reduce((m,b)=>Math.max(m,b.length),0);function findBoundary(buf,len,from){for(let i=from;i<len;i++)if(!(buf[i]!==CR&&buf[i]!==LF))for(let boundary of BOUNDARIES){if(i+boundary.length>len)continue;let match2=!0;for(let j=0;j<boundary.length;j++)if(buf[i+j]!==boundary[j]){match2=!1;break}if(match2)return{index:i,length:boundary.length}}return null}function parseMessage(chunk,parse,state,dataRequired){let lines=new TextDecoder().decode(chunk).split(/\r\n|\r|\n/),dataLines=[],ret={},ignore=!0;for(let line of lines){if(!line||line.startsWith(":"))continue;ignore=!1;let i=line.indexOf(":"),field=line,value="";i>0&&(field=line.slice(0,i),value=line[i+1]===" "?line.slice(i+2):line.slice(i+1)),field==="data"?dataLines.push(value):field==="event"?ret.event=value:field==="id"&&!value.includes("\0")?state.eventId=value:field==="retry"&&/^\d+$/.test(value)&&(ret.retry=Number(value))}if(!ignore){if(ret.id=state.eventId,dataLines.length)ret.data=dataLines.join(`
43
- `);else if(dataRequired)return;return parse(ret)}}var DEFAULT_CONTENT_TYPES={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function jsonErr(codes,errorClass,options){return Object.assign(Object.assign({},options),{err:!0,enc:"json",codes,errorClass})}function json(codes,options){return Object.assign(Object.assign({},options),{enc:"json",codes})}function sse(codes,sse2,options){return Object.assign(Object.assign(Object.assign({},options),{enc:"sse",codes}),sse2?{sse:sse2}:{})}function nil(codes,options){return Object.assign(Object.assign({},options),{enc:"nil",codes})}function fail(codes){return{enc:"fail",codes}}function match(...matchers){return async function(response,request,options){let raw,matcher;for(let match2 of matchers){let{codes}=match2,ctpattern="ctype"in match2?match2.ctype:DEFAULT_CONTENT_TYPES[match2.enc];if(ctpattern&&matchResponse(response,codes,ctpattern)){matcher=match2;break}else if(!ctpattern&&matchStatusCode(response,codes)){matcher=match2;break}}if(!matcher)return[{ok:!1,error:new GoogleGenAiDefaultError("Unexpected Status or Content-Type",{response,request,body:await response.text().catch(()=>"")})},raw];let encoding=matcher.enc,body="";switch(encoding){case"json":body=await response.text();try{raw=JSON.parse(body)}catch(err){if(!("err"in matcher))throw err;raw=body}break;case"jsonl":raw=response.body;break;case"bytes":raw=new Uint8Array(await response.arrayBuffer());break;case"stream":raw=response.body;break;case"text":body=await response.text(),raw=body;break;case"sse":if(response.body){let sseOpts="sse"in matcher&&matcher.sse||{};raw=wrapEventStreamResponse(response.body,sseOpts)}else raw=null;break;case"nil":body=await response.text(),raw=void 0;break;case"fail":body=await response.text(),raw=body;break;default:throw new Error(`Unsupported response type: ${encoding}`)}if(matcher.enc==="fail")return[{ok:!1,error:new GoogleGenAiDefaultError("API error occurred",{request,response,body})},raw];let resultKey=matcher.key||options?.resultKey,data,headersField=matcher.hdrs?{headers:unpackHeaders(response.headers)}:null;return"err"in matcher?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),isPlainObject$1(raw)?raw:null):resultKey?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),{[resultKey]:raw}):matcher.hdrs?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),isPlainObject$1(raw)?raw:null):data=raw,"err"in matcher?[{ok:!1,error:matcher.errorClass?new matcher.errorClass(data,{request,response,body}):data},raw]:[{ok:!0,value:data},raw]}}var headerValRE=/, */;function unpackHeaders(headers){let out={};for(let[k,v]of headers.entries())out[k]=v.split(headerValRE);return out}var SecurityErrorCode={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},SecurityError=class _SecurityError extends Error{constructor(code,message){super(message),this.code=code,this.name="SecurityError"}static incomplete(){return new _SecurityError(SecurityErrorCode.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(type){return new _SecurityError(SecurityErrorCode.UnrecognisedSecurityType,`Unrecognised security type: ${type}`)}};function resolveSecurity(...options){let state={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},option=options.find(opts=>opts.every(o=>{if(o.value==null)return!1;if(o.type==="http:basic")return o.value.username!=null||o.value.password!=null;if(o.type==="http:custom")return null;if(o.type==="oauth2:password")return typeof o.value=="string"&&!!o.value;if(o.type==="oauth2:client_credentials")return typeof o.value=="string"?!!o.value:o.value.client_id!=null||o.value.client_secret!=null;if(typeof o.value=="string")return!!o.value;throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`)}));return option==null?null:(option.forEach(spec=>{if(spec.value==null)return;let{type}=spec;switch(type){case"apiKey:header":state.headers[spec.fieldName]=spec.value;break;case"apiKey:query":state.queryParams[spec.fieldName]=spec.value;break;case"apiKey:cookie":state.cookies[spec.fieldName]=spec.value;break;case"http:basic":applyBasic(state,spec);break;case"http:custom":break;case"http:bearer":applyBearer(state,spec);break;case"oauth2":applyBearer(state,spec);break;case"oauth2:password":applyBearer(state,spec);break;case"oauth2:client_credentials":break;case"openIdConnect":applyBearer(state,spec);break;default:throw SecurityError.unrecognizedType(type)}}),state)}function applyBasic(state,spec){spec.value!=null&&(state.basic=spec.value)}function applyBearer(state,spec){if(typeof spec.value!="string"||!spec.value)return;let value=spec.value;value.slice(0,7).toLowerCase()!=="bearer "&&(value=`Bearer ${value}`),spec.fieldName!==void 0&&(state.headers[spec.fieldName]=value)}function resolveGlobalSecurity(security,allowedFields){var _a2,_b;let inputs=[[{fieldName:"accessToken",type:"http:custom",value:(_a2=security?.access_token)!==null&&_a2!==void 0?_a2:env().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(_b=security?.api_key)!==null&&_b!==void 0?_b:env().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:security?.default_headers}]];return resolveSecurity(...inputs)}async function extractSecurity(sec){if(sec!=null)return typeof sec=="function"?sec():sec}var _a,APIPromise=class _APIPromise{constructor(p,callSource){this[_a]="APIPromise",this._promise=p instanceof Promise?p:Promise.resolve(p),this._unwrapped=p instanceof Promise?null:Promise.resolve(p[0]),this._callSource=callSource??null}_getUnwrapped(){var _b;return(_b=this._unwrapped)!==null&&_b!==void 0?_b:this._unwrapped=this._promise.then(([value])=>value)}then(onfulfilled,onrejected){return this._promise.then(onfulfilled?([value])=>onfulfilled(value):void 0,onrejected)}catch(onrejected){return this._getUnwrapped().catch(onrejected)}finally(onfinally){return this._getUnwrapped().finally(onfinally)}$inspect(){return this._promise}asResponse(){var _b;return((_b=this._callSource)!==null&&_b!==void 0?_b:this._callSource=this._promise.then(([,call])=>call)).then(call=>{if(!call.response)throw new Error("APIPromise.asResponse: response unavailable");return call.response})}async withResponse(){let[[data],response]=await Promise.all([this._promise,this.asResponse()]);return{data,response}}_thenUnwrap(transform){var _b;let data=this._promise.then(([value,call])=>[transform(value),call]);return data.catch(()=>{}),new _APIPromise(data,(_b=this._callSource)!==null&&_b!==void 0?_b:void 0)}};_a=Symbol.toStringTag;function unwrapAsAPIPromise(p){let inner=p.$inspect(),data=inner.then(([r,call])=>{if(!r.ok)throw r.error;return[r.value,call]}),callSource=inner.then(([r,call])=>{var _b;if(!r.ok&&!(!((_b=call.response)===null||_b===void 0)&&_b.ok))throw r.error;return call});return data.catch(()=>{}),callSource.catch(()=>{}),new APIPromise(data,callSource)}function agentsCreate(client,body,api_version,options){return new APIPromise($do$q(client,body,api_version,options))}async function $do$q(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsDelete(client,id,api_version,options){return new APIPromise($do$p(client,id,api_version,options))}async function $do$p(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsGet(client,id,api_version,options){return new APIPromise($do$o(client,id,api_version,options))}async function $do$o(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsList(client,api_version,page_size,page_token,parent,options){return new APIPromise($do$n(client,api_version,page_size,page_token,parent,options))}async function $do$n(client,api_version,page_size,page_token,parent,options){var _a2,_b,_c;let payload={api_version,page_size,page_token,parent},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token,parent:payload?.parent}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Agents=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(agentsList(this,params?.api_version,params?.page_size,params?.page_token,params?.parent,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(agentsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(agentsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(agentsGet(this,id,params?.api_version,options))}};function environmentsCreateEnvironment(client,body,api_version,options){return new APIPromise($do$m(client,body,api_version,options))}async function $do$m(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsDeleteEnvironment(client,id,api_version,options){return new APIPromise($do$l(client,id,api_version,options))}async function $do$l(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsGetEnvironment(client,id,api_version,options){return new APIPromise($do$k(client,id,api_version,options))}async function $do$k(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsListEnvironments(client,api_version,page_size,page_token,options){return new APIPromise($do$j(client,api_version,page_size,page_token,options))}async function $do$j(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsFilesList(client,environment,path2,api_version,page_size,page_token,recursive,options){return new APIPromise($do$i(client,environment,path2,api_version,page_size,page_token,recursive,options))}async function $do$i(client,environment,path2,api_version,page_size,page_token,recursive,options){var _a2,_b,_c;let payload={environment,path:path2,api_version,page_size,page_token,recursive},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),environment:encodeSimple("environment",payload.environment,{explode:!1,charEncoding:"percent"}),path:encodeSimple("path",payload.path,{explode:!1,charEncoding:"percent"})},path$=pathToFunc("/{api_version}/environments/{environment}/files/{path}")(pathParams),query=encodeFormQuery({page_size:payload.page_size,page_token:payload.page_token,recursive:payload.recursive}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path$,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Files2=class extends ClientSDK{list(environment,path2,params,options){return unwrapAsAPIPromise(environmentsFilesList(this,environment,path2,params?.api_version,params?.page_size,params?.page_token,params?.recursive,options))}};var Environments=class extends ClientSDK{get files(){var _a2;return(_a2=this._files)!==null&&_a2!==void 0?_a2:this._files=new Files2(this._options)}listEnvironments(params,options){return unwrapAsAPIPromise(environmentsListEnvironments(this,params?.api_version,params?.page_size,params?.page_token,options))}createEnvironment(body,api_version,options){return unwrapAsAPIPromise(environmentsCreateEnvironment(this,body,api_version,options))}deleteEnvironment(id,params,options){return unwrapAsAPIPromise(environmentsDeleteEnvironment(this,id,params?.api_version,options))}getEnvironment(id,params,options){return unwrapAsAPIPromise(environmentsGetEnvironment(this,id,params?.api_version,options))}};var CancelInteractionByIdServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CancelInteractionByIdServerError"}},CancelInteractionByIdClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CancelInteractionByIdClientError"}};var CreateInteractionServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CreateInteractionServerError"}},CreateInteractionClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CreateInteractionClientError"}};var DeleteInteractionServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="DeleteInteractionServerError"}},DeleteInteractionClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="DeleteInteractionClientError"}};var GetInteractionByIdServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="GetInteractionByIdServerError"}},GetInteractionByIdClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="GetInteractionByIdClientError"}};function interactionsCancel(client,id,api_version,options){return new APIPromise($do$h(client,id,api_version,options))}async function $do$h(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}/cancel")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),jsonErr("4XX",CancelInteractionByIdClientError),jsonErr("5XX",CancelInteractionByIdServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsCreate(client,body,api_version,options){return new APIPromise($do$g(client,body,api_version,options))}async function $do$g(client,body,api_version,options){var _a2,_b,_c,_d;let input={body,api_version},payload=input,body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:!((_b=input?.body)===null||_b===void 0)&&_b.stream?"text/event-stream":"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_d=(_c=options?.server_url)!==null&&_c!==void 0?_c:client._baseURL)!==null&&_d!==void 0?_d:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),sse(200,{sentinel:"[DONE]",flattened:!0}),jsonErr("4XX",CreateInteractionClientError),jsonErr("5XX",CreateInteractionServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsDelete(client,id,api_version,options){return new APIPromise($do$f(client,id,api_version,options))}async function $do$f(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(nil(200),jsonErr("4XX",DeleteInteractionClientError),jsonErr("5XX",DeleteInteractionServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsGet(client,id,api_version,include_input,last_event_id,stream,options){return new APIPromise($do$e(client,id,api_version,include_input,last_event_id,stream,options))}async function $do$e(client,id,api_version,include_input,last_event_id,stream,options){var _a2,_b,_c;let input={id,api_version,include_input,last_event_id,stream},payload=input,body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}")(pathParams),query=encodeFormQuery({include_input:payload.include_input,last_event_id:payload.last_event_id,stream:payload.stream}),headers=new Headers(compactMap({Accept:input?.stream?"text/event-stream":"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),sse(200,{sentinel:"[DONE]",flattened:!0}),jsonErr("4XX",GetInteractionByIdClientError),jsonErr("5XX",GetInteractionByIdServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Interactions=class extends ClientSDK{create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(interactionsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(interactionsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(interactionsGet(this,id,params?.api_version,params?.include_input,params?.last_event_id,params?.stream,options))}cancel(id,params,options){return unwrapAsAPIPromise(interactionsCancel(this,id,params?.api_version,options))}};function triggersCreate(client,body,api_version,options){return new APIPromise($do$d(client,body,api_version,options))}async function $do$d(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersDelete(client,id,api_version,options){return new APIPromise($do$c(client,id,api_version,options))}async function $do$c(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersGet(client,id,api_version,options){return new APIPromise($do$b(client,id,api_version,options))}async function $do$b(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersListExecutions(client,trigger_id,api_version,page_size,page_token,options){return new APIPromise($do$a(client,trigger_id,api_version,page_size,page_token,options))}async function $do$a(client,trigger_id,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={trigger_id,api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:encodeSimple("trigger_id",payload.trigger_id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams),query=encodeFormQuery({page_size:payload.page_size,page_token:payload.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersList(client,api_version,filter,page_size,page_token,options){return new APIPromise($do$9(client,api_version,filter,page_size,page_token,options))}async function $do$9(client,api_version,filter,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,filter,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers")(pathParams),query=encodeFormQuery({filter:payload?.filter,page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersRun(client,trigger_id,api_version,options){return new APIPromise($do$8(client,trigger_id,api_version,options))}async function $do$8(client,trigger_id,api_version,options){var _a2,_b,_c;let payload={trigger_id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:encodeSimple("trigger_id",payload.trigger_id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersUpdate(client,id,body,api_version,options){return new APIPromise($do$7(client,id,body,api_version,options))}async function $do$7(client,id,body,api_version,options){var _a2,_b,_c;let payload={id,body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Triggers=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(triggersList(this,params?.api_version,params?.filter,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(triggersCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(triggersDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(triggersGet(this,id,params?.api_version,options))}update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(triggersUpdate(this,id,body,api_version,options))}listExecutions(trigger_id,params,options){return unwrapAsAPIPromise(triggersListExecutions(this,trigger_id,params?.api_version,params?.page_size,params?.page_token,options))}run(trigger_id,params,options){return unwrapAsAPIPromise(triggersRun(this,trigger_id,params?.api_version,options))}};function webhooksCreate(client,body,api_version,options){return new APIPromise($do$6(client,body,api_version,options))}async function $do$6(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksDelete(client,id,api_version,options){return new APIPromise($do$5(client,id,api_version,options))}async function $do$5(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksGet(client,id,api_version,options){return new APIPromise($do$4(client,id,api_version,options))}async function $do$4(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksList(client,api_version,page_size,page_token,options){return new APIPromise($do$3(client,api_version,page_size,page_token,options))}async function $do$3(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksPing(client,id,api_version,body,options){return new APIPromise($do$2(client,id,api_version,body,options))}async function $do$2(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:ping")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksRotateSigningSecret(client,id,api_version,body,options){return new APIPromise($do$1(client,id,api_version,body,options))}async function $do$1(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:rotateSigningSecret")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksUpdate(client,id,api_version,update_mask,body,options){return new APIPromise($do(client,id,api_version,update_mask,body,options))}async function $do(client,id,api_version,update_mask,body,options){var _a2,_b,_c;let payload={id,api_version,update_mask,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),query=encodeFormQuery({update_mask:payload.update_mask}),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,query,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Webhooks=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(webhooksList(this,params?.api_version,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(webhooksCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(webhooksDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(webhooksGet(this,id,params?.api_version,options))}update(id,params,options){let _a2=params??{},{api_version,update_mask}=_a2,body$body=__rest(_a2,["api_version","update_mask"]),body=params===void 0||Object.keys(body$body).length===0?void 0:body$body;return unwrapAsAPIPromise(webhooksUpdate(this,id,api_version,update_mask,body,options))}ping(id,api_version,body,options){return unwrapAsAPIPromise(webhooksPing(this,id,api_version,body,options))}rotateSigningSecret(id,api_version,body,options){return unwrapAsAPIPromise(webhooksRotateSigningSecret(this,id,api_version,body,options))}};var GoogleGenAI$1=class extends ClientSDK{get agents(){var _a2;return(_a2=this._agents)!==null&&_a2!==void 0?_a2:this._agents=new Agents(this._options)}get environments(){var _a2;return(_a2=this._environments)!==null&&_a2!==void 0?_a2:this._environments=new Environments(this._options)}get interactions(){var _a2;return(_a2=this._interactions)!==null&&_a2!==void 0?_a2:this._interactions=new Interactions(this._options)}get triggers(){var _a2;return(_a2=this._triggers)!==null&&_a2!==void 0?_a2:this._triggers=new Triggers(this._options)}get webhooks(){var _a2;return(_a2=this._webhooks)!==null&&_a2!==void 0?_a2:this._webhooks=new Webhooks(this._options)}};var LEGACY_LYRIA_MODELS=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function getGoogleGenAIServerURL(parentClient){let serverURL=parentClient.getBaseUrl();if(!serverURL)throw new Error("Base URL must be set.");return serverURL.replace(/\/+$/,"")}function getGoogleGenAIAPIVersion(parentClient){let apiVersion=trimSlashes(parentClient.getApiVersion()),project=parentClient.getProject(),location=parentClient.getLocation();return parentClient.isVertexAI()&&apiVersion&&project&&location?`${apiVersion}/projects/${encodeURIComponent(project)}/locations/${encodeURIComponent(location)}`:apiVersion}function buildGoogleGenAIClient(parentClient,options={}){var _a2,_b,_c,_d,_e;return new GoogleGenAI$1(Object.assign(Object.assign({},options),{api_version:(_a2=options.api_version)!==null&&_a2!==void 0?_a2:getGoogleGenAIAPIVersion(parentClient),security:(_b=options.security)!==null&&_b!==void 0?_b:new GoogleGenAISecurityProvider({defaultHeaders:Object.assign(Object.assign({},(_c=parentClient.getDefaultHeaders)===null||_c===void 0?void 0:_c.call(parentClient)),(_d=parentClient.getHeaders)===null||_d===void 0?void 0:_d.call(parentClient)),getAuthHeaders:url=>parentClient.getAuthHeaders(url)}),server_url:(_e=options.server_url)!==null&&_e!==void 0?_e:getGoogleGenAIServerURL(parentClient)}))}var GeminiNextGenInteractions=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,request=__rest(params,["api_version"]);if(request.stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.create(Object.assign(Object.assign({},request),{stream:!0,api_version}),toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsCreate(this.getClient(api_version),request,api_version,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async get(id,params={},options){let{api_version,stream=!1,last_event_id,include_input}=params??{};if(stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.get(id,{stream,last_event_id,include_input,api_version},toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsGet(this.getClient(api_version),id,api_version,include_input,last_event_id,stream,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async delete(id,params={},options){return wrapSDKCall(()=>this.getClient(params?.api_version).interactions.delete(id,{api_version:params?.api_version},toGoogleGenAIRequestOptions(options)))}async cancel(id,params={},options){return addOutputPropertiesIfInteraction(await unwrapWithSdkHttpResponse(interactionsCancel(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options))))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenAgents=class{constructor(parentClient){this.parentClient=parentClient}async create(params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(agentsCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,pageSize,pageToken,parent}=params??{};return unwrapWithSdkHttpResponse(agentsList(this.getClient(api_version),api_version,pageSize,pageToken,parent,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(agentsGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(agentsDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenWebhooks=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(webhooksCreate(this.getClient(),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(webhooksList(this.getClient(),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(webhooksGet(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params={},options){let _a2=params??{},{api_version,update_mask}=_a2,body=__rest(_a2,["api_version","update_mask"]);return unwrapWithSdkHttpResponse(webhooksUpdate(this.getClient(),id,api_version,update_mask,body,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(webhooksDelete(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async rotateSigningSecret(id,params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(webhooksRotateSigningSecret(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}async ping(id,params=void 0,options){let{api_version,body}=params??{};return unwrapWithSdkHttpResponse(webhooksPing(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}getClient(){var _a2;return(_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk}},GeminiNextGenTriggers=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,filter,pageSize,pageToken}=params??{};return unwrapWithSdkHttpResponse(triggersList(this.getClient(api_version),api_version,filter,pageSize,pageToken,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(triggersGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersUpdate(this.getClient(api_version),id,body,api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(triggersDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async run(trigger_id,params={},options){return unwrapWithSdkHttpResponse(triggersRun(this.getClient(params?.api_version),trigger_id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async listExecutions(trigger_id,params={},options){let{api_version,pageSize,pageToken}=params??{};return unwrapWithSdkHttpResponse(triggersListExecutions(this.getClient(api_version),trigger_id,api_version,pageSize,pageToken,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};function trimSlashes(value){return value.replace(/^\/+|\/+$/g,"")}function toGoogleGenAIRequestOptions(options,streaming=!1){var _a2,_b,_c,_d;if(!options&&!streaming)return;let _e=options??{},{timeout,maxRetries,defaultBaseURL,query,body,fetchOptions}=_e,rest=__rest(_e,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),nextOptions=Object.assign({},rest);isPlainObject(query)?nextOptions.extra_query=query:warnIgnoredOption("query",query),isPlainObject(body)?nextOptions.extra_body=body:warnIgnoredOption("body",body);let fetch_options=(_a2=rest.fetch_options)!==null&&_a2!==void 0?_a2:fetchOptions;fetch_options&&(nextOptions.fetch_options=fetch_options);let server_url=(_b=rest.server_url)!==null&&_b!==void 0?_b:defaultBaseURL;server_url&&(nextOptions.server_url=server_url);let timeout_ms=(_c=rest.timeout_ms)!==null&&_c!==void 0?_c:timeout;if(timeout_ms!==void 0&&(nextOptions.timeout_ms=timeout_ms),maxRetries!==void 0&&(nextOptions.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries}),streaming){let headers=new Headers((_d=nextOptions.headers)!==null&&_d!==void 0?_d:fetch_options?.headers);headers.set("Accept","text/event-stream"),nextOptions.headers=headers}return nextOptions}function warnIgnoredOption(name,value){value!=null&&console.warn(`GoogleGenAI.interactions: request option ${name} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function unwrapWithSdkHttpResponse(promise){let[result,call]=await promise.$inspect();if(!result.ok)throw wrapSDKError(result.error);return attachSdkHttpResponse(result.value,call)}async function wrapSDKCall(operation){try{return await operation()}catch(error){throw wrapSDKError(error)}}function wrapStreamErrors(stream){let asyncIterable=stream;return new Proxy(stream,{get(target,property){if(property!==Symbol.asyncIterator){let value=Reflect.get(target,property,target);return typeof value=="function"?value.bind(target):value}return function(){let iterator=asyncIterable[Symbol.asyncIterator]();return{async next(...args){try{return await iterator.next(...args)}catch(error){throw wrapSDKError(error)}},async return(value){if(!iterator.return)return{done:!0,value};try{return await iterator.return(value)}catch(error){throw wrapSDKError(error)}},async throw(error){if(!iterator.throw)throw wrapSDKError(error);try{return await iterator.throw(error)}catch(caught){throw wrapSDKError(caught)}},[Symbol.asyncIterator](){return this}}}}})}function attachSdkHttpResponse(value,call){return!isPlainObject(value)||call.status!=="complete"?value:Object.assign(Object.assign({},value),{sdkHttpResponse:createSdkHttpResponse(call.response,value)})}function createSdkHttpResponse(response,parsedBody){let headers={};for(let[key,value]of response.headers.entries())headers[key]=value;return{headers,responseInternal:response,json:async()=>parsedBody}}function addOutputPropertiesIfInteraction(value){let interaction=normalizeInteractionShape(value);return interaction?addOutputProperties(interaction):value}function normalizeInteractionShape(value){if(isPlainObject(value)){if(Array.isArray(value.steps))return value;if(isLegacyLyriaInteraction(value)){let outputs=value.outputs;if(Array.isArray(outputs)){let{outputs:_outputs}=value,rest=__rest(value,["outputs"]);return Object.assign(Object.assign({},rest),{steps:[{type:"model_output",content:outputs}]})}}return Object.assign(Object.assign({},value),{steps:[]})}}function isLegacyLyriaInteraction(value){let model=value.model;return typeof model=="string"&&LEGACY_LYRIA_MODELS.has(model)}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function addOutputProperties(interaction){var _a2,_b;let normalized=normalizeInteractionDates(interaction),steps=(_a2=normalized.steps)!==null&&_a2!==void 0?_a2:[],textParts=[],collecting=!1;outer:for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type!=="model_output"||!step.content){if(collecting)break;continue}let content=step.content;for(let j=content.length-1;j>=0;j--){let item=content[j];if(item.type==="text")collecting=!0,textParts.push((_b=item.text)!==null&&_b!==void 0?_b:"");else if(collecting)break outer}}let output_image,output_audio,output_video;for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type==="model_output"&&step.content)for(let j=step.content.length-1;j>=0;j--){let content=step.content[j];content.type==="image"&&!output_image&&(output_image=content),content.type==="audio"&&!output_audio&&(output_audio=content),content.type==="video"&&!output_video&&(output_video=content)}}let output_text=textParts.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},normalized),output_text&&{output_text}),output_image?{output_image}:{}),output_audio?{output_audio}:{}),output_video?{output_video}:{})}function normalizeInteractionDates(interaction){return Object.assign(Object.assign({},interaction),{created:normalizeDateLike(interaction.created),updated:normalizeDateLike(interaction.updated)})}function normalizeDateLike(value){return value instanceof Date?value.toISOString():value}var GeminiNextGenEnvironmentFiles=class{constructor(resolveClient){this.resolveClient=resolveClient}async list(params,options){let{environment,path:path2,page_size,page_token,recursive,api_version}=params;return unwrapWithSdkHttpResponse(environmentsFilesList(this.resolveClient(api_version),environment,path2,api_version,page_size,page_token,recursive,toGoogleGenAIRequestOptions(options)))}},GeminiNextGenEnvironments=class{constructor(parentClient){this.parentClient=parentClient,this.files=new GeminiNextGenEnvironmentFiles(apiVersion=>this.getClient(apiVersion))}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(environmentsCreateEnvironment(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(environmentsListEnvironments(this.getClient(api_version),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(environmentsGetEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(environmentsDeleteEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};var GOOGLE_API_KEY_HEADER="x-goog-api-key",REQUIRED_VERTEX_AI_SCOPE="https://www.googleapis.com/auth/cloud-platform",NodeAuth=class{constructor(opts){if(opts.apiKey!==void 0){this.apiKey=opts.apiKey;return}let vertexAuthOptions=buildGoogleAuthOptions(opts.googleAuthOptions);this.googleAuth=new import_google_auth_library.GoogleAuth(vertexAuthOptions)}async addAuthHeaders(headers,url){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(headers);return}return this.addGoogleAuthHeaders(headers,url)}addKeyHeader(headers){if(headers.get(GOOGLE_API_KEY_HEADER)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");headers.append(GOOGLE_API_KEY_HEADER,this.apiKey)}}async addGoogleAuthHeaders(headers,url){if(this.googleAuth===void 0)throw new Error("Trying to set google-auth headers but googleAuth is unset");let authHeaders=await this.googleAuth.getRequestHeaders(url);for(let[key,value]of authHeaders)headers.get(key)===null&&headers.append(key,value)}};function buildGoogleAuthOptions(googleAuthOptions){let authOptions;if(googleAuthOptions){if(authOptions=googleAuthOptions,authOptions.scopes){if(typeof authOptions.scopes=="string"&&authOptions.scopes!==REQUIRED_VERTEX_AI_SCOPE||Array.isArray(authOptions.scopes)&&authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`)}else return authOptions.scopes=[REQUIRED_VERTEX_AI_SCOPE],authOptions;return authOptions}else return authOptions={scopes:[REQUIRED_VERTEX_AI_SCOPE]},authOptions}var NodeDownloader=class{async download(params,apiClient){if(params.downloadPath){let response=await downloadFile(params,apiClient);if(response instanceof HttpResponse){let writer=createWriteStream(params.downloadPath);Readable.fromWeb(response.responseInternal.body).pipe(writer),await finished(writer)}else try{await writeFile(params.downloadPath,response,{encoding:"base64"})}catch(error){throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`)}}}};async function downloadFile(params,apiClient){var _a2,_b,_c;let name=tFileName(params.file);if(name!==void 0)return await apiClient.request({path:`files/${name}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal});if(isGeneratedVideo(params.file)){let videoBytes=(_c=params.file.video)===null||_c===void 0?void 0:_c.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(isVideo(params.file)){let videoBytes=params.file.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var NodeWebSocketFactory=class{create(url,headers,callbacks){return new NodeWebSocket(url,headers,callbacks)}},NodeWebSocket=class{constructor(url,headers,callbacks){this.url=url,this.headers=headers,this.callbacks=callbacks}connect(){this.ws=new import_websocket.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(message){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(message)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function cancelTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function cancelTuningJobResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function contentToVertex(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createTuningJobConfigToMldev(fromObject,parentObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);if(parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromTunedModelDisplayName),getValueByPath(fromObject,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);if(fromLearningRateMultiplier!=null&&setValueByPath(toObject,["tuningTask","hyperparameters","learningRateMultiplier"],fromLearningRateMultiplier),getValueByPath(fromObject,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);if(parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","learningRate"],fromLearningRate),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function createTuningJobConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorValidationDataset=getValueByPath(rootObject,["config","method"]);if(discriminatorValidationDataset===void 0&&(discriminatorValidationDataset="SUPERVISED_FINE_TUNING"),discriminatorValidationDataset==="SUPERVISED_FINE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["supervisedTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="PREFERENCE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="DISTILLATION"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["distillationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="REINFORCEMENT_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["reinforcementTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let discriminatorEpochCount=getValueByPath(rootObject,["config","method"]);if(discriminatorEpochCount===void 0&&(discriminatorEpochCount="SUPERVISED_FINE_TUNING"),discriminatorEpochCount==="SUPERVISED_FINE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="PREFERENCE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="DISTILLATION"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="REINFORCEMENT_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","epochCount"],fromEpochCount)}let discriminatorLearningRateMultiplier=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRateMultiplier===void 0&&(discriminatorLearningRateMultiplier="SUPERVISED_FINE_TUNING"),discriminatorLearningRateMultiplier==="SUPERVISED_FINE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="PREFERENCE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="DISTILLATION"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="REINFORCEMENT_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}let discriminatorExportLastCheckpointOnly=getValueByPath(rootObject,["config","method"]);if(discriminatorExportLastCheckpointOnly===void 0&&(discriminatorExportLastCheckpointOnly="SUPERVISED_FINE_TUNING"),discriminatorExportLastCheckpointOnly==="SUPERVISED_FINE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["supervisedTuningSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="PREFERENCE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="DISTILLATION"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["distillationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}let discriminatorAdapterSize=getValueByPath(rootObject,["config","method"]);if(discriminatorAdapterSize===void 0&&(discriminatorAdapterSize="SUPERVISED_FINE_TUNING"),discriminatorAdapterSize==="SUPERVISED_FINE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="PREFERENCE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="DISTILLATION"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="REINFORCEMENT_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}let discriminatorTuningMode=getValueByPath(rootObject,["config","method"]);if(discriminatorTuningMode===void 0&&(discriminatorTuningMode="SUPERVISED_FINE_TUNING"),discriminatorTuningMode==="SUPERVISED_FINE_TUNING"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["supervisedTuningSpec","tuningMode"],fromTuningMode)}else if(discriminatorTuningMode==="DISTILLATION"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["distillationSpec","tuningMode"],fromTuningMode)}let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);parentObject!==void 0&&fromCustomBaseModel!=null&&setValueByPath(parentObject,["customBaseModel"],fromCustomBaseModel);let discriminatorBatchSize=getValueByPath(rootObject,["config","method"]);if(discriminatorBatchSize===void 0&&(discriminatorBatchSize="SUPERVISED_FINE_TUNING"),discriminatorBatchSize==="SUPERVISED_FINE_TUNING"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="DISTILLATION"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="REINFORCEMENT_TUNING"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","batchSize"],fromBatchSize)}let discriminatorLearningRate=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRate===void 0&&(discriminatorLearningRate="SUPERVISED_FINE_TUNING"),discriminatorLearningRate==="SUPERVISED_FINE_TUNING"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRate"],fromLearningRate)}else if(discriminatorLearningRate==="DISTILLATION"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRate"],fromLearningRate)}let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromBeta=getValueByPath(fromObject,["beta"]);parentObject!==void 0&&fromBeta!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","beta"],fromBeta);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);parentObject!==void 0&&fromBaseTeacherModel!=null&&setValueByPath(parentObject,["distillationSpec","baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);parentObject!==void 0&&fromTunedTeacherModelSource!=null&&setValueByPath(parentObject,["distillationSpec","tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromSftLossWeightMultiplier=getValueByPath(fromObject,["sftLossWeightMultiplier"]);parentObject!==void 0&&fromSftLossWeightMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],fromSftLossWeightMultiplier);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);parentObject!==void 0&&fromOutputUri!=null&&setValueByPath(parentObject,["outputUri"],fromOutputUri);let fromRewardConfig=getValueByPath(fromObject,["rewardConfig"]);parentObject!==void 0&&fromRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","singleRewardConfig"],fromRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);parentObject!==void 0&&fromCompositeRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","compositeRewardConfig"],fromCompositeRewardConfig);let fromSamplesPerPrompt=getValueByPath(fromObject,["samplesPerPrompt"]);parentObject!==void 0&&fromSamplesPerPrompt!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],fromSamplesPerPrompt);let fromEvaluateInterval=getValueByPath(fromObject,["evaluateInterval"]);parentObject!==void 0&&fromEvaluateInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],fromEvaluateInterval);let fromCheckpointInterval=getValueByPath(fromObject,["checkpointInterval"]);parentObject!==void 0&&fromCheckpointInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],fromCheckpointInterval);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],fromMaxOutputTokens);let fromThinkingLevel=getValueByPath(fromObject,["thinkingLevel"]);parentObject!==void 0&&fromThinkingLevel!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],fromThinkingLevel);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);parentObject!==void 0&&fromValidationDatasetUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","validationDatasetUri"],fromValidationDatasetUri);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);return parentObject!==void 0&&fromEncryptionSpec!=null&&setValueByPath(parentObject,["encryptionSpec"],fromEncryptionSpec),toObject}function createTuningJobParametersPrivateToMldev(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToMldev(fromTrainingDataset);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToMldev(fromConfig,toObject),toObject}function createTuningJobParametersPrivateToVertex(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToVertex(fromTrainingDataset,toObject,rootObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToVertex(fromConfig,toObject,rootObject),toObject}function distillationHyperParametersFromVertex(fromObject,rootObject){let toObject={},fromEpochCount=getValueByPath(fromObject,["epochCount"]);fromEpochCount!=null&&setValueByPath(toObject,["epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);fromLearningRateMultiplier!=null&&setValueByPath(toObject,["learningRateMultiplier"],fromLearningRateMultiplier);let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);fromAdapterSize!=null&&setValueByPath(toObject,["adapterSize"],fromAdapterSize);let fromBatchSize=getValueByPath(fromObject,["batchSize"]);fromBatchSize!=null&&setValueByPath(toObject,["batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);fromLearningRate!=null&&setValueByPath(toObject,["learningRate"],fromLearningRate);let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return fromGenerationConfig!=null&&setValueByPath(toObject,["generationConfig"],generationConfigFromVertex(fromGenerationConfig)),toObject}function distillationSamplingSpecFromVertex(fromObject,rootObject){let toObject={},fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromHyperparameters=getValueByPath(fromObject,["hyperparameters"]);return fromHyperparameters!=null&&setValueByPath(toObject,["hyperparameters"],distillationHyperParametersFromVertex(fromHyperparameters)),toObject}function distillationSpecFromVertex(fromObject,rootObject){let toObject={},fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromHyperParameters=getValueByPath(fromObject,["hyperParameters"]);fromHyperParameters!=null&&setValueByPath(toObject,["hyperParameters"],distillationHyperParametersFromVertex(fromHyperParameters));let fromPipelineRootDirectory=getValueByPath(fromObject,["pipelineRootDirectory"]);fromPipelineRootDirectory!=null&&setValueByPath(toObject,["pipelineRootDirectory"],fromPipelineRootDirectory);let fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromStudentModel=getValueByPath(fromObject,["studentModel"]);fromStudentModel!=null&&setValueByPath(toObject,["studentModel"],fromStudentModel);let fromTrainingDatasetUri=getValueByPath(fromObject,["trainingDatasetUri"]);fromTrainingDatasetUri!=null&&setValueByPath(toObject,["trainingDatasetUri"],fromTrainingDatasetUri);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);fromTuningMode!=null&&setValueByPath(toObject,["tuningMode"],fromTuningMode);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);return fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri),toObject}function generationConfigFromVertex(fromObject,_rootObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelSelectionConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],fromSpeechConfig);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);return fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),toObject}function getTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function getTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function listTuningJobsConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);return parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter),toObject}function listTuningJobsParametersToVertex(fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listTuningJobsConfigToVertex(fromConfig,toObject),toObject}function listTuningJobsResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromTuningJobs=getValueByPath(fromObject,["tuningJobs"]);if(fromTuningJobs!=null){let transformedList=fromTuningJobs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>tuningJobFromVertex(item))),setValueByPath(toObject,["tuningJobs"],transformedList)}return toObject}function partToVertex(fromObject,_rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function reinforcementTuningExampleToVertex(fromObject,rootObject){let toObject={},fromReferences=getValueByPath(fromObject,["references"]);fromReferences!=null&&setValueByPath(toObject,["references"],fromReferences);let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=fromContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex(item))),setValueByPath(toObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);return fromSystemInstruction!=null&&setValueByPath(toObject,["systemInstruction"],contentToVertex(fromSystemInstruction)),toObject}function tunedModelFromMldev(fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["name"]);fromModel!=null&&setValueByPath(toObject,["model"],fromModel);let fromEndpoint=getValueByPath(fromObject,["name"]);return fromEndpoint!=null&&setValueByPath(toObject,["endpoint"],fromEndpoint),toObject}function tuningDatasetToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromExamples=getValueByPath(fromObject,["examples"]);if(fromExamples!=null){let transformedList=fromExamples;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["examples","examples"],transformedList)}return toObject}function tuningDatasetToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorGcsUri=getValueByPath(rootObject,["config","method"]);if(discriminatorGcsUri===void 0&&(discriminatorGcsUri="SUPERVISED_FINE_TUNING"),discriminatorGcsUri==="SUPERVISED_FINE_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["supervisedTuningSpec","trainingDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="PREFERENCE_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","trainingDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="DISTILLATION"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["distillationSpec","promptDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="REINFORCEMENT_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","trainingDatasetUri"],fromGcsUri)}let discriminatorVertexDatasetResource=getValueByPath(rootObject,["config","method"]);if(discriminatorVertexDatasetResource===void 0&&(discriminatorVertexDatasetResource="SUPERVISED_FINE_TUNING"),discriminatorVertexDatasetResource==="SUPERVISED_FINE_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["supervisedTuningSpec","trainingDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="PREFERENCE_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","trainingDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="DISTILLATION"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["distillationSpec","promptDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="REINFORCEMENT_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","trainingDatasetUri"],fromVertexDatasetResource)}if(getValueByPath(fromObject,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tuningJobFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tTuningJobStatus(fromState));let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["tuningTask","startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["tuningTask","completeTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromTunedModel=getValueByPath(fromObject,["_self"]);return fromTunedModel!=null&&setValueByPath(toObject,["tunedModel"],tunedModelFromMldev(fromTunedModel)),toObject}function tuningJobFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tTuningJobStatus(fromState));let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["endTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromTunedModel=getValueByPath(fromObject,["tunedModel"]);fromTunedModel!=null&&setValueByPath(toObject,["tunedModel"],fromTunedModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromSupervisedTuningSpec=getValueByPath(fromObject,["supervisedTuningSpec"]);fromSupervisedTuningSpec!=null&&setValueByPath(toObject,["supervisedTuningSpec"],fromSupervisedTuningSpec);let fromPreferenceOptimizationSpec=getValueByPath(fromObject,["preferenceOptimizationSpec"]);fromPreferenceOptimizationSpec!=null&&setValueByPath(toObject,["preferenceOptimizationSpec"],fromPreferenceOptimizationSpec);let fromDistillationSamplingSpec=getValueByPath(fromObject,["distillationSamplingSpec"]);fromDistillationSamplingSpec!=null&&setValueByPath(toObject,["distillationSamplingSpec"],distillationSamplingSpecFromVertex(fromDistillationSamplingSpec));let fromDistillationSpec=getValueByPath(fromObject,["distillationSpec"]);fromDistillationSpec!=null&&setValueByPath(toObject,["distillationSpec"],distillationSpecFromVertex(fromDistillationSpec));let fromReinforcementTuningSpec=getValueByPath(fromObject,["reinforcementTuningSpec"]);fromReinforcementTuningSpec!=null&&setValueByPath(toObject,["reinforcementTuningSpec"],fromReinforcementTuningSpec);let fromTuningDataStats=getValueByPath(fromObject,["tuningDataStats"]);fromTuningDataStats!=null&&setValueByPath(toObject,["tuningDataStats"],fromTuningDataStats);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);fromEncryptionSpec!=null&&setValueByPath(toObject,["encryptionSpec"],fromEncryptionSpec);let fromPartnerModelTuningSpec=getValueByPath(fromObject,["partnerModelTuningSpec"]);fromPartnerModelTuningSpec!=null&&setValueByPath(toObject,["partnerModelTuningSpec"],fromPartnerModelTuningSpec);let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);fromCustomBaseModel!=null&&setValueByPath(toObject,["customBaseModel"],fromCustomBaseModel);let fromEvaluateDatasetRuns=getValueByPath(fromObject,["evaluateDatasetRuns"]);if(fromEvaluateDatasetRuns!=null){let transformedList=fromEvaluateDatasetRuns;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["evaluateDatasetRuns"],transformedList)}let fromExperiment=getValueByPath(fromObject,["experiment"]);fromExperiment!=null&&setValueByPath(toObject,["experiment"],fromExperiment);let fromFullFineTuningSpec=getValueByPath(fromObject,["fullFineTuningSpec"]);fromFullFineTuningSpec!=null&&setValueByPath(toObject,["fullFineTuningSpec"],fromFullFineTuningSpec);let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);fromOutputUri!=null&&setValueByPath(toObject,["outputUri"],fromOutputUri);let fromPipelineJob=getValueByPath(fromObject,["pipelineJob"]);fromPipelineJob!=null&&setValueByPath(toObject,["pipelineJob"],fromPipelineJob);let fromServiceAccount=getValueByPath(fromObject,["serviceAccount"]);fromServiceAccount!=null&&setValueByPath(toObject,["serviceAccount"],fromServiceAccount);let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);fromTunedModelDisplayName!=null&&setValueByPath(toObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromTuningJobMetadata=getValueByPath(fromObject,["tuningJobMetadata"]);fromTuningJobMetadata!=null&&setValueByPath(toObject,["tuningJobMetadata"],fromTuningJobMetadata);let fromTuningJobState=getValueByPath(fromObject,["tuningJobState"]);fromTuningJobState!=null&&setValueByPath(toObject,["tuningJobState"],fromTuningJobState);let fromVeoLoraTuningSpec=getValueByPath(fromObject,["veoLoraTuningSpec"]);fromVeoLoraTuningSpec!=null&&setValueByPath(toObject,["veoLoraTuningSpec"],fromVeoLoraTuningSpec);let fromVeoTuningSpec=getValueByPath(fromObject,["veoTuningSpec"]);return fromVeoTuningSpec!=null&&setValueByPath(toObject,["veoTuningSpec"],fromVeoTuningSpec),toObject}function tuningOperationFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function tuningValidationDatasetToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromGcsUri);let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);return fromVertexDatasetResource!=null&&setValueByPath(toObject,["validationDatasetUri"],fromVertexDatasetResource),toObject}function validateRewardParametersToVertex(fromObject,rootObject){let toObject={},fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["_url","parent"],fromParent);let fromSampleResponse=getValueByPath(fromObject,["sampleResponse"]);fromSampleResponse!=null&&setValueByPath(toObject,["sampleResponse"],contentToVertex(fromSampleResponse));let fromExample=getValueByPath(fromObject,["example"]);fromExample!=null&&setValueByPath(toObject,["example"],reinforcementTuningExampleToVertex(fromExample));let fromSingleRewardConfig=getValueByPath(fromObject,["singleRewardConfig"]);fromSingleRewardConfig!=null&&setValueByPath(toObject,["singleRewardConfig"],fromSingleRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);return fromCompositeRewardConfig!=null&&setValueByPath(toObject,["compositeRewardConfig"],fromCompositeRewardConfig),toObject}function validateRewardResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromOverallReward=getValueByPath(fromObject,["overallReward"]);fromOverallReward!=null&&setValueByPath(toObject,["overallReward"],fromOverallReward);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromRewardInfoDetails=getValueByPath(fromObject,["rewardInfoDetails"]);return fromRewardInfoDetails!=null&&setValueByPath(toObject,["rewardInfoDetails"],fromRewardInfoDetails),toObject}var Tunings=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS,x=>this.listInternal(x),await this.listInternal(params),params),this.get=async params=>await this.getInternal(params),this.tune=async params=>{var _a2;if(this.apiClient.isVertexAI())if(params.baseModel.startsWith("projects/")){let preTunedModel={tunedModelName:params.baseModel};!((_a2=params.config)===null||_a2===void 0)&&_a2.preTunedModelCheckpointId&&(preTunedModel.checkpointId=params.config.preTunedModelCheckpointId);let paramsPrivate=Object.assign(Object.assign({},params),{preTunedModel});return paramsPrivate.baseModel=void 0,await this.tuneInternal(paramsPrivate)}else{let paramsPrivate=Object.assign({},params);return await this.tuneInternal(paramsPrivate)}else{let paramsPrivate=Object.assign({},params),operation=await this.tuneMldevInternal(paramsPrivate),tunedModelName="";return operation.metadata!==void 0&&operation.metadata.tunedModel!==void 0?tunedModelName=operation.metadata.tunedModel:operation.name!==void 0&&operation.name.includes("/operations/")&&(tunedModelName=operation.name.split("/operations/")[0]),{name:tunedModelName,state:JobState.JOB_STATE_QUEUED}}}}async getInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getTuningJobParametersToVertex(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromVertex(apiResponse))}else{let body=getTuningJobParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromMldev(apiResponse))}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listTuningJobsParametersToVertex(params);return path2=formatMap("tuningJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listTuningJobsResponseFromVertex(apiResponse),typedResp=new ListTuningJobsResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=cancelTuningJobParametersToVertex(params);return path2=formatMap("{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=cancelTuningJobResponseFromVertex(apiResponse),typedResp=new CancelTuningJobResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=cancelTuningJobParametersToMldev(params);return path2=formatMap("{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=cancelTuningJobResponseFromMldev(apiResponse),typedResp=new CancelTuningJobResponse;return Object.assign(typedResp,resp),typedResp})}}async tuneInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createTuningJobParametersPrivateToVertex(params,params);return path2=formatMap("tuningJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromVertex(apiResponse))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createTuningJobParametersPrivateToMldev(params);return path2=formatMap("tunedModels",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningOperationFromMldev(apiResponse))}}async validateReward(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=validateRewardParametersToVertex(params);return path2=formatMap("{parent}/tuningJobs:validateReinforcementTuningReward",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=validateRewardResponseFromVertex(apiResponse),typedResp=new ValidateRewardResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},MAX_CHUNK_SIZE=1024*1024*8,MAX_RETRY_COUNT=3,INITIAL_RETRY_DELAY_MS=1e3,DELAY_MULTIPLIER=2,X_GOOG_UPLOAD_STATUS_HEADER_FIELD="x-goog-upload-status";async function uploadBlob(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await uploadBlobInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return responseJson.file}async function uploadBlobToFileSearchStore(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await uploadBlobInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let resp=uploadToFileSearchStoreOperationFromMldev(responseJson),typedResp=new UploadToFileSearchStoreOperation;return Object.assign(typedResp,resp),typedResp}async function uploadBlobInternal(file,uploadUrl,apiClient,httpOptions){var _a2,_b,_c;let finalUrl=uploadUrl,effectiveBaseUrl=httpOptions?.baseUrl||((_a2=apiClient.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl);if(effectiveBaseUrl){let baseUri=new URL(effectiveBaseUrl),uploadUri=new URL(uploadUrl);uploadUri.protocol=baseUri.protocol,uploadUri.host=baseUri.host,uploadUri.port=baseUri.port,finalUrl=uploadUri.toString()}let fileSize=0,offset=0,response=new HttpResponse(new Response),uploadCommand="upload";for(fileSize=file.size;offset<fileSize;){let chunkSize=Math.min(MAX_CHUNK_SIZE,fileSize-offset),chunk=file.slice(offset,offset+chunkSize);offset+chunkSize>=fileSize&&(uploadCommand+=", finalize");let retryCount=0,currentDelayMs=INITIAL_RETRY_DELAY_MS;for(;retryCount<MAX_RETRY_COUNT;){let mergedHeaders=Object.assign(Object.assign({},httpOptions?.headers||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":String(offset)});if(response=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},httpOptions),{apiVersion:"",baseUrl:finalUrl,headers:mergedHeaders})}),!((_b=response?.headers)===null||_b===void 0)&&_b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])break;retryCount++,await sleep(currentDelayMs),currentDelayMs=currentDelayMs*DELAY_MULTIPLIER}if(offset+=chunkSize,((_c=response?.headers)===null||_c===void 0?void 0:_c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="active")break;if(fileSize<=offset)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return response}async function getBlobStat(file){return{size:file.size,type:file.type}}function sleep(ms){return new Promise(resolvePromise=>setTimeout(resolvePromise,ms))}var NodeUploader=class{async stat(file){let fileStat={size:0,type:void 0};if(typeof file=="string"){let originalStat=await fs.stat(file);return fileStat.size=originalStat.size,fileStat.type=this.inferMimeType(file),fileStat}else return await getBlobStat(file)}async upload(file,uploadUrl,apiClient,httpOptions){return typeof file=="string"?await this.uploadFileFromPath(file,uploadUrl,apiClient,httpOptions):uploadBlob(file,uploadUrl,apiClient,httpOptions)}async uploadToFileSearchStore(file,uploadUrl,apiClient,httpOptions){return typeof file=="string"?await this.uploadFileToFileSearchStoreFromPath(file,uploadUrl,apiClient,httpOptions):uploadBlobToFileSearchStore(file,uploadUrl,apiClient,httpOptions)}inferMimeType(filePath){let fileExtension=filePath.slice(filePath.lastIndexOf(".")+1);return{aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"}[fileExtension.toLowerCase()]}async uploadFileFromPath(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await this.uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return responseJson.file}async uploadFileToFileSearchStoreFromPath(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await this.uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let resp=uploadToFileSearchStoreOperationFromMldev(responseJson),typedResp=new UploadToFileSearchStoreOperation;return Object.assign(typedResp,resp),typedResp}async uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions){var _a2,_b,_c;let finalUrl=uploadUrl,effectiveBaseUrl=httpOptions?.baseUrl||((_a2=apiClient.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl);if(effectiveBaseUrl){let baseUri=new URL(effectiveBaseUrl),uploadUri=new URL(uploadUrl);uploadUri.protocol=baseUri.protocol,uploadUri.host=baseUri.host,uploadUri.port=baseUri.port,finalUrl=uploadUri.toString()}let fileSize=0,offset=0,response=new HttpResponse(new Response),uploadCommand="upload",fileHandle,fileName=path.basename(file);try{if(fileHandle=await fs.open(file,"r"),!fileHandle)throw new Error("Failed to open file");for(fileSize=(await fileHandle.stat()).size;offset<fileSize;){let chunkSize=Math.min(MAX_CHUNK_SIZE,fileSize-offset);offset+chunkSize>=fileSize&&(uploadCommand+=", finalize");let buffer=new Uint8Array(chunkSize),{bytesRead}=await fileHandle.read(buffer,0,chunkSize,offset);if(bytesRead!==chunkSize)throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`);let chunk=new Blob([buffer]),retryCount=0,currentDelayMs=INITIAL_RETRY_DELAY_MS;for(;retryCount<MAX_RETRY_COUNT;){let mergedHeaders=Object.assign(Object.assign({},httpOptions?.headers||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":String(offset),"X-Goog-Upload-File-Name":fileName});if(response=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},httpOptions),{apiVersion:"",baseUrl:finalUrl,headers:mergedHeaders})}),!((_b=response?.headers)===null||_b===void 0)&&_b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])break;retryCount++,await sleep(currentDelayMs),currentDelayMs=currentDelayMs*DELAY_MULTIPLIER}if(offset+=bytesRead,((_c=response?.headers)===null||_c===void 0?void 0:_c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="active")break;if(fileSize<=offset)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return response}finally{fileHandle&&await fileHandle.close()}}};var NodeFiles=class extends Files$1{async registerFiles(params){if(typeof process>"u"||!process.versions||!process.versions.node)throw new Error("registerFiles is only supported in Node.js environments.");let authHeaders=await params.auth.getRequestHeaders(),config=params.config||{},httpOptions=config.httpOptions||{},headers=Object.assign({},httpOptions.headers||{});if(authHeaders)if(typeof authHeaders[Symbol.iterator]=="function")for(let[key,value]of authHeaders)headers[key]=value;else for(let[key,value]of Object.entries(authHeaders))headers[key]=value;return this._registerFiles({uris:params.uris,config:Object.assign(Object.assign({},config),{httpOptions:Object.assign(Object.assign({},httpOptions),{headers})})})}};var LANGUAGE_LABEL_PREFIX="gl-node/";function resolveCloudFlag(options){var _a2;if(options&&(options.enterprise!==void 0||options.vertexai!==void 0)){if(options.enterprise!==void 0&&options.vertexai!==void 0&&options.enterprise!==options.vertexai)throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(_a2=options.enterprise)!==null&&_a2!==void 0?_a2:options.vertexai}let envEnterpriseStr=getEnv("GOOGLE_GENAI_USE_ENTERPRISE"),envVertexaiStr=getEnv("GOOGLE_GENAI_USE_VERTEXAI"),useEnterpriseEnv=stringToBoolean(envEnterpriseStr),useVertexaiEnv=stringToBoolean(envVertexaiStr);return envEnterpriseStr!==void 0&&envVertexaiStr!==void 0&&useEnterpriseEnv!==useVertexaiEnv&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),envEnterpriseStr!==void 0?useEnterpriseEnv:envVertexaiStr!==void 0?useVertexaiEnv:!1}var GoogleGenAI2=class{getNextGenClient(){let httpOpts=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=buildGoogleGenAIClient(this.apiClient,{timeout_ms:httpOpts?.timeout})),httpOpts?.extraBody&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(this._interactions=new GeminiNextGenInteractions(this.apiClient),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new GeminiNextGenWebhooks(this.apiClient),this._webhooks)}get agents(){return this._agents!==void 0?this._agents:(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new GeminiNextGenAgents(this.apiClient),this._agents)}get triggers(){return this._triggers!==void 0?this._triggers:(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new GeminiNextGenTriggers(this.apiClient),this._triggers)}get environments(){return this._environments!==void 0?this._environments:(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new GeminiNextGenEnvironments(this.apiClient),this._environments)}constructor(options={}){var _a2,_b,_c,_d;if(this.vertexai=resolveCloudFlag(options),(options.project||options.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let envApiKey=getApiKeyFromEnv(),envProject=getEnv("GOOGLE_CLOUD_PROJECT"),envLocation=getEnv("GOOGLE_CLOUD_LOCATION");this.apiKey=(_a2=options.apiKey)!==null&&_a2!==void 0?_a2:envApiKey,this.project=(_b=options.project)!==null&&_b!==void 0?_b:envProject,this.location=(_c=options.location)!==null&&_c!==void 0?_c:envLocation,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((_d=options.googleAuthOptions)===null||_d===void 0)&&_d.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!options.project&&!options.location&&(envProject||envLocation)&&options.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(options.project||options.location)&&!options.apiKey&&envApiKey?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!options.project&&!options.location&&!options.apiKey&&(envProject||envLocation)&&envApiKey&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),!this.location&&!this.apiKey&&(this.location="global"));let baseUrl=getBaseUrl(options.httpOptions,this.vertexai,getEnv("GOOGLE_VERTEX_BASE_URL"),getEnv("GOOGLE_GEMINI_BASE_URL"));baseUrl&&(options.httpOptions?options.httpOptions.baseUrl=baseUrl:options.httpOptions={baseUrl}),this.apiVersion=options.apiVersion,this.httpOptions=options.httpOptions;let auth=new NodeAuth({apiKey:this.apiKey,googleAuthOptions:options.googleAuthOptions});this.apiClient=new ApiClient({auth,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:LANGUAGE_LABEL_PREFIX+process.version,uploader:new NodeUploader,downloader:new NodeDownloader}),this.models=new Models(this.apiClient),this.live=new Live(this.apiClient,auth,new NodeWebSocketFactory),this.batches=new Batches(this.apiClient),this.chats=new Chats(this.models,this.apiClient),this.caches=new Caches(this.apiClient),this.files=new NodeFiles(this.apiClient),this.operations=new Operations(this.apiClient),this.authTokens=new Tokens(this.apiClient),this.tunings=new Tunings(this.apiClient),this.fileSearchStores=new FileSearchStores(this.apiClient)}};function getEnv(env2){var _a2,_b,_c;return(_c=(_b=(_a2=process==null?void 0:process.env)===null||_a2===void 0?void 0:_a2[env2])===null||_b===void 0?void 0:_b.trim())!==null&&_c!==void 0?_c:void 0}function stringToBoolean(str){return str===void 0?!1:str.toLowerCase()==="true"}function getApiKeyFromEnv(){let envGoogleApiKey=getEnv("GOOGLE_API_KEY"),envGeminiApiKey=getEnv("GEMINI_API_KEY");return envGoogleApiKey&&envGeminiApiKey&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),envGoogleApiKey||envGeminiApiKey||void 0}function resolveGoogleThinkingLevel(model,level){if(level==="off")return"high";let mapped=model.thinkingLevelMap?.[level],resolvedLevel=typeof mapped=="string"?mapped.toLowerCase():level;switch(resolvedLevel){case"minimal":case"low":case"medium":case"high":return resolvedLevel;default:throw new Error(`Unsupported Google thinking level mapping for ${model.provider}/${model.id}: ${level} -> ${String(mapped)}`)}}function isThinkingPart(part){return part.thought===!0}function retainThoughtSignature(existing,incoming){return typeof incoming=="string"&&incoming.length>0?incoming:existing}var base64SignaturePattern=/^[A-Za-z0-9+/]+={0,2}$/;function isValidThoughtSignature(signature){return!signature||signature.length%4!==0?!1:base64SignaturePattern.test(signature)}function resolveThoughtSignature(isSameProviderAndModel,signature){return isSameProviderAndModel&&isValidThoughtSignature(signature)?signature:void 0}function requiresToolCallId(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return modelId.startsWith("claude-")||modelId.startsWith("gpt-oss-")||geminiMajorVersion!==void 0&&geminiMajorVersion>=3}function getGeminiMajorVersion(modelId){let match2=modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(match2)return Number.parseInt(match2[1],10)}function supportsMultimodalFunctionResponse(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return geminiMajorVersion!==void 0?geminiMajorVersion>=3:!0}function convertMessages(model,context){let contents=[],normalizeToolCallId=id=>requiresToolCallId(model.id)?id.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):id,transformedMessages=transformMessages(context.messages,model,normalizeToolCallId);for(let msg of transformedMessages)if(msg.role==="user")if(typeof msg.content=="string")contents.push({role:"user",parts:[{text:sanitizeSurrogates(msg.content)}]});else{let parts=msg.content.map(item=>item.type==="text"?{text:sanitizeSurrogates(item.text)}:{inlineData:{mimeType:item.mimeType,data:item.data}});if(parts.length===0)continue;contents.push({role:"user",parts})}else if(msg.role==="assistant"){let parts=[],isSameProviderAndModel=msg.provider===model.provider&&msg.model===model.id;for(let block of msg.content)if(block.type==="text"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.textSignature);if((!block.text||block.text.trim()==="")&&!thoughtSignature)continue;parts.push({text:sanitizeSurrogates(block.text),...thoughtSignature&&{thoughtSignature}})}else if(block.type==="thinking")if(isSameProviderAndModel){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thinkingSignature);if((!block.thinking||block.thinking.trim()==="")&&!thoughtSignature)continue;parts.push({thought:!0,text:sanitizeSurrogates(block.thinking),...thoughtSignature&&{thoughtSignature}})}else{if(!block.thinking||block.thinking.trim()==="")continue;parts.push({text:sanitizeSurrogates(block.thinking)})}else if(block.type==="toolCall"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thoughtSignature),part={functionCall:{name:block.name,args:block.arguments??{},...requiresToolCallId(model.id)?{id:block.id}:{}},...thoughtSignature&&{thoughtSignature}};parts.push(part)}if(parts.length===0)continue;contents.push({role:"model",parts})}else if(msg.role==="toolResult"){let textResult=msg.content.filter(c=>c.type==="text").map(c=>c.text).join(`
44
- `),imageContent=model.input.includes("image")?msg.content.filter(c=>c.type==="image"):[],hasText=textResult.length>0,hasImages=imageContent.length>0,modelSupportsMultimodalFunctionResponse=supportsMultimodalFunctionResponse(model.id),responseValue=hasText?sanitizeSurrogates(textResult):hasImages?"(see attached image)":"",imageParts=imageContent.map(imageBlock=>({inlineData:{mimeType:imageBlock.mimeType,data:imageBlock.data}})),includeId=requiresToolCallId(model.id),functionResponsePart={functionResponse:{name:msg.toolName,response:msg.isError?{error:responseValue}:{output:responseValue},...hasImages&&modelSupportsMultimodalFunctionResponse&&{parts:imageParts},...includeId?{id:msg.toolCallId}:{}}},lastContent=contents[contents.length-1];lastContent?.role==="user"&&lastContent.parts?.some(p=>p.functionResponse)?lastContent.parts.push(functionResponsePart):contents.push({role:"user",parts:[functionResponsePart]}),hasImages&&!modelSupportsMultimodalFunctionResponse&&contents.push({role:"user",parts:[{text:"Tool result image:"},...imageParts]})}return contents}var JSON_SCHEMA_META_DECLARATIONS=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function sanitizeForOpenApi(schema){if(typeof schema!="object"||schema===null||Array.isArray(schema))return schema;let result={};for(let[key,value]of Object.entries(schema))JSON_SCHEMA_META_DECLARATIONS.has(key)||(result[key]=sanitizeForOpenApi(value));return result}function convertTools(tools,useParameters=!1,supportsStrictMode=!0){if(tools.length!==0)return[{functionDeclarations:tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode),parameters=getJsonSchemaToolParameters(tool,strict);return{name:tool.name,description:tool.description,...useParameters?{parameters:sanitizeForOpenApi(parameters)}:{parametersJsonSchema:parameters}}})}]}function supportsGoogleStrictToolSampling(modelId){let majorVersion=getGeminiMajorVersion(modelId);return majorVersion!==void 0&&majorVersion>=3}function mapToolChoice(choice){switch(choice){case"auto":return FunctionCallingConfigMode.AUTO;case"none":return FunctionCallingConfigMode.NONE;case"any":return FunctionCallingConfigMode.ANY;default:return FunctionCallingConfigMode.AUTO}}function resolveGoogleFunctionCallingMode(tools,toolChoice,supportsStrictMode){let useStrictMode=tools.some(tool=>resolveJsonSchemaStrictSampling(tool,supportsStrictMode)===!0);return toolChoice==="none"||toolChoice==="any"?mapToolChoice(toolChoice):useStrictMode?FunctionCallingConfigMode.VALIDATED:toolChoice?mapToolChoice(toolChoice):void 0}function mapStopReason(reason){switch(reason){case FinishReason.STOP:return"stop";case FinishReason.MAX_TOKENS:return"length";case FinishReason.BLOCKLIST:case FinishReason.PROHIBITED_CONTENT:case FinishReason.SPII:case FinishReason.SAFETY:case FinishReason.IMAGE_SAFETY:case FinishReason.IMAGE_PROHIBITED_CONTENT:case FinishReason.IMAGE_RECITATION:case FinishReason.IMAGE_OTHER:case FinishReason.RECITATION:case FinishReason.FINISH_REASON_UNSPECIFIED:case FinishReason.OTHER:case FinishReason.LANGUAGE:case FinishReason.MALFORMED_FUNCTION_CALL:case FinishReason.UNEXPECTED_TOOL_CALL:case FinishReason.TOO_MANY_TOOL_CALLS:case FinishReason.NO_IMAGE:return"error";default:{let _exhaustive=reason;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}function retryGoogleRequest(request,options){return retryProviderRequest(async()=>{try{return await request()}catch(error){throw error instanceof Error&&"status"in error&&!("headers"in error)&&(error.headers=void 0),error}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal})}export{ThinkingLevel,ResourceScope,GoogleGenAI2 as GoogleGenAI,resolveGoogleThinkingLevel,isThinkingPart,retainThoughtSignature,convertMessages,convertTools,supportsGoogleStrictToolSampling,resolveGoogleFunctionCallingMode,mapStopReason,retryGoogleRequest};
43
+ `);else if(dataRequired)return;return parse(ret)}}var DEFAULT_CONTENT_TYPES={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function jsonErr(codes,errorClass,options){return Object.assign(Object.assign({},options),{err:!0,enc:"json",codes,errorClass})}function json(codes,options){return Object.assign(Object.assign({},options),{enc:"json",codes})}function sse(codes,sse2,options){return Object.assign(Object.assign(Object.assign({},options),{enc:"sse",codes}),sse2?{sse:sse2}:{})}function nil(codes,options){return Object.assign(Object.assign({},options),{enc:"nil",codes})}function fail(codes){return{enc:"fail",codes}}function match(...matchers){return async function(response,request,options){let raw,matcher;for(let match2 of matchers){let{codes}=match2,ctpattern="ctype"in match2?match2.ctype:DEFAULT_CONTENT_TYPES[match2.enc];if(ctpattern&&matchResponse(response,codes,ctpattern)){matcher=match2;break}else if(!ctpattern&&matchStatusCode(response,codes)){matcher=match2;break}}if(!matcher)return[{ok:!1,error:new GoogleGenAiDefaultError("Unexpected Status or Content-Type",{response,request,body:await response.text().catch(()=>"")})},raw];let encoding=matcher.enc,body="";switch(encoding){case"json":body=await response.text();try{raw=JSON.parse(body)}catch(err){if(!("err"in matcher))throw err;raw=body}break;case"jsonl":raw=response.body;break;case"bytes":raw=new Uint8Array(await response.arrayBuffer());break;case"stream":raw=response.body;break;case"text":body=await response.text(),raw=body;break;case"sse":if(response.body){let sseOpts="sse"in matcher&&matcher.sse||{};raw=wrapEventStreamResponse(response.body,sseOpts)}else raw=null;break;case"nil":body=await response.text(),raw=void 0;break;case"fail":body=await response.text(),raw=body;break;default:throw new Error(`Unsupported response type: ${encoding}`)}if(matcher.enc==="fail")return[{ok:!1,error:new GoogleGenAiDefaultError("API error occurred",{request,response,body})},raw];let resultKey=matcher.key||options?.resultKey,data,headersField=matcher.hdrs?{headers:unpackHeaders(response.headers)}:null;return"err"in matcher?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),isPlainObject$1(raw)?raw:null):resultKey?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),{[resultKey]:raw}):matcher.hdrs?data=Object.assign(Object.assign(Object.assign({},options?.extraFields),headersField),isPlainObject$1(raw)?raw:null):data=raw,"err"in matcher?[{ok:!1,error:matcher.errorClass?new matcher.errorClass(data,{request,response,body}):data},raw]:[{ok:!0,value:data},raw]}}var headerValRE=/, */;function unpackHeaders(headers){let out={};for(let[k,v]of headers.entries())out[k]=v.split(headerValRE);return out}var SecurityErrorCode={Incomplete:"incomplete",UnrecognisedSecurityType:"unrecognized_security_type"},SecurityError=class _SecurityError extends Error{constructor(code,message){super(message),this.code=code,this.name="SecurityError"}static incomplete(){return new _SecurityError(SecurityErrorCode.Incomplete,"Security requirements not met in order to perform the operation")}static unrecognizedType(type){return new _SecurityError(SecurityErrorCode.UnrecognisedSecurityType,`Unrecognised security type: ${type}`)}};function resolveSecurity(...options){let state={basic:{},headers:{},queryParams:{},cookies:{},oauth2:{type:"none"}},option=options.find(opts=>opts.every(o=>{if(o.value==null)return!1;if(o.type==="http:basic")return o.value.username!=null||o.value.password!=null;if(o.type==="http:custom")return null;if(o.type==="oauth2:password")return typeof o.value=="string"&&!!o.value;if(o.type==="oauth2:client_credentials")return typeof o.value=="string"?!!o.value:o.value.client_id!=null||o.value.client_secret!=null;if(typeof o.value=="string")return!!o.value;throw new Error(`Unrecognized security type: ${o.type} (value type: ${typeof o.value})`)}));return option==null?null:(option.forEach(spec=>{if(spec.value==null)return;let{type}=spec;switch(type){case"apiKey:header":state.headers[spec.fieldName]=spec.value;break;case"apiKey:query":state.queryParams[spec.fieldName]=spec.value;break;case"apiKey:cookie":state.cookies[spec.fieldName]=spec.value;break;case"http:basic":applyBasic(state,spec);break;case"http:custom":break;case"http:bearer":applyBearer(state,spec);break;case"oauth2":applyBearer(state,spec);break;case"oauth2:password":applyBearer(state,spec);break;case"oauth2:client_credentials":break;case"openIdConnect":applyBearer(state,spec);break;default:throw SecurityError.unrecognizedType(type)}}),state)}function applyBasic(state,spec){spec.value!=null&&(state.basic=spec.value)}function applyBearer(state,spec){if(typeof spec.value!="string"||!spec.value)return;let value=spec.value;value.slice(0,7).toLowerCase()!=="bearer "&&(value=`Bearer ${value}`),spec.fieldName!==void 0&&(state.headers[spec.fieldName]=value)}function resolveGlobalSecurity(security,allowedFields){var _a2,_b;let inputs=[[{fieldName:"accessToken",type:"http:custom",value:(_a2=security?.access_token)!==null&&_a2!==void 0?_a2:env().GOOGLE_GENAI_ACCESS_TOKEN},{fieldName:"apiKey",type:"http:custom",value:(_b=security?.api_key)!==null&&_b!==void 0?_b:env().GOOGLE_GENAI_API_KEY},{fieldName:"defaultHeaders",type:"http:custom",value:security?.default_headers}]];return resolveSecurity(...inputs)}async function extractSecurity(sec){if(sec!=null)return typeof sec=="function"?sec():sec}var _a,APIPromise=class _APIPromise{constructor(p,callSource){this[_a]="APIPromise",this._promise=p instanceof Promise?p:Promise.resolve(p),this._unwrapped=p instanceof Promise?null:Promise.resolve(p[0]),this._callSource=callSource??null}_getUnwrapped(){var _b;return(_b=this._unwrapped)!==null&&_b!==void 0?_b:this._unwrapped=this._promise.then(([value])=>value)}then(onfulfilled,onrejected){return this._promise.then(onfulfilled?([value])=>onfulfilled(value):void 0,onrejected)}catch(onrejected){return this._getUnwrapped().catch(onrejected)}finally(onfinally){return this._getUnwrapped().finally(onfinally)}$inspect(){return this._promise}asResponse(){var _b;return((_b=this._callSource)!==null&&_b!==void 0?_b:this._callSource=this._promise.then(([,call])=>call)).then(call=>{if(!call.response)throw new Error("APIPromise.asResponse: response unavailable");return call.response})}async withResponse(){let[[data],response]=await Promise.all([this._promise,this.asResponse()]);return{data,response}}_thenUnwrap(transform){var _b;let data=this._promise.then(([value,call])=>[transform(value),call]);return data.catch(()=>{}),new _APIPromise(data,(_b=this._callSource)!==null&&_b!==void 0?_b:void 0)}};_a=Symbol.toStringTag;function unwrapAsAPIPromise(p){let inner=p.$inspect(),data=inner.then(([r,call])=>{if(!r.ok)throw r.error;return[r.value,call]}),callSource=inner.then(([r,call])=>{var _b;if(!r.ok&&!(!((_b=call.response)===null||_b===void 0)&&_b.ok))throw r.error;return call});return data.catch(()=>{}),callSource.catch(()=>{}),new APIPromise(data,callSource)}function agentsCreate(client,body,api_version,options){return new APIPromise($do$q(client,body,api_version,options))}async function $do$q(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsDelete(client,id,api_version,options){return new APIPromise($do$p(client,id,api_version,options))}async function $do$p(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsGet(client,id,api_version,options){return new APIPromise($do$o(client,id,api_version,options))}async function $do$o(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetAgent",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function agentsList(client,api_version,page_size,page_token,parent,options){return new APIPromise($do$n(client,api_version,page_size,page_token,parent,options))}async function $do$n(client,api_version,page_size,page_token,parent,options){var _a2,_b,_c;let payload={api_version,page_size,page_token,parent},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/agents")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token,parent:payload?.parent}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListAgents",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Agents=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(agentsList(this,params?.api_version,params?.page_size,params?.page_token,params?.parent,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(agentsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(agentsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(agentsGet(this,id,params?.api_version,options))}};function environmentsCreateEnvironment(client,body,api_version,options){return new APIPromise($do$m(client,body,api_version,options))}async function $do$m(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsDeleteEnvironment(client,id,api_version,options){return new APIPromise($do$l(client,id,api_version,options))}async function $do$l(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsGetEnvironment(client,id,api_version,options){return new APIPromise($do$k(client,id,api_version,options))}async function $do$k(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetEnvironment",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsListEnvironments(client,api_version,page_size,page_token,options){return new APIPromise($do$j(client,api_version,page_size,page_token,options))}async function $do$j(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/environments")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListEnvironments",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function environmentsFilesList(client,environment,path2,api_version,page_size,page_token,recursive,options){return new APIPromise($do$i(client,environment,path2,api_version,page_size,page_token,recursive,options))}async function $do$i(client,environment,path2,api_version,page_size,page_token,recursive,options){var _a2,_b,_c;let payload={environment,path:path2,api_version,page_size,page_token,recursive},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),environment:encodeSimple("environment",payload.environment,{explode:!1,charEncoding:"percent"}),path:encodeSimple("path",payload.path,{explode:!1,charEncoding:"percent"})},path$=pathToFunc("/{api_version}/environments/{environment}/files/{path}")(pathParams),query=encodeFormQuery({page_size:payload.page_size,page_token:payload.page_token,recursive:payload.recursive}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetEnvironmentFiles",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path$,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Files2=class extends ClientSDK{list(environment,path2,params,options){return unwrapAsAPIPromise(environmentsFilesList(this,environment,path2,params?.api_version,params?.page_size,params?.page_token,params?.recursive,options))}};var Environments=class extends ClientSDK{get files(){var _a2;return(_a2=this._files)!==null&&_a2!==void 0?_a2:this._files=new Files2(this._options)}listEnvironments(params,options){return unwrapAsAPIPromise(environmentsListEnvironments(this,params?.api_version,params?.page_size,params?.page_token,options))}createEnvironment(body,api_version,options){return unwrapAsAPIPromise(environmentsCreateEnvironment(this,body,api_version,options))}deleteEnvironment(id,params,options){return unwrapAsAPIPromise(environmentsDeleteEnvironment(this,id,params?.api_version,options))}getEnvironment(id,params,options){return unwrapAsAPIPromise(environmentsGetEnvironment(this,id,params?.api_version,options))}};var CancelInteractionByIdServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CancelInteractionByIdServerError"}},CancelInteractionByIdClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CancelInteractionByIdClientError"}};var CreateInteractionServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CreateInteractionServerError"}},CreateInteractionClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="CreateInteractionClientError"}};var DeleteInteractionServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="DeleteInteractionServerError"}},DeleteInteractionClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="DeleteInteractionClientError"}};var GetInteractionByIdServerError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="GetInteractionByIdServerError"}},GetInteractionByIdClientError=class extends GoogleGenAiError{constructor(err,httpMeta){var _a2;let message=((_a2=err.error)===null||_a2===void 0?void 0:_a2.message)||`API error occurred: ${JSON.stringify(err)}`;super(message,httpMeta),this.data$=err,this.error=err.error,this.name="GetInteractionByIdClientError"}};function interactionsCancel(client,id,api_version,options){return new APIPromise($do$h(client,id,api_version,options))}async function $do$h(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}/cancel")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"cancelInteractionById",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),jsonErr("4XX",CancelInteractionByIdClientError),jsonErr("5XX",CancelInteractionByIdServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsCreate(client,body,api_version,options){return new APIPromise($do$g(client,body,api_version,options))}async function $do$g(client,body,api_version,options){var _a2,_b,_c,_d;let input={body,api_version},payload=input,body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:!((_b=input?.body)===null||_b===void 0)&&_b.stream?"text/event-stream":"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_d=(_c=options?.server_url)!==null&&_c!==void 0?_c:client._baseURL)!==null&&_d!==void 0?_d:"",operation_id:"CreateInteraction",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),sse(200,{sentinel:"[DONE]",flattened:!0}),jsonErr("4XX",CreateInteractionClientError),jsonErr("5XX",CreateInteractionServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsDelete(client,id,api_version,options){return new APIPromise($do$f(client,id,api_version,options))}async function $do$f(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"deleteInteraction",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(nil(200),jsonErr("4XX",DeleteInteractionClientError),jsonErr("5XX",DeleteInteractionServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function interactionsGet(client,id,api_version,include_input,last_event_id,stream,options){return new APIPromise($do$e(client,id,api_version,include_input,last_event_id,stream,options))}async function $do$e(client,id,api_version,include_input,last_event_id,stream,options){var _a2,_b,_c;let input={id,api_version,include_input,last_event_id,stream},payload=input,body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/interactions/{id}")(pathParams),query=encodeFormQuery({include_input:payload.include_input,last_event_id:payload.last_event_id,stream:payload.stream}),headers=new Headers(compactMap({Accept:input?.stream?"text/event-stream":"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"getInteractionById",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,responseFields={httpMeta:{response,request:req}},[result]=await match(json(200),sse(200,{sentinel:"[DONE]",flattened:!0}),jsonErr("4XX",GetInteractionByIdClientError),jsonErr("5XX",GetInteractionByIdServerError))(response,req,{extraFields:responseFields});return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Interactions=class extends ClientSDK{create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(interactionsCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(interactionsDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(interactionsGet(this,id,params?.api_version,params?.include_input,params?.last_event_id,params?.stream,options))}cancel(id,params,options){return unwrapAsAPIPromise(interactionsCancel(this,id,params?.api_version,options))}};function triggersCreate(client,body,api_version,options){return new APIPromise($do$d(client,body,api_version,options))}async function $do$d(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersDelete(client,id,api_version,options){return new APIPromise($do$c(client,id,api_version,options))}async function $do$c(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersGet(client,id,api_version,options){return new APIPromise($do$b(client,id,api_version,options))}async function $do$b(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersListExecutions(client,trigger_id,api_version,page_size,page_token,options){return new APIPromise($do$a(client,trigger_id,api_version,page_size,page_token,options))}async function $do$a(client,trigger_id,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={trigger_id,api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:encodeSimple("trigger_id",payload.trigger_id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams),query=encodeFormQuery({page_size:payload.page_size,page_token:payload.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListTriggerExecutions",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersList(client,api_version,filter,page_size,page_token,options){return new APIPromise($do$9(client,api_version,filter,page_size,page_token,options))}async function $do$9(client,api_version,filter,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,filter,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers")(pathParams),query=encodeFormQuery({filter:payload?.filter,page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListTriggers",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersRun(client,trigger_id,api_version,options){return new APIPromise($do$8(client,trigger_id,api_version,options))}async function $do$8(client,trigger_id,api_version,options){var _a2,_b,_c;let payload={trigger_id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),trigger_id:encodeSimple("trigger_id",payload.trigger_id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{trigger_id}/executions")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RunTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function triggersUpdate(client,id,body,api_version,options){return new APIPromise($do$7(client,id,body,api_version,options))}async function $do$7(client,id,body,api_version,options){var _a2,_b,_c;let payload={id,body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/triggers/{id}")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateTrigger",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(json(200),fail("4XX"),fail("5XX"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Triggers=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(triggersList(this,params?.api_version,params?.filter,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(triggersCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(triggersDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(triggersGet(this,id,params?.api_version,options))}update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(triggersUpdate(this,id,body,api_version,options))}listExecutions(trigger_id,params,options){return unwrapAsAPIPromise(triggersListExecutions(this,trigger_id,params?.api_version,params?.page_size,params?.page_token,options))}run(trigger_id,params,options){return unwrapAsAPIPromise(triggersRun(this,trigger_id,params?.api_version,options))}};function webhooksCreate(client,body,api_version,options){return new APIPromise($do$6(client,body,api_version,options))}async function $do$6(client,body,api_version,options){var _a2,_b,_c;let payload={body,api_version},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"CreateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksDelete(client,id,api_version,options){return new APIPromise($do$5(client,id,api_version,options))}async function $do$5(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"DeleteWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"DELETE",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksGet(client,id,api_version,options){return new APIPromise($do$4(client,id,api_version,options))}async function $do$4(client,id,api_version,options){var _a2,_b,_c;let payload={id,api_version},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"GetWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksList(client,api_version,page_size,page_token,options){return new APIPromise($do$3(client,api_version,page_size,page_token,options))}async function $do$3(client,api_version,page_size,page_token,options){var _a2,_b,_c;let payload={api_version,page_size,page_token},body=null,pathParams={api_version:encodeSimple("api_version",(_a2=payload?.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks")(pathParams),query=encodeFormQuery({page_size:payload?.page_size,page_token:payload?.page_token}),headers=new Headers(compactMap({Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"ListWebhooks",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"GET",baseURL:options?.server_url,path:path2,headers,query,body,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksPing(client,id,api_version,body,options){return new APIPromise($do$2(client,id,api_version,body,options))}async function $do$2(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:ping")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"PingWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksRotateSigningSecret(client,id,api_version,body,options){return new APIPromise($do$1(client,id,api_version,body,options))}async function $do$1(client,id,api_version,body,options){var _a2,_b,_c;let payload={id,api_version,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}:rotateSigningSecret")(pathParams),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"RotateSigningSecret",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"POST",baseURL:options?.server_url,path:path2,headers,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}function webhooksUpdate(client,id,api_version,update_mask,body,options){return new APIPromise($do(client,id,api_version,update_mask,body,options))}async function $do(client,id,api_version,update_mask,body,options){var _a2,_b,_c;let payload={id,api_version,update_mask,body},body$=encodeJSON("body",payload.body,{explode:!0}),pathParams={api_version:encodeSimple("api_version",(_a2=payload.api_version)!==null&&_a2!==void 0?_a2:client._options.api_version,{explode:!1,charEncoding:"percent"}),id:encodeSimple("id",payload.id,{explode:!1,charEncoding:"percent"})},path2=pathToFunc("/{api_version}/webhooks/{id}")(pathParams),query=encodeFormQuery({update_mask:payload.update_mask}),headers=new Headers(compactMap({"Content-Type":"application/json",Accept:"application/json"})),securityInput=await extractSecurity(client._options.security),requestSecurity=resolveGlobalSecurity(securityInput),context={options:client._options,base_url:(_c=(_b=options?.server_url)!==null&&_b!==void 0?_b:client._baseURL)!==null&&_c!==void 0?_c:"",operation_id:"UpdateWebhook",o_auth2_scopes:null,resolved_security:requestSecurity,security_source:client._options.security,retry_config:options?.retries||client._options.retry_config||{strategy:"attempt-count-backoff",backoff:{initialInterval:500,maxInterval:8e3,exponent:2,maxElapsedTime:3e4},retryConnectionErrors:!0,maxRetries:4},retry_codes:options?.retry_codes||["408","409","429","5XX"]},requestRes=client._createRequest(context,{security:requestSecurity,method:"PATCH",baseURL:options?.server_url,path:path2,headers,query,body:body$,userAgent:client._options.user_agent,timeout_ms:options?.timeout_ms||client._options.timeout_ms||-1},options);if(!requestRes.ok)return[requestRes,{status:"invalid"}];let req=requestRes.value,doResult=await client._do(req,{context,isErrorStatusCode:statusCode=>matchStatusCode({status:statusCode},["4XX","5XX"]),retryConfig:context.retry_config,retryCodes:context.retry_codes});if(!doResult.ok)return[doResult,{status:"request-error",request:req}];let response=doResult.value,[result]=await match(fail("4XX"),fail("5XX"),json("default"))(response,req);return result.ok?[result,{status:"complete",request:req,response}]:[result,{status:"complete",request:req,response}]}var Webhooks=class extends ClientSDK{list(params,options){return unwrapAsAPIPromise(webhooksList(this,params?.api_version,params?.page_size,params?.page_token,options))}create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapAsAPIPromise(webhooksCreate(this,body,api_version,options))}delete(id,params,options){return unwrapAsAPIPromise(webhooksDelete(this,id,params?.api_version,options))}get(id,params,options){return unwrapAsAPIPromise(webhooksGet(this,id,params?.api_version,options))}update(id,params,options){let _a2=params??{},{api_version,update_mask}=_a2,body$body=__rest(_a2,["api_version","update_mask"]),body=params===void 0||Object.keys(body$body).length===0?void 0:body$body;return unwrapAsAPIPromise(webhooksUpdate(this,id,api_version,update_mask,body,options))}ping(id,api_version,body,options){return unwrapAsAPIPromise(webhooksPing(this,id,api_version,body,options))}rotateSigningSecret(id,api_version,body,options){return unwrapAsAPIPromise(webhooksRotateSigningSecret(this,id,api_version,body,options))}};var GoogleGenAI$1=class extends ClientSDK{get agents(){var _a2;return(_a2=this._agents)!==null&&_a2!==void 0?_a2:this._agents=new Agents(this._options)}get environments(){var _a2;return(_a2=this._environments)!==null&&_a2!==void 0?_a2:this._environments=new Environments(this._options)}get interactions(){var _a2;return(_a2=this._interactions)!==null&&_a2!==void 0?_a2:this._interactions=new Interactions(this._options)}get triggers(){var _a2;return(_a2=this._triggers)!==null&&_a2!==void 0?_a2:this._triggers=new Triggers(this._options)}get webhooks(){var _a2;return(_a2=this._webhooks)!==null&&_a2!==void 0?_a2:this._webhooks=new Webhooks(this._options)}};var LEGACY_LYRIA_MODELS=new Set(["lyria-3-pro-preview","lyria-3-clip-preview"]);function getGoogleGenAIServerURL(parentClient){let serverURL=parentClient.getBaseUrl();if(!serverURL)throw new Error("Base URL must be set.");return serverURL.replace(/\/+$/,"")}function getGoogleGenAIAPIVersion(parentClient){let apiVersion=trimSlashes(parentClient.getApiVersion()),project=parentClient.getProject(),location=parentClient.getLocation();return parentClient.isVertexAI()&&apiVersion&&project&&location?`${apiVersion}/projects/${encodeURIComponent(project)}/locations/${encodeURIComponent(location)}`:apiVersion}function buildGoogleGenAIClient(parentClient,options={}){var _a2,_b,_c,_d,_e;return new GoogleGenAI$1(Object.assign(Object.assign({},options),{api_version:(_a2=options.api_version)!==null&&_a2!==void 0?_a2:getGoogleGenAIAPIVersion(parentClient),security:(_b=options.security)!==null&&_b!==void 0?_b:new GoogleGenAISecurityProvider({defaultHeaders:Object.assign(Object.assign({},(_c=parentClient.getDefaultHeaders)===null||_c===void 0?void 0:_c.call(parentClient)),(_d=parentClient.getHeaders)===null||_d===void 0?void 0:_d.call(parentClient)),getAuthHeaders:url=>parentClient.getAuthHeaders(url)}),server_url:(_e=options.server_url)!==null&&_e!==void 0?_e:getGoogleGenAIServerURL(parentClient)}))}var GeminiNextGenInteractions=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,request=__rest(params,["api_version"]);if(request.stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.create(Object.assign(Object.assign({},request),{stream:!0,api_version}),toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsCreate(this.getClient(api_version),request,api_version,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async get(id,params={},options){let{api_version,stream=!1,last_event_id,include_input}=params??{};if(stream===!0){let response2=await wrapSDKCall(()=>this.getClient(api_version).interactions.get(id,{stream,last_event_id,include_input,api_version},toGoogleGenAIRequestOptions(options,!0)));return wrapStreamErrors(response2)}let response=await unwrapWithSdkHttpResponse(interactionsGet(this.getClient(api_version),id,api_version,include_input,last_event_id,stream,toGoogleGenAIRequestOptions(options)));return addOutputPropertiesIfInteraction(response)}async delete(id,params={},options){return wrapSDKCall(()=>this.getClient(params?.api_version).interactions.delete(id,{api_version:params?.api_version},toGoogleGenAIRequestOptions(options)))}async cancel(id,params={},options){return addOutputPropertiesIfInteraction(await unwrapWithSdkHttpResponse(interactionsCancel(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options))))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenAgents=class{constructor(parentClient){this.parentClient=parentClient}async create(params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(agentsCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,pageSize,pageToken,parent}=params??{};return unwrapWithSdkHttpResponse(agentsList(this.getClient(api_version),api_version,pageSize,pageToken,parent,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(agentsGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(agentsDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}},GeminiNextGenWebhooks=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(webhooksCreate(this.getClient(),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(webhooksList(this.getClient(),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(webhooksGet(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params={},options){let _a2=params??{},{api_version,update_mask}=_a2,body=__rest(_a2,["api_version","update_mask"]);return unwrapWithSdkHttpResponse(webhooksUpdate(this.getClient(),id,api_version,update_mask,body,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(webhooksDelete(this.getClient(),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async rotateSigningSecret(id,params={},options){let _a2=params??{},{api_version}=_a2,body=__rest(_a2,["api_version"]);return unwrapWithSdkHttpResponse(webhooksRotateSigningSecret(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}async ping(id,params=void 0,options){let{api_version,body}=params??{};return unwrapWithSdkHttpResponse(webhooksPing(this.getClient(),id,api_version,body,toGoogleGenAIRequestOptions(options)))}getClient(){var _a2;return(_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk}},GeminiNextGenTriggers=class{constructor(parentClient){this.parentClient=parentClient}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersCreate(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,filter,pageSize,pageToken}=params??{};return unwrapWithSdkHttpResponse(triggersList(this.getClient(api_version),api_version,filter,pageSize,pageToken,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(triggersGet(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async update(id,params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(triggersUpdate(this.getClient(api_version),id,body,api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(triggersDelete(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async run(trigger_id,params={},options){return unwrapWithSdkHttpResponse(triggersRun(this.getClient(params?.api_version),trigger_id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async listExecutions(trigger_id,params={},options){let{api_version,pageSize,pageToken}=params??{};return unwrapWithSdkHttpResponse(triggersListExecutions(this.getClient(api_version),trigger_id,api_version,pageSize,pageToken,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};function trimSlashes(value){return value.replace(/^\/+|\/+$/g,"")}function toGoogleGenAIRequestOptions(options,streaming=!1){var _a2,_b,_c,_d;if(!options&&!streaming)return;let _e=options??{},{timeout,maxRetries,defaultBaseURL,query,body,fetchOptions}=_e,rest=__rest(_e,["timeout","maxRetries","defaultBaseURL","query","body","fetchOptions"]),nextOptions=Object.assign({},rest);isPlainObject(query)?nextOptions.extra_query=query:warnIgnoredOption("query",query),isPlainObject(body)?nextOptions.extra_body=body:warnIgnoredOption("body",body);let fetch_options=(_a2=rest.fetch_options)!==null&&_a2!==void 0?_a2:fetchOptions;fetch_options&&(nextOptions.fetch_options=fetch_options);let server_url=(_b=rest.server_url)!==null&&_b!==void 0?_b:defaultBaseURL;server_url&&(nextOptions.server_url=server_url);let timeout_ms=(_c=rest.timeout_ms)!==null&&_c!==void 0?_c:timeout;if(timeout_ms!==void 0&&(nextOptions.timeout_ms=timeout_ms),maxRetries!==void 0&&(nextOptions.retries={strategy:"attempt-count-backoff",retryConnectionErrors:!0,maxRetries}),streaming){let headers=new Headers((_d=nextOptions.headers)!==null&&_d!==void 0?_d:fetch_options?.headers);headers.set("Accept","text/event-stream"),nextOptions.headers=headers}return nextOptions}function warnIgnoredOption(name,value){value!=null&&console.warn(`GoogleGenAI.interactions: request option ${name} is not supported by the Google GenAI interactions bridge and will be ignored.`)}async function unwrapWithSdkHttpResponse(promise){let[result,call]=await promise.$inspect();if(!result.ok)throw wrapSDKError(result.error);return attachSdkHttpResponse(result.value,call)}async function wrapSDKCall(operation){try{return await operation()}catch(error){throw wrapSDKError(error)}}function wrapStreamErrors(stream){let asyncIterable=stream;return new Proxy(stream,{get(target,property){if(property!==Symbol.asyncIterator){let value=Reflect.get(target,property,target);return typeof value=="function"?value.bind(target):value}return function(){let iterator=asyncIterable[Symbol.asyncIterator]();return{async next(...args){try{return await iterator.next(...args)}catch(error){throw wrapSDKError(error)}},async return(value){if(!iterator.return)return{done:!0,value};try{return await iterator.return(value)}catch(error){throw wrapSDKError(error)}},async throw(error){if(!iterator.throw)throw wrapSDKError(error);try{return await iterator.throw(error)}catch(caught){throw wrapSDKError(caught)}},[Symbol.asyncIterator](){return this}}}}})}function attachSdkHttpResponse(value,call){return!isPlainObject(value)||call.status!=="complete"?value:Object.assign(Object.assign({},value),{sdkHttpResponse:createSdkHttpResponse(call.response,value)})}function createSdkHttpResponse(response,parsedBody){let headers={};for(let[key,value]of response.headers.entries())headers[key]=value;return{headers,responseInternal:response,json:async()=>parsedBody}}function addOutputPropertiesIfInteraction(value){let interaction=normalizeInteractionShape(value);return interaction?addOutputProperties(interaction):value}function normalizeInteractionShape(value){if(isPlainObject(value)){if(Array.isArray(value.steps))return value;if(isLegacyLyriaInteraction(value)){let outputs=value.outputs;if(Array.isArray(outputs)){let{outputs:_outputs}=value,rest=__rest(value,["outputs"]);return Object.assign(Object.assign({},rest),{steps:[{type:"model_output",content:outputs}]})}}return Object.assign(Object.assign({},value),{steps:[]})}}function isLegacyLyriaInteraction(value){let model=value.model;return typeof model=="string"&&LEGACY_LYRIA_MODELS.has(model)}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function addOutputProperties(interaction){var _a2,_b;let normalized=normalizeInteractionDates(interaction),steps=(_a2=normalized.steps)!==null&&_a2!==void 0?_a2:[],textParts=[],collecting=!1;outer:for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type!=="model_output"||!step.content){if(collecting)break;continue}let content=step.content;for(let j=content.length-1;j>=0;j--){let item=content[j];if(item.type==="text")collecting=!0,textParts.push((_b=item.text)!==null&&_b!==void 0?_b:"");else if(collecting)break outer}}let output_image,output_audio,output_video;for(let i=steps.length-1;i>=0;i--){let step=steps[i];if(step.type==="user_input")break;if(step.type==="model_output"&&step.content)for(let j=step.content.length-1;j>=0;j--){let content=step.content[j];content.type==="image"&&!output_image&&(output_image=content),content.type==="audio"&&!output_audio&&(output_audio=content),content.type==="video"&&!output_video&&(output_video=content)}}let output_text=textParts.reverse().join("");return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},normalized),output_text&&{output_text}),output_image?{output_image}:{}),output_audio?{output_audio}:{}),output_video?{output_video}:{})}function normalizeInteractionDates(interaction){return Object.assign(Object.assign({},interaction),{created:normalizeDateLike(interaction.created),updated:normalizeDateLike(interaction.updated)})}function normalizeDateLike(value){return value instanceof Date?value.toISOString():value}var GeminiNextGenEnvironmentFiles=class{constructor(resolveClient){this.resolveClient=resolveClient}async list(params,options){let{environment,path:path2,page_size,page_token,recursive,api_version}=params;return unwrapWithSdkHttpResponse(environmentsFilesList(this.resolveClient(api_version),environment,path2,api_version,page_size,page_token,recursive,toGoogleGenAIRequestOptions(options)))}},GeminiNextGenEnvironments=class{constructor(parentClient){this.parentClient=parentClient,this.files=new GeminiNextGenEnvironmentFiles(apiVersion=>this.getClient(apiVersion))}async create(params,options){let{api_version}=params,body=__rest(params,["api_version"]);return unwrapWithSdkHttpResponse(environmentsCreateEnvironment(this.getClient(api_version),body,api_version,toGoogleGenAIRequestOptions(options)))}async list(params={},options){let{api_version,page_size,page_token}=params??{};return unwrapWithSdkHttpResponse(environmentsListEnvironments(this.getClient(api_version),api_version,page_size,page_token,toGoogleGenAIRequestOptions(options)))}async get(id,params={},options){return unwrapWithSdkHttpResponse(environmentsGetEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}async delete(id,params={},options){return unwrapWithSdkHttpResponse(environmentsDeleteEnvironment(this.getClient(params?.api_version),id,params?.api_version,toGoogleGenAIRequestOptions(options)))}getClient(apiVersion){var _a2;return apiVersion?buildGoogleGenAIClient(this.parentClient,{api_version:apiVersion}):((_a2=this.sdk)!==null&&_a2!==void 0||(this.sdk=buildGoogleGenAIClient(this.parentClient)),this.sdk)}};var GOOGLE_API_KEY_HEADER="x-goog-api-key",REQUIRED_VERTEX_AI_SCOPE="https://www.googleapis.com/auth/cloud-platform",NodeAuth=class{constructor(opts){if(opts.apiKey!==void 0){this.apiKey=opts.apiKey;return}let vertexAuthOptions=buildGoogleAuthOptions(opts.googleAuthOptions);this.googleAuth=new import_google_auth_library.GoogleAuth(vertexAuthOptions)}async addAuthHeaders(headers,url){if(this.apiKey!==void 0){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(headers);return}return this.addGoogleAuthHeaders(headers,url)}addKeyHeader(headers){if(headers.get(GOOGLE_API_KEY_HEADER)===null){if(this.apiKey===void 0)throw new Error("Trying to set API key header but apiKey is not set");headers.append(GOOGLE_API_KEY_HEADER,this.apiKey)}}async addGoogleAuthHeaders(headers,url){if(this.googleAuth===void 0)throw new Error("Trying to set google-auth headers but googleAuth is unset");let authHeaders=await this.googleAuth.getRequestHeaders(url);for(let[key,value]of authHeaders)headers.get(key)===null&&headers.append(key,value)}};function buildGoogleAuthOptions(googleAuthOptions){let authOptions;if(googleAuthOptions){if(authOptions=googleAuthOptions,authOptions.scopes){if(typeof authOptions.scopes=="string"&&authOptions.scopes!==REQUIRED_VERTEX_AI_SCOPE||Array.isArray(authOptions.scopes)&&authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE)<0)throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`)}else return authOptions.scopes=[REQUIRED_VERTEX_AI_SCOPE],authOptions;return authOptions}else return authOptions={scopes:[REQUIRED_VERTEX_AI_SCOPE]},authOptions}var NodeDownloader=class{async download(params,apiClient){if(params.downloadPath){let response=await downloadFile(params,apiClient);if(response instanceof HttpResponse){let writer=createWriteStream(params.downloadPath);Readable.fromWeb(response.responseInternal.body).pipe(writer),await finished(writer)}else try{await writeFile(params.downloadPath,response,{encoding:"base64"})}catch(error){throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`)}}}};async function downloadFile(params,apiClient){var _a2,_b,_c;let name=tFileName(params.file);if(name!==void 0)return await apiClient.request({path:`files/${name}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal});if(isGeneratedVideo(params.file)){let videoBytes=(_c=params.file.video)===null||_c===void 0?void 0:_c.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download generated video, Uri or videoBytes not found.")}else if(isVideo(params.file)){let videoBytes=params.file.videoBytes;if(typeof videoBytes=="string")return videoBytes;throw new Error("Failed to download video, Uri or videoBytes not found.")}else throw new Error("Unsupported file type")}var NodeWebSocketFactory=class{create(url,headers,callbacks){return new NodeWebSocket(url,headers,callbacks)}},NodeWebSocket=class{constructor(url,headers,callbacks){this.url=url,this.headers=headers,this.callbacks=callbacks}connect(){this.ws=new import_websocket.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(message){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(message)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}};function cancelTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function cancelTuningJobResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function cancelTuningJobResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function contentToVertex(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function createTuningJobConfigToMldev(fromObject,parentObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);if(parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromTunedModelDisplayName),getValueByPath(fromObject,["description"])!==void 0)throw new Error("description parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);if(fromLearningRateMultiplier!=null&&setValueByPath(toObject,["tuningTask","hyperparameters","learningRateMultiplier"],fromLearningRateMultiplier),getValueByPath(fromObject,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);if(parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["tuningTask","hyperparameters","learningRate"],fromLearningRate),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["beta"])!==void 0)throw new Error("beta parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputUri"])!==void 0)throw new Error("outputUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["rewardConfig"])!==void 0)throw new Error("rewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compositeRewardConfig"])!==void 0)throw new Error("compositeRewardConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["samplesPerPrompt"])!==void 0)throw new Error("samplesPerPrompt parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["evaluateInterval"])!==void 0)throw new Error("evaluateInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["checkpointInterval"])!==void 0)throw new Error("checkpointInterval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["maxOutputTokens"])!==void 0)throw new Error("maxOutputTokens parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["thinkingLevel"])!==void 0)throw new Error("thinkingLevel parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["validationDatasetUri"])!==void 0)throw new Error("validationDatasetUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function createTuningJobConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorValidationDataset=getValueByPath(rootObject,["config","method"]);if(discriminatorValidationDataset===void 0&&(discriminatorValidationDataset="SUPERVISED_FINE_TUNING"),discriminatorValidationDataset==="SUPERVISED_FINE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["supervisedTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="PREFERENCE_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="DISTILLATION"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["distillationSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}else if(discriminatorValidationDataset==="REINFORCEMENT_TUNING"){let fromValidationDataset=getValueByPath(fromObject,["validationDataset"]);parentObject!==void 0&&fromValidationDataset!=null&&setValueByPath(parentObject,["reinforcementTuningSpec"],tuningValidationDatasetToVertex(fromValidationDataset))}let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);parentObject!==void 0&&fromTunedModelDisplayName!=null&&setValueByPath(parentObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let discriminatorEpochCount=getValueByPath(rootObject,["config","method"]);if(discriminatorEpochCount===void 0&&(discriminatorEpochCount="SUPERVISED_FINE_TUNING"),discriminatorEpochCount==="SUPERVISED_FINE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="PREFERENCE_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="DISTILLATION"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","epochCount"],fromEpochCount)}else if(discriminatorEpochCount==="REINFORCEMENT_TUNING"){let fromEpochCount=getValueByPath(fromObject,["epochCount"]);parentObject!==void 0&&fromEpochCount!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","epochCount"],fromEpochCount)}let discriminatorLearningRateMultiplier=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRateMultiplier===void 0&&(discriminatorLearningRateMultiplier="SUPERVISED_FINE_TUNING"),discriminatorLearningRateMultiplier==="SUPERVISED_FINE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="PREFERENCE_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="DISTILLATION"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}else if(discriminatorLearningRateMultiplier==="REINFORCEMENT_TUNING"){let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);parentObject!==void 0&&fromLearningRateMultiplier!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","learningRateMultiplier"],fromLearningRateMultiplier)}let discriminatorExportLastCheckpointOnly=getValueByPath(rootObject,["config","method"]);if(discriminatorExportLastCheckpointOnly===void 0&&(discriminatorExportLastCheckpointOnly="SUPERVISED_FINE_TUNING"),discriminatorExportLastCheckpointOnly==="SUPERVISED_FINE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["supervisedTuningSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="PREFERENCE_TUNING"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}else if(discriminatorExportLastCheckpointOnly==="DISTILLATION"){let fromExportLastCheckpointOnly=getValueByPath(fromObject,["exportLastCheckpointOnly"]);parentObject!==void 0&&fromExportLastCheckpointOnly!=null&&setValueByPath(parentObject,["distillationSpec","exportLastCheckpointOnly"],fromExportLastCheckpointOnly)}let discriminatorAdapterSize=getValueByPath(rootObject,["config","method"]);if(discriminatorAdapterSize===void 0&&(discriminatorAdapterSize="SUPERVISED_FINE_TUNING"),discriminatorAdapterSize==="SUPERVISED_FINE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="PREFERENCE_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="DISTILLATION"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","adapterSize"],fromAdapterSize)}else if(discriminatorAdapterSize==="REINFORCEMENT_TUNING"){let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);parentObject!==void 0&&fromAdapterSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","adapterSize"],fromAdapterSize)}let discriminatorTuningMode=getValueByPath(rootObject,["config","method"]);if(discriminatorTuningMode===void 0&&(discriminatorTuningMode="SUPERVISED_FINE_TUNING"),discriminatorTuningMode==="SUPERVISED_FINE_TUNING"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["supervisedTuningSpec","tuningMode"],fromTuningMode)}else if(discriminatorTuningMode==="DISTILLATION"){let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);parentObject!==void 0&&fromTuningMode!=null&&setValueByPath(parentObject,["distillationSpec","tuningMode"],fromTuningMode)}let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);parentObject!==void 0&&fromCustomBaseModel!=null&&setValueByPath(parentObject,["customBaseModel"],fromCustomBaseModel);let discriminatorBatchSize=getValueByPath(rootObject,["config","method"]);if(discriminatorBatchSize===void 0&&(discriminatorBatchSize="SUPERVISED_FINE_TUNING"),discriminatorBatchSize==="SUPERVISED_FINE_TUNING"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="DISTILLATION"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","batchSize"],fromBatchSize)}else if(discriminatorBatchSize==="REINFORCEMENT_TUNING"){let fromBatchSize=getValueByPath(fromObject,["batchSize"]);parentObject!==void 0&&fromBatchSize!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","batchSize"],fromBatchSize)}let discriminatorLearningRate=getValueByPath(rootObject,["config","method"]);if(discriminatorLearningRate===void 0&&(discriminatorLearningRate="SUPERVISED_FINE_TUNING"),discriminatorLearningRate==="SUPERVISED_FINE_TUNING"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["supervisedTuningSpec","hyperParameters","learningRate"],fromLearningRate)}else if(discriminatorLearningRate==="DISTILLATION"){let fromLearningRate=getValueByPath(fromObject,["learningRate"]);parentObject!==void 0&&fromLearningRate!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","learningRate"],fromLearningRate)}let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromBeta=getValueByPath(fromObject,["beta"]);parentObject!==void 0&&fromBeta!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","hyperParameters","beta"],fromBeta);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);parentObject!==void 0&&fromBaseTeacherModel!=null&&setValueByPath(parentObject,["distillationSpec","baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);parentObject!==void 0&&fromTunedTeacherModelSource!=null&&setValueByPath(parentObject,["distillationSpec","tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromSftLossWeightMultiplier=getValueByPath(fromObject,["sftLossWeightMultiplier"]);parentObject!==void 0&&fromSftLossWeightMultiplier!=null&&setValueByPath(parentObject,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],fromSftLossWeightMultiplier);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);parentObject!==void 0&&fromOutputUri!=null&&setValueByPath(parentObject,["outputUri"],fromOutputUri);let fromRewardConfig=getValueByPath(fromObject,["rewardConfig"]);parentObject!==void 0&&fromRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","singleRewardConfig"],fromRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);parentObject!==void 0&&fromCompositeRewardConfig!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","compositeRewardConfig"],fromCompositeRewardConfig);let fromSamplesPerPrompt=getValueByPath(fromObject,["samplesPerPrompt"]);parentObject!==void 0&&fromSamplesPerPrompt!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","samplesPerPrompt"],fromSamplesPerPrompt);let fromEvaluateInterval=getValueByPath(fromObject,["evaluateInterval"]);parentObject!==void 0&&fromEvaluateInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","evaluateInterval"],fromEvaluateInterval);let fromCheckpointInterval=getValueByPath(fromObject,["checkpointInterval"]);parentObject!==void 0&&fromCheckpointInterval!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","checkpointInterval"],fromCheckpointInterval);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);parentObject!==void 0&&fromMaxOutputTokens!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","maxOutputTokens"],fromMaxOutputTokens);let fromThinkingLevel=getValueByPath(fromObject,["thinkingLevel"]);parentObject!==void 0&&fromThinkingLevel!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","hyperParameters","thinkingLevel"],fromThinkingLevel);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);parentObject!==void 0&&fromValidationDatasetUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","validationDatasetUri"],fromValidationDatasetUri);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);return parentObject!==void 0&&fromEncryptionSpec!=null&&setValueByPath(parentObject,["encryptionSpec"],fromEncryptionSpec),toObject}function createTuningJobParametersPrivateToMldev(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToMldev(fromTrainingDataset);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToMldev(fromConfig,toObject),toObject}function createTuningJobParametersPrivateToVertex(fromObject,rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromTrainingDataset=getValueByPath(fromObject,["trainingDataset"]);fromTrainingDataset!=null&&tuningDatasetToVertex(fromTrainingDataset,toObject,rootObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&createTuningJobConfigToVertex(fromConfig,toObject,rootObject),toObject}function distillationHyperParametersFromVertex(fromObject,rootObject){let toObject={},fromEpochCount=getValueByPath(fromObject,["epochCount"]);fromEpochCount!=null&&setValueByPath(toObject,["epochCount"],fromEpochCount);let fromLearningRateMultiplier=getValueByPath(fromObject,["learningRateMultiplier"]);fromLearningRateMultiplier!=null&&setValueByPath(toObject,["learningRateMultiplier"],fromLearningRateMultiplier);let fromAdapterSize=getValueByPath(fromObject,["adapterSize"]);fromAdapterSize!=null&&setValueByPath(toObject,["adapterSize"],fromAdapterSize);let fromBatchSize=getValueByPath(fromObject,["batchSize"]);fromBatchSize!=null&&setValueByPath(toObject,["batchSize"],fromBatchSize);let fromLearningRate=getValueByPath(fromObject,["learningRate"]);fromLearningRate!=null&&setValueByPath(toObject,["learningRate"],fromLearningRate);let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return fromGenerationConfig!=null&&setValueByPath(toObject,["generationConfig"],generationConfigFromVertex(fromGenerationConfig)),toObject}function distillationSamplingSpecFromVertex(fromObject,rootObject){let toObject={},fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri);let fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromHyperparameters=getValueByPath(fromObject,["hyperparameters"]);return fromHyperparameters!=null&&setValueByPath(toObject,["hyperparameters"],distillationHyperParametersFromVertex(fromHyperparameters)),toObject}function distillationSpecFromVertex(fromObject,rootObject){let toObject={},fromBaseTeacherModel=getValueByPath(fromObject,["baseTeacherModel"]);fromBaseTeacherModel!=null&&setValueByPath(toObject,["baseTeacherModel"],fromBaseTeacherModel);let fromHyperParameters=getValueByPath(fromObject,["hyperParameters"]);fromHyperParameters!=null&&setValueByPath(toObject,["hyperParameters"],distillationHyperParametersFromVertex(fromHyperParameters));let fromPipelineRootDirectory=getValueByPath(fromObject,["pipelineRootDirectory"]);fromPipelineRootDirectory!=null&&setValueByPath(toObject,["pipelineRootDirectory"],fromPipelineRootDirectory);let fromPromptDatasetUri=getValueByPath(fromObject,["promptDatasetUri"]);fromPromptDatasetUri!=null&&setValueByPath(toObject,["promptDatasetUri"],fromPromptDatasetUri);let fromStudentModel=getValueByPath(fromObject,["studentModel"]);fromStudentModel!=null&&setValueByPath(toObject,["studentModel"],fromStudentModel);let fromTrainingDatasetUri=getValueByPath(fromObject,["trainingDatasetUri"]);fromTrainingDatasetUri!=null&&setValueByPath(toObject,["trainingDatasetUri"],fromTrainingDatasetUri);let fromTunedTeacherModelSource=getValueByPath(fromObject,["tunedTeacherModelSource"]);fromTunedTeacherModelSource!=null&&setValueByPath(toObject,["tunedTeacherModelSource"],fromTunedTeacherModelSource);let fromTuningMode=getValueByPath(fromObject,["tuningMode"]);fromTuningMode!=null&&setValueByPath(toObject,["tuningMode"],fromTuningMode);let fromValidationDatasetUri=getValueByPath(fromObject,["validationDatasetUri"]);return fromValidationDatasetUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromValidationDatasetUri),toObject}function generationConfigFromVertex(fromObject,_rootObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelSelectionConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],fromSpeechConfig);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);return fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),toObject}function getTuningJobParametersToMldev(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function getTuningJobParametersToVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);return fromName!=null&&setValueByPath(toObject,["_url","name"],fromName),toObject}function listTuningJobsConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);return parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter),toObject}function listTuningJobsParametersToVertex(fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listTuningJobsConfigToVertex(fromConfig,toObject),toObject}function listTuningJobsResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromTuningJobs=getValueByPath(fromObject,["tuningJobs"]);if(fromTuningJobs!=null){let transformedList=fromTuningJobs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>tuningJobFromVertex(item))),setValueByPath(toObject,["tuningJobs"],transformedList)}return toObject}function partToVertex(fromObject,_rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function reinforcementTuningExampleToVertex(fromObject,rootObject){let toObject={},fromReferences=getValueByPath(fromObject,["references"]);fromReferences!=null&&setValueByPath(toObject,["references"],fromReferences);let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=fromContents;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex(item))),setValueByPath(toObject,["contents"],transformedList)}let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);return fromSystemInstruction!=null&&setValueByPath(toObject,["systemInstruction"],contentToVertex(fromSystemInstruction)),toObject}function tunedModelFromMldev(fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["name"]);fromModel!=null&&setValueByPath(toObject,["model"],fromModel);let fromEndpoint=getValueByPath(fromObject,["name"]);return fromEndpoint!=null&&setValueByPath(toObject,["endpoint"],fromEndpoint),toObject}function tuningDatasetToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromExamples=getValueByPath(fromObject,["examples"]);if(fromExamples!=null){let transformedList=fromExamples;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["examples","examples"],transformedList)}return toObject}function tuningDatasetToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorGcsUri=getValueByPath(rootObject,["config","method"]);if(discriminatorGcsUri===void 0&&(discriminatorGcsUri="SUPERVISED_FINE_TUNING"),discriminatorGcsUri==="SUPERVISED_FINE_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["supervisedTuningSpec","trainingDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="PREFERENCE_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","trainingDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="DISTILLATION"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["distillationSpec","promptDatasetUri"],fromGcsUri)}else if(discriminatorGcsUri==="REINFORCEMENT_TUNING"){let fromGcsUri=getValueByPath(fromObject,["gcsUri"]);parentObject!==void 0&&fromGcsUri!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","trainingDatasetUri"],fromGcsUri)}let discriminatorVertexDatasetResource=getValueByPath(rootObject,["config","method"]);if(discriminatorVertexDatasetResource===void 0&&(discriminatorVertexDatasetResource="SUPERVISED_FINE_TUNING"),discriminatorVertexDatasetResource==="SUPERVISED_FINE_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["supervisedTuningSpec","trainingDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="PREFERENCE_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["preferenceOptimizationSpec","trainingDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="DISTILLATION"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["distillationSpec","promptDatasetUri"],fromVertexDatasetResource)}else if(discriminatorVertexDatasetResource==="REINFORCEMENT_TUNING"){let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);parentObject!==void 0&&fromVertexDatasetResource!=null&&setValueByPath(parentObject,["reinforcementTuningSpec","trainingDatasetUri"],fromVertexDatasetResource)}if(getValueByPath(fromObject,["examples"])!==void 0)throw new Error("examples parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tuningJobFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tTuningJobStatus(fromState));let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["tuningTask","startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["tuningTask","completeTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromTunedModel=getValueByPath(fromObject,["_self"]);return fromTunedModel!=null&&setValueByPath(toObject,["tunedModel"],tunedModelFromMldev(fromTunedModel)),toObject}function tuningJobFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromState=getValueByPath(fromObject,["state"]);fromState!=null&&setValueByPath(toObject,["state"],tTuningJobStatus(fromState));let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromStartTime=getValueByPath(fromObject,["startTime"]);fromStartTime!=null&&setValueByPath(toObject,["startTime"],fromStartTime);let fromEndTime=getValueByPath(fromObject,["endTime"]);fromEndTime!=null&&setValueByPath(toObject,["endTime"],fromEndTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromTunedModel=getValueByPath(fromObject,["tunedModel"]);fromTunedModel!=null&&setValueByPath(toObject,["tunedModel"],fromTunedModel);let fromPreTunedModel=getValueByPath(fromObject,["preTunedModel"]);fromPreTunedModel!=null&&setValueByPath(toObject,["preTunedModel"],fromPreTunedModel);let fromSupervisedTuningSpec=getValueByPath(fromObject,["supervisedTuningSpec"]);fromSupervisedTuningSpec!=null&&setValueByPath(toObject,["supervisedTuningSpec"],fromSupervisedTuningSpec);let fromPreferenceOptimizationSpec=getValueByPath(fromObject,["preferenceOptimizationSpec"]);fromPreferenceOptimizationSpec!=null&&setValueByPath(toObject,["preferenceOptimizationSpec"],fromPreferenceOptimizationSpec);let fromDistillationSamplingSpec=getValueByPath(fromObject,["distillationSamplingSpec"]);fromDistillationSamplingSpec!=null&&setValueByPath(toObject,["distillationSamplingSpec"],distillationSamplingSpecFromVertex(fromDistillationSamplingSpec));let fromDistillationSpec=getValueByPath(fromObject,["distillationSpec"]);fromDistillationSpec!=null&&setValueByPath(toObject,["distillationSpec"],distillationSpecFromVertex(fromDistillationSpec));let fromReinforcementTuningSpec=getValueByPath(fromObject,["reinforcementTuningSpec"]);fromReinforcementTuningSpec!=null&&setValueByPath(toObject,["reinforcementTuningSpec"],fromReinforcementTuningSpec);let fromTuningDataStats=getValueByPath(fromObject,["tuningDataStats"]);fromTuningDataStats!=null&&setValueByPath(toObject,["tuningDataStats"],fromTuningDataStats);let fromEncryptionSpec=getValueByPath(fromObject,["encryptionSpec"]);fromEncryptionSpec!=null&&setValueByPath(toObject,["encryptionSpec"],fromEncryptionSpec);let fromPartnerModelTuningSpec=getValueByPath(fromObject,["partnerModelTuningSpec"]);fromPartnerModelTuningSpec!=null&&setValueByPath(toObject,["partnerModelTuningSpec"],fromPartnerModelTuningSpec);let fromCustomBaseModel=getValueByPath(fromObject,["customBaseModel"]);fromCustomBaseModel!=null&&setValueByPath(toObject,["customBaseModel"],fromCustomBaseModel);let fromEvaluateDatasetRuns=getValueByPath(fromObject,["evaluateDatasetRuns"]);if(fromEvaluateDatasetRuns!=null){let transformedList=fromEvaluateDatasetRuns;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["evaluateDatasetRuns"],transformedList)}let fromExperiment=getValueByPath(fromObject,["experiment"]);fromExperiment!=null&&setValueByPath(toObject,["experiment"],fromExperiment);let fromFullFineTuningSpec=getValueByPath(fromObject,["fullFineTuningSpec"]);fromFullFineTuningSpec!=null&&setValueByPath(toObject,["fullFineTuningSpec"],fromFullFineTuningSpec);let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromOutputUri=getValueByPath(fromObject,["outputUri"]);fromOutputUri!=null&&setValueByPath(toObject,["outputUri"],fromOutputUri);let fromPipelineJob=getValueByPath(fromObject,["pipelineJob"]);fromPipelineJob!=null&&setValueByPath(toObject,["pipelineJob"],fromPipelineJob);let fromServiceAccount=getValueByPath(fromObject,["serviceAccount"]);fromServiceAccount!=null&&setValueByPath(toObject,["serviceAccount"],fromServiceAccount);let fromTunedModelDisplayName=getValueByPath(fromObject,["tunedModelDisplayName"]);fromTunedModelDisplayName!=null&&setValueByPath(toObject,["tunedModelDisplayName"],fromTunedModelDisplayName);let fromTuningJobMetadata=getValueByPath(fromObject,["tuningJobMetadata"]);fromTuningJobMetadata!=null&&setValueByPath(toObject,["tuningJobMetadata"],fromTuningJobMetadata);let fromTuningJobState=getValueByPath(fromObject,["tuningJobState"]);fromTuningJobState!=null&&setValueByPath(toObject,["tuningJobState"],fromTuningJobState);let fromVeoLoraTuningSpec=getValueByPath(fromObject,["veoLoraTuningSpec"]);fromVeoLoraTuningSpec!=null&&setValueByPath(toObject,["veoLoraTuningSpec"],fromVeoLoraTuningSpec);let fromVeoTuningSpec=getValueByPath(fromObject,["veoTuningSpec"]);return fromVeoTuningSpec!=null&&setValueByPath(toObject,["veoTuningSpec"],fromVeoTuningSpec),toObject}function tuningOperationFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);return fromError!=null&&setValueByPath(toObject,["error"],fromError),toObject}function tuningValidationDatasetToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["validationDatasetUri"],fromGcsUri);let fromVertexDatasetResource=getValueByPath(fromObject,["vertexDatasetResource"]);return fromVertexDatasetResource!=null&&setValueByPath(toObject,["validationDatasetUri"],fromVertexDatasetResource),toObject}function validateRewardParametersToVertex(fromObject,rootObject){let toObject={},fromParent=getValueByPath(fromObject,["parent"]);fromParent!=null&&setValueByPath(toObject,["_url","parent"],fromParent);let fromSampleResponse=getValueByPath(fromObject,["sampleResponse"]);fromSampleResponse!=null&&setValueByPath(toObject,["sampleResponse"],contentToVertex(fromSampleResponse));let fromExample=getValueByPath(fromObject,["example"]);fromExample!=null&&setValueByPath(toObject,["example"],reinforcementTuningExampleToVertex(fromExample));let fromSingleRewardConfig=getValueByPath(fromObject,["singleRewardConfig"]);fromSingleRewardConfig!=null&&setValueByPath(toObject,["singleRewardConfig"],fromSingleRewardConfig);let fromCompositeRewardConfig=getValueByPath(fromObject,["compositeRewardConfig"]);return fromCompositeRewardConfig!=null&&setValueByPath(toObject,["compositeRewardConfig"],fromCompositeRewardConfig),toObject}function validateRewardResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromOverallReward=getValueByPath(fromObject,["overallReward"]);fromOverallReward!=null&&setValueByPath(toObject,["overallReward"],fromOverallReward);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromRewardInfoDetails=getValueByPath(fromObject,["rewardInfoDetails"]);return fromRewardInfoDetails!=null&&setValueByPath(toObject,["rewardInfoDetails"],fromRewardInfoDetails),toObject}var Tunings=class extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.list=async(params={})=>new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS,x=>this.listInternal(x),await this.listInternal(params),params),this.get=async params=>await this.getInternal(params),this.tune=async params=>{var _a2;if(this.apiClient.isVertexAI())if(params.baseModel.startsWith("projects/")){let preTunedModel={tunedModelName:params.baseModel};!((_a2=params.config)===null||_a2===void 0)&&_a2.preTunedModelCheckpointId&&(preTunedModel.checkpointId=params.config.preTunedModelCheckpointId);let paramsPrivate=Object.assign(Object.assign({},params),{preTunedModel});return paramsPrivate.baseModel=void 0,await this.tuneInternal(paramsPrivate)}else{let paramsPrivate=Object.assign({},params);return await this.tuneInternal(paramsPrivate)}else{let paramsPrivate=Object.assign({},params),operation=await this.tuneMldevInternal(paramsPrivate),tunedModelName="";return operation.metadata!==void 0&&operation.metadata.tunedModel!==void 0?tunedModelName=operation.metadata.tunedModel:operation.name!==void 0&&operation.name.includes("/operations/")&&(tunedModelName=operation.name.split("/operations/")[0]),{name:tunedModelName,state:JobState.JOB_STATE_QUEUED}}}}async getInternal(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=getTuningJobParametersToVertex(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromVertex(apiResponse))}else{let body=getTuningJobParametersToMldev(params);return path2=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromMldev(apiResponse))}}async listInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=listTuningJobsParametersToVertex(params);return path2=formatMap("tuningJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"GET",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=listTuningJobsResponseFromVertex(apiResponse),typedResp=new ListTuningJobsResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(params){var _a2,_b,_c,_d;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=cancelTuningJobParametersToVertex(params);return path2=formatMap("{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=cancelTuningJobResponseFromVertex(apiResponse),typedResp=new CancelTuningJobResponse;return Object.assign(typedResp,resp),typedResp})}else{let body=cancelTuningJobParametersToMldev(params);return path2=formatMap("{name}:cancel",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_c=params.config)===null||_c===void 0?void 0:_c.httpOptions,abortSignal:(_d=params.config)===null||_d===void 0?void 0:_d.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=cancelTuningJobResponseFromMldev(apiResponse),typedResp=new CancelTuningJobResponse;return Object.assign(typedResp,resp),typedResp})}}async tuneInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=createTuningJobParametersPrivateToVertex(params,params);return path2=formatMap("tuningJobs",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningJobFromVertex(apiResponse))}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{let body=createTuningJobParametersPrivateToMldev(params);return path2=formatMap("tunedModels",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>tuningOperationFromMldev(apiResponse))}}async validateReward(params){var _a2,_b;let response,path2="",queryParams={};if(this.apiClient.isVertexAI()){let body=validateRewardParametersToVertex(params);return path2=formatMap("{parent}/tuningJobs:validateReinforcementTuningReward",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path:path2,queryParams,body:JSON.stringify(body),httpMethod:"POST",httpOptions:(_a2=params.config)===null||_a2===void 0?void 0:_a2.httpOptions,abortSignal:(_b=params.config)===null||_b===void 0?void 0:_b.abortSignal}).then(httpResponse=>httpResponse.json().then(jsonResponse=>{let response2=jsonResponse;return response2.sdkHttpResponse={headers:httpResponse.headers},response2})),response.then(apiResponse=>{let resp=validateRewardResponseFromVertex(apiResponse),typedResp=new ValidateRewardResponse;return Object.assign(typedResp,resp),typedResp})}else throw new Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}},MAX_CHUNK_SIZE=1024*1024*8,MAX_RETRY_COUNT=3,INITIAL_RETRY_DELAY_MS=1e3,DELAY_MULTIPLIER=2,X_GOOG_UPLOAD_STATUS_HEADER_FIELD="x-goog-upload-status";async function uploadBlob(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await uploadBlobInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return responseJson.file}async function uploadBlobToFileSearchStore(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await uploadBlobInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let resp=uploadToFileSearchStoreOperationFromMldev(responseJson),typedResp=new UploadToFileSearchStoreOperation;return Object.assign(typedResp,resp),typedResp}async function uploadBlobInternal(file,uploadUrl,apiClient,httpOptions){var _a2,_b,_c;let finalUrl=uploadUrl,effectiveBaseUrl=httpOptions?.baseUrl||((_a2=apiClient.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl);if(effectiveBaseUrl){let baseUri=new URL(effectiveBaseUrl),uploadUri=new URL(uploadUrl);uploadUri.protocol=baseUri.protocol,uploadUri.host=baseUri.host,uploadUri.port=baseUri.port,finalUrl=uploadUri.toString()}let fileSize=0,offset=0,response=new HttpResponse(new Response),uploadCommand="upload";for(fileSize=file.size;offset<fileSize;){let chunkSize=Math.min(MAX_CHUNK_SIZE,fileSize-offset),chunk=file.slice(offset,offset+chunkSize);offset+chunkSize>=fileSize&&(uploadCommand+=", finalize");let retryCount=0,currentDelayMs=INITIAL_RETRY_DELAY_MS;for(;retryCount<MAX_RETRY_COUNT;){let mergedHeaders=Object.assign(Object.assign({},httpOptions?.headers||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":String(offset)});if(response=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},httpOptions),{apiVersion:"",baseUrl:finalUrl,headers:mergedHeaders})}),!((_b=response?.headers)===null||_b===void 0)&&_b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])break;retryCount++,await sleep(currentDelayMs),currentDelayMs=currentDelayMs*DELAY_MULTIPLIER}if(offset+=chunkSize,((_c=response?.headers)===null||_c===void 0?void 0:_c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="active")break;if(fileSize<=offset)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return response}async function getBlobStat(file){return{size:file.size,type:file.type}}function sleep(ms){return new Promise(resolvePromise=>setTimeout(resolvePromise,ms))}var NodeUploader=class{async stat(file){let fileStat={size:0,type:void 0};if(typeof file=="string"){let originalStat=await fs.stat(file);return fileStat.size=originalStat.size,fileStat.type=this.inferMimeType(file),fileStat}else return await getBlobStat(file)}async upload(file,uploadUrl,apiClient,httpOptions){return typeof file=="string"?await this.uploadFileFromPath(file,uploadUrl,apiClient,httpOptions):uploadBlob(file,uploadUrl,apiClient,httpOptions)}async uploadToFileSearchStore(file,uploadUrl,apiClient,httpOptions){return typeof file=="string"?await this.uploadFileToFileSearchStoreFromPath(file,uploadUrl,apiClient,httpOptions):uploadBlobToFileSearchStore(file,uploadUrl,apiClient,httpOptions)}inferMimeType(filePath){let fileExtension=filePath.slice(filePath.lastIndexOf(".")+1);return{aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"}[fileExtension.toLowerCase()]}async uploadFileFromPath(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await this.uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return responseJson.file}async uploadFileToFileSearchStoreFromPath(file,uploadUrl,apiClient,httpOptions){var _a2;let response=await this.uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions),responseJson=await response?.json();if(((_a2=response?.headers)===null||_a2===void 0?void 0:_a2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let resp=uploadToFileSearchStoreOperationFromMldev(responseJson),typedResp=new UploadToFileSearchStoreOperation;return Object.assign(typedResp,resp),typedResp}async uploadFileFromPathInternal(file,uploadUrl,apiClient,httpOptions){var _a2,_b,_c;let finalUrl=uploadUrl,effectiveBaseUrl=httpOptions?.baseUrl||((_a2=apiClient.clientOptions.httpOptions)===null||_a2===void 0?void 0:_a2.baseUrl);if(effectiveBaseUrl){let baseUri=new URL(effectiveBaseUrl),uploadUri=new URL(uploadUrl);uploadUri.protocol=baseUri.protocol,uploadUri.host=baseUri.host,uploadUri.port=baseUri.port,finalUrl=uploadUri.toString()}let fileSize=0,offset=0,response=new HttpResponse(new Response),uploadCommand="upload",fileHandle,fileName=path.basename(file);try{if(fileHandle=await fs.open(file,"r"),!fileHandle)throw new Error("Failed to open file");for(fileSize=(await fileHandle.stat()).size;offset<fileSize;){let chunkSize=Math.min(MAX_CHUNK_SIZE,fileSize-offset);offset+chunkSize>=fileSize&&(uploadCommand+=", finalize");let buffer=new Uint8Array(chunkSize),{bytesRead}=await fileHandle.read(buffer,0,chunkSize,offset);if(bytesRead!==chunkSize)throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`);let chunk=new Blob([buffer]),retryCount=0,currentDelayMs=INITIAL_RETRY_DELAY_MS;for(;retryCount<MAX_RETRY_COUNT;){let mergedHeaders=Object.assign(Object.assign({},httpOptions?.headers||{}),{"X-Goog-Upload-Command":uploadCommand,"X-Goog-Upload-Offset":String(offset),"X-Goog-Upload-File-Name":fileName});if(response=await apiClient.request({path:"",body:chunk,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},httpOptions),{apiVersion:"",baseUrl:finalUrl,headers:mergedHeaders})}),!((_b=response?.headers)===null||_b===void 0)&&_b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])break;retryCount++,await sleep(currentDelayMs),currentDelayMs=currentDelayMs*DELAY_MULTIPLIER}if(offset+=bytesRead,((_c=response?.headers)===null||_c===void 0?void 0:_c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD])!=="active")break;if(fileSize<=offset)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return response}finally{fileHandle&&await fileHandle.close()}}};var NodeFiles=class extends Files$1{async registerFiles(params){if(typeof process>"u"||!process.versions||!process.versions.node)throw new Error("registerFiles is only supported in Node.js environments.");let authHeaders=await params.auth.getRequestHeaders(),config=params.config||{},httpOptions=config.httpOptions||{},headers=Object.assign({},httpOptions.headers||{});if(authHeaders)if(typeof authHeaders[Symbol.iterator]=="function")for(let[key,value]of authHeaders)headers[key]=value;else for(let[key,value]of Object.entries(authHeaders))headers[key]=value;return this._registerFiles({uris:params.uris,config:Object.assign(Object.assign({},config),{httpOptions:Object.assign(Object.assign({},httpOptions),{headers})})})}};var LANGUAGE_LABEL_PREFIX="gl-node/";function resolveCloudFlag(options){var _a2;if(options&&(options.enterprise!==void 0||options.vertexai!==void 0)){if(options.enterprise!==void 0&&options.vertexai!==void 0&&options.enterprise!==options.vertexai)throw new Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return(_a2=options.enterprise)!==null&&_a2!==void 0?_a2:options.vertexai}let envEnterpriseStr=getEnv("GOOGLE_GENAI_USE_ENTERPRISE"),envVertexaiStr=getEnv("GOOGLE_GENAI_USE_VERTEXAI"),useEnterpriseEnv=stringToBoolean(envEnterpriseStr),useVertexaiEnv=stringToBoolean(envVertexaiStr);return envEnterpriseStr!==void 0&&envVertexaiStr!==void 0&&useEnterpriseEnv!==useVertexaiEnv&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),envEnterpriseStr!==void 0?useEnterpriseEnv:envVertexaiStr!==void 0?useVertexaiEnv:!1}var GoogleGenAI2=class{getNextGenClient(){let httpOpts=this.httpOptions;return this._nextGenClient===void 0&&(this._nextGenClient=buildGoogleGenAIClient(this.apiClient,{timeout_ms:httpOpts?.timeout})),httpOpts?.extraBody&&console.warn("GoogleGenAI: Client level httpOptions.extraBody is not supported by the Gemini NextGen client and will be ignored."),this._nextGenClient}get interactions(){return this._interactions!==void 0?this._interactions:(this._interactions=new GeminiNextGenInteractions(this.apiClient),this._interactions)}get webhooks(){return this._webhooks!==void 0?this._webhooks:(this._webhooks=new GeminiNextGenWebhooks(this.apiClient),this._webhooks)}get agents(){return this._agents!==void 0?this._agents:(console.warn("GoogleGenAI.agents: Agents usage is experimental and may change in future versions."),this._agents=new GeminiNextGenAgents(this.apiClient),this._agents)}get triggers(){return this._triggers!==void 0?this._triggers:(console.warn("GoogleGenAI.triggers: Triggers usage is experimental and may change in future versions."),this._triggers=new GeminiNextGenTriggers(this.apiClient),this._triggers)}get environments(){return this._environments!==void 0?this._environments:(console.warn("GoogleGenAI.environments: Environments usage is experimental and may change in future versions."),this._environments=new GeminiNextGenEnvironments(this.apiClient),this._environments)}constructor(options={}){var _a2,_b,_c,_d;if(this.vertexai=resolveCloudFlag(options),(options.project||options.location)&&!this.vertexai)throw new Error("Project and location are not supported for Gemini API backend.");let envApiKey=getApiKeyFromEnv(),envProject=getEnv("GOOGLE_CLOUD_PROJECT"),envLocation=getEnv("GOOGLE_CLOUD_LOCATION");this.apiKey=(_a2=options.apiKey)!==null&&_a2!==void 0?_a2:envApiKey,this.project=(_b=options.project)!==null&&_b!==void 0?_b:envProject,this.location=(_c=options.location)!==null&&_c!==void 0?_c:envLocation,!this.vertexai&&!this.apiKey&&console.warn("API key should be set when using the Gemini API."),this.vertexai&&(!((_d=options.googleAuthOptions)===null||_d===void 0)&&_d.credentials&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),!options.project&&!options.location&&(envProject||envLocation)&&options.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(options.project||options.location)&&!options.apiKey&&envApiKey?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):!options.project&&!options.location&&!options.apiKey&&(envProject||envLocation)&&envApiKey&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),!this.location&&!this.apiKey&&(this.location="global"));let baseUrl=getBaseUrl(options.httpOptions,this.vertexai,getEnv("GOOGLE_VERTEX_BASE_URL"),getEnv("GOOGLE_GEMINI_BASE_URL"));baseUrl&&(options.httpOptions?options.httpOptions.baseUrl=baseUrl:options.httpOptions={baseUrl}),this.apiVersion=options.apiVersion,this.httpOptions=options.httpOptions;let auth=new NodeAuth({apiKey:this.apiKey,googleAuthOptions:options.googleAuthOptions});this.apiClient=new ApiClient({auth,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:LANGUAGE_LABEL_PREFIX+process.version,uploader:new NodeUploader,downloader:new NodeDownloader}),this.models=new Models(this.apiClient),this.live=new Live(this.apiClient,auth,new NodeWebSocketFactory),this.batches=new Batches(this.apiClient),this.chats=new Chats(this.models,this.apiClient),this.caches=new Caches(this.apiClient),this.files=new NodeFiles(this.apiClient),this.operations=new Operations(this.apiClient),this.authTokens=new Tokens(this.apiClient),this.tunings=new Tunings(this.apiClient),this.fileSearchStores=new FileSearchStores(this.apiClient)}};function getEnv(env2){var _a2,_b,_c;return(_c=(_b=(_a2=process==null?void 0:process.env)===null||_a2===void 0?void 0:_a2[env2])===null||_b===void 0?void 0:_b.trim())!==null&&_c!==void 0?_c:void 0}function stringToBoolean(str){return str===void 0?!1:str.toLowerCase()==="true"}function getApiKeyFromEnv(){let envGoogleApiKey=getEnv("GOOGLE_API_KEY"),envGeminiApiKey=getEnv("GEMINI_API_KEY");return envGoogleApiKey&&envGeminiApiKey&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),envGoogleApiKey||envGeminiApiKey||void 0}var GOOGLE_SDK_THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH};function resolveGoogleThinkingLevel(model,level){let mapped=model.thinkingLevelMap?.[level],resolvedLevel=typeof mapped=="string"?mapped.toLowerCase():level;switch(resolvedLevel){case"minimal":case"low":case"medium":case"high":return resolvedLevel;default:throw new Error(`Unsupported Google thinking level mapping for ${model.provider}/${model.id}: ${level} -> ${String(mapped)}`)}}function usesGoogleThinkingLevel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-(?:pro|flash)/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"||/gemma-?4/.test(id)}function toGoogleThinkingLevel(level){switch(level){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function toGoogleSdkThinkingLevel(level){return GOOGLE_SDK_THINKING_LEVEL_MAP[level]}function getDisabledGoogleThinkingConfig(model){if(!usesGoogleThinkingLevel(model))return{thinkingBudget:0};let fallback=clampThinkingLevel(model,"off");if(fallback==="off")return{thinkingBudget:0};let resolvedLevel=resolveGoogleThinkingLevel(model,fallback),apiLevel=toGoogleThinkingLevel(resolvedLevel);return{thinkingLevel:toGoogleSdkThinkingLevel(apiLevel)}}function isThinkingPart(part){return part.thought===!0}function retainThoughtSignature(existing,incoming){return typeof incoming=="string"&&incoming.length>0?incoming:existing}var base64SignaturePattern=/^[A-Za-z0-9+/]+={0,2}$/;function isValidThoughtSignature(signature){return!signature||signature.length%4!==0?!1:base64SignaturePattern.test(signature)}function resolveThoughtSignature(isSameProviderAndModel,signature){return isSameProviderAndModel&&isValidThoughtSignature(signature)?signature:void 0}function requiresToolCallId(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return modelId.startsWith("claude-")||modelId.startsWith("gpt-oss-")||geminiMajorVersion!==void 0&&geminiMajorVersion>=3}function getGeminiMajorVersion(modelId){let match2=modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(match2)return Number.parseInt(match2[1],10)}function supportsMultimodalFunctionResponse(modelId){let geminiMajorVersion=getGeminiMajorVersion(modelId);return geminiMajorVersion!==void 0?geminiMajorVersion>=3:!0}function convertMessages(model,context){let conversation=withoutInitialSystemMessage(collapseSystemMessages(context).messages),contents=[],transformedMessages=transformMessages(conversation,model,id=>requiresToolCallId(model.id)?id.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64):id);for(let msg of transformedMessages)if(msg.role==="user")if(typeof msg.content=="string")contents.push({role:"user",parts:[{text:sanitizeSurrogates(msg.content)}]});else{let parts=msg.content.map(item=>item.type==="text"?{text:sanitizeSurrogates(item.text)}:{inlineData:{mimeType:item.mimeType,data:item.data}});if(parts.length===0)continue;contents.push({role:"user",parts})}else if(msg.role==="assistant"){let parts=[],isSameProviderAndModel=msg.provider===model.provider&&msg.model===model.id;for(let block of msg.content)if(block.type==="text"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.textSignature);if((!block.text||block.text.trim()==="")&&!thoughtSignature)continue;parts.push({text:sanitizeSurrogates(block.text),...thoughtSignature&&{thoughtSignature}})}else if(block.type==="thinking")if(isSameProviderAndModel){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thinkingSignature);if((!block.thinking||block.thinking.trim()==="")&&!thoughtSignature)continue;parts.push({thought:!0,text:sanitizeSurrogates(block.thinking),...thoughtSignature&&{thoughtSignature}})}else{if(!block.thinking||block.thinking.trim()==="")continue;parts.push({text:sanitizeSurrogates(block.thinking)})}else if(block.type==="toolCall"){let thoughtSignature=resolveThoughtSignature(isSameProviderAndModel,block.thoughtSignature),part={functionCall:{name:block.name,args:block.arguments??{},...requiresToolCallId(model.id)?{id:block.id}:{}},...thoughtSignature&&{thoughtSignature}};parts.push(part)}if(parts.length===0)continue;contents.push({role:"model",parts})}else if(msg.role==="toolResult"){let textResult=msg.content.filter(c=>c.type==="text").map(c=>c.text).join(`
44
+ `),imageContent=model.input.includes("image")?msg.content.filter(c=>c.type==="image"):[],hasText=textResult.length>0,hasImages=imageContent.length>0,modelSupportsMultimodalFunctionResponse=supportsMultimodalFunctionResponse(model.id),responseValue=hasText?sanitizeSurrogates(textResult):hasImages?"(see attached image)":"",imageParts=imageContent.map(imageBlock=>({inlineData:{mimeType:imageBlock.mimeType,data:imageBlock.data}})),includeId=requiresToolCallId(model.id),functionResponsePart={functionResponse:{name:msg.toolName,response:msg.isError?{error:responseValue}:{output:responseValue},...hasImages&&modelSupportsMultimodalFunctionResponse&&{parts:imageParts},...includeId?{id:msg.toolCallId}:{}}},lastContent=contents[contents.length-1];lastContent?.role==="user"&&lastContent.parts?.some(p=>p.functionResponse)?lastContent.parts.push(functionResponsePart):contents.push({role:"user",parts:[functionResponsePart]}),hasImages&&!modelSupportsMultimodalFunctionResponse&&contents.push({role:"user",parts:[{text:"Tool result image:"},...imageParts]})}return contents}var JSON_SCHEMA_META_DECLARATIONS=new Set(["$schema","$id","$anchor","$dynamicAnchor","$vocabulary","$comment","$defs","definitions"]);function sanitizeForOpenApi(schema){if(typeof schema!="object"||schema===null||Array.isArray(schema))return schema;let result={};for(let[key,value]of Object.entries(schema))JSON_SCHEMA_META_DECLARATIONS.has(key)||(result[key]=sanitizeForOpenApi(value));return result}function convertTools(tools,useParameters=!1,supportsStrictMode=!0){if(tools.length!==0)return[{functionDeclarations:tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode),parameters=getJsonSchemaToolParameters(tool,strict);return{name:tool.name,description:tool.description,...useParameters?{parameters:sanitizeForOpenApi(parameters)}:{parametersJsonSchema:parameters}}})}]}function supportsGoogleStrictToolSampling(modelId){let majorVersion=getGeminiMajorVersion(modelId);return majorVersion!==void 0&&majorVersion>=3}function mapToolChoice(choice){switch(choice){case"auto":return FunctionCallingConfigMode.AUTO;case"none":return FunctionCallingConfigMode.NONE;case"any":return FunctionCallingConfigMode.ANY;default:return FunctionCallingConfigMode.AUTO}}function resolveGoogleFunctionCallingMode(tools,toolChoice,supportsStrictMode){let useStrictMode=tools.some(tool=>resolveJsonSchemaStrictSampling(tool,supportsStrictMode)===!0);return toolChoice==="none"||toolChoice==="any"?mapToolChoice(toolChoice):useStrictMode?FunctionCallingConfigMode.VALIDATED:toolChoice?mapToolChoice(toolChoice):void 0}function mapStopReason(reason){switch(reason){case FinishReason.STOP:return"stop";case FinishReason.MAX_TOKENS:return"length";case FinishReason.BLOCKLIST:case FinishReason.PROHIBITED_CONTENT:case FinishReason.SPII:case FinishReason.SAFETY:case FinishReason.IMAGE_SAFETY:case FinishReason.IMAGE_PROHIBITED_CONTENT:case FinishReason.IMAGE_RECITATION:case FinishReason.IMAGE_OTHER:case FinishReason.RECITATION:case FinishReason.FINISH_REASON_UNSPECIFIED:case FinishReason.OTHER:case FinishReason.LANGUAGE:case FinishReason.MALFORMED_FUNCTION_CALL:case FinishReason.UNEXPECTED_TOOL_CALL:case FinishReason.TOO_MANY_TOOL_CALLS:case FinishReason.NO_IMAGE:return"error";default:{let _exhaustive=reason;throw new Error(`Unhandled stop reason: ${_exhaustive}`)}}}function retryGoogleRequest(request,options){return retryProviderRequest(async()=>{try{return await request()}catch(error){throw error instanceof Error&&"status"in error&&!("headers"in error)&&(error.headers=void 0),error}},{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal})}export{ResourceScope,GoogleGenAI2 as GoogleGenAI,resolveGoogleThinkingLevel,usesGoogleThinkingLevel,toGoogleThinkingLevel,toGoogleSdkThinkingLevel,getDisabledGoogleThinkingConfig,isThinkingPart,retainThoughtSignature,convertMessages,convertTools,supportsGoogleStrictToolSampling,resolveGoogleFunctionCallingMode,mapStopReason,retryGoogleRequest};