@averyyy/pi-coding-agent 1.5.2-piclient.2 → 1.5.2-piclient.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.
- package/CHANGELOG.md +2 -0
- package/dist/bundle/chunks/{anthropic-messages-KT6DV7MK.js → anthropic-messages-VSHI7RJC.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-E2Z734ES.js → azure-openai-responses-2AM6PDVN.js} +1 -1
- package/dist/bundle/chunks/{chunk-TCESBBFS.js → chunk-44JAKV5S.js} +1 -1
- package/dist/bundle/chunks/{chunk-FA5D3PPT.js → chunk-BQO4LGBH.js} +1 -1
- package/dist/bundle/chunks/chunk-DELINJAJ.js +35 -0
- package/dist/bundle/chunks/{chunk-M4NMEBFE.js → chunk-F7UBMF24.js} +1 -1
- package/dist/bundle/chunks/{chunk-ECEUFETK.js → chunk-GBIOAONG.js} +1 -1
- package/dist/bundle/chunks/{chunk-IYMNLY6C.js → chunk-RULD2HDT.js} +1 -1
- package/dist/bundle/chunks/{chunk-D2LWHJJD.js → chunk-VFGCY2DT.js} +3 -3
- package/dist/bundle/chunks/{chunk-ZFWVOFG2.js → chunk-VZXIWQ47.js} +1 -1
- package/dist/bundle/chunks/{chunk-VZFAYNKC.js → chunk-YJ55KUA7.js} +1 -1
- package/dist/bundle/chunks/{cli-M6DJI5GJ.js → cli-DS5HPHA5.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-6TWKBBSR.js → cloudflare-workers-ai-system-one-HWYGT2VX.js} +1 -1
- package/dist/bundle/chunks/google-antigravity-runtime.js +9 -3
- package/dist/bundle/chunks/google-antigravity.js +2 -2
- package/dist/bundle/chunks/{google-generative-ai-YSOYXY5K.js → google-generative-ai-7QTEXJ7X.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-X3ELXR2J.js → google-vertex-4XFVETQW.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-J4IL2HMK.js → mistral-conversations-GI7TFE4O.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-GULSUKQ4.js → openai-codex-responses-QEMRM66X.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-ZGWBSKNR.js → openai-completions-TASJGYUH.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-BU2ER6AQ.js → openai-decisions-WHK2TWME.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-WDSDROXC.js → openai-responses-SWPNADFU.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-LXDZKNJW.js → typesafe-system-one-KFYBTFIN.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-N6RDW4TA.js → virtual-modules-GFB4VJAT.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +17 -3
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +3 -77
- package/dist/core/provider-composer.js.map +1 -1
- package/docs/models.md +2 -0
- package/package.json +4 -4
- package/dist/bundle/chunks/chunk-OMUE475A.js +0 -35
|
@@ -52,7 +52,7 @@ https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOU
|
|
|
52
52
|
To learn more about authentication and Google APIs, visit:
|
|
53
53
|
https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
|
|
54
54
|
To learn more about Universe Domain retrieval, visit:
|
|
55
|
-
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var GoogleAuth2=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#pendingAuthClient=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(opts={}){if(this._cachedProjectId=opts.projectId||null,this.cachedCredential=opts.authClient||null,this.keyFilename=opts.keyFilename||opts.keyFile,this.scopes=opts.scopes,this.clientOptions=opts.clientOptions||{},this.jsonContent=opts.credentials||null,this.apiKey=opts.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);opts.universeDomain&&(this.clientOptions.universeDomain=opts.universeDomain)}setGapicJWTValues(client){client.defaultServicePath=this.defaultServicePath,client.useJWTAccessWithScope=this.useJWTAccessWithScope,client.defaultScopes=this.defaultScopes}getProjectId(callback){if(callback)this.getProjectIdAsync().then(r2=>callback(null,r2),callback);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e2){if(e2 instanceof Error&&e2.message===exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e2}}async findAndCacheProjectId(){let projectId=null;if(projectId||=await this.getProductionProjectId(),projectId||=await this.getFileProjectId(),projectId||=await this.getDefaultServiceProjectId(),projectId||=await this.getGCEProjectId(),projectId||=await this.getExternalAccountClientProjectId(),projectId)return this._cachedProjectId=projectId,projectId;throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let universeDomain;try{universeDomain=await gcpMetadata.universe("universe-domain"),universeDomain||=authclient_1.DEFAULT_UNIVERSE}catch(e2){if(e2&&e2?.response?.status===404)universeDomain=authclient_1.DEFAULT_UNIVERSE;else throw e2}return universeDomain}async getUniverseDomain(){let universeDomain=(0,util_1.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{universeDomain??=(await this.getClient()).universeDomain}catch{universeDomain??=authclient_1.DEFAULT_UNIVERSE}return universeDomain}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(optionsOrCallback={},callback){let options;if(typeof optionsOrCallback=="function"?callback=optionsOrCallback:options=optionsOrCallback,callback)this.getApplicationDefaultAsync(options).then(r2=>callback(null,r2.credential,r2.projectId),callback);else return this.getApplicationDefaultAsync(options)}async getApplicationDefaultAsync(options={}){if(this.cachedCredential)return await this.#prepareAndCacheClient(this.cachedCredential,null);let credential;if(credential=await this._tryGetApplicationCredentialsFromEnvironmentVariable(options),credential)return credential instanceof jwtclient_1.JWT?credential.scopes=this.scopes:credential instanceof baseexternalclient_1.BaseExternalAccountClient&&(credential.scopes=this.getAnyScopes()),await this.#prepareAndCacheClient(credential);if(credential=await this._tryGetApplicationCredentialsFromWellKnownFile(options),credential)return credential instanceof jwtclient_1.JWT?credential.scopes=this.scopes:credential instanceof baseexternalclient_1.BaseExternalAccountClient&&(credential.scopes=this.getAnyScopes()),await this.#prepareAndCacheClient(credential);if(await this._checkIsGCE())return options.scopes=this.getAnyScopes(),await this.#prepareAndCacheClient(new computeclient_1.Compute(options));throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#prepareAndCacheClient(credential,quotaProjectIdOverride=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let projectId=await this.getProjectIdOptional();return quotaProjectIdOverride&&(credential.quotaProjectId=quotaProjectIdOverride),this.cachedCredential=credential,{credential,projectId}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=gcpMetadata.getGCPResidency()||await gcpMetadata.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(options){let credentialsPath=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!credentialsPath||credentialsPath.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(credentialsPath,options)}catch(e2){throw e2 instanceof Error&&(e2.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e2.message}`),e2}}async _tryGetApplicationCredentialsFromWellKnownFile(options){let location=null;if(this._isWindows())location=process.env.APPDATA;else{let home=process.env.HOME;home&&(location=path.join(home,".config"))}return location&&(location=path.join(location,"gcloud","application_default_credentials.json"),fs2.existsSync(location)||(location=null)),location?await this._getApplicationCredentialsFromFilePath(location,options):null}async _getApplicationCredentialsFromFilePath(filePath,options={}){if(!filePath||filePath.length===0)throw new Error("The file path is invalid.");try{if(filePath=fs2.realpathSync(filePath),!fs2.lstatSync(filePath).isFile())throw new Error}catch(err){throw err instanceof Error&&(err.message=`The file at ${filePath} does not exist, or it is not a file. ${err.message}`),err}let readStream=fs2.createReadStream(filePath);return this.fromStream(readStream,options)}fromImpersonatedJSON(json){if(!json)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(json.type!==impersonated_1.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!json.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!json.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let sourceClient=this.fromJSON(json.source_credentials);if(json.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`);let targetPrincipal=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)?.groups?.target;if(!targetPrincipal)throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`);let targetScopes=(this.scopes||json.scopes||this.defaultScopes)??[];return new impersonated_1.Impersonated({...json,sourceClient,targetPrincipal,targetScopes:Array.isArray(targetScopes)?targetScopes:[targetScopes]})}fromJSON(json,options={}){let client,preferredUniverseDomain=(0,util_1.originalOrCamelOptions)(options).get("universe_domain");return json.type===refreshclient_1.USER_REFRESH_ACCOUNT_TYPE?(client=new refreshclient_1.UserRefreshClient(options),client.fromJSON(json)):json.type===impersonated_1.IMPERSONATED_ACCOUNT_TYPE?client=this.fromImpersonatedJSON(json):json.type===baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE?(client=externalclient_1.ExternalAccountClient.fromJSON({...json,...options}),client.scopes=this.getAnyScopes()):json.type===externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?client=new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({...json,...options}):(options.scopes=this.scopes,client=new jwtclient_1.JWT(options),this.setGapicJWTValues(client),client.fromJSON(json)),preferredUniverseDomain&&(client.universeDomain=preferredUniverseDomain),client}_cacheClientFromJSON(json,options){let client=this.fromJSON(json,options);return this.jsonContent=json,this.cachedCredential=client,client}fromStream(inputStream,optionsOrCallback={},callback){let options={};if(typeof optionsOrCallback=="function"?callback=optionsOrCallback:options=optionsOrCallback,callback)this.fromStreamAsync(inputStream,options).then(r2=>callback(null,r2),callback);else return this.fromStreamAsync(inputStream,options)}fromStreamAsync(inputStream,options){return new Promise((resolve,reject)=>{if(!inputStream)throw new Error("Must pass in a stream containing the Google auth settings.");let chunks=[];inputStream.setEncoding("utf8").on("error",reject).on("data",chunk=>chunks.push(chunk)).on("end",()=>{try{try{let data=JSON.parse(chunks.join("")),r2=this._cacheClientFromJSON(data,options);return resolve(r2)}catch(err){if(!this.keyFilename)throw err;let client=new jwtclient_1.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=client,this.setGapicJWTValues(client),resolve(client)}}catch(err){return reject(err)}})})}fromAPIKey(apiKey,options={}){return new jwtclient_1.JWT({...options,apiKey})}_isWindows(){let sys=os2.platform();return!!(sys&&sys.length>=3&&sys.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(resolve=>{(0,child_process_1.exec)("gcloud config config-helper --format json",(err,stdout)=>{if(!err&&stdout)try{let projectId=JSON.parse(stdout).configuration.properties.core.project;resolve(projectId);return}catch{}resolve(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let creds=await this.getClient();if(creds&&creds.projectId)return creds.projectId}let r2=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return r2?r2.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await gcpMetadata.project("project-id")}catch{return null}}getCredentials(callback){if(callback)this.getCredentialsAsync().then(r2=>callback(null,r2),callback);else return this.getCredentialsAsync()}async getCredentialsAsync(){let client=await this.getClient();if(client instanceof impersonated_1.Impersonated)return{client_email:client.getTargetPrincipal()};if(client instanceof baseexternalclient_1.BaseExternalAccountClient){let serviceAccountEmail=client.getServiceAccountEmail();if(serviceAccountEmail)return{client_email:serviceAccountEmail,universe_domain:client.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[client_email,universe_domain]=await Promise.all([gcpMetadata.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email,universe_domain}}throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#pendingAuthClient=this.#pendingAuthClient||this.#determineClient();try{return await this.#pendingAuthClient}finally{this.#pendingAuthClient=null}}async#determineClient(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let filePath=path.resolve(this.keyFilename),stream2=fs2.createReadStream(filePath);return await this.fromStreamAsync(stream2,this.clientOptions)}else if(this.apiKey){let client=await this.fromAPIKey(this.apiKey,this.clientOptions);client.scopes=this.scopes;let{credential}=await this.#prepareAndCacheClient(client);return credential}else{let{credential}=await this.getApplicationDefaultAsync(this.clientOptions);return credential}}async getIdTokenClient(targetAudience){let client=await this.getClient();if(!("fetchIdToken"in client))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new idtokenclient_1.IdTokenClient({targetAudience,idTokenProvider:client})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(url){return(await this.getClient()).getRequestHeaders(url)}async authorizeRequest(opts={}){let url=opts.url,headers=await(await this.getClient()).getRequestHeaders(url);return opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers,headers),opts}async fetch(...args){return(await this.getClient()).fetch(...args)}async request(opts){return(await this.getClient()).request(opts)}getEnv(){return(0,envDetect_1.getEnv)()}async sign(data,endpoint){let client=await this.getClient(),universe=await this.getUniverseDomain();if(endpoint=endpoint||`https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`,client instanceof impersonated_1.Impersonated)return(await client.sign(data)).signedBlob;let crypto2=(0,crypto_1.createCrypto)();if(client instanceof jwtclient_1.JWT&&client.key)return await crypto2.sign(client.key,data);let creds=await this.getCredentials();if(!creds.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(crypto2,creds.client_email,data,endpoint)}async signBlob(crypto2,emailOrUniqueId,data,endpoint){let url=new URL(endpoint+`${emailOrUniqueId}:signBlob`);return(await this.request({method:"POST",url:url.href,data:{payload:crypto2.encodeBase64StringUtf8(data)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};exports.GoogleAuth=GoogleAuth2}});var require_iam=__commonJS({"node_modules/google-auth-library/build/src/auth/iam.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.IAMAuth=void 0;var IAMAuth=class{selector;token;constructor(selector,token){this.selector=selector,this.token=token,this.selector=selector,this.token=token}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};exports.IAMAuth=IAMAuth}});var require_downscopedclient=__commonJS({"node_modules/google-auth-library/build/src/auth/downscopedclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.DownscopedClient=exports.EXPIRATION_TIME_OFFSET=exports.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var gaxios_1=require_src2(),stream2=__require("stream"),authclient_1=require_authclient(),sts=require_stscredentials(),STS_GRANT_TYPE="urn:ietf:params:oauth:grant-type:token-exchange",STS_REQUEST_TOKEN_TYPE="urn:ietf:params:oauth:token-type:access_token",STS_SUBJECT_TOKEN_TYPE="urn:ietf:params:oauth:token-type:access_token";exports.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;exports.EXPIRATION_TIME_OFFSET=300*1e3;var DownscopedClient=class extends authclient_1.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(options,credentialAccessBoundary={accessBoundary:{accessBoundaryRules:[]}}){if(super(options instanceof authclient_1.AuthClient?{}:options),options instanceof authclient_1.AuthClient?(this.authClient=options,this.credentialAccessBoundary=credentialAccessBoundary):(this.authClient=options.authClient,this.credentialAccessBoundary=options.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>exports.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let rule of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(rule.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new sts.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(credentials){if(!credentials.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(credentials),this.cachedDownscopedAccessToken=credentials}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let accessTokenResponse=await this.getAccessToken(),headers=new Headers({authorization:`Bearer ${accessTokenResponse.token}`});return this.addSharedMetadataHeaders(headers)}request(opts,callback){if(callback)this.requestAsync(opts).then(r2=>callback(null,r2),e2=>callback(e2,e2.response));else return this.requestAsync(opts)}async requestAsync(opts,reAuthRetried=!1){let response;try{let requestHeaders=await this.getRequestHeaders();opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers),this.addUserProjectAndAuthHeaders(opts.headers,requestHeaders),response=await this.transporter.request(opts)}catch(e2){let res=e2.response;if(res){let statusCode=res.status,isReadableStream=res.config.data instanceof stream2.Readable;if(!reAuthRetried&&(statusCode===401||statusCode===403)&&!isReadableStream&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(opts,!0)}throw e2}return response}async refreshAccessTokenAsync(){let subjectToken=(await this.authClient.getAccessToken()).token,stsCredentialsOptions={grantType:STS_GRANT_TYPE,requestedTokenType:STS_REQUEST_TOKEN_TYPE,subjectToken,subjectTokenType:STS_SUBJECT_TOKEN_TYPE},stsResponse=await this.stsCredential.exchangeToken(stsCredentialsOptions,void 0,this.credentialAccessBoundary),sourceCredExpireDate=this.authClient.credentials?.expiry_date||null,expiryDate=stsResponse.expires_in?new Date().getTime()+stsResponse.expires_in*1e3:sourceCredExpireDate;return this.cachedDownscopedAccessToken={access_token:stsResponse.access_token,expiry_date:expiryDate,res:stsResponse.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(downscopedAccessToken){let now=new Date().getTime();return downscopedAccessToken.expiry_date?now>=downscopedAccessToken.expiry_date-this.eagerRefreshThresholdMillis:!1}};exports.DownscopedClient=DownscopedClient}});var require_passthrough=__commonJS({"node_modules/google-auth-library/build/src/auth/passthrough.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.PassThroughClient=void 0;var authclient_1=require_authclient(),PassThroughClient=class extends authclient_1.AuthClient{async request(opts){return this.transporter.request(opts)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};exports.PassThroughClient=PassThroughClient}});var require_src5=__commonJS({"node_modules/google-auth-library/build/src/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m2,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m2,k);(!desc||("get"in desc?!m2.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m2[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m2,k,k2){k2===void 0&&(k2=k),o[k2]=m2[k]})),__exportStar=exports&&exports.__exportStar||function(m2,exports2){for(var p in m2)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m2,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.GoogleAuth=exports.auth=exports.PassThroughClient=exports.ExternalAccountAuthorizedUserClient=exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=exports.ExecutableError=exports.PluggableAuthClient=exports.DownscopedClient=exports.BaseExternalAccountClient=exports.ExternalAccountClient=exports.IdentityPoolClient=exports.AwsRequestSigner=exports.AwsClient=exports.UserRefreshClient=exports.LoginTicket=exports.ClientAuthentication=exports.OAuth2Client=exports.CodeChallengeMethod=exports.Impersonated=exports.JWT=exports.JWTAccess=exports.IdTokenClient=exports.IAMAuth=exports.GCPEnv=exports.Compute=exports.DEFAULT_UNIVERSE=exports.AuthClient=exports.gaxios=exports.gcpMetadata=void 0;var googleauth_1=require_googleauth();Object.defineProperty(exports,"GoogleAuth",{enumerable:!0,get:function(){return googleauth_1.GoogleAuth}});exports.gcpMetadata=require_src4();exports.gaxios=require_src2();var authclient_1=require_authclient();Object.defineProperty(exports,"AuthClient",{enumerable:!0,get:function(){return authclient_1.AuthClient}});Object.defineProperty(exports,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return authclient_1.DEFAULT_UNIVERSE}});var computeclient_1=require_computeclient();Object.defineProperty(exports,"Compute",{enumerable:!0,get:function(){return computeclient_1.Compute}});var envDetect_1=require_envDetect();Object.defineProperty(exports,"GCPEnv",{enumerable:!0,get:function(){return envDetect_1.GCPEnv}});var iam_1=require_iam();Object.defineProperty(exports,"IAMAuth",{enumerable:!0,get:function(){return iam_1.IAMAuth}});var idtokenclient_1=require_idtokenclient();Object.defineProperty(exports,"IdTokenClient",{enumerable:!0,get:function(){return idtokenclient_1.IdTokenClient}});var jwtaccess_1=require_jwtaccess();Object.defineProperty(exports,"JWTAccess",{enumerable:!0,get:function(){return jwtaccess_1.JWTAccess}});var jwtclient_1=require_jwtclient();Object.defineProperty(exports,"JWT",{enumerable:!0,get:function(){return jwtclient_1.JWT}});var impersonated_1=require_impersonated();Object.defineProperty(exports,"Impersonated",{enumerable:!0,get:function(){return impersonated_1.Impersonated}});var oauth2client_1=require_oauth2client();Object.defineProperty(exports,"CodeChallengeMethod",{enumerable:!0,get:function(){return oauth2client_1.CodeChallengeMethod}});Object.defineProperty(exports,"OAuth2Client",{enumerable:!0,get:function(){return oauth2client_1.OAuth2Client}});Object.defineProperty(exports,"ClientAuthentication",{enumerable:!0,get:function(){return oauth2client_1.ClientAuthentication}});var loginticket_1=require_loginticket();Object.defineProperty(exports,"LoginTicket",{enumerable:!0,get:function(){return loginticket_1.LoginTicket}});var refreshclient_1=require_refreshclient();Object.defineProperty(exports,"UserRefreshClient",{enumerable:!0,get:function(){return refreshclient_1.UserRefreshClient}});var awsclient_1=require_awsclient();Object.defineProperty(exports,"AwsClient",{enumerable:!0,get:function(){return awsclient_1.AwsClient}});var awsrequestsigner_1=require_awsrequestsigner();Object.defineProperty(exports,"AwsRequestSigner",{enumerable:!0,get:function(){return awsrequestsigner_1.AwsRequestSigner}});var identitypoolclient_1=require_identitypoolclient();Object.defineProperty(exports,"IdentityPoolClient",{enumerable:!0,get:function(){return identitypoolclient_1.IdentityPoolClient}});var externalclient_1=require_externalclient();Object.defineProperty(exports,"ExternalAccountClient",{enumerable:!0,get:function(){return externalclient_1.ExternalAccountClient}});var baseexternalclient_1=require_baseexternalclient();Object.defineProperty(exports,"BaseExternalAccountClient",{enumerable:!0,get:function(){return baseexternalclient_1.BaseExternalAccountClient}});var downscopedclient_1=require_downscopedclient();Object.defineProperty(exports,"DownscopedClient",{enumerable:!0,get:function(){return downscopedclient_1.DownscopedClient}});var pluggable_auth_client_1=require_pluggable_auth_client();Object.defineProperty(exports,"PluggableAuthClient",{enumerable:!0,get:function(){return pluggable_auth_client_1.PluggableAuthClient}});Object.defineProperty(exports,"ExecutableError",{enumerable:!0,get:function(){return pluggable_auth_client_1.ExecutableError}});var externalAccountAuthorizedUserClient_1=require_externalAccountAuthorizedUserClient();Object.defineProperty(exports,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(exports,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient}});var passthrough_1=require_passthrough();Object.defineProperty(exports,"PassThroughClient",{enumerable:!0,get:function(){return passthrough_1.PassThroughClient}});__exportStar(require_googleToken(),exports);var auth=new googleauth_1.GoogleAuth;exports.auth=auth}});var require_constants=__commonJS({"node_modules/ws/lib/constants.js"(exports,module){"use strict";var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"],hasBlob=typeof Blob<"u";hasBlob&&BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports,module){"use strict";var{EMPTY_BUFFER}=require_constants(),FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];let target=Buffer.allocUnsafe(totalLength),offset=0;for(let i2=0;i2<list.length;i2++){let buf=list[i2];target.set(buf,offset),offset+=buf.length}return offset<totalLength?new FastBuffer(target.buffer,target.byteOffset,offset):target}function _mask(source,mask,output,offset,length){for(let i2=0;i2<length;i2++)output[offset+i2]=source[i2]^mask[i2&3]}function _unmask(buffer,mask){for(let i2=0;i2<buffer.length;i2++)buffer[i2]^=mask[i2&3]}function toArrayBuffer(buf){return buf.length===buf.buffer.byteLength?buf.buffer:buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){if(toBuffer.readOnly=!0,Buffer.isBuffer(data))return data;let buf;return data instanceof ArrayBuffer?buf=new FastBuffer(data):ArrayBuffer.isView(data)?buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength):(buf=Buffer.from(data),toBuffer.readOnly=!1),buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL)try{let bufferUtil=__require("bufferutil");module.exports.mask=function(source,mask,output,offset,length){length<48?_mask(source,mask,output,offset,length):bufferUtil.mask(source,mask,output,offset,length)},module.exports.unmask=function(buffer,mask){buffer.length<32?_unmask(buffer,mask):bufferUtil.unmask(buffer,mask)}}catch{}}});var require_limiter=__commonJS({"node_modules/ws/lib/limiter.js"(exports,module){"use strict";var kDone=Symbol("kDone"),kRun=Symbol("kRun"),Limiter=class{constructor(concurrency){this[kDone]=()=>{this.pending--,this[kRun]()},this.concurrency=concurrency||1/0,this.jobs=[],this.pending=0}add(job){this.jobs.push(job),this[kRun]()}[kRun](){if(this.pending!==this.concurrency&&this.jobs.length){let job=this.jobs.shift();this.pending++,job(this[kDone])}}};module.exports=Limiter}});var require_permessage_deflate=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports,module){"use strict";var zlib2=__require("zlib"),bufferUtil=require_buffer_util(),Limiter=require_limiter(),{kStatusCode}=require_constants(),FastBuffer=Buffer[Symbol.species],TRAILER=Buffer.from([0,0,255,255]),kPerMessageDeflate=Symbol("permessage-deflate"),kTotalLength=Symbol("total-length"),kCallback=Symbol("callback"),kBuffers=Symbol("buffers"),kError=Symbol("error"),zlibLimiter,PerMessageDeflate2=class{constructor(options){if(this._options=options||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!zlibLimiter){let concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){let params={};return this._options.serverNoContextTakeover&&(params.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(params.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(params.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?params.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(params.client_max_window_bits=!0),params}accept(configurations){return configurations=this.normalizeParams(configurations),this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let callback=this._deflate[kCallback];this._deflate.close(),this._deflate=null,callback&&callback(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(offers){let opts=this._options,accepted=offers.find(params=>!(opts.serverNoContextTakeover===!1&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===!1||typeof opts.serverMaxWindowBits=="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits=="number"&&!params.client_max_window_bits));if(!accepted)throw new Error("None of the extension offers can be accepted");return opts.serverNoContextTakeover&&(accepted.server_no_context_takeover=!0),opts.clientNoContextTakeover&&(accepted.client_no_context_takeover=!0),typeof opts.serverMaxWindowBits=="number"&&(accepted.server_max_window_bits=opts.serverMaxWindowBits),typeof opts.clientMaxWindowBits=="number"?accepted.client_max_window_bits=opts.clientMaxWindowBits:(accepted.client_max_window_bits===!0||opts.clientMaxWindowBits===!1)&&delete accepted.client_max_window_bits,accepted}acceptAsClient(response){let params=response[0];if(this._options.clientNoContextTakeover===!1&¶ms.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!params.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(params.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return params}normalizeParams(configurations){return configurations.forEach(params=>{Object.keys(params).forEach(key=>{let value=params[key];if(value.length>1)throw new Error(`Parameter "${key}" must have only a single value`);if(value=value[0],key==="client_max_window_bits"){if(value!==!0){let num=+value;if(!Number.isInteger(num)||num<8||num>15)throw new TypeError(`Invalid value for parameter "${key}": ${value}`);value=num}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}else if(key==="server_max_window_bits"){let num=+value;if(!Number.isInteger(num)||num<8||num>15)throw new TypeError(`Invalid value for parameter "${key}": ${value}`);value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==!0)throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}else throw new Error(`Unknown parameter "${key}"`);params[key]=value})}),configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err,result)=>{done(),callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err,result)=>{done(),callback(err,result)})})}_decompress(data,fin,callback){let endpoint=this._isServer?"client":"server";if(!this._inflate){let key=`${endpoint}_max_window_bits`,windowBits=typeof this.params[key]!="number"?zlib2.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib2.createInflateRaw({...this._options.zlibInflateOptions,windowBits}),this._inflate[kPerMessageDeflate]=this,this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],this._inflate.on("error",inflateOnError),this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback,this._inflate.write(data),fin&&this._inflate.write(TRAILER),this._inflate.flush(()=>{let err=this._inflate[kError];if(err){this._inflate.close(),this._inflate=null,callback(err);return}let data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],fin&&this.params[`${endpoint}_no_context_takeover`]&&this._inflate.reset()),callback(null,data2)})}_compress(data,fin,callback){let endpoint=this._isServer?"server":"client";if(!this._deflate){let key=`${endpoint}_max_window_bits`,windowBits=typeof this.params[key]!="number"?zlib2.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib2.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits}),this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback,this._deflate.write(data),this._deflate.flush(zlib2.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);fin&&(data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)),this._deflate[kCallback]=null,this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],fin&&this.params[`${endpoint}_no_context_takeover`]&&this._deflate.reset(),callback(null,data2)})}};module.exports=PerMessageDeflate2;function deflateOnData(chunk){this[kBuffers].push(chunk),this[kTotalLength]+=chunk.length}function inflateOnData(chunk){if(this[kTotalLength]+=chunk.length,this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded"),this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[kError][kStatusCode]=1009,this.removeListener("data",inflateOnData),this.reset()}function inflateOnError(err){if(this[kPerMessageDeflate]._inflate=null,this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007,this[kCallback](err)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports,module){"use strict";var{isUtf8}=__require("buffer"),{hasBlob}=require_constants(),tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){let len=buf.length,i2=0;for(;i2<len;)if((buf[i2]&128)===0)i2++;else if((buf[i2]&224)===192){if(i2+1===len||(buf[i2+1]&192)!==128||(buf[i2]&254)===192)return!1;i2+=2}else if((buf[i2]&240)===224){if(i2+2>=len||(buf[i2+1]&192)!==128||(buf[i2+2]&192)!==128||buf[i2]===224&&(buf[i2+1]&224)===128||buf[i2]===237&&(buf[i2+1]&224)===160)return!1;i2+=3}else if((buf[i2]&248)===240){if(i2+3>=len||(buf[i2+1]&192)!==128||(buf[i2+2]&192)!==128||(buf[i2+3]&192)!==128||buf[i2]===240&&(buf[i2+1]&240)===128||buf[i2]===244&&buf[i2+1]>143||buf[i2]>244)return!1;i2+=4}else return!1;return!0}function isBlob2(value){return hasBlob&&typeof value=="object"&&typeof value.arrayBuffer=="function"&&typeof value.type=="string"&&typeof value.stream=="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob:isBlob2,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8)module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let isValidUTF8=__require("utf-8-validate");module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch{}}});var require_receiver=__commonJS({"node_modules/ws/lib/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream"),PerMessageDeflate2=require_permessage_deflate(),{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants(),{concat,toArrayBuffer,unmask}=require_buffer_util(),{isValidStatusCode,isValidUTF8}=require_validation(),FastBuffer=Buffer[Symbol.species],GET_INFO=0,GET_PAYLOAD_LENGTH_16=1,GET_PAYLOAD_LENGTH_64=2,GET_MASK=3,GET_DATA=4,INFLATING=5,DEFER_EVENT=6,Receiver2=class extends Writable{constructor(options={}){super(),this._allowSynchronousEvents=options.allowSynchronousEvents!==void 0?options.allowSynchronousEvents:!0,this._binaryType=options.binaryType||BINARY_TYPES[0],this._extensions=options.extensions||{},this._isServer=!!options.isServer,this._maxBufferedChunks=options.maxBufferedChunks|0,this._maxFragments=options.maxFragments|0,this._maxPayload=options.maxPayload|0,this._skipUTF8Validation=!!options.skipUTF8Validation,this[kWebSocket]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length,this._buffers.push(chunk),this.startLoop(cb)}consume(n){if(this._bufferedBytes-=n,n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){let buf=this._buffers[0];return this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n),new FastBuffer(buf.buffer,buf.byteOffset,n)}let dst=Buffer.allocUnsafe(n);do{let buf=this._buffers[0],offset=dst.length-n;n>=buf.length?dst.set(this._buffers.shift(),offset):(dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset),this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)),n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=!0;do switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=!1;return}while(this._loop);this._errored||cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=!1;return}let buf=this.consume(2);if((buf[0]&48)!==0){let error=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}let compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate2.extensionName]){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._fin=(buf[0]&128)===128,this._opcode=buf[0]&15,this._payloadLength=buf[1]&127,this._opcode===0){if(compressed){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){let error=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let error=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let error=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{let error=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(buf[1]&128)===128,this._isServer){if(!this._masked){let error=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){let error=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}this._payloadLength===126?this._state=GET_PAYLOAD_LENGTH_16:this._payloadLength===127?this._state=GET_PAYLOAD_LENGTH_64:this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=!1;return}let buf=this.consume(8),num=buf.readUInt32BE(0);if(num>Math.pow(2,21)-1){let error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4),this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let error=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._masked?this._state=GET_MASK:this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}data=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&unmask(data,this._mask)}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._compressed){this._state=INFLATING,this.decompress(data,cb);return}if(data.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let error=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}this._messageLength=this._totalPayloadLength,this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){this._extensions[PerMessageDeflate2.extensionName].decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){if(this._messageLength+=buf.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let error=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let error=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb),this._state===GET_INFO&&this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}let messageLength=this._messageLength,fragments=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let data;this._binaryType==="nodebuffer"?data=concat(fragments,messageLength):this._binaryType==="arraybuffer"?data=toArrayBuffer(concat(fragments,messageLength)):this._binaryType==="blob"?data=new Blob(fragments):data=fragments,this._allowSynchronousEvents?(this.emit("message",data,!0),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit("message",data,!0),this._state=GET_INFO,this.startLoop(cb)}))}else{let buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){let error=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._state===INFLATING||this._allowSynchronousEvents?(this.emit("message",buf,!1),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit("message",buf,!1),this._state=GET_INFO,this.startLoop(cb)}))}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0)this._loop=!1,this.emit("conclude",1005,EMPTY_BUFFER),this.end();else{let code=data.readUInt16BE(0);if(!isValidStatusCode(code)){let error=this.createError(RangeError,`invalid status code ${code}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}let buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){let error=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=!1,this.emit("conclude",code,buf),this.end()}this._state=GET_INFO;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",data),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data),this._state=GET_INFO,this.startLoop(cb)}))}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=!1,this._errored=!0;let err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);return Error.captureStackTrace(err,this.createError),err.code=errorCode,err[kStatusCode]=statusCode,err}};module.exports=Receiver2}});var require_sender=__commonJS({"node_modules/ws/lib/sender.js"(exports,module){"use strict";var{Duplex}=__require("stream"),{randomFillSync}=__require("crypto"),{types:{isUint8Array}}=__require("util"),PerMessageDeflate2=require_permessage_deflate(),{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants(),{isBlob:isBlob2,isValidStatusCode}=require_validation(),{mask:applyMask,toBuffer}=require_buffer_util(),kByteLength=Symbol("kByteLength"),maskBuffer=Buffer.alloc(4),RANDOM_POOL_SIZE=8*1024,randomPool,randomPoolPointer=RANDOM_POOL_SIZE,DEFAULT=0,DEFLATING=1,GET_BLOB_DATA=2,Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{},generateMask&&(this._generateMask=generateMask,this._maskBuffer=Buffer.alloc(4)),this._socket=socket,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=DEFAULT,this.onerror=NOOP,this[kWebSocket]=void 0}static frame(data,options){let mask,merge=!1,offset=2,skipMasking=!1;options.mask&&(mask=options.maskBuffer||maskBuffer,options.generateMask?options.generateMask(mask):(randomPoolPointer===RANDOM_POOL_SIZE&&(randomPool===void 0&&(randomPool=Buffer.alloc(RANDOM_POOL_SIZE)),randomFillSync(randomPool,0,RANDOM_POOL_SIZE),randomPoolPointer=0),mask[0]=randomPool[randomPoolPointer++],mask[1]=randomPool[randomPoolPointer++],mask[2]=randomPool[randomPoolPointer++],mask[3]=randomPool[randomPoolPointer++]),skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0,offset=6);let dataLength;typeof data=="string"?(!options.mask||skipMasking)&&options[kByteLength]!==void 0?dataLength=options[kByteLength]:(data=Buffer.from(data),dataLength=data.length):(dataLength=data.length,merge=options.mask&&options.readOnly&&!skipMasking);let payloadLength=dataLength;dataLength>=65536?(offset+=8,payloadLength=127):dataLength>125&&(offset+=2,payloadLength=126);let target=Buffer.allocUnsafe(merge?dataLength+offset:offset);return target[0]=options.fin?options.opcode|128:options.opcode,options.rsv1&&(target[0]|=64),target[1]=payloadLength,payloadLength===126?target.writeUInt16BE(dataLength,2):payloadLength===127&&(target[2]=target[3]=0,target.writeUIntBE(dataLength,4,6)),options.mask?(target[1]|=128,target[offset-4]=mask[0],target[offset-3]=mask[1],target[offset-2]=mask[2],target[offset-1]=mask[3],skipMasking?[target,data]:merge?(applyMask(data,mask,target,offset,dataLength),[target]):(applyMask(data,mask,data,0,dataLength),[target,data])):[target,data]}close(code,data,mask,cb){let buf;if(code===void 0)buf=EMPTY_BUFFER;else{if(typeof code!="number"||!isValidStatusCode(code))throw new TypeError("First argument must be a valid error code number");if(data===void 0||!data.length)buf=Buffer.allocUnsafe(2),buf.writeUInt16BE(code,0);else{let length=Buffer.byteLength(data);if(length>123)throw new RangeError("The message must not be greater than 123 bytes");if(buf=Buffer.allocUnsafe(2+length),buf.writeUInt16BE(code,0),typeof data=="string")buf.write(data,2);else if(isUint8Array(data))buf.set(data,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let options={[kByteLength]:buf.length,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==DEFAULT?this.enqueue([this.dispatch,buf,!1,options,cb]):this.sendFrame(_Sender.frame(buf,options),cb)}ping(data,mask,cb){let byteLength,readOnly;if(typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob2(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),byteLength>125)throw new RangeError("The data size must not be greater than 125 bytes");let options={[kByteLength]:byteLength,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:!1};isBlob2(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,!1,options,cb]):this.getBlobData(data,!1,options,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,!1,options,cb]):this.sendFrame(_Sender.frame(data,options),cb)}pong(data,mask,cb){let byteLength,readOnly;if(typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob2(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),byteLength>125)throw new RangeError("The data size must not be greater than 125 bytes");let options={[kByteLength]:byteLength,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:!1};isBlob2(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,!1,options,cb]):this.getBlobData(data,!1,options,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,!1,options,cb]):this.sendFrame(_Sender.frame(data,options),cb)}send(data,options,cb){let perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName],opcode=options.binary?2:1,rsv1=options.compress,byteLength,readOnly;typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob2(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),this._firstFragment?(this._firstFragment=!1,rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(rsv1=byteLength>=perMessageDeflate._threshold),this._compress=rsv1):(rsv1=!1,opcode=0),options.fin&&(this._firstFragment=!0);let opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};isBlob2(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,this._compress,opts,cb]):this.getBlobData(data,this._compress,opts,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,this._compress,opts,cb]):this.dispatch(data,this._compress,opts,cb)}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength],this._state=GET_BLOB_DATA,blob.arrayBuffer().then(arrayBuffer=>{if(this._socket.destroyed){let err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];let data=toBuffer(arrayBuffer);compress?this.dispatch(data,compress,options,cb):(this._state=DEFAULT,this.sendFrame(_Sender.frame(data,options),cb),this.dequeue())}).catch(err=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}let perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];this._bufferedBytes+=options[kByteLength],this._state=DEFLATING,perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){let err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength],this._state=DEFAULT,options.readOnly=!1,this.sendFrame(_Sender.frame(buf,options),cb),this.dequeue()})}dequeue(){for(;this._state===DEFAULT&&this._queue.length;){let params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength],Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength],this._queue.push(params)}sendFrame(list,cb){list.length===2?(this._socket.cork(),this._socket.write(list[0]),this._socket.write(list[1],cb),this._socket.uncork()):this._socket.write(list[0],cb)}};module.exports=Sender2;function callCallbacks(sender,err,cb){typeof cb=="function"&&cb(err);for(let i2=0;i2<sender._queue.length;i2++){let params=sender._queue[i2],callback=params[params.length-1];typeof callback=="function"&&callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb),sender.onerror(err)}}});var require_event_target=__commonJS({"node_modules/ws/lib/event-target.js"(exports,module){"use strict";var{kForOnEventAttribute,kListener}=require_constants(),kCode=Symbol("kCode"),kData=Symbol("kData"),kError=Symbol("kError"),kMessage=Symbol("kMessage"),kReason=Symbol("kReason"),kTarget=Symbol("kTarget"),kType=Symbol("kType"),kWasClean=Symbol("kWasClean"),Event=class{constructor(type){this[kTarget]=null,this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}};Object.defineProperty(Event.prototype,"target",{enumerable:!0});Object.defineProperty(Event.prototype,"type",{enumerable:!0});var CloseEvent=class extends Event{constructor(type,options={}){super(type),this[kCode]=options.code===void 0?0:options.code,this[kReason]=options.reason===void 0?"":options.reason,this[kWasClean]=options.wasClean===void 0?!1:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}};Object.defineProperty(CloseEvent.prototype,"code",{enumerable:!0});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:!0});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:!0});var ErrorEvent=class extends Event{constructor(type,options={}){super(type),this[kError]=options.error===void 0?null:options.error,this[kMessage]=options.message===void 0?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}};Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:!0});var MessageEvent=class extends Event{constructor(type,options={}){super(type),this[kData]=options.data===void 0?null:options.data}get data(){return this[kData]}};Object.defineProperty(MessageEvent.prototype,"data",{enumerable:!0});var EventTarget={addEventListener(type,handler,options={}){for(let listener of this.listeners(type))if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute])return;let wrapper;if(type==="message")wrapper=function(data,isBinary){let event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this,callListener(handler,this,event)};else if(type==="close")wrapper=function(code,message){let event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this,callListener(handler,this,event)};else if(type==="error")wrapper=function(error){let event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this,callListener(handler,this,event)};else if(type==="open")wrapper=function(){let event=new Event("open");event[kTarget]=this,callListener(handler,this,event)};else return;wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute],wrapper[kListener]=handler,options.once?this.once(type,wrapper):this.on(type,wrapper)},removeEventListener(type,handler){for(let listener of this.listeners(type))if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){typeof listener=="object"&&listener.handleEvent?listener.handleEvent.call(listener,event):listener.call(thisArg,event)}}});var require_extension=__commonJS({"node_modules/ws/lib/extension.js"(exports,module){"use strict";var{tokenChars}=require_validation();function push(dest,name,elem){dest[name]===void 0?dest[name]=[elem]:dest[name].push(elem)}function parse(header){let offers=Object.create(null),params=Object.create(null),mustUnescape=!1,isEscaping=!1,inQuotes=!1,extensionName,paramName,start=-1,code=-1,end=-1,i2=0;for(;i2<header.length;i2++)if(code=header.charCodeAt(i2),extensionName===void 0)if(end===-1&&tokenChars[code]===1)start===-1&&(start=i2);else if(i2!==0&&(code===32||code===9))end===-1&&start!==-1&&(end=i2);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i2}`);end===-1&&(end=i2);let name=header.slice(start,end);code===44?(push(offers,name,params),params=Object.create(null)):extensionName=name,start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i2}`);else if(paramName===void 0)if(end===-1&&tokenChars[code]===1)start===-1&&(start=i2);else if(code===32||code===9)end===-1&&start!==-1&&(end=i2);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i2}`);end===-1&&(end=i2),push(params,header.slice(start,end),!0),code===44&&(push(offers,extensionName,params),params=Object.create(null),extensionName=void 0),start=end=-1}else if(code===61&&start!==-1&&end===-1)paramName=header.slice(start,i2),start=end=-1;else throw new SyntaxError(`Unexpected character at index ${i2}`);else if(isEscaping){if(tokenChars[code]!==1)throw new SyntaxError(`Unexpected character at index ${i2}`);start===-1?start=i2:mustUnescape||(mustUnescape=!0),isEscaping=!1}else if(inQuotes)if(tokenChars[code]===1)start===-1&&(start=i2);else if(code===34&&start!==-1)inQuotes=!1,end=i2;else if(code===92)isEscaping=!0;else throw new SyntaxError(`Unexpected character at index ${i2}`);else if(code===34&&header.charCodeAt(i2-1)===61)inQuotes=!0;else if(end===-1&&tokenChars[code]===1)start===-1&&(start=i2);else if(start!==-1&&(code===32||code===9))end===-1&&(end=i2);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i2}`);end===-1&&(end=i2);let value=header.slice(start,end);mustUnescape&&(value=value.replace(/\\/g,""),mustUnescape=!1),push(params,paramName,value),code===44&&(push(offers,extensionName,params),params=Object.create(null),extensionName=void 0),paramName=void 0,start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i2}`);if(start===-1||inQuotes||code===32||code===9)throw new SyntaxError("Unexpected end of input");end===-1&&(end=i2);let token=header.slice(start,end);return extensionName===void 0?push(offers,token,params):(paramName===void 0?push(params,token,!0):mustUnescape?push(params,paramName,token.replace(/\\/g,"")):push(params,paramName,token),push(offers,extensionName,params)),offers}function format(extensions){return Object.keys(extensions).map(extension2=>{let configurations=extensions[extension2];return Array.isArray(configurations)||(configurations=[configurations]),configurations.map(params=>[extension2].concat(Object.keys(params).map(k=>{let values=params[k];return Array.isArray(values)||(values=[values]),values.map(v=>v===!0?k:`${k}=${v}`).join("; ")})).join("; ")).join(", ")}).join(", ")}module.exports={format,parse}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter=__require("events"),https2=__require("https"),http3=__require("http"),net=__require("net"),tls=__require("tls"),{randomBytes,createHash}=__require("crypto"),{Duplex,Readable}=__require("stream"),{URL:URL2}=__require("url"),PerMessageDeflate2=require_permessage_deflate(),Receiver2=require_receiver(),Sender2=require_sender(),{isBlob:isBlob2}=require_validation(),{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants(),{EventTarget:{addEventListener,removeEventListener}}=require_event_target(),{format,parse}=require_extension(),{toBuffer}=require_buffer_util(),kAborted=Symbol("kAborted"),protocolVersions=[8,13],readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"],subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,WebSocket2=class _WebSocket extends EventEmitter{constructor(address,protocols,options){super(),this._binaryType=BINARY_TYPES[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=EMPTY_BUFFER,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=_WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,address!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,protocols===void 0?protocols=[]:Array.isArray(protocols)||(typeof protocols=="object"&&protocols!==null?(options=protocols,protocols=[]):protocols=[protocols]),initAsClient(this,address,protocols,options)):(this._autoPong=options.autoPong,this._closeTimeout=options.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(type){BINARY_TYPES.includes(type)&&(this._binaryType=type,this._receiver&&(this._receiver._binaryType=type))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){let receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation}),sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver,this._sender=sender,this._socket=socket,receiver[kWebSocket]=this,sender[kWebSocket]=this,socket[kWebSocket]=this,receiver.on("conclude",receiverOnConclude),receiver.on("drain",receiverOnDrain),receiver.on("error",receiverOnError),receiver.on("message",receiverOnMessage),receiver.on("ping",receiverOnPing),receiver.on("pong",receiverOnPong),sender.onerror=senderOnError,socket.setTimeout&&socket.setTimeout(0),socket.setNoDelay&&socket.setNoDelay(),head.length>0&&socket.unshift(head),socket.on("close",socketOnClose),socket.on("data",socketOnData),socket.on("end",socketOnEnd),socket.on("error",socketOnError),this._readyState=_WebSocket.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[PerMessageDeflate2.extensionName]&&this._extensions[PerMessageDeflate2.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===_WebSocket.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=_WebSocket.CLOSING,this._sender.close(code,data,!this._isServer,err=>{err||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),setCloseTimer(this)}}pause(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!0,this._socket.pause())}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof options=="function"&&(cb=options,options={}),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}let opts={binary:typeof data!="string",mask:!this._isServer,compress:!0,fin:!0,...options};this._extensions[PerMessageDeflate2.extensionName]||(opts.compress=!1),this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=_WebSocket.CLOSING,this._socket.destroy())}}};Object.defineProperty(WebSocket2,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2.prototype,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2.prototype,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2.prototype,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket2.prototype,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket2.prototype,property,{enumerable:!0})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket2.prototype,`on${method}`,{enumerable:!0,get(){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute])return listener[kListener];return null},set(handler){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}typeof handler=="function"&&this.addEventListener(method,handler,{[kForOnEventAttribute]:!0})}})});WebSocket2.prototype.addEventListener=addEventListener;WebSocket2.prototype.removeEventListener=removeEventListener;module.exports=WebSocket2;function initAsClient(websocket,address,protocols,options){let opts={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(websocket._autoPong=opts.autoPong,websocket._closeTimeout=opts.closeTimeout,!protocolVersions.includes(opts.protocolVersion))throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);let parsedUrl;if(address instanceof URL2)parsedUrl=address;else try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}parsedUrl.protocol==="http:"?parsedUrl.protocol="ws:":parsedUrl.protocol==="https:"&&(parsedUrl.protocol="wss:"),websocket._url=parsedUrl.href;let isSecure=parsedUrl.protocol==="wss:",isIpcUrl=parsedUrl.protocol==="ws+unix:",invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl?invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:isIpcUrl&&!parsedUrl.pathname?invalidUrlMessage="The URL's pathname is empty":parsedUrl.hash&&(invalidUrlMessage="The URL contains a fragment identifier"),invalidUrlMessage){let err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0)throw err;emitErrorAndClose(websocket,err);return}let defaultPort=isSecure?443:80,key=randomBytes(16).toString("base64"),request=isSecure?https2.request:http3.request,protocolSet=new Set,perMessageDeflate;if(opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect),opts.defaultPort=opts.defaultPort||defaultPort,opts.port=parsedUrl.port||defaultPort,opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname,opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"},opts.path=parsedUrl.pathname+parsedUrl.search,opts.timeout=opts.handshakeTimeout,opts.perMessageDeflate&&(perMessageDeflate=new PerMessageDeflate2({...opts.perMessageDeflate,isServer:!1,maxPayload:opts.maxPayload}),opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})),protocols.length){for(let protocol of protocols){if(typeof protocol!="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol))throw new SyntaxError("An invalid or duplicated subprotocol was specified");protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin&&(opts.protocolVersion<13?opts.headers["Sec-WebSocket-Origin"]=opts.origin:opts.headers.Origin=opts.origin),(parsedUrl.username||parsedUrl.password)&&(opts.auth=`${parsedUrl.username}:${parsedUrl.password}`),isIpcUrl){let parts=opts.path.split(":");opts.socketPath=parts[0],opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl,websocket._originalSecure=isSecure,websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;let headers=options&&options.headers;if(options={...options,headers:{}},headers)for(let[key2,value]of Object.entries(headers))options.headers[key2.toLowerCase()]=value}else if(websocket.listenerCount("redirect")===0){let isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:!1:websocket._originalIpc?!1:parsedUrl.host===websocket._originalHostOrSocketPath;(!isSameHost||websocket._originalSecure&&!isSecure)&&(delete opts.headers.authorization,delete opts.headers.cookie,isSameHost||delete opts.headers.host,opts.auth=void 0)}opts.auth&&!options.headers.authorization&&(options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")),req=websocket._req=request(opts),websocket._redirects&&websocket.emit("redirect",websocket.url,req)}else req=websocket._req=request(opts);opts.timeout&&req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")}),req.on("error",err=>{req===null||req[kAborted]||(req=websocket._req=null,emitErrorAndClose(websocket,err))}),req.on("response",res=>{let location=res.headers.location,statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address)}catch{let err=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else websocket.emit("unexpected-response",req,res)||abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}),req.on("upgrade",(res,socket,head)=>{if(websocket.emit("upgrade",res),websocket.readyState!==WebSocket2.CONNECTING)return;req=websocket._req=null;let upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}let digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}let serverProt=res.headers["sec-websocket-protocol"],protError;if(serverProt!==void 0?protocolSet.size?protocolSet.has(serverProt)||(protError="Server sent an invalid subprotocol"):protError="Server sent a subprotocol but none was requested":protocolSet.size&&(protError="Server sent no subprotocol"),protError){abortHandshake(websocket,socket,protError);return}serverProt&&(websocket._protocol=serverProt);let secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){abortHandshake(websocket,socket,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}let extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){abortHandshake(websocket,socket,"Server indicated an extension that was not requested");return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})}),opts.finishRequest?opts.finishRequest(req,websocket):req.end()}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket2.CLOSING,websocket._errorEmitted=!0,websocket.emit("error",err),websocket.emitClose()}function netConnect(options){return options.path=options.socketPath,net.connect(options)}function tlsConnect(options){return options.path=void 0,!options.servername&&options.servername!==""&&(options.servername=net.isIP(options.host)?"":options.host),tls.connect(options)}function abortHandshake(websocket,stream2,message){websocket._readyState=WebSocket2.CLOSING;let err=new Error(message);Error.captureStackTrace(err,abortHandshake),stream2.setHeader?(stream2[kAborted]=!0,stream2.abort(),stream2.socket&&!stream2.socket.destroyed&&stream2.socket.destroy(),process.nextTick(emitErrorAndClose,websocket,err)):(stream2.destroy(err),stream2.once("error",websocket.emit.bind(websocket,"error")),stream2.once("close",websocket.emitClose.bind(websocket)))}function sendAfterClose(websocket,data,cb){if(data){let length=isBlob2(data)?data.size:toBuffer(data).length;websocket._socket?websocket._sender._bufferedBytes+=length:websocket._bufferedAmount+=length}if(cb){let err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){let websocket=this[kWebSocket];websocket._closeFrameReceived=!0,websocket._closeMessage=reason,websocket._closeCode=code,websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),code===1005?websocket.close():websocket.close(code,reason))}function receiverOnDrain(){let websocket=this[kWebSocket];websocket.isPaused||websocket._socket.resume()}function receiverOnError(err){let websocket=this[kWebSocket];websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),websocket.close(err[kStatusCode])),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err))}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){let websocket=this[kWebSocket];websocket._autoPong&&websocket.pong(data,!this._isServer,NOOP),websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream2){stream2.resume()}function senderOnError(err){let websocket=this[kWebSocket];websocket.readyState!==WebSocket2.CLOSED&&(websocket.readyState===WebSocket2.OPEN&&(websocket._readyState=WebSocket2.CLOSING,setCloseTimer(websocket)),this._socket.end(),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err)))}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){let websocket=this[kWebSocket];if(this.removeListener("close",socketOnClose),this.removeListener("data",socketOnData),this.removeListener("end",socketOnEnd),websocket._readyState=WebSocket2.CLOSING,!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){let chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end(),this[kWebSocket]=void 0,clearTimeout(websocket._closeTimer),websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted?websocket.emitClose():(websocket._receiver.on("error",receiverOnFinish),websocket._receiver.on("finish",receiverOnFinish))}function socketOnData(chunk){this[kWebSocket]._receiver.write(chunk)||this.pause()}function socketOnEnd(){let websocket=this[kWebSocket];websocket._readyState=WebSocket2.CLOSING,websocket._receiver.end(),this.end()}function socketOnError(){let websocket=this[kWebSocket];this.removeListener("error",socketOnError),this.on("error",NOOP),websocket&&(websocket._readyState=WebSocket2.CLOSING,this.destroy())}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket2=require_websocket(),{Duplex}=__require("stream");function emitClose(stream2){stream2.emit("close")}function duplexOnEnd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function duplexOnError(err){this.removeListener("error",duplexOnError),this.destroy(),this.listenerCount("error")===0&&this.emit("error",err)}function createWebSocketStream2(ws,options){let terminateOnDestroy=!0,duplex=new Duplex({...options,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return ws.on("message",function(msg,isBinary){let data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;duplex.push(data)||ws.pause()}),ws.once("error",function(err){duplex.destroyed||(terminateOnDestroy=!1,duplex.destroy(err))}),ws.once("close",function(){duplex.destroyed||duplex.push(null)}),duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err),process.nextTick(emitClose,duplex);return}let called=!1;ws.once("error",function(err2){called=!0,callback(err2)}),ws.once("close",function(){called||callback(err),process.nextTick(emitClose,duplex)}),terminateOnDestroy&&ws.terminate()},duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._final(callback)});return}ws._socket!==null&&(ws._socket._writableState.finished?(callback(),duplex._readableState.endEmitted&&duplex.destroy()):(ws._socket.once("finish",function(){callback()}),ws.close()))},duplex._read=function(){ws.isPaused&&ws.resume()},duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)},duplex.on("end",duplexOnEnd),duplex.on("error",duplexOnError),duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse(header){let protocols=new Set,start=-1,end=-1,i2=0;for(i2;i2<header.length;i2++){let code=header.charCodeAt(i2);if(end===-1&&tokenChars[code]===1)start===-1&&(start=i2);else if(i2!==0&&(code===32||code===9))end===-1&&start!==-1&&(end=i2);else if(code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i2}`);end===-1&&(end=i2);let protocol2=header.slice(start,end);if(protocols.has(protocol2))throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);protocols.add(protocol2),start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i2}`)}if(start===-1||end!==-1)throw new SyntaxError("Unexpected end of input");let protocol=header.slice(start,i2);if(protocols.has(protocol))throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);return protocols.add(protocol),protocols}module.exports={parse}}});var require_websocket_server=__commonJS({"node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter=__require("events"),http3=__require("http"),{Duplex}=__require("stream"),{createHash}=__require("crypto"),extension2=require_extension(),PerMessageDeflate2=require_permessage_deflate(),subprotocol2=require_subprotocol(),WebSocket2=require_websocket(),{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants(),keyRegex=/^[+/0-9A-Za-z]{22}==$/,RUNNING=0,CLOSING=1,CLOSED=2,WebSocketServer2=class extends EventEmitter{constructor(options,callback){if(super(),options={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:WebSocket2,...options},options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(options.port!=null?(this._server=http3.createServer((req,res)=>{let body=http3.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"}),res.end(body)}),this._server.listen(options.port,options.host,options.backlog,callback)):options.server&&(this._server=options.server),this._server){let emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}options.perMessageDeflate===!0&&(options.perMessageDeflate={}),options.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=options,this._state=RUNNING}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(cb){if(this._state===CLOSED){cb&&this.once("close",()=>{cb(new Error("The server is not running"))}),process.nextTick(emitClose,this);return}if(cb&&this.once("close",cb),this._state!==CLOSING)if(this._state=CLOSING,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(emitClose,this):process.nextTick(emitClose,this);else{let server=this._server;this._removeListeners(),this._removeListeners=this._server=null,server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){let index=req.url.indexOf("?");if((index!==-1?req.url.slice(0,index):req.url)!==this.options.path)return!1}return!0}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);let key=req.headers["sec-websocket-key"],upgrade=req.headers.upgrade,version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){abortHandshakeOrEmitwsClientError(this,req,socket,405,"Invalid HTTP method");return}if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid Upgrade header");return}if(key===void 0||!keyRegex.test(key)){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Missing or invalid Sec-WebSocket-Key header");return}if(version!==13&&version!==8){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}let secWebSocketProtocol=req.headers["sec-websocket-protocol"],protocols=new Set;if(secWebSocketProtocol!==void 0)try{protocols=subprotocol2.parse(secWebSocketProtocol)}catch{abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid Sec-WebSocket-Protocol header");return}let secWebSocketExtensions=req.headers["sec-websocket-extensions"],extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){let perMessageDeflate=new PerMessageDeflate2({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let offers=extension2.parse(secWebSocketExtensions);offers[PerMessageDeflate2.extensionName]&&(perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]),extensions[PerMessageDeflate2.extensionName]=perMessageDeflate)}catch{abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified)return abortHandshake(socket,code||401,message,headers);this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>RUNNING)return abortHandshake(socket,503);let headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${createHash("sha1").update(key+GUID).digest("base64")}`],ws=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){let protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;protocol&&(headers.push(`Sec-WebSocket-Protocol: ${protocol}`),ws._protocol=protocol)}if(extensions[PerMessageDeflate2.extensionName]){let params=extensions[PerMessageDeflate2.extensionName].params,value=extension2.format({[PerMessageDeflate2.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`),ws._extensions=extensions}this.emit("headers",headers,req),socket.write(headers.concat(`\r
|
|
55
|
+
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var GoogleAuth2=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#pendingAuthClient=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(opts={}){if(this._cachedProjectId=opts.projectId||null,this.cachedCredential=opts.authClient||null,this.keyFilename=opts.keyFilename||opts.keyFile,this.scopes=opts.scopes,this.clientOptions=opts.clientOptions||{},this.jsonContent=opts.credentials||null,this.apiKey=opts.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);opts.universeDomain&&(this.clientOptions.universeDomain=opts.universeDomain)}setGapicJWTValues(client){client.defaultServicePath=this.defaultServicePath,client.useJWTAccessWithScope=this.useJWTAccessWithScope,client.defaultScopes=this.defaultScopes}getProjectId(callback){if(callback)this.getProjectIdAsync().then(r2=>callback(null,r2),callback);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e2){if(e2 instanceof Error&&e2.message===exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e2}}async findAndCacheProjectId(){let projectId=null;if(projectId||=await this.getProductionProjectId(),projectId||=await this.getFileProjectId(),projectId||=await this.getDefaultServiceProjectId(),projectId||=await this.getGCEProjectId(),projectId||=await this.getExternalAccountClientProjectId(),projectId)return this._cachedProjectId=projectId,projectId;throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let universeDomain;try{universeDomain=await gcpMetadata.universe("universe-domain"),universeDomain||=authclient_1.DEFAULT_UNIVERSE}catch(e2){if(e2&&e2?.response?.status===404)universeDomain=authclient_1.DEFAULT_UNIVERSE;else throw e2}return universeDomain}async getUniverseDomain(){let universeDomain=(0,util_1.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{universeDomain??=(await this.getClient()).universeDomain}catch{universeDomain??=authclient_1.DEFAULT_UNIVERSE}return universeDomain}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(optionsOrCallback={},callback){let options;if(typeof optionsOrCallback=="function"?callback=optionsOrCallback:options=optionsOrCallback,callback)this.getApplicationDefaultAsync(options).then(r2=>callback(null,r2.credential,r2.projectId),callback);else return this.getApplicationDefaultAsync(options)}async getApplicationDefaultAsync(options={}){if(this.cachedCredential)return await this.#prepareAndCacheClient(this.cachedCredential,null);let credential;if(credential=await this._tryGetApplicationCredentialsFromEnvironmentVariable(options),credential)return credential instanceof jwtclient_1.JWT?credential.scopes=this.scopes:credential instanceof baseexternalclient_1.BaseExternalAccountClient&&(credential.scopes=this.getAnyScopes()),await this.#prepareAndCacheClient(credential);if(credential=await this._tryGetApplicationCredentialsFromWellKnownFile(options),credential)return credential instanceof jwtclient_1.JWT?credential.scopes=this.scopes:credential instanceof baseexternalclient_1.BaseExternalAccountClient&&(credential.scopes=this.getAnyScopes()),await this.#prepareAndCacheClient(credential);if(await this._checkIsGCE())return options.scopes=this.getAnyScopes(),await this.#prepareAndCacheClient(new computeclient_1.Compute(options));throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#prepareAndCacheClient(credential,quotaProjectIdOverride=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let projectId=await this.getProjectIdOptional();return quotaProjectIdOverride&&(credential.quotaProjectId=quotaProjectIdOverride),this.cachedCredential=credential,{credential,projectId}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=gcpMetadata.getGCPResidency()||await gcpMetadata.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(options){let credentialsPath=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!credentialsPath||credentialsPath.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(credentialsPath,options)}catch(e2){throw e2 instanceof Error&&(e2.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e2.message}`),e2}}async _tryGetApplicationCredentialsFromWellKnownFile(options){let location=null;if(this._isWindows())location=process.env.APPDATA;else{let home=process.env.HOME;home&&(location=path.join(home,".config"))}return location&&(location=path.join(location,"gcloud","application_default_credentials.json"),fs2.existsSync(location)||(location=null)),location?await this._getApplicationCredentialsFromFilePath(location,options):null}async _getApplicationCredentialsFromFilePath(filePath,options={}){if(!filePath||filePath.length===0)throw new Error("The file path is invalid.");try{if(filePath=fs2.realpathSync(filePath),!fs2.lstatSync(filePath).isFile())throw new Error}catch(err){throw err instanceof Error&&(err.message=`The file at ${filePath} does not exist, or it is not a file. ${err.message}`),err}let readStream=fs2.createReadStream(filePath);return this.fromStream(readStream,options)}fromImpersonatedJSON(json){if(!json)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(json.type!==impersonated_1.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!json.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!json.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let sourceClient=this.fromJSON(json.source_credentials);if(json.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`);let targetPrincipal=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)?.groups?.target;if(!targetPrincipal)throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`);let targetScopes=(this.scopes||json.scopes||this.defaultScopes)??[];return new impersonated_1.Impersonated({...json,sourceClient,targetPrincipal,targetScopes:Array.isArray(targetScopes)?targetScopes:[targetScopes]})}fromJSON(json,options={}){let client,preferredUniverseDomain=(0,util_1.originalOrCamelOptions)(options).get("universe_domain");return json.type===refreshclient_1.USER_REFRESH_ACCOUNT_TYPE?(client=new refreshclient_1.UserRefreshClient(options),client.fromJSON(json)):json.type===impersonated_1.IMPERSONATED_ACCOUNT_TYPE?client=this.fromImpersonatedJSON(json):json.type===baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE?(client=externalclient_1.ExternalAccountClient.fromJSON({...json,...options}),client.scopes=this.getAnyScopes()):json.type===externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?client=new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({...json,...options}):(options.scopes=this.scopes,client=new jwtclient_1.JWT(options),this.setGapicJWTValues(client),client.fromJSON(json)),preferredUniverseDomain&&(client.universeDomain=preferredUniverseDomain),client}_cacheClientFromJSON(json,options){let client=this.fromJSON(json,options);return this.jsonContent=json,this.cachedCredential=client,client}fromStream(inputStream,optionsOrCallback={},callback){let options={};if(typeof optionsOrCallback=="function"?callback=optionsOrCallback:options=optionsOrCallback,callback)this.fromStreamAsync(inputStream,options).then(r2=>callback(null,r2),callback);else return this.fromStreamAsync(inputStream,options)}fromStreamAsync(inputStream,options){return new Promise((resolve,reject)=>{if(!inputStream)throw new Error("Must pass in a stream containing the Google auth settings.");let chunks=[];inputStream.setEncoding("utf8").on("error",reject).on("data",chunk=>chunks.push(chunk)).on("end",()=>{try{try{let data=JSON.parse(chunks.join("")),r2=this._cacheClientFromJSON(data,options);return resolve(r2)}catch(err){if(!this.keyFilename)throw err;let client=new jwtclient_1.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=client,this.setGapicJWTValues(client),resolve(client)}}catch(err){return reject(err)}})})}fromAPIKey(apiKey,options={}){return new jwtclient_1.JWT({...options,apiKey})}_isWindows(){let sys=os2.platform();return!!(sys&&sys.length>=3&&sys.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(resolve=>{(0,child_process_1.exec)("gcloud config config-helper --format json",(err,stdout)=>{if(!err&&stdout)try{let projectId=JSON.parse(stdout).configuration.properties.core.project;resolve(projectId);return}catch{}resolve(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let creds=await this.getClient();if(creds&&creds.projectId)return creds.projectId}let r2=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return r2?r2.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await gcpMetadata.project("project-id")}catch{return null}}getCredentials(callback){if(callback)this.getCredentialsAsync().then(r2=>callback(null,r2),callback);else return this.getCredentialsAsync()}async getCredentialsAsync(){let client=await this.getClient();if(client instanceof impersonated_1.Impersonated)return{client_email:client.getTargetPrincipal()};if(client instanceof baseexternalclient_1.BaseExternalAccountClient){let serviceAccountEmail=client.getServiceAccountEmail();if(serviceAccountEmail)return{client_email:serviceAccountEmail,universe_domain:client.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[client_email,universe_domain]=await Promise.all([gcpMetadata.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email,universe_domain}}throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#pendingAuthClient=this.#pendingAuthClient||this.#determineClient();try{return await this.#pendingAuthClient}finally{this.#pendingAuthClient=null}}async#determineClient(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let filePath=path.resolve(this.keyFilename),stream2=fs2.createReadStream(filePath);return await this.fromStreamAsync(stream2,this.clientOptions)}else if(this.apiKey){let client=await this.fromAPIKey(this.apiKey,this.clientOptions);client.scopes=this.scopes;let{credential}=await this.#prepareAndCacheClient(client);return credential}else{let{credential}=await this.getApplicationDefaultAsync(this.clientOptions);return credential}}async getIdTokenClient(targetAudience){let client=await this.getClient();if(!("fetchIdToken"in client))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new idtokenclient_1.IdTokenClient({targetAudience,idTokenProvider:client})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(url){return(await this.getClient()).getRequestHeaders(url)}async authorizeRequest(opts={}){let url=opts.url,headers=await(await this.getClient()).getRequestHeaders(url);return opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers,headers),opts}async fetch(...args){return(await this.getClient()).fetch(...args)}async request(opts){return(await this.getClient()).request(opts)}getEnv(){return(0,envDetect_1.getEnv)()}async sign(data,endpoint){let client=await this.getClient(),universe=await this.getUniverseDomain();if(endpoint=endpoint||`https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`,client instanceof impersonated_1.Impersonated)return(await client.sign(data)).signedBlob;let crypto2=(0,crypto_1.createCrypto)();if(client instanceof jwtclient_1.JWT&&client.key)return await crypto2.sign(client.key,data);let creds=await this.getCredentials();if(!creds.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(crypto2,creds.client_email,data,endpoint)}async signBlob(crypto2,emailOrUniqueId,data,endpoint){let url=new URL(endpoint+`${emailOrUniqueId}:signBlob`);return(await this.request({method:"POST",url:url.href,data:{payload:crypto2.encodeBase64StringUtf8(data)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};exports.GoogleAuth=GoogleAuth2}});var require_iam=__commonJS({"node_modules/google-auth-library/build/src/auth/iam.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.IAMAuth=void 0;var IAMAuth=class{selector;token;constructor(selector,token){this.selector=selector,this.token=token,this.selector=selector,this.token=token}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};exports.IAMAuth=IAMAuth}});var require_downscopedclient=__commonJS({"node_modules/google-auth-library/build/src/auth/downscopedclient.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.DownscopedClient=exports.EXPIRATION_TIME_OFFSET=exports.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var gaxios_1=require_src2(),stream2=__require("stream"),authclient_1=require_authclient(),sts=require_stscredentials(),STS_GRANT_TYPE="urn:ietf:params:oauth:grant-type:token-exchange",STS_REQUEST_TOKEN_TYPE="urn:ietf:params:oauth:token-type:access_token",STS_SUBJECT_TOKEN_TYPE="urn:ietf:params:oauth:token-type:access_token";exports.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;exports.EXPIRATION_TIME_OFFSET=300*1e3;var DownscopedClient=class extends authclient_1.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(options,credentialAccessBoundary={accessBoundary:{accessBoundaryRules:[]}}){if(super(options instanceof authclient_1.AuthClient?{}:options),options instanceof authclient_1.AuthClient?(this.authClient=options,this.credentialAccessBoundary=credentialAccessBoundary):(this.authClient=options.authClient,this.credentialAccessBoundary=options.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>exports.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let rule of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(rule.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new sts.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(credentials){if(!credentials.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(credentials),this.cachedDownscopedAccessToken=credentials}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let accessTokenResponse=await this.getAccessToken(),headers=new Headers({authorization:`Bearer ${accessTokenResponse.token}`});return this.addSharedMetadataHeaders(headers)}request(opts,callback){if(callback)this.requestAsync(opts).then(r2=>callback(null,r2),e2=>callback(e2,e2.response));else return this.requestAsync(opts)}async requestAsync(opts,reAuthRetried=!1){let response;try{let requestHeaders=await this.getRequestHeaders();opts.headers=gaxios_1.Gaxios.mergeHeaders(opts.headers),this.addUserProjectAndAuthHeaders(opts.headers,requestHeaders),response=await this.transporter.request(opts)}catch(e2){let res=e2.response;if(res){let statusCode=res.status,isReadableStream=res.config.data instanceof stream2.Readable;if(!reAuthRetried&&(statusCode===401||statusCode===403)&&!isReadableStream&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(opts,!0)}throw e2}return response}async refreshAccessTokenAsync(){let subjectToken=(await this.authClient.getAccessToken()).token,stsCredentialsOptions={grantType:STS_GRANT_TYPE,requestedTokenType:STS_REQUEST_TOKEN_TYPE,subjectToken,subjectTokenType:STS_SUBJECT_TOKEN_TYPE},stsResponse=await this.stsCredential.exchangeToken(stsCredentialsOptions,void 0,this.credentialAccessBoundary),sourceCredExpireDate=this.authClient.credentials?.expiry_date||null,expiryDate=stsResponse.expires_in?new Date().getTime()+stsResponse.expires_in*1e3:sourceCredExpireDate;return this.cachedDownscopedAccessToken={access_token:stsResponse.access_token,expiry_date:expiryDate,res:stsResponse.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(downscopedAccessToken){let now=new Date().getTime();return downscopedAccessToken.expiry_date?now>=downscopedAccessToken.expiry_date-this.eagerRefreshThresholdMillis:!1}};exports.DownscopedClient=DownscopedClient}});var require_passthrough=__commonJS({"node_modules/google-auth-library/build/src/auth/passthrough.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.PassThroughClient=void 0;var authclient_1=require_authclient(),PassThroughClient=class extends authclient_1.AuthClient{async request(opts){return this.transporter.request(opts)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};exports.PassThroughClient=PassThroughClient}});var require_src5=__commonJS({"node_modules/google-auth-library/build/src/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m2,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m2,k);(!desc||("get"in desc?!m2.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m2[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m2,k,k2){k2===void 0&&(k2=k),o[k2]=m2[k]})),__exportStar=exports&&exports.__exportStar||function(m2,exports2){for(var p in m2)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m2,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.GoogleAuth=exports.auth=exports.PassThroughClient=exports.ExternalAccountAuthorizedUserClient=exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=exports.ExecutableError=exports.PluggableAuthClient=exports.DownscopedClient=exports.BaseExternalAccountClient=exports.ExternalAccountClient=exports.IdentityPoolClient=exports.AwsRequestSigner=exports.AwsClient=exports.UserRefreshClient=exports.LoginTicket=exports.ClientAuthentication=exports.OAuth2Client=exports.CodeChallengeMethod=exports.Impersonated=exports.JWT=exports.JWTAccess=exports.IdTokenClient=exports.IAMAuth=exports.GCPEnv=exports.Compute=exports.DEFAULT_UNIVERSE=exports.AuthClient=exports.gaxios=exports.gcpMetadata=void 0;var googleauth_1=require_googleauth();Object.defineProperty(exports,"GoogleAuth",{enumerable:!0,get:function(){return googleauth_1.GoogleAuth}});exports.gcpMetadata=require_src4();exports.gaxios=require_src2();var authclient_1=require_authclient();Object.defineProperty(exports,"AuthClient",{enumerable:!0,get:function(){return authclient_1.AuthClient}});Object.defineProperty(exports,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return authclient_1.DEFAULT_UNIVERSE}});var computeclient_1=require_computeclient();Object.defineProperty(exports,"Compute",{enumerable:!0,get:function(){return computeclient_1.Compute}});var envDetect_1=require_envDetect();Object.defineProperty(exports,"GCPEnv",{enumerable:!0,get:function(){return envDetect_1.GCPEnv}});var iam_1=require_iam();Object.defineProperty(exports,"IAMAuth",{enumerable:!0,get:function(){return iam_1.IAMAuth}});var idtokenclient_1=require_idtokenclient();Object.defineProperty(exports,"IdTokenClient",{enumerable:!0,get:function(){return idtokenclient_1.IdTokenClient}});var jwtaccess_1=require_jwtaccess();Object.defineProperty(exports,"JWTAccess",{enumerable:!0,get:function(){return jwtaccess_1.JWTAccess}});var jwtclient_1=require_jwtclient();Object.defineProperty(exports,"JWT",{enumerable:!0,get:function(){return jwtclient_1.JWT}});var impersonated_1=require_impersonated();Object.defineProperty(exports,"Impersonated",{enumerable:!0,get:function(){return impersonated_1.Impersonated}});var oauth2client_1=require_oauth2client();Object.defineProperty(exports,"CodeChallengeMethod",{enumerable:!0,get:function(){return oauth2client_1.CodeChallengeMethod}});Object.defineProperty(exports,"OAuth2Client",{enumerable:!0,get:function(){return oauth2client_1.OAuth2Client}});Object.defineProperty(exports,"ClientAuthentication",{enumerable:!0,get:function(){return oauth2client_1.ClientAuthentication}});var loginticket_1=require_loginticket();Object.defineProperty(exports,"LoginTicket",{enumerable:!0,get:function(){return loginticket_1.LoginTicket}});var refreshclient_1=require_refreshclient();Object.defineProperty(exports,"UserRefreshClient",{enumerable:!0,get:function(){return refreshclient_1.UserRefreshClient}});var awsclient_1=require_awsclient();Object.defineProperty(exports,"AwsClient",{enumerable:!0,get:function(){return awsclient_1.AwsClient}});var awsrequestsigner_1=require_awsrequestsigner();Object.defineProperty(exports,"AwsRequestSigner",{enumerable:!0,get:function(){return awsrequestsigner_1.AwsRequestSigner}});var identitypoolclient_1=require_identitypoolclient();Object.defineProperty(exports,"IdentityPoolClient",{enumerable:!0,get:function(){return identitypoolclient_1.IdentityPoolClient}});var externalclient_1=require_externalclient();Object.defineProperty(exports,"ExternalAccountClient",{enumerable:!0,get:function(){return externalclient_1.ExternalAccountClient}});var baseexternalclient_1=require_baseexternalclient();Object.defineProperty(exports,"BaseExternalAccountClient",{enumerable:!0,get:function(){return baseexternalclient_1.BaseExternalAccountClient}});var downscopedclient_1=require_downscopedclient();Object.defineProperty(exports,"DownscopedClient",{enumerable:!0,get:function(){return downscopedclient_1.DownscopedClient}});var pluggable_auth_client_1=require_pluggable_auth_client();Object.defineProperty(exports,"PluggableAuthClient",{enumerable:!0,get:function(){return pluggable_auth_client_1.PluggableAuthClient}});Object.defineProperty(exports,"ExecutableError",{enumerable:!0,get:function(){return pluggable_auth_client_1.ExecutableError}});var externalAccountAuthorizedUserClient_1=require_externalAccountAuthorizedUserClient();Object.defineProperty(exports,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(exports,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient}});var passthrough_1=require_passthrough();Object.defineProperty(exports,"PassThroughClient",{enumerable:!0,get:function(){return passthrough_1.PassThroughClient}});__exportStar(require_googleToken(),exports);var auth=new googleauth_1.GoogleAuth;exports.auth=auth}});var require_constants=__commonJS({"node_modules/ws/lib/constants.js"(exports,module){"use strict";var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"],hasBlob=typeof Blob<"u";hasBlob&&BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports,module){"use strict";var{EMPTY_BUFFER}=require_constants(),FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];let target=Buffer.allocUnsafe(totalLength),offset=0;for(let i2=0;i2<list.length;i2++){let buf=list[i2];target.set(buf,offset),offset+=buf.length}return offset<totalLength?new FastBuffer(target.buffer,target.byteOffset,offset):target}function _mask(source,mask,output,offset,length){for(let i2=0;i2<length;i2++)output[offset+i2]=source[i2]^mask[i2&3]}function _unmask(buffer,mask){for(let i2=0;i2<buffer.length;i2++)buffer[i2]^=mask[i2&3]}function toArrayBuffer(buf){return buf.length===buf.buffer.byteLength?buf.buffer:buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){if(toBuffer.readOnly=!0,Buffer.isBuffer(data))return data;let buf;return data instanceof ArrayBuffer?buf=new FastBuffer(data):ArrayBuffer.isView(data)?buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength):(buf=Buffer.from(data),toBuffer.readOnly=!1),buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL)try{let bufferUtil=__require("bufferutil");module.exports.mask=function(source,mask,output,offset,length){length<48?_mask(source,mask,output,offset,length):bufferUtil.mask(source,mask,output,offset,length)},module.exports.unmask=function(buffer,mask){buffer.length<32?_unmask(buffer,mask):bufferUtil.unmask(buffer,mask)}}catch{}}});var require_limiter=__commonJS({"node_modules/ws/lib/limiter.js"(exports,module){"use strict";var kDone=Symbol("kDone"),kRun=Symbol("kRun"),Limiter=class{constructor(concurrency){this[kDone]=()=>{this.pending--,this[kRun]()},this.concurrency=concurrency||1/0,this.jobs=[],this.pending=0}add(job){this.jobs.push(job),this[kRun]()}[kRun](){if(this.pending!==this.concurrency&&this.jobs.length){let job=this.jobs.shift();this.pending++,job(this[kDone])}}};module.exports=Limiter}});var require_permessage_deflate=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports,module){"use strict";var zlib2=__require("zlib"),bufferUtil=require_buffer_util(),Limiter=require_limiter(),{kStatusCode}=require_constants(),FastBuffer=Buffer[Symbol.species],TRAILER=Buffer.from([0,0,255,255]),kPerMessageDeflate=Symbol("permessage-deflate"),kTotalLength=Symbol("total-length"),kCallback=Symbol("callback"),kBuffers=Symbol("buffers"),kError=Symbol("error"),zlibLimiter,PerMessageDeflate2=class{constructor(options){if(this._options=options||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!zlibLimiter){let concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){let params={};return this._options.serverNoContextTakeover&&(params.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(params.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(params.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?params.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(params.client_max_window_bits=!0),params}accept(configurations){return configurations=this.normalizeParams(configurations),this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let callback=this._deflate[kCallback];this._deflate.close(),this._deflate=null,callback&&callback(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(offers){let opts=this._options,accepted=offers.find(params=>!(opts.serverNoContextTakeover===!1&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===!1||typeof opts.serverMaxWindowBits=="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits=="number"&&!params.client_max_window_bits));if(!accepted)throw new Error("None of the extension offers can be accepted");return opts.serverNoContextTakeover&&(accepted.server_no_context_takeover=!0),opts.clientNoContextTakeover&&(accepted.client_no_context_takeover=!0),typeof opts.serverMaxWindowBits=="number"&&(accepted.server_max_window_bits=opts.serverMaxWindowBits),typeof opts.clientMaxWindowBits=="number"?accepted.client_max_window_bits=opts.clientMaxWindowBits:(accepted.client_max_window_bits===!0||opts.clientMaxWindowBits===!1)&&delete accepted.client_max_window_bits,accepted}acceptAsClient(response){let params=response[0];if(this._options.clientNoContextTakeover===!1&¶ms.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!params.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(params.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return params}normalizeParams(configurations){return configurations.forEach(params=>{Object.keys(params).forEach(key=>{let value=params[key];if(value.length>1)throw new Error(`Parameter "${key}" must have only a single value`);if(value=value[0],key==="client_max_window_bits"){if(value!==!0){let num=+value;if(!Number.isInteger(num)||num<8||num>15)throw new TypeError(`Invalid value for parameter "${key}": ${value}`);value=num}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}else if(key==="server_max_window_bits"){let num=+value;if(!Number.isInteger(num)||num<8||num>15)throw new TypeError(`Invalid value for parameter "${key}": ${value}`);value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==!0)throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}else throw new Error(`Unknown parameter "${key}"`);params[key]=value})}),configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err,result)=>{done(),callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err,result)=>{done(),callback(err,result)})})}_decompress(data,fin,callback){let endpoint=this._isServer?"client":"server";if(!this._inflate){let key=`${endpoint}_max_window_bits`,windowBits=typeof this.params[key]!="number"?zlib2.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib2.createInflateRaw({...this._options.zlibInflateOptions,windowBits}),this._inflate[kPerMessageDeflate]=this,this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],this._inflate.on("error",inflateOnError),this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback,this._inflate.write(data),fin&&this._inflate.write(TRAILER),this._inflate.flush(()=>{let err=this._inflate[kError];if(err){this._inflate.close(),this._inflate=null,callback(err);return}let data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],fin&&this.params[`${endpoint}_no_context_takeover`]&&this._inflate.reset()),callback(null,data2)})}_compress(data,fin,callback){let endpoint=this._isServer?"server":"client";if(!this._deflate){let key=`${endpoint}_max_window_bits`,windowBits=typeof this.params[key]!="number"?zlib2.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib2.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits}),this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback,this._deflate.write(data),this._deflate.flush(zlib2.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);fin&&(data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)),this._deflate[kCallback]=null,this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],fin&&this.params[`${endpoint}_no_context_takeover`]&&this._deflate.reset(),callback(null,data2)})}};module.exports=PerMessageDeflate2;function deflateOnData(chunk){this[kBuffers].push(chunk),this[kTotalLength]+=chunk.length}function inflateOnData(chunk){if(this[kTotalLength]+=chunk.length,this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded"),this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[kError][kStatusCode]=1009,this.removeListener("data",inflateOnData),this.reset()}function inflateOnError(err){if(this[kPerMessageDeflate]._inflate=null,this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007,this[kCallback](err)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports,module){"use strict";var{isUtf8}=__require("buffer"),{hasBlob}=require_constants(),tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){let len=buf.length,i2=0;for(;i2<len;)if((buf[i2]&128)===0)i2++;else if((buf[i2]&224)===192){if(i2+1===len||(buf[i2+1]&192)!==128||(buf[i2]&254)===192)return!1;i2+=2}else if((buf[i2]&240)===224){if(i2+2>=len||(buf[i2+1]&192)!==128||(buf[i2+2]&192)!==128||buf[i2]===224&&(buf[i2+1]&224)===128||buf[i2]===237&&(buf[i2+1]&224)===160)return!1;i2+=3}else if((buf[i2]&248)===240){if(i2+3>=len||(buf[i2+1]&192)!==128||(buf[i2+2]&192)!==128||(buf[i2+3]&192)!==128||buf[i2]===240&&(buf[i2+1]&240)===128||buf[i2]===244&&buf[i2+1]>143||buf[i2]>244)return!1;i2+=4}else return!1;return!0}function isBlob2(value){return hasBlob&&typeof value=="object"&&typeof value.arrayBuffer=="function"&&typeof value.type=="string"&&typeof value.stream=="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob:isBlob2,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8)module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let isValidUTF8=__require("utf-8-validate");module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch{}}});var require_receiver=__commonJS({"node_modules/ws/lib/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream"),PerMessageDeflate2=require_permessage_deflate(),{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants(),{concat,toArrayBuffer,unmask}=require_buffer_util(),{isValidStatusCode,isValidUTF8}=require_validation(),FastBuffer=Buffer[Symbol.species],GET_INFO=0,GET_PAYLOAD_LENGTH_16=1,GET_PAYLOAD_LENGTH_64=2,GET_MASK=3,GET_DATA=4,INFLATING=5,DEFER_EVENT=6,Receiver2=class extends Writable{constructor(options={}){super(),this._allowSynchronousEvents=options.allowSynchronousEvents!==void 0?options.allowSynchronousEvents:!0,this._binaryType=options.binaryType||BINARY_TYPES[0],this._extensions=options.extensions||{},this._isServer=!!options.isServer,this._maxBufferedChunks=options.maxBufferedChunks|0,this._maxFragments=options.maxFragments|0,this._maxPayload=options.maxPayload|0,this._skipUTF8Validation=!!options.skipUTF8Validation,this[kWebSocket]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length,this._buffers.push(chunk),this.startLoop(cb)}consume(n){if(this._bufferedBytes-=n,n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){let buf=this._buffers[0];return this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n),new FastBuffer(buf.buffer,buf.byteOffset,n)}let dst=Buffer.allocUnsafe(n);do{let buf=this._buffers[0],offset=dst.length-n;n>=buf.length?dst.set(this._buffers.shift(),offset):(dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset),this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)),n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=!0;do switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=!1;return}while(this._loop);this._errored||cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=!1;return}let buf=this.consume(2);if((buf[0]&48)!==0){let error=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}let compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate2.extensionName]){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._fin=(buf[0]&128)===128,this._opcode=buf[0]&15,this._payloadLength=buf[1]&127,this._opcode===0){if(compressed){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){let error=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let error=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let error=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){let error=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{let error=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(buf[1]&128)===128,this._isServer){if(!this._masked){let error=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){let error=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}this._payloadLength===126?this._state=GET_PAYLOAD_LENGTH_16:this._payloadLength===127?this._state=GET_PAYLOAD_LENGTH_64:this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=!1;return}let buf=this.consume(8),num=buf.readUInt32BE(0);if(num>Math.pow(2,21)-1){let error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4),this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let error=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._masked?this._state=GET_MASK:this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}data=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&unmask(data,this._mask)}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._compressed){this._state=INFLATING,this.decompress(data,cb);return}if(data.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let error=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}this._messageLength=this._totalPayloadLength,this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){this._extensions[PerMessageDeflate2.extensionName].decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){if(this._messageLength+=buf.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let error=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let error=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}this._fragments.push(buf)}this.dataMessage(cb),this._state===GET_INFO&&this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}let messageLength=this._messageLength,fragments=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let data;this._binaryType==="nodebuffer"?data=concat(fragments,messageLength):this._binaryType==="arraybuffer"?data=toArrayBuffer(concat(fragments,messageLength)):this._binaryType==="blob"?data=new Blob(fragments):data=fragments,this._allowSynchronousEvents?(this.emit("message",data,!0),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit("message",data,!0),this._state=GET_INFO,this.startLoop(cb)}))}else{let buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){let error=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._state===INFLATING||this._allowSynchronousEvents?(this.emit("message",buf,!1),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit("message",buf,!1),this._state=GET_INFO,this.startLoop(cb)}))}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0)this._loop=!1,this.emit("conclude",1005,EMPTY_BUFFER),this.end();else{let code=data.readUInt16BE(0);if(!isValidStatusCode(code)){let error=this.createError(RangeError,`invalid status code ${code}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error);return}let buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){let error=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=!1,this.emit("conclude",code,buf),this.end()}this._state=GET_INFO;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",data),this._state=GET_INFO):(this._state=DEFER_EVENT,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data),this._state=GET_INFO,this.startLoop(cb)}))}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=!1,this._errored=!0;let err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);return Error.captureStackTrace(err,this.createError),err.code=errorCode,err[kStatusCode]=statusCode,err}};module.exports=Receiver2}});var require_sender=__commonJS({"node_modules/ws/lib/sender.js"(exports,module){"use strict";var{Duplex}=__require("stream"),{randomFillSync}=__require("crypto"),{types:{isUint8Array}}=__require("util"),PerMessageDeflate2=require_permessage_deflate(),{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants(),{isBlob:isBlob2,isValidStatusCode}=require_validation(),{mask:applyMask,toBuffer}=require_buffer_util(),kByteLength=Symbol("kByteLength"),maskBuffer=Buffer.alloc(4),RANDOM_POOL_SIZE=8*1024,randomPool,randomPoolPointer=RANDOM_POOL_SIZE,DEFAULT=0,DEFLATING=1,GET_BLOB_DATA=2,Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{},generateMask&&(this._generateMask=generateMask,this._maskBuffer=Buffer.alloc(4)),this._socket=socket,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=DEFAULT,this.onerror=NOOP,this[kWebSocket]=void 0}static frame(data,options){let mask,merge=!1,offset=2,skipMasking=!1;options.mask&&(mask=options.maskBuffer||maskBuffer,options.generateMask?options.generateMask(mask):(randomPoolPointer===RANDOM_POOL_SIZE&&(randomPool===void 0&&(randomPool=Buffer.alloc(RANDOM_POOL_SIZE)),randomFillSync(randomPool,0,RANDOM_POOL_SIZE),randomPoolPointer=0),mask[0]=randomPool[randomPoolPointer++],mask[1]=randomPool[randomPoolPointer++],mask[2]=randomPool[randomPoolPointer++],mask[3]=randomPool[randomPoolPointer++]),skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0,offset=6);let dataLength;typeof data=="string"?(!options.mask||skipMasking)&&options[kByteLength]!==void 0?dataLength=options[kByteLength]:(data=Buffer.from(data),dataLength=data.length):(dataLength=data.length,merge=options.mask&&options.readOnly&&!skipMasking);let payloadLength=dataLength;dataLength>=65536?(offset+=8,payloadLength=127):dataLength>125&&(offset+=2,payloadLength=126);let target=Buffer.allocUnsafe(merge?dataLength+offset:offset);return target[0]=options.fin?options.opcode|128:options.opcode,options.rsv1&&(target[0]|=64),target[1]=payloadLength,payloadLength===126?target.writeUInt16BE(dataLength,2):payloadLength===127&&(target[2]=target[3]=0,target.writeUIntBE(dataLength,4,6)),options.mask?(target[1]|=128,target[offset-4]=mask[0],target[offset-3]=mask[1],target[offset-2]=mask[2],target[offset-1]=mask[3],skipMasking?[target,data]:merge?(applyMask(data,mask,target,offset,dataLength),[target]):(applyMask(data,mask,data,0,dataLength),[target,data])):[target,data]}close(code,data,mask,cb){let buf;if(code===void 0)buf=EMPTY_BUFFER;else{if(typeof code!="number"||!isValidStatusCode(code))throw new TypeError("First argument must be a valid error code number");if(data===void 0||!data.length)buf=Buffer.allocUnsafe(2),buf.writeUInt16BE(code,0);else{let length=Buffer.byteLength(data);if(length>123)throw new RangeError("The message must not be greater than 123 bytes");if(buf=Buffer.allocUnsafe(2+length),buf.writeUInt16BE(code,0),typeof data=="string")buf.write(data,2);else if(isUint8Array(data))buf.set(data,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let options={[kByteLength]:buf.length,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==DEFAULT?this.enqueue([this.dispatch,buf,!1,options,cb]):this.sendFrame(_Sender.frame(buf,options),cb)}ping(data,mask,cb){let byteLength,readOnly;if(typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob2(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),byteLength>125)throw new RangeError("The data size must not be greater than 125 bytes");let options={[kByteLength]:byteLength,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:!1};isBlob2(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,!1,options,cb]):this.getBlobData(data,!1,options,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,!1,options,cb]):this.sendFrame(_Sender.frame(data,options),cb)}pong(data,mask,cb){let byteLength,readOnly;if(typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob2(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),byteLength>125)throw new RangeError("The data size must not be greater than 125 bytes");let options={[kByteLength]:byteLength,fin:!0,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:!1};isBlob2(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,!1,options,cb]):this.getBlobData(data,!1,options,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,!1,options,cb]):this.sendFrame(_Sender.frame(data,options),cb)}send(data,options,cb){let perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName],opcode=options.binary?2:1,rsv1=options.compress,byteLength,readOnly;typeof data=="string"?(byteLength=Buffer.byteLength(data),readOnly=!1):isBlob2(data)?(byteLength=data.size,readOnly=!1):(data=toBuffer(data),byteLength=data.length,readOnly=toBuffer.readOnly),this._firstFragment?(this._firstFragment=!1,rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(rsv1=byteLength>=perMessageDeflate._threshold),this._compress=rsv1):(rsv1=!1,opcode=0),options.fin&&(this._firstFragment=!0);let opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};isBlob2(data)?this._state!==DEFAULT?this.enqueue([this.getBlobData,data,this._compress,opts,cb]):this.getBlobData(data,this._compress,opts,cb):this._state!==DEFAULT?this.enqueue([this.dispatch,data,this._compress,opts,cb]):this.dispatch(data,this._compress,opts,cb)}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength],this._state=GET_BLOB_DATA,blob.arrayBuffer().then(arrayBuffer=>{if(this._socket.destroyed){let err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];let data=toBuffer(arrayBuffer);compress?this.dispatch(data,compress,options,cb):(this._state=DEFAULT,this.sendFrame(_Sender.frame(data,options),cb),this.dequeue())}).catch(err=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}let perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];this._bufferedBytes+=options[kByteLength],this._state=DEFLATING,perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){let err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength],this._state=DEFAULT,options.readOnly=!1,this.sendFrame(_Sender.frame(buf,options),cb),this.dequeue()})}dequeue(){for(;this._state===DEFAULT&&this._queue.length;){let params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength],Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength],this._queue.push(params)}sendFrame(list,cb){list.length===2?(this._socket.cork(),this._socket.write(list[0]),this._socket.write(list[1],cb),this._socket.uncork()):this._socket.write(list[0],cb)}};module.exports=Sender2;function callCallbacks(sender,err,cb){typeof cb=="function"&&cb(err);for(let i2=0;i2<sender._queue.length;i2++){let params=sender._queue[i2],callback=params[params.length-1];typeof callback=="function"&&callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb),sender.onerror(err)}}});var require_event_target=__commonJS({"node_modules/ws/lib/event-target.js"(exports,module){"use strict";var{kForOnEventAttribute,kListener}=require_constants(),kCode=Symbol("kCode"),kData=Symbol("kData"),kError=Symbol("kError"),kMessage=Symbol("kMessage"),kReason=Symbol("kReason"),kTarget=Symbol("kTarget"),kType=Symbol("kType"),kWasClean=Symbol("kWasClean"),Event=class{constructor(type){this[kTarget]=null,this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}};Object.defineProperty(Event.prototype,"target",{enumerable:!0});Object.defineProperty(Event.prototype,"type",{enumerable:!0});var CloseEvent=class extends Event{constructor(type,options={}){super(type),this[kCode]=options.code===void 0?0:options.code,this[kReason]=options.reason===void 0?"":options.reason,this[kWasClean]=options.wasClean===void 0?!1:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}};Object.defineProperty(CloseEvent.prototype,"code",{enumerable:!0});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:!0});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:!0});var ErrorEvent=class extends Event{constructor(type,options={}){super(type),this[kError]=options.error===void 0?null:options.error,this[kMessage]=options.message===void 0?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}};Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:!0});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:!0});var MessageEvent=class extends Event{constructor(type,options={}){super(type),this[kData]=options.data===void 0?null:options.data}get data(){return this[kData]}};Object.defineProperty(MessageEvent.prototype,"data",{enumerable:!0});var EventTarget={addEventListener(type,handler,options={}){for(let listener of this.listeners(type))if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute])return;let wrapper;if(type==="message")wrapper=function(data,isBinary){let event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this,callListener(handler,this,event)};else if(type==="close")wrapper=function(code,message){let event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this,callListener(handler,this,event)};else if(type==="error")wrapper=function(error){let event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this,callListener(handler,this,event)};else if(type==="open")wrapper=function(){let event=new Event("open");event[kTarget]=this,callListener(handler,this,event)};else return;wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute],wrapper[kListener]=handler,options.once?this.once(type,wrapper):this.on(type,wrapper)},removeEventListener(type,handler){for(let listener of this.listeners(type))if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){typeof listener=="object"&&listener.handleEvent?listener.handleEvent.call(listener,event):listener.call(thisArg,event)}}});var require_extension=__commonJS({"node_modules/ws/lib/extension.js"(exports,module){"use strict";var{tokenChars}=require_validation();function push(dest,name,elem){dest[name]===void 0?dest[name]=[elem]:dest[name].push(elem)}function parse(header){let offers=Object.create(null),params=Object.create(null),mustUnescape=!1,isEscaping=!1,inQuotes=!1,extensionName,paramName,start=-1,code=-1,end=-1,i2=0;for(;i2<header.length;i2++)if(code=header.charCodeAt(i2),extensionName===void 0)if(end===-1&&tokenChars[code]===1)start===-1&&(start=i2);else if(i2!==0&&(code===32||code===9))end===-1&&start!==-1&&(end=i2);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i2}`);end===-1&&(end=i2);let name=header.slice(start,end);code===44?(push(offers,name,params),params=Object.create(null)):extensionName=name,start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i2}`);else if(paramName===void 0)if(end===-1&&tokenChars[code]===1)start===-1&&(start=i2);else if(code===32||code===9)end===-1&&start!==-1&&(end=i2);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i2}`);end===-1&&(end=i2),push(params,header.slice(start,end),!0),code===44&&(push(offers,extensionName,params),params=Object.create(null),extensionName=void 0),start=end=-1}else if(code===61&&start!==-1&&end===-1)paramName=header.slice(start,i2),start=end=-1;else throw new SyntaxError(`Unexpected character at index ${i2}`);else if(isEscaping){if(tokenChars[code]!==1)throw new SyntaxError(`Unexpected character at index ${i2}`);start===-1?start=i2:mustUnescape||(mustUnescape=!0),isEscaping=!1}else if(inQuotes)if(tokenChars[code]===1)start===-1&&(start=i2);else if(code===34&&start!==-1)inQuotes=!1,end=i2;else if(code===92)isEscaping=!0;else throw new SyntaxError(`Unexpected character at index ${i2}`);else if(code===34&&header.charCodeAt(i2-1)===61)inQuotes=!0;else if(end===-1&&tokenChars[code]===1)start===-1&&(start=i2);else if(start!==-1&&(code===32||code===9))end===-1&&(end=i2);else if(code===59||code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i2}`);end===-1&&(end=i2);let value=header.slice(start,end);mustUnescape&&(value=value.replace(/\\/g,""),mustUnescape=!1),push(params,paramName,value),code===44&&(push(offers,extensionName,params),params=Object.create(null),extensionName=void 0),paramName=void 0,start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i2}`);if(start===-1||inQuotes||code===32||code===9)throw new SyntaxError("Unexpected end of input");end===-1&&(end=i2);let token=header.slice(start,end);return extensionName===void 0?push(offers,token,params):(paramName===void 0?push(params,token,!0):mustUnescape?push(params,paramName,token.replace(/\\/g,"")):push(params,paramName,token),push(offers,extensionName,params)),offers}function format(extensions){return Object.keys(extensions).map(extension2=>{let configurations=extensions[extension2];return Array.isArray(configurations)||(configurations=[configurations]),configurations.map(params=>[extension2].concat(Object.keys(params).map(k=>{let values=params[k];return Array.isArray(values)||(values=[values]),values.map(v=>v===!0?k:`${k}=${v}`).join("; ")})).join("; ")).join(", ")}).join(", ")}module.exports={format,parse}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter=__require("events"),https2=__require("https"),http3=__require("http"),net=__require("net"),tls=__require("tls"),{randomBytes,createHash:createHash2}=__require("crypto"),{Duplex,Readable}=__require("stream"),{URL:URL2}=__require("url"),PerMessageDeflate2=require_permessage_deflate(),Receiver2=require_receiver(),Sender2=require_sender(),{isBlob:isBlob2}=require_validation(),{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants(),{EventTarget:{addEventListener,removeEventListener}}=require_event_target(),{format,parse}=require_extension(),{toBuffer}=require_buffer_util(),kAborted=Symbol("kAborted"),protocolVersions=[8,13],readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"],subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,WebSocket2=class _WebSocket extends EventEmitter{constructor(address,protocols,options){super(),this._binaryType=BINARY_TYPES[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=EMPTY_BUFFER,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=_WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,address!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,protocols===void 0?protocols=[]:Array.isArray(protocols)||(typeof protocols=="object"&&protocols!==null?(options=protocols,protocols=[]):protocols=[protocols]),initAsClient(this,address,protocols,options)):(this._autoPong=options.autoPong,this._closeTimeout=options.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(type){BINARY_TYPES.includes(type)&&(this._binaryType=type,this._receiver&&(this._receiver._binaryType=type))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){let receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation}),sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver,this._sender=sender,this._socket=socket,receiver[kWebSocket]=this,sender[kWebSocket]=this,socket[kWebSocket]=this,receiver.on("conclude",receiverOnConclude),receiver.on("drain",receiverOnDrain),receiver.on("error",receiverOnError),receiver.on("message",receiverOnMessage),receiver.on("ping",receiverOnPing),receiver.on("pong",receiverOnPong),sender.onerror=senderOnError,socket.setTimeout&&socket.setTimeout(0),socket.setNoDelay&&socket.setNoDelay(),head.length>0&&socket.unshift(head),socket.on("close",socketOnClose),socket.on("data",socketOnData),socket.on("end",socketOnEnd),socket.on("error",socketOnError),this._readyState=_WebSocket.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[PerMessageDeflate2.extensionName]&&this._extensions[PerMessageDeflate2.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===_WebSocket.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=_WebSocket.CLOSING,this._sender.close(code,data,!this._isServer,err=>{err||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),setCloseTimer(this)}}pause(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!0,this._socket.pause())}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof data=="function"?(cb=data,data=mask=void 0):typeof mask=="function"&&(cb=mask,mask=void 0),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}mask===void 0&&(mask=!this._isServer),this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof options=="function"&&(cb=options,options={}),typeof data=="number"&&(data=data.toString()),this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}let opts={binary:typeof data!="string",mask:!this._isServer,compress:!0,fin:!0,...options};this._extensions[PerMessageDeflate2.extensionName]||(opts.compress=!1),this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){abortHandshake(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=_WebSocket.CLOSING,this._socket.destroy())}}};Object.defineProperty(WebSocket2,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2.prototype,"CONNECTING",{enumerable:!0,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2.prototype,"OPEN",{enumerable:!0,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2.prototype,"CLOSING",{enumerable:!0,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket2.prototype,"CLOSED",{enumerable:!0,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket2.prototype,property,{enumerable:!0})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket2.prototype,`on${method}`,{enumerable:!0,get(){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute])return listener[kListener];return null},set(handler){for(let listener of this.listeners(method))if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}typeof handler=="function"&&this.addEventListener(method,handler,{[kForOnEventAttribute]:!0})}})});WebSocket2.prototype.addEventListener=addEventListener;WebSocket2.prototype.removeEventListener=removeEventListener;module.exports=WebSocket2;function initAsClient(websocket,address,protocols,options){let opts={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(websocket._autoPong=opts.autoPong,websocket._closeTimeout=opts.closeTimeout,!protocolVersions.includes(opts.protocolVersion))throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);let parsedUrl;if(address instanceof URL2)parsedUrl=address;else try{parsedUrl=new URL2(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}parsedUrl.protocol==="http:"?parsedUrl.protocol="ws:":parsedUrl.protocol==="https:"&&(parsedUrl.protocol="wss:"),websocket._url=parsedUrl.href;let isSecure=parsedUrl.protocol==="wss:",isIpcUrl=parsedUrl.protocol==="ws+unix:",invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl?invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:isIpcUrl&&!parsedUrl.pathname?invalidUrlMessage="The URL's pathname is empty":parsedUrl.hash&&(invalidUrlMessage="The URL contains a fragment identifier"),invalidUrlMessage){let err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0)throw err;emitErrorAndClose(websocket,err);return}let defaultPort=isSecure?443:80,key=randomBytes(16).toString("base64"),request=isSecure?https2.request:http3.request,protocolSet=new Set,perMessageDeflate;if(opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect),opts.defaultPort=opts.defaultPort||defaultPort,opts.port=parsedUrl.port||defaultPort,opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname,opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"},opts.path=parsedUrl.pathname+parsedUrl.search,opts.timeout=opts.handshakeTimeout,opts.perMessageDeflate&&(perMessageDeflate=new PerMessageDeflate2({...opts.perMessageDeflate,isServer:!1,maxPayload:opts.maxPayload}),opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})),protocols.length){for(let protocol of protocols){if(typeof protocol!="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol))throw new SyntaxError("An invalid or duplicated subprotocol was specified");protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin&&(opts.protocolVersion<13?opts.headers["Sec-WebSocket-Origin"]=opts.origin:opts.headers.Origin=opts.origin),(parsedUrl.username||parsedUrl.password)&&(opts.auth=`${parsedUrl.username}:${parsedUrl.password}`),isIpcUrl){let parts=opts.path.split(":");opts.socketPath=parts[0],opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl,websocket._originalSecure=isSecure,websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;let headers=options&&options.headers;if(options={...options,headers:{}},headers)for(let[key2,value]of Object.entries(headers))options.headers[key2.toLowerCase()]=value}else if(websocket.listenerCount("redirect")===0){let isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:!1:websocket._originalIpc?!1:parsedUrl.host===websocket._originalHostOrSocketPath;(!isSameHost||websocket._originalSecure&&!isSecure)&&(delete opts.headers.authorization,delete opts.headers.cookie,isSameHost||delete opts.headers.host,opts.auth=void 0)}opts.auth&&!options.headers.authorization&&(options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")),req=websocket._req=request(opts),websocket._redirects&&websocket.emit("redirect",websocket.url,req)}else req=websocket._req=request(opts);opts.timeout&&req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")}),req.on("error",err=>{req===null||req[kAborted]||(req=websocket._req=null,emitErrorAndClose(websocket,err))}),req.on("response",res=>{let location=res.headers.location,statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address)}catch{let err=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else websocket.emit("unexpected-response",req,res)||abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}),req.on("upgrade",(res,socket,head)=>{if(websocket.emit("upgrade",res),websocket.readyState!==WebSocket2.CONNECTING)return;req=websocket._req=null;let upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}let digest=createHash2("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}let serverProt=res.headers["sec-websocket-protocol"],protError;if(serverProt!==void 0?protocolSet.size?protocolSet.has(serverProt)||(protError="Server sent an invalid subprotocol"):protError="Server sent a subprotocol but none was requested":protocolSet.size&&(protError="Server sent no subprotocol"),protError){abortHandshake(websocket,socket,protError);return}serverProt&&(websocket._protocol=serverProt);let secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){abortHandshake(websocket,socket,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}let extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){abortHandshake(websocket,socket,"Server indicated an extension that was not requested");return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch{abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Extensions header");return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})}),opts.finishRequest?opts.finishRequest(req,websocket):req.end()}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket2.CLOSING,websocket._errorEmitted=!0,websocket.emit("error",err),websocket.emitClose()}function netConnect(options){return options.path=options.socketPath,net.connect(options)}function tlsConnect(options){return options.path=void 0,!options.servername&&options.servername!==""&&(options.servername=net.isIP(options.host)?"":options.host),tls.connect(options)}function abortHandshake(websocket,stream2,message){websocket._readyState=WebSocket2.CLOSING;let err=new Error(message);Error.captureStackTrace(err,abortHandshake),stream2.setHeader?(stream2[kAborted]=!0,stream2.abort(),stream2.socket&&!stream2.socket.destroyed&&stream2.socket.destroy(),process.nextTick(emitErrorAndClose,websocket,err)):(stream2.destroy(err),stream2.once("error",websocket.emit.bind(websocket,"error")),stream2.once("close",websocket.emitClose.bind(websocket)))}function sendAfterClose(websocket,data,cb){if(data){let length=isBlob2(data)?data.size:toBuffer(data).length;websocket._socket?websocket._sender._bufferedBytes+=length:websocket._bufferedAmount+=length}if(cb){let err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){let websocket=this[kWebSocket];websocket._closeFrameReceived=!0,websocket._closeMessage=reason,websocket._closeCode=code,websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),code===1005?websocket.close():websocket.close(code,reason))}function receiverOnDrain(){let websocket=this[kWebSocket];websocket.isPaused||websocket._socket.resume()}function receiverOnError(err){let websocket=this[kWebSocket];websocket._socket[kWebSocket]!==void 0&&(websocket._socket.removeListener("data",socketOnData),process.nextTick(resume,websocket._socket),websocket.close(err[kStatusCode])),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err))}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){let websocket=this[kWebSocket];websocket._autoPong&&websocket.pong(data,!this._isServer,NOOP),websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream2){stream2.resume()}function senderOnError(err){let websocket=this[kWebSocket];websocket.readyState!==WebSocket2.CLOSED&&(websocket.readyState===WebSocket2.OPEN&&(websocket._readyState=WebSocket2.CLOSING,setCloseTimer(websocket)),this._socket.end(),websocket._errorEmitted||(websocket._errorEmitted=!0,websocket.emit("error",err)))}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){let websocket=this[kWebSocket];if(this.removeListener("close",socketOnClose),this.removeListener("data",socketOnData),this.removeListener("end",socketOnEnd),websocket._readyState=WebSocket2.CLOSING,!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){let chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end(),this[kWebSocket]=void 0,clearTimeout(websocket._closeTimer),websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted?websocket.emitClose():(websocket._receiver.on("error",receiverOnFinish),websocket._receiver.on("finish",receiverOnFinish))}function socketOnData(chunk){this[kWebSocket]._receiver.write(chunk)||this.pause()}function socketOnEnd(){let websocket=this[kWebSocket];websocket._readyState=WebSocket2.CLOSING,websocket._receiver.end(),this.end()}function socketOnError(){let websocket=this[kWebSocket];this.removeListener("error",socketOnError),this.on("error",NOOP),websocket&&(websocket._readyState=WebSocket2.CLOSING,this.destroy())}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket2=require_websocket(),{Duplex}=__require("stream");function emitClose(stream2){stream2.emit("close")}function duplexOnEnd(){!this.destroyed&&this._writableState.finished&&this.destroy()}function duplexOnError(err){this.removeListener("error",duplexOnError),this.destroy(),this.listenerCount("error")===0&&this.emit("error",err)}function createWebSocketStream2(ws,options){let terminateOnDestroy=!0,duplex=new Duplex({...options,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return ws.on("message",function(msg,isBinary){let data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;duplex.push(data)||ws.pause()}),ws.once("error",function(err){duplex.destroyed||(terminateOnDestroy=!1,duplex.destroy(err))}),ws.once("close",function(){duplex.destroyed||duplex.push(null)}),duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err),process.nextTick(emitClose,duplex);return}let called=!1;ws.once("error",function(err2){called=!0,callback(err2)}),ws.once("close",function(){called||callback(err),process.nextTick(emitClose,duplex)}),terminateOnDestroy&&ws.terminate()},duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._final(callback)});return}ws._socket!==null&&(ws._socket._writableState.finished?(callback(),duplex._readableState.endEmitted&&duplex.destroy()):(ws._socket.once("finish",function(){callback()}),ws.close()))},duplex._read=function(){ws.isPaused&&ws.resume()},duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)},duplex.on("end",duplexOnEnd),duplex.on("error",duplexOnError),duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse(header){let protocols=new Set,start=-1,end=-1,i2=0;for(i2;i2<header.length;i2++){let code=header.charCodeAt(i2);if(end===-1&&tokenChars[code]===1)start===-1&&(start=i2);else if(i2!==0&&(code===32||code===9))end===-1&&start!==-1&&(end=i2);else if(code===44){if(start===-1)throw new SyntaxError(`Unexpected character at index ${i2}`);end===-1&&(end=i2);let protocol2=header.slice(start,end);if(protocols.has(protocol2))throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);protocols.add(protocol2),start=end=-1}else throw new SyntaxError(`Unexpected character at index ${i2}`)}if(start===-1||end!==-1)throw new SyntaxError("Unexpected end of input");let protocol=header.slice(start,i2);if(protocols.has(protocol))throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);return protocols.add(protocol),protocols}module.exports={parse}}});var require_websocket_server=__commonJS({"node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter=__require("events"),http3=__require("http"),{Duplex}=__require("stream"),{createHash:createHash2}=__require("crypto"),extension2=require_extension(),PerMessageDeflate2=require_permessage_deflate(),subprotocol2=require_subprotocol(),WebSocket2=require_websocket(),{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants(),keyRegex=/^[+/0-9A-Za-z]{22}==$/,RUNNING=0,CLOSING=1,CLOSED=2,WebSocketServer2=class extends EventEmitter{constructor(options,callback){if(super(),options={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:WebSocket2,...options},options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(options.port!=null?(this._server=http3.createServer((req,res)=>{let body=http3.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"}),res.end(body)}),this._server.listen(options.port,options.host,options.backlog,callback)):options.server&&(this._server=options.server),this._server){let emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}options.perMessageDeflate===!0&&(options.perMessageDeflate={}),options.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=options,this._state=RUNNING}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(cb){if(this._state===CLOSED){cb&&this.once("close",()=>{cb(new Error("The server is not running"))}),process.nextTick(emitClose,this);return}if(cb&&this.once("close",cb),this._state!==CLOSING)if(this._state=CLOSING,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(emitClose,this):process.nextTick(emitClose,this);else{let server=this._server;this._removeListeners(),this._removeListeners=this._server=null,server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){let index=req.url.indexOf("?");if((index!==-1?req.url.slice(0,index):req.url)!==this.options.path)return!1}return!0}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);let key=req.headers["sec-websocket-key"],upgrade=req.headers.upgrade,version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){abortHandshakeOrEmitwsClientError(this,req,socket,405,"Invalid HTTP method");return}if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid Upgrade header");return}if(key===void 0||!keyRegex.test(key)){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Missing or invalid Sec-WebSocket-Key header");return}if(version!==13&&version!==8){abortHandshakeOrEmitwsClientError(this,req,socket,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}let secWebSocketProtocol=req.headers["sec-websocket-protocol"],protocols=new Set;if(secWebSocketProtocol!==void 0)try{protocols=subprotocol2.parse(secWebSocketProtocol)}catch{abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid Sec-WebSocket-Protocol header");return}let secWebSocketExtensions=req.headers["sec-websocket-extensions"],extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){let perMessageDeflate=new PerMessageDeflate2({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let offers=extension2.parse(secWebSocketExtensions);offers[PerMessageDeflate2.extensionName]&&(perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]),extensions[PerMessageDeflate2.extensionName]=perMessageDeflate)}catch{abortHandshakeOrEmitwsClientError(this,req,socket,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified)return abortHandshake(socket,code||401,message,headers);this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>RUNNING)return abortHandshake(socket,503);let headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${createHash2("sha1").update(key+GUID).digest("base64")}`],ws=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){let protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;protocol&&(headers.push(`Sec-WebSocket-Protocol: ${protocol}`),ws._protocol=protocol)}if(extensions[PerMessageDeflate2.extensionName]){let params=extensions[PerMessageDeflate2.extensionName].params,value=extension2.format({[PerMessageDeflate2.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`),ws._extensions=extensions}this.emit("headers",headers,req),socket.write(headers.concat(`\r
|
|
56
56
|
`).join(`\r
|
|
57
57
|
`)),socket.removeListener("error",socketOnError),ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(ws),ws.on("close",()=>{this.clients.delete(ws),this._shouldEmitClose&&!this.clients.size&&process.nextTick(emitClose,this)})),cb(ws,req)}};module.exports=WebSocketServer2;function addListeners(server,map){for(let event of Object.keys(map))server.on(event,map[event]);return function(){for(let event of Object.keys(map))server.removeListener(event,map[event])}}function emitClose(server){server._state=CLOSED,server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http3.STATUS_CODES[code],headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers},socket.once("finish",socket.destroy),socket.end(`HTTP/1.1 ${code} ${http3.STATUS_CODES[code]}\r
|
|
58
58
|
`+Object.keys(headers).map(h2=>`${h2}: ${headers[h2]}`).join(`\r
|
|
@@ -63,9 +63,15 @@ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Go
|
|
|
63
63
|
|
|
64
64
|
`)}function ownedSlice(text,start,end=text.length){return`${text.slice(start,end)} `.slice(0,-1)}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
|
|
65
65
|
|
|
66
|
-
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function getCurrentSystemPrompt(messages){let message=getCurrentSystemMessage(messages);return message?getSystemMessageText(message):""}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost.totalFromProvider=!1,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i2=requestedIndex;i2<EXTENDED_THINKING_LEVELS.length;i2++){let candidate=EXTENDED_THINKING_LEVELS[i2];if(availableLevels.includes(candidate))return candidate}for(let i2=requestedIndex-1;i2>=0;i2--){let candidate=EXTENDED_THINKING_LEVELS[i2];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}var MAX_PROVIDER_ERROR_BODY_CHARS=4e3;function normalizeProviderError(error){if(!(error instanceof Error))return{message:safeJsonStringify(error),messageCarriesBody:!1};let sdkError=error,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error.message.includes(body),message=status===void 0&&body===void 0?withCauseDetail(error):error.message;return{status,body,message,messageCarriesBody}}var MAX_CAUSE_DEPTH=5;function withCauseDetail(error){let deepest,current=error.cause;for(let depth=0;depth<MAX_CAUSE_DEPTH&¤t instanceof Error;depth++)deepest=current,current=current.cause;if(!deepest)return error.message;let detail=(deepest.message||deepest.name).trim(),code=deepest.code;return(typeof code=="string"||typeof code=="number")&&!detail.includes(String(code))&&(detail=detail?`${detail} (${code})`:String(code)),!detail||error.message.includes(detail)?error.message:error.message?`${error.message}: ${detail}`:detail}function extractStatus(error){if(typeof error.statusCode=="number")return error.statusCode;if(typeof error.status=="number")return error.status;if(typeof error.$metadata?.httpStatusCode=="number")return error.$metadata.httpStatusCode;if(typeof error.$response?.statusCode=="number")return error.$response.statusCode}function extractBody(error){let bodyText=pickBodyText(error);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error){if(typeof error.body=="string")return error.body;if(isPlainNonEmptyObject(error.error))return safeJsonStringify(error.error);let responseBody=error.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function formatProviderError(norm,prefix){return norm.messageCarriesBody||norm.status===void 0||norm.body===void 0?prefix!==void 0&&norm.status!==void 0?`${prefix} (${norm.status}): ${norm.message}`:norm.message:prefix!==void 0?`${prefix} (${norm.status}): ${norm.body}`:`${norm.status}: ${norm.body}`}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${ownedSlice(text,0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function headersToRecord(headers){let result={};for(let[key,value]of headers.entries())result[key]=value;return result}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}function isProviderError(error){return!(error instanceof Error)||!("status"in error)||!("headers"in error)?!1:(error.status===void 0||typeof error.status=="number")&&(error.headers===void 0||error.headers instanceof Headers)}function isRetryableProviderError(error){let shouldRetry=error.headers?.get("x-should-retry");return shouldRetry==="true"?!0:shouldRetry==="false"?!1:error.status===void 0?!0:error.status===408||error.status===409||error.status===429||typeof error.status=="number"&&error.status>=500}function validateServerRetryDelayMs(delayMs,maxRetryDelayMs,providerErrorMessage){let maxDelayMs=maxRetryDelayMs??6e4;if(maxDelayMs>0&&delayMs>maxDelayMs)throw new Error(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxDelayMs/1e3)}s). ${providerErrorMessage}`);return delayMs}function getRetryDelayMs(error,retryIndex,maxRetryDelayMs){let retryAfterMs=error.headers?.get("retry-after-ms");if(retryAfterMs){let value=Number.parseFloat(retryAfterMs);if(Number.isFinite(value))return validateServerRetryDelayMs(value,maxRetryDelayMs,error.message)}let retryAfter=error.headers?.get("retry-after");if(retryAfter){let seconds=Number.parseFloat(retryAfter),delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3;if(Number.isFinite(delayMs))return validateServerRetryDelayMs(delayMs,maxRetryDelayMs,error.message)}return Math.min(.5*2**retryIndex,8)*1e3*(1-Math.random()*.25)}function createAbortError(){let error=new Error("Request aborted");return error.name="AbortError",error}function abortableSleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(createAbortError());return}let onAbort=()=>{clearTimeout(timeout),reject(createAbortError())},timeout=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},Math.max(0,ms));signal?.addEventListener("abort",onAbort,{once:!0})})}async function retryProviderRequest(request,options={}){let maxRetries=options.maxRetries??0,retriesRemaining=maxRetries;for(;;)try{return await request()}catch(error){if(options.signal?.aborted)throw createAbortError();if(retriesRemaining<=0||!isProviderError(error)||!isRetryableProviderError(error)||error.status!==void 0&&options.noRetryStatuses?.includes(error.status))throw error;let retryIndex=maxRetries-retriesRemaining;retriesRemaining--,await abortableSleep(getRetryDelayMs(error,retryIndex,options.maxRetryDelayMs),options.signal)}}function sanitizeSurrogates(text){return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}var import_p_retry=__toESM(require_p_retry(),1),import_google_auth_library=__toESM(require_src5(),1);var import_stream=__toESM(require_stream(),1),import_extension=__toESM(require_extension(),1),import_permessage_deflate=__toESM(require_permessage_deflate(),1),import_receiver=__toESM(require_receiver(),1),import_sender=__toESM(require_sender(),1),import_subprotocol=__toESM(require_subprotocol(),1),import_websocket=__toESM(require_websocket(),1),import_websocket_server=__toESM(require_websocket_server(),1);var BaseModule=class{};function formatMap(templateString,valueMap){let regex=/\{([^}]+)\}/g;return templateString.replace(regex,(match,key)=>{if(Object.prototype.hasOwnProperty.call(valueMap,key)){let value=valueMap[key];return value!=null?String(value):""}else throw new Error(`Key '${key}' not found in valueMap.`)})}function setValueByPath(data,keys,value){for(let i2=0;i2<keys.length-1;i2++){let key=keys[i2];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(!(keyName in data))if(Array.isArray(value))data[keyName]=Array.from({length:value.length},()=>({}));else throw new Error(`Value must be a list given an array path ${key}`);if(Array.isArray(data[keyName])){let arrayData=data[keyName];if(Array.isArray(value))for(let j=0;j<arrayData.length;j++){let entry=arrayData[j];setValueByPath(entry,keys.slice(i2+1),value[j])}else for(let d of arrayData)setValueByPath(d,keys.slice(i2+1),value)}return}else if(key.endsWith("[0]")){let keyName=key.slice(0,-3);keyName in data||(data[keyName]=[{}]);let arrayData=data[keyName];setValueByPath(arrayData[0],keys.slice(i2+1),value);return}(!data[key]||typeof data[key]!="object")&&(data[key]={}),data=data[key]}let keyToSet=keys[keys.length-1],existingData=data[keyToSet];if(existingData!==void 0){if(!value||typeof value=="object"&&Object.keys(value).length===0||value===existingData)return;if(typeof existingData=="object"&&typeof value=="object"&&existingData!==null&&value!==null)Object.assign(existingData,value);else throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`)}else keyToSet==="_self"&&typeof value=="object"&&value!==null&&!Array.isArray(value)?Object.assign(data,value):data[keyToSet]=value}function getValueByPath(data,keys,defaultValue=void 0){try{if(keys.length===1&&keys[0]==="_self")return data;for(let i2=0;i2<keys.length;i2++){if(typeof data!="object"||data===null)return defaultValue;let key=keys[i2];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(keyName in data){let arrayData=data[keyName];return Array.isArray(arrayData)?arrayData.map(d=>getValueByPath(d,keys.slice(i2+1),defaultValue)):defaultValue}else return defaultValue}else data=data[key]}return data}catch(error){if(error instanceof TypeError)return defaultValue;throw error}}function tBytes$1(fromBytes){if(typeof fromBytes!="string")throw new Error("fromImageBytes must be a string");return fromBytes}function generateVideosOperationFromMldev$1(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev$1(fromResponse)),toObject}function generateVideosOperationFromVertex$1(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex$1(fromResponse)),toObject}function generateVideosResponseFromMldev$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev$1(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex$1(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generatedVideoFromMldev$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev$1(fromVideo)),toObject}function generatedVideoFromVertex$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex$1(fromVideo)),toObject}function videoFromMldev$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}var Outcome;(function(Outcome2){Outcome2.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",Outcome2.OUTCOME_OK="OUTCOME_OK",Outcome2.OUTCOME_FAILED="OUTCOME_FAILED",Outcome2.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(Outcome||(Outcome={}));var Language;(function(Language2){Language2.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",Language2.PYTHON="PYTHON"})(Language||(Language={}));var FunctionResponseScheduling;(function(FunctionResponseScheduling2){FunctionResponseScheduling2.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",FunctionResponseScheduling2.SILENT="SILENT",FunctionResponseScheduling2.WHEN_IDLE="WHEN_IDLE",FunctionResponseScheduling2.INTERRUPT="INTERRUPT"})(FunctionResponseScheduling||(FunctionResponseScheduling={}));var Type;(function(Type2){Type2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",Type2.STRING="STRING",Type2.NUMBER="NUMBER",Type2.INTEGER="INTEGER",Type2.BOOLEAN="BOOLEAN",Type2.ARRAY="ARRAY",Type2.OBJECT="OBJECT",Type2.NULL="NULL"})(Type||(Type={}));var AuthType;(function(AuthType2){AuthType2.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",AuthType2.NO_AUTH="NO_AUTH",AuthType2.API_KEY_AUTH="API_KEY_AUTH",AuthType2.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",AuthType2.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",AuthType2.OAUTH="OAUTH",AuthType2.OIDC_AUTH="OIDC_AUTH"})(AuthType||(AuthType={}));var HttpElementLocation;(function(HttpElementLocation2){HttpElementLocation2.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",HttpElementLocation2.HTTP_IN_QUERY="HTTP_IN_QUERY",HttpElementLocation2.HTTP_IN_HEADER="HTTP_IN_HEADER",HttpElementLocation2.HTTP_IN_PATH="HTTP_IN_PATH",HttpElementLocation2.HTTP_IN_BODY="HTTP_IN_BODY",HttpElementLocation2.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(HttpElementLocation||(HttpElementLocation={}));var ApiSpec;(function(ApiSpec2){ApiSpec2.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",ApiSpec2.SIMPLE_SEARCH="SIMPLE_SEARCH",ApiSpec2.ELASTIC_SEARCH="ELASTIC_SEARCH"})(ApiSpec||(ApiSpec={}));var Environment;(function(Environment2){Environment2.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",Environment2.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",Environment2.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",Environment2.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(Environment||(Environment={}));var SafetyPolicy;(function(SafetyPolicy2){SafetyPolicy2.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",SafetyPolicy2.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",SafetyPolicy2.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",SafetyPolicy2.COMMUNICATION_TOOL="COMMUNICATION_TOOL",SafetyPolicy2.ACCOUNT_CREATION="ACCOUNT_CREATION",SafetyPolicy2.DATA_MODIFICATION="DATA_MODIFICATION",SafetyPolicy2.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",SafetyPolicy2.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(SafetyPolicy||(SafetyPolicy={}));var PhishBlockThreshold;(function(PhishBlockThreshold2){PhishBlockThreshold2.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",PhishBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",PhishBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",PhishBlockThreshold2.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",PhishBlockThreshold2.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",PhishBlockThreshold2.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",PhishBlockThreshold2.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(PhishBlockThreshold||(PhishBlockThreshold={}));var Behavior;(function(Behavior2){Behavior2.UNSPECIFIED="UNSPECIFIED",Behavior2.BLOCKING="BLOCKING",Behavior2.NON_BLOCKING="NON_BLOCKING"})(Behavior||(Behavior={}));var DynamicRetrievalConfigMode;(function(DynamicRetrievalConfigMode2){DynamicRetrievalConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",DynamicRetrievalConfigMode2.MODE_DYNAMIC="MODE_DYNAMIC"})(DynamicRetrievalConfigMode||(DynamicRetrievalConfigMode={}));var ThinkingLevel;(function(ThinkingLevel2){ThinkingLevel2.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",ThinkingLevel2.MINIMAL="MINIMAL",ThinkingLevel2.LOW="LOW",ThinkingLevel2.MEDIUM="MEDIUM",ThinkingLevel2.HIGH="HIGH"})(ThinkingLevel||(ThinkingLevel={}));var PersonGeneration;(function(PersonGeneration2){PersonGeneration2.DONT_ALLOW="DONT_ALLOW",PersonGeneration2.ALLOW_ADULT="ALLOW_ADULT",PersonGeneration2.ALLOW_ALL="ALLOW_ALL"})(PersonGeneration||(PersonGeneration={}));var ProminentPeople;(function(ProminentPeople2){ProminentPeople2.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",ProminentPeople2.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",ProminentPeople2.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(ProminentPeople||(ProminentPeople={}));var HarmCategory;(function(HarmCategory2){HarmCategory2.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",HarmCategory2.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",HarmCategory2.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",HarmCategory2.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",HarmCategory2.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",HarmCategory2.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",HarmCategory2.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",HarmCategory2.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",HarmCategory2.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(HarmCategory||(HarmCategory={}));var HarmBlockMethod;(function(HarmBlockMethod2){HarmBlockMethod2.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",HarmBlockMethod2.SEVERITY="SEVERITY",HarmBlockMethod2.PROBABILITY="PROBABILITY"})(HarmBlockMethod||(HarmBlockMethod={}));var HarmBlockThreshold;(function(HarmBlockThreshold2){HarmBlockThreshold2.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",HarmBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",HarmBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",HarmBlockThreshold2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",HarmBlockThreshold2.BLOCK_NONE="BLOCK_NONE",HarmBlockThreshold2.OFF="OFF"})(HarmBlockThreshold||(HarmBlockThreshold={}));var FunctionCallingConfigMode;(function(FunctionCallingConfigMode2){FunctionCallingConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",FunctionCallingConfigMode2.AUTO="AUTO",FunctionCallingConfigMode2.ANY="ANY",FunctionCallingConfigMode2.NONE="NONE",FunctionCallingConfigMode2.VALIDATED="VALIDATED"})(FunctionCallingConfigMode||(FunctionCallingConfigMode={}));var FinishReason;(function(FinishReason2){FinishReason2.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",FinishReason2.STOP="STOP",FinishReason2.MAX_TOKENS="MAX_TOKENS",FinishReason2.SAFETY="SAFETY",FinishReason2.RECITATION="RECITATION",FinishReason2.LANGUAGE="LANGUAGE",FinishReason2.OTHER="OTHER",FinishReason2.BLOCKLIST="BLOCKLIST",FinishReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",FinishReason2.SPII="SPII",FinishReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",FinishReason2.IMAGE_SAFETY="IMAGE_SAFETY",FinishReason2.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",FinishReason2.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",FinishReason2.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",FinishReason2.NO_IMAGE="NO_IMAGE",FinishReason2.IMAGE_RECITATION="IMAGE_RECITATION",FinishReason2.IMAGE_OTHER="IMAGE_OTHER"})(FinishReason||(FinishReason={}));var HarmProbability;(function(HarmProbability2){HarmProbability2.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",HarmProbability2.NEGLIGIBLE="NEGLIGIBLE",HarmProbability2.LOW="LOW",HarmProbability2.MEDIUM="MEDIUM",HarmProbability2.HIGH="HIGH"})(HarmProbability||(HarmProbability={}));var HarmSeverity;(function(HarmSeverity2){HarmSeverity2.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",HarmSeverity2.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",HarmSeverity2.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",HarmSeverity2.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",HarmSeverity2.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(HarmSeverity||(HarmSeverity={}));var UrlRetrievalStatus;(function(UrlRetrievalStatus2){UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(UrlRetrievalStatus||(UrlRetrievalStatus={}));var BlockedReason;(function(BlockedReason2){BlockedReason2.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",BlockedReason2.SAFETY="SAFETY",BlockedReason2.OTHER="OTHER",BlockedReason2.BLOCKLIST="BLOCKLIST",BlockedReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",BlockedReason2.IMAGE_SAFETY="IMAGE_SAFETY",BlockedReason2.MODEL_ARMOR="MODEL_ARMOR",BlockedReason2.JAILBREAK="JAILBREAK"})(BlockedReason||(BlockedReason={}));var TrafficType;(function(TrafficType2){TrafficType2.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",TrafficType2.ON_DEMAND="ON_DEMAND",TrafficType2.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",TrafficType2.ON_DEMAND_FLEX="ON_DEMAND_FLEX",TrafficType2.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(TrafficType||(TrafficType={}));var MediaModality;(function(MediaModality2){MediaModality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",MediaModality2.TEXT="TEXT",MediaModality2.IMAGE="IMAGE",MediaModality2.VIDEO="VIDEO",MediaModality2.AUDIO="AUDIO",MediaModality2.DOCUMENT="DOCUMENT"})(MediaModality||(MediaModality={}));var ModelStage;(function(ModelStage2){ModelStage2.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",ModelStage2.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",ModelStage2.EXPERIMENTAL="EXPERIMENTAL",ModelStage2.PREVIEW="PREVIEW",ModelStage2.STABLE="STABLE",ModelStage2.LEGACY="LEGACY",ModelStage2.DEPRECATED="DEPRECATED",ModelStage2.RETIRED="RETIRED"})(ModelStage||(ModelStage={}));var MediaResolution;(function(MediaResolution2){MediaResolution2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",MediaResolution2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",MediaResolution2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",MediaResolution2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(MediaResolution||(MediaResolution={}));var Modality;(function(Modality2){Modality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",Modality2.TEXT="TEXT",Modality2.IMAGE="IMAGE",Modality2.AUDIO="AUDIO",Modality2.VIDEO="VIDEO"})(Modality||(Modality={}));var Delivery;(function(Delivery2){Delivery2.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",Delivery2.INLINE="INLINE",Delivery2.URI="URI"})(Delivery||(Delivery={}));var AspectRatio;(function(AspectRatio2){AspectRatio2.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",AspectRatio2.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",AspectRatio2.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",AspectRatio2.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",AspectRatio2.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",AspectRatio2.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",AspectRatio2.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",AspectRatio2.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",AspectRatio2.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",AspectRatio2.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",AspectRatio2.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",AspectRatio2.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",AspectRatio2.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(AspectRatio||(AspectRatio={}));var ImageSize;(function(ImageSize2){ImageSize2.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",ImageSize2.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",ImageSize2.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",ImageSize2.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",ImageSize2.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(ImageSize||(ImageSize={}));var TuningMode;(function(TuningMode2){TuningMode2.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",TuningMode2.TUNING_MODE_FULL="TUNING_MODE_FULL",TuningMode2.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(TuningMode||(TuningMode={}));var AdapterSize;(function(AdapterSize2){AdapterSize2.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",AdapterSize2.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",AdapterSize2.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",AdapterSize2.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",AdapterSize2.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",AdapterSize2.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",AdapterSize2.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(AdapterSize||(AdapterSize={}));var ResponseParseType;(function(ResponseParseType2){ResponseParseType2.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",ResponseParseType2.IDENTITY="IDENTITY",ResponseParseType2.REGEX_EXTRACT="REGEX_EXTRACT"})(ResponseParseType||(ResponseParseType={}));var MatchOperation;(function(MatchOperation2){MatchOperation2.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",MatchOperation2.REGEX_CONTAINS="REGEX_CONTAINS",MatchOperation2.PARTIAL_MATCH="PARTIAL_MATCH",MatchOperation2.EXACT_MATCH="EXACT_MATCH"})(MatchOperation||(MatchOperation={}));var ReinforcementTuningThinkingLevel;(function(ReinforcementTuningThinkingLevel2){ReinforcementTuningThinkingLevel2.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",ReinforcementTuningThinkingLevel2.MINIMAL="MINIMAL",ReinforcementTuningThinkingLevel2.HIGH="HIGH"})(ReinforcementTuningThinkingLevel||(ReinforcementTuningThinkingLevel={}));var JobState;(function(JobState2){JobState2.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",JobState2.JOB_STATE_QUEUED="JOB_STATE_QUEUED",JobState2.JOB_STATE_PENDING="JOB_STATE_PENDING",JobState2.JOB_STATE_RUNNING="JOB_STATE_RUNNING",JobState2.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",JobState2.JOB_STATE_FAILED="JOB_STATE_FAILED",JobState2.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",JobState2.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",JobState2.JOB_STATE_PAUSED="JOB_STATE_PAUSED",JobState2.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",JobState2.JOB_STATE_UPDATING="JOB_STATE_UPDATING",JobState2.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(JobState||(JobState={}));var TuningJobState;(function(TuningJobState2){TuningJobState2.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",TuningJobState2.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",TuningJobState2.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",TuningJobState2.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(TuningJobState||(TuningJobState={}));var AggregationMetric;(function(AggregationMetric2){AggregationMetric2.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",AggregationMetric2.AVERAGE="AVERAGE",AggregationMetric2.MODE="MODE",AggregationMetric2.STANDARD_DEVIATION="STANDARD_DEVIATION",AggregationMetric2.VARIANCE="VARIANCE",AggregationMetric2.MINIMUM="MINIMUM",AggregationMetric2.MAXIMUM="MAXIMUM",AggregationMetric2.MEDIAN="MEDIAN",AggregationMetric2.PERCENTILE_P90="PERCENTILE_P90",AggregationMetric2.PERCENTILE_P95="PERCENTILE_P95",AggregationMetric2.PERCENTILE_P99="PERCENTILE_P99"})(AggregationMetric||(AggregationMetric={}));var PairwiseChoice;(function(PairwiseChoice2){PairwiseChoice2.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",PairwiseChoice2.BASELINE="BASELINE",PairwiseChoice2.CANDIDATE="CANDIDATE",PairwiseChoice2.TIE="TIE"})(PairwiseChoice||(PairwiseChoice={}));var VideoOrientation;(function(VideoOrientation2){VideoOrientation2.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",VideoOrientation2.LANDSCAPE="LANDSCAPE",VideoOrientation2.PORTRAIT="PORTRAIT"})(VideoOrientation||(VideoOrientation={}));var TuningSpeed;(function(TuningSpeed2){TuningSpeed2.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",TuningSpeed2.REGULAR="REGULAR",TuningSpeed2.FAST="FAST"})(TuningSpeed||(TuningSpeed={}));var TuningTask;(function(TuningTask2){TuningTask2.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",TuningTask2.TUNING_TASK_I2V="TUNING_TASK_I2V",TuningTask2.TUNING_TASK_T2V="TUNING_TASK_T2V",TuningTask2.TUNING_TASK_R2V="TUNING_TASK_R2V"})(TuningTask||(TuningTask={}));var DocumentState;(function(DocumentState2){DocumentState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",DocumentState2.STATE_PENDING="STATE_PENDING",DocumentState2.STATE_ACTIVE="STATE_ACTIVE",DocumentState2.STATE_FAILED="STATE_FAILED"})(DocumentState||(DocumentState={}));var ServiceTier;(function(ServiceTier2){ServiceTier2.UNSPECIFIED="unspecified",ServiceTier2.FLEX="flex",ServiceTier2.STANDARD="standard",ServiceTier2.PRIORITY="priority"})(ServiceTier||(ServiceTier={}));var MediaProcessing;(function(MediaProcessing2){MediaProcessing2.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",MediaProcessing2.STATIC="STATIC",MediaProcessing2.AGENTIC="AGENTIC"})(MediaProcessing||(MediaProcessing={}));var PartMediaResolutionLevel;(function(PartMediaResolutionLevel2){PartMediaResolutionLevel2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",PartMediaResolutionLevel2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",PartMediaResolutionLevel2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",PartMediaResolutionLevel2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",PartMediaResolutionLevel2.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(PartMediaResolutionLevel||(PartMediaResolutionLevel={}));var ToolType;(function(ToolType2){ToolType2.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",ToolType2.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",ToolType2.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",ToolType2.URL_CONTEXT="URL_CONTEXT",ToolType2.GOOGLE_MAPS="GOOGLE_MAPS",ToolType2.FILE_SEARCH="FILE_SEARCH",ToolType2.MEDIA_PROCESSING="MEDIA_PROCESSING"})(ToolType||(ToolType={}));var ResourceScope;(function(ResourceScope2){ResourceScope2.COLLECTION="COLLECTION"})(ResourceScope||(ResourceScope={}));var FeatureSelectionPreference;(function(FeatureSelectionPreference2){FeatureSelectionPreference2.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",FeatureSelectionPreference2.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",FeatureSelectionPreference2.BALANCED="BALANCED",FeatureSelectionPreference2.PRIORITIZE_COST="PRIORITIZE_COST"})(FeatureSelectionPreference||(FeatureSelectionPreference={}));var EmbeddingApiType;(function(EmbeddingApiType2){EmbeddingApiType2.PREDICT="PREDICT",EmbeddingApiType2.EMBED_CONTENT="EMBED_CONTENT"})(EmbeddingApiType||(EmbeddingApiType={}));var SafetyFilterLevel;(function(SafetyFilterLevel2){SafetyFilterLevel2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",SafetyFilterLevel2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",SafetyFilterLevel2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",SafetyFilterLevel2.BLOCK_NONE="BLOCK_NONE"})(SafetyFilterLevel||(SafetyFilterLevel={}));var ImagePromptLanguage;(function(ImagePromptLanguage2){ImagePromptLanguage2.auto="auto",ImagePromptLanguage2.en="en",ImagePromptLanguage2.ja="ja",ImagePromptLanguage2.ko="ko",ImagePromptLanguage2.hi="hi",ImagePromptLanguage2.zh="zh",ImagePromptLanguage2.pt="pt",ImagePromptLanguage2.es="es"})(ImagePromptLanguage||(ImagePromptLanguage={}));var MaskReferenceMode;(function(MaskReferenceMode2){MaskReferenceMode2.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",MaskReferenceMode2.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",MaskReferenceMode2.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",MaskReferenceMode2.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",MaskReferenceMode2.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(MaskReferenceMode||(MaskReferenceMode={}));var ControlReferenceType;(function(ControlReferenceType2){ControlReferenceType2.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",ControlReferenceType2.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",ControlReferenceType2.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",ControlReferenceType2.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(ControlReferenceType||(ControlReferenceType={}));var SubjectReferenceType;(function(SubjectReferenceType2){SubjectReferenceType2.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",SubjectReferenceType2.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",SubjectReferenceType2.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",SubjectReferenceType2.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(SubjectReferenceType||(SubjectReferenceType={}));var EditMode;(function(EditMode2){EditMode2.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",EditMode2.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",EditMode2.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",EditMode2.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",EditMode2.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",EditMode2.EDIT_MODE_STYLE="EDIT_MODE_STYLE",EditMode2.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",EditMode2.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(EditMode||(EditMode={}));var SegmentMode;(function(SegmentMode2){SegmentMode2.FOREGROUND="FOREGROUND",SegmentMode2.BACKGROUND="BACKGROUND",SegmentMode2.PROMPT="PROMPT",SegmentMode2.SEMANTIC="SEMANTIC",SegmentMode2.INTERACTIVE="INTERACTIVE"})(SegmentMode||(SegmentMode={}));var VideoGenerationReferenceType;(function(VideoGenerationReferenceType2){VideoGenerationReferenceType2.ASSET="ASSET",VideoGenerationReferenceType2.STYLE="STYLE"})(VideoGenerationReferenceType||(VideoGenerationReferenceType={}));var VideoGenerationMaskMode;(function(VideoGenerationMaskMode2){VideoGenerationMaskMode2.INSERT="INSERT",VideoGenerationMaskMode2.REMOVE="REMOVE",VideoGenerationMaskMode2.REMOVE_STATIC="REMOVE_STATIC",VideoGenerationMaskMode2.OUTPAINT="OUTPAINT"})(VideoGenerationMaskMode||(VideoGenerationMaskMode={}));var VideoCompressionQuality;(function(VideoCompressionQuality2){VideoCompressionQuality2.OPTIMIZED="OPTIMIZED",VideoCompressionQuality2.LOSSLESS="LOSSLESS"})(VideoCompressionQuality||(VideoCompressionQuality={}));var ImageResizeMode;(function(ImageResizeMode2){ImageResizeMode2.CROP="CROP",ImageResizeMode2.PAD="PAD"})(ImageResizeMode||(ImageResizeMode={}));var TuningMethod;(function(TuningMethod2){TuningMethod2.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",TuningMethod2.PREFERENCE_TUNING="PREFERENCE_TUNING",TuningMethod2.DISTILLATION="DISTILLATION",TuningMethod2.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(TuningMethod||(TuningMethod={}));var FileState;(function(FileState2){FileState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",FileState2.PROCESSING="PROCESSING",FileState2.ACTIVE="ACTIVE",FileState2.FAILED="FAILED"})(FileState||(FileState={}));var FileSource;(function(FileSource2){FileSource2.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",FileSource2.UPLOADED="UPLOADED",FileSource2.GENERATED="GENERATED",FileSource2.REGISTERED="REGISTERED"})(FileSource||(FileSource={}));var TurnCompleteReason;(function(TurnCompleteReason2){TurnCompleteReason2.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",TurnCompleteReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",TurnCompleteReason2.RESPONSE_REJECTED="RESPONSE_REJECTED",TurnCompleteReason2.NEED_MORE_INPUT="NEED_MORE_INPUT",TurnCompleteReason2.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",TurnCompleteReason2.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",TurnCompleteReason2.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",TurnCompleteReason2.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",TurnCompleteReason2.INPUT_OTHER="INPUT_OTHER",TurnCompleteReason2.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",TurnCompleteReason2.BLOCKLIST="BLOCKLIST",TurnCompleteReason2.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",TurnCompleteReason2.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",TurnCompleteReason2.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",TurnCompleteReason2.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",TurnCompleteReason2.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",TurnCompleteReason2.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",TurnCompleteReason2.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",TurnCompleteReason2.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",TurnCompleteReason2.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",TurnCompleteReason2.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",TurnCompleteReason2.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",TurnCompleteReason2.GENERATED_OTHER="GENERATED_OTHER",TurnCompleteReason2.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(TurnCompleteReason||(TurnCompleteReason={}));var InteractionStatus;(function(InteractionStatus2){InteractionStatus2.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",InteractionStatus2.IN_PROGRESS="IN_PROGRESS",InteractionStatus2.REQUIRES_ACTION="REQUIRES_ACTION",InteractionStatus2.IDLE="IDLE"})(InteractionStatus||(InteractionStatus={}));var VadSignalType;(function(VadSignalType2){VadSignalType2.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",VadSignalType2.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",VadSignalType2.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(VadSignalType||(VadSignalType={}));var VoiceActivityType;(function(VoiceActivityType2){VoiceActivityType2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",VoiceActivityType2.ACTIVITY_START="ACTIVITY_START",VoiceActivityType2.ACTIVITY_END="ACTIVITY_END"})(VoiceActivityType||(VoiceActivityType={}));var StartSensitivity;(function(StartSensitivity2){StartSensitivity2.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",StartSensitivity2.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",StartSensitivity2.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(StartSensitivity||(StartSensitivity={}));var EndSensitivity;(function(EndSensitivity2){EndSensitivity2.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",EndSensitivity2.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",EndSensitivity2.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(EndSensitivity||(EndSensitivity={}));var ActivityHandling;(function(ActivityHandling2){ActivityHandling2.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",ActivityHandling2.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",ActivityHandling2.NO_INTERRUPTION="NO_INTERRUPTION"})(ActivityHandling||(ActivityHandling={}));var TurnCoverage;(function(TurnCoverage2){TurnCoverage2.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",TurnCoverage2.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",TurnCoverage2.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",TurnCoverage2.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(TurnCoverage||(TurnCoverage={}));var AudioTranscriptionConfigMode;(function(AudioTranscriptionConfigMode2){AudioTranscriptionConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",AudioTranscriptionConfigMode2.VERBATIM="VERBATIM",AudioTranscriptionConfigMode2.SMART="SMART"})(AudioTranscriptionConfigMode||(AudioTranscriptionConfigMode={}));var Scale;(function(Scale2){Scale2.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",Scale2.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",Scale2.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",Scale2.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",Scale2.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",Scale2.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",Scale2.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",Scale2.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",Scale2.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",Scale2.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",Scale2.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",Scale2.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",Scale2.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(Scale||(Scale={}));var MusicGenerationMode;(function(MusicGenerationMode2){MusicGenerationMode2.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",MusicGenerationMode2.QUALITY="QUALITY",MusicGenerationMode2.DIVERSITY="DIVERSITY",MusicGenerationMode2.VOCALIZATION="VOCALIZATION"})(MusicGenerationMode||(MusicGenerationMode={}));var LiveMusicPlaybackControl;(function(LiveMusicPlaybackControl2){LiveMusicPlaybackControl2.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",LiveMusicPlaybackControl2.PLAY="PLAY",LiveMusicPlaybackControl2.PAUSE="PAUSE",LiveMusicPlaybackControl2.STOP="STOP",LiveMusicPlaybackControl2.RESET_CONTEXT="RESET_CONTEXT"})(LiveMusicPlaybackControl||(LiveMusicPlaybackControl={}));var GenerateContentResponse=class{get text(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let text="",anyTextPartText=!1,nonTextParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="text"&&fieldName!=="thought"&&fieldName!=="thoughtSignature"&&(fieldValue!==null||fieldValue!==void 0)&&nonTextParts.push(fieldName);if(typeof part.text=="string"){if(typeof part.thought=="boolean"&&part.thought)continue;anyTextPartText=!0,text+=part.text}}return nonTextParts.length>0&&console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),anyTextPartText?text:void 0}get data(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let data="",nonDataParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="inlineData"&&(fieldValue!==null||fieldValue!==void 0)&&nonDataParts.push(fieldName);part.inlineData&&typeof part.inlineData.data=="string"&&(data+=atob(part.inlineData.data))}return nonDataParts.length>0&&console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),data.length>0?btoa(data):void 0}get functionCalls(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let functionCalls=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.functionCall).map(part=>part.functionCall).filter(functionCall=>functionCall!==void 0);if(functionCalls?.length!==0)return functionCalls}get executableCode(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let executableCode=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.executableCode).map(part=>part.executableCode).filter(executableCode2=>executableCode2!==void 0);if(executableCode?.length!==0)return(_j=executableCode?.[0])===null||_j===void 0?void 0:_j.code}get codeExecutionResult(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let codeExecutionResult=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.codeExecutionResult).map(part=>part.codeExecutionResult).filter(codeExecutionResult2=>codeExecutionResult2!==void 0);if(codeExecutionResult?.length!==0)return(_j=codeExecutionResult?.[0])===null||_j===void 0?void 0:_j.output}},EmbedContentResponse=class{},GenerateImagesResponse=class{},EditImageResponse=class{},UpscaleImageResponse=class{},RecontextImageResponse=class{},SegmentImageResponse=class{},ListModelsResponse=class{},DeleteModelResponse=class{};var CountTokensResponse=class{},ComputeTokensResponse=class{};var GenerateVideosOperation=class _GenerateVideosOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _GenerateVideosOperation,response,op=apiResponse;return _isVertexAI?response=generateVideosOperationFromVertex$1(op):response=generateVideosOperationFromMldev$1(op),Object.assign(operation,response),operation}};function tModel(apiClient,model){if(!model||typeof model!="string")throw new Error("model is required and must be a string");if(model.includes("..")||model.includes("?")||model.includes("&"))throw new Error("invalid model parameter");if(apiClient.isVertexAI()){if(model.startsWith("publishers/")||model.startsWith("projects/")||model.startsWith("models/"))return model;if(model.indexOf("/")>=0){let parts=model.split("/",2);return`publishers/${parts[0]}/models/${parts[1]}`}else return`publishers/google/models/${model}`}else return model.startsWith("models/")||model.startsWith("tunedModels/")?model:`models/${model}`}function tPart(origin){if(origin==null)throw new Error("PartUnion is required");if(typeof origin=="object")return origin;if(typeof origin=="string")return{text:origin};throw new Error(`Unsupported part type: ${typeof origin}`)}function tParts(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("PartListUnion is required");return Array.isArray(origin)?origin.map(item=>tPart(item)):[tPart(origin)]}function _isContent(origin){return origin!=null&&typeof origin=="object"&&"parts"in origin&&Array.isArray(origin.parts)}function _isFunctionCallPart(origin){return origin!=null&&typeof origin=="object"&&"functionCall"in origin}function _isFunctionResponsePart(origin){return origin!=null&&typeof origin=="object"&&"functionResponse"in origin}function tContent(origin){if(origin==null)throw new Error("ContentUnion is required");return _isContent(origin)?origin:{role:"user",parts:tParts(origin)}}function tContentsForEmbed(apiClient,origin){if(!origin)return[];if(apiClient.isVertexAI()&&Array.isArray(origin))return origin.flatMap(item=>{let content=tContent(item);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]});if(apiClient.isVertexAI()){let content=tContent(origin);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]}return Array.isArray(origin)?origin.map(item=>tContent(item)):[tContent(origin)]}function tContents(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("contents are required");if(!Array.isArray(origin)){if(_isFunctionCallPart(origin)||_isFunctionResponsePart(origin))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[tContent(origin)]}let result=[],accumulatedParts=[],isContentArray=_isContent(origin[0]);for(let item of origin){let isContent=_isContent(item);if(isContent!=isContentArray)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(isContent)result.push(item);else{if(_isFunctionCallPart(item)||_isFunctionResponsePart(item))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");accumulatedParts.push(item)}}return isContentArray||result.push({role:"user",parts:tParts(accumulatedParts)}),result}function flattenTypeArrayToAnyOf(typeList,resultingSchema){typeList.includes("null")&&(resultingSchema.nullable=!0);let listWithoutNull=typeList.filter(type=>type!=="null");if(listWithoutNull.length===1)resultingSchema.type=Object.values(Type).includes(listWithoutNull[0].toUpperCase())?listWithoutNull[0].toUpperCase():Type.TYPE_UNSPECIFIED;else{resultingSchema.anyOf=[];for(let i2 of listWithoutNull)resultingSchema.anyOf.push({type:Object.values(Type).includes(i2.toUpperCase())?i2.toUpperCase():Type.TYPE_UNSPECIFIED})}}function processJsonSchema(_jsonSchema){let genAISchema={},schemaFieldNames=["items"],listSchemaFieldNames=["anyOf"],dictSchemaFieldNames=["properties"];if(_jsonSchema.type&&_jsonSchema.anyOf)throw new Error("type and anyOf cannot be both populated.");let incomingAnyOf=_jsonSchema.anyOf;incomingAnyOf!=null&&incomingAnyOf.length==2&&(incomingAnyOf[0].type==="null"?(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[1]):incomingAnyOf[1].type==="null"&&(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[0])),_jsonSchema.type instanceof Array&&flattenTypeArrayToAnyOf(_jsonSchema.type,genAISchema);for(let[fieldName,fieldValue]of Object.entries(_jsonSchema))if(fieldValue!=null)if(fieldName=="type"){if(fieldValue==="null")throw new Error("type: null can not be the only possible type for the field.");if(fieldValue instanceof Array)continue;genAISchema.type=Object.values(Type).includes(fieldValue.toUpperCase())?fieldValue.toUpperCase():Type.TYPE_UNSPECIFIED}else if(schemaFieldNames.includes(fieldName))genAISchema[fieldName]=processJsonSchema(fieldValue);else if(listSchemaFieldNames.includes(fieldName)){let listSchemaFieldValue=[];for(let item of fieldValue){if(item.type=="null"){genAISchema.nullable=!0;continue}listSchemaFieldValue.push(processJsonSchema(item))}genAISchema[fieldName]=listSchemaFieldValue}else if(dictSchemaFieldNames.includes(fieldName)){let dictSchemaFieldValue={};for(let[key,value]of Object.entries(fieldValue))dictSchemaFieldValue[key]=processJsonSchema(value);genAISchema[fieldName]=dictSchemaFieldValue}else{if(fieldName==="additionalProperties")continue;genAISchema[fieldName]=fieldValue}return genAISchema}function tSchema(schema){return processJsonSchema(schema)}function tSpeechConfig(speechConfig){if(typeof speechConfig=="object")return speechConfig;if(typeof speechConfig=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:speechConfig}}};throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`)}function tTool(tool){if(tool.functionDeclarations)for(let functionDeclaration of tool.functionDeclarations)functionDeclaration.parameters&&(Object.keys(functionDeclaration.parameters).includes("$schema")?functionDeclaration.parametersJsonSchema||(functionDeclaration.parametersJsonSchema=functionDeclaration.parameters,delete functionDeclaration.parameters):functionDeclaration.parameters=processJsonSchema(functionDeclaration.parameters)),functionDeclaration.response&&(Object.keys(functionDeclaration.response).includes("$schema")?functionDeclaration.responseJsonSchema||(functionDeclaration.responseJsonSchema=functionDeclaration.response,delete functionDeclaration.response):functionDeclaration.response=processJsonSchema(functionDeclaration.response));return tool}function tTools(tools){if(tools==null)throw new Error("tools is required");if(!Array.isArray(tools))throw new Error("tools is required and must be an array of Tools");let result=[];for(let tool of tools)result.push(tool);return result}function resourceName(client,resourceName2,resourcePrefix,splitsAfterPrefix=1){let shouldAppendPrefix=!resourceName2.startsWith(`${resourcePrefix}/`)&&resourceName2.split("/").length===splitsAfterPrefix;return client.isVertexAI()?resourceName2.startsWith("projects/")?resourceName2:resourceName2.startsWith("locations/")?`projects/${client.getProject()}/${resourceName2}`:resourceName2.startsWith(`${resourcePrefix}/`)?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName2}`:shouldAppendPrefix?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName2}`:resourceName2:shouldAppendPrefix?`${resourcePrefix}/${resourceName2}`:resourceName2}function tCachedContentName(apiClient,name){if(typeof name!="string")throw new Error("name must be a string");return resourceName(apiClient,name,"cachedContents")}function tBytes(fromImageBytes){return tBytes$1(fromImageBytes)}function tModelsUrl(apiClient,baseModels){let res;return apiClient.isVertexAI()?res=baseModels?"publishers/google/models":"models":res=baseModels?"models":"tunedModels",res}function tExtractModels(response){for(let key of["models","tunedModels","publisherModels"])if(hasField(response,key))return response[key];return[]}function hasField(data,fieldName){return data!==null&&typeof data=="object"&&fieldName in data}function mcpToGeminiTool(mcpTool,config={}){let mcpToolSchema=mcpTool,functionDeclaration={name:mcpToolSchema.name,description:mcpToolSchema.description,parametersJsonSchema:mcpToolSchema.inputSchema};return mcpToolSchema.outputSchema&&(functionDeclaration.responseJsonSchema=mcpToolSchema.outputSchema),config.behavior&&(functionDeclaration.behavior=config.behavior),{functionDeclarations:[functionDeclaration]}}function mcpToolsToGeminiTool(mcpTools,config={}){let functionDeclarations=[],toolNames=new Set;for(let mcpTool of mcpTools){let mcpToolName=mcpTool.name;if(toolNames.has(mcpToolName))throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);toolNames.add(mcpToolName);let geminiTool=mcpToGeminiTool(mcpTool,config);geminiTool.functionDeclarations&&functionDeclarations.push(...geminiTool.functionDeclarations)}return{functionDeclarations}}function tIsVertexEmbedContentModel(model){return model.includes("gemini")&&model!=="gemini-embedding-001"||model.includes("maas")}var PagedItem;(function(PagedItem2){PagedItem2.PAGED_ITEM_BATCH_JOBS="batchJobs",PagedItem2.PAGED_ITEM_MODELS="models",PagedItem2.PAGED_ITEM_TUNING_JOBS="tuningJobs",PagedItem2.PAGED_ITEM_FILES="files",PagedItem2.PAGED_ITEM_CACHED_CONTENTS="cachedContents",PagedItem2.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",PagedItem2.PAGED_ITEM_DOCUMENTS="documents",PagedItem2.PAGED_ITEM_SKILLS="skills"})(PagedItem||(PagedItem={}));var Pager=class{constructor(name,request,response,params){this.pageInternal=[],this.paramsInternal={},this.requestInternal=request,this.init(name,response,params)}init(name,response,params){var _a2,_b;this.nameInternal=name,this.pageInternal=response[this.nameInternal]||[],this.sdkHttpResponseInternal=response?.sdkHttpResponse,this.idxInternal=0;let requestParams={config:{}};!params||Object.keys(params).length===0?requestParams={config:{}}:typeof params=="object"?requestParams=Object.assign({},params):requestParams=params,requestParams.config&&(requestParams.config.pageToken=response.nextPageToken),this.paramsInternal=requestParams,this.pageInternalSize=(_b=(_a2=requestParams.config)===null||_a2===void 0?void 0:_a2.pageSize)!==null&&_b!==void 0?_b:this.pageInternal.length}initNextPage(response){this.init(this.nameInternal,response,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(index){return this.pageInternal[index]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let item=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:item,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let response=await this.requestInternal(this.params);return this.initNextPage(response),this.page}hasNextPage(){var _a2;return((_a2=this.params.config)===null||_a2===void 0?void 0:_a2.pageToken)!==void 0}};function __values(o){var s2=typeof Symbol=="function"&&Symbol.iterator,m2=s2&&o[s2],i2=0;if(m2)return m2.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i2>=o.length&&(o=void 0),{value:o&&o[i2++],done:!o}}};throw new TypeError(s2?"Object is not iterable.":"Symbol.iterator is not defined.")}function __await(v){return this instanceof __await?(this.v=v,this):new __await(v)}function __asyncGenerator(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var g=generator.apply(thisArg,_arguments||[]),i2,q=[];return i2=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i2[Symbol.asyncIterator]=function(){return this},i2;function awaitReturn(f3){return function(v){return Promise.resolve(v).then(f3,reject)}}function verb(n,f3){g[n]&&(i2[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})},f3&&(i2[n]=f3(i2[n])))}function resume(n,v){try{step(g[n](v))}catch(e2){settle(q[0][3],e2)}}function step(r2){r2.value instanceof __await?Promise.resolve(r2.value.v).then(fulfill,reject):settle(q[0][2],r2)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f3,v){f3(v),q.shift(),q.length&&resume(q[0][0],q[0][1])}}function __asyncValues(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m2=o[Symbol.asyncIterator],i2;return m2?m2.call(o):(o=typeof __values=="function"?__values(o):o[Symbol.iterator](),i2={},verb("next"),verb("throw"),verb("return"),i2[Symbol.asyncIterator]=function(){return this},i2);function verb(n){i2[n]=o[n]&&function(v){return new Promise(function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value)})}}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v2){resolve({value:v2,done:d})},reject)}}function authConfigToMldev$1(fromObject,_rootObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev$1(fromObject,_rootObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function candidateFromMldev(fromObject,rootObject){let toObject={},fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],fromContent);let fromCitationMetadata=getValueByPath(fromObject,["citationMetadata"]);fromCitationMetadata!=null&&setValueByPath(toObject,["citationMetadata"],citationMetadataFromMldev(fromCitationMetadata));let fromTokenCount=getValueByPath(fromObject,["tokenCount"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromFinishReason=getValueByPath(fromObject,["finishReason"]);fromFinishReason!=null&&setValueByPath(toObject,["finishReason"],fromFinishReason);let fromGroundingMetadata=getValueByPath(fromObject,["groundingMetadata"]);fromGroundingMetadata!=null&&setValueByPath(toObject,["groundingMetadata"],fromGroundingMetadata);let fromAvgLogprobs=getValueByPath(fromObject,["avgLogprobs"]);fromAvgLogprobs!=null&&setValueByPath(toObject,["avgLogprobs"],fromAvgLogprobs);let fromIndex=getValueByPath(fromObject,["index"]);fromIndex!=null&&setValueByPath(toObject,["index"],fromIndex);let fromLogprobsResult=getValueByPath(fromObject,["logprobsResult"]);fromLogprobsResult!=null&&setValueByPath(toObject,["logprobsResult"],fromLogprobsResult);let fromSafetyRatings=getValueByPath(fromObject,["safetyRatings"]);if(fromSafetyRatings!=null){let transformedList=fromSafetyRatings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["safetyRatings"],transformedList)}let fromUrlContextMetadata=getValueByPath(fromObject,["urlContextMetadata"]);return fromUrlContextMetadata!=null&&setValueByPath(toObject,["urlContextMetadata"],fromUrlContextMetadata),toObject}function citationMetadataFromMldev(fromObject,_rootObject){let toObject={},fromCitations=getValueByPath(fromObject,["citationSources"]);if(fromCitations!=null){let transformedList=fromCitations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["citations"],transformedList)}return toObject}function computeTokensParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}return toObject}function computeTokensResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTokensInfo=getValueByPath(fromObject,["tokensInfo"]);if(fromTokensInfo!=null){let transformedList=fromTokensInfo;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensInfo"],transformedList)}return toObject}function computerUseToVertex(fromObject,_rootObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentEmbeddingFromVertex(fromObject,rootObject){let toObject={},fromValues=getValueByPath(fromObject,["values"]);fromValues!=null&&setValueByPath(toObject,["values"],fromValues);let fromStatistics=getValueByPath(fromObject,["statistics"]);return fromStatistics!=null&&setValueByPath(toObject,["statistics"],contentEmbeddingStatisticsFromVertex(fromStatistics)),toObject}function contentEmbeddingStatisticsFromVertex(fromObject,_rootObject){let toObject={},fromTruncated=getValueByPath(fromObject,["truncated"]);fromTruncated!=null&&setValueByPath(toObject,["truncated"],fromTruncated);let fromTokenCount=getValueByPath(fromObject,["token_count"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromTokensDetails=getValueByPath(fromObject,["tokensDetails"]);if(fromTokensDetails!=null){let transformedList=fromTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensDetails"],transformedList)}return toObject}function contentToMldev$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function controlReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromControlType=getValueByPath(fromObject,["controlType"]);fromControlType!=null&&setValueByPath(toObject,["controlType"],fromControlType);let fromEnableControlImageComputation=getValueByPath(fromObject,["enableControlImageComputation"]);return fromEnableControlImageComputation!=null&&setValueByPath(toObject,["computeControl"],fromEnableControlImageComputation),toObject}function countTokensConfigToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function countTokensConfigToVertex(fromObject,parentObject,rootObject){let toObject={},fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["generationConfig"],generationConfigToVertex(fromGenerationConfig)),toObject}function countTokensParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToMldev(fromConfig),toObject}function countTokensParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToVertex(fromConfig,toObject),toObject}function countTokensResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens);let fromCachedContentTokenCount=getValueByPath(fromObject,["cachedContentTokenCount"]);return fromCachedContentTokenCount!=null&&setValueByPath(toObject,["cachedContentTokenCount"],fromCachedContentTokenCount),toObject}function countTokensResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);return fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens),toObject}function deleteModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteModelResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function editImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromEditMode=getValueByPath(fromObject,["editMode"]);parentObject!==void 0&&fromEditMode!=null&&setValueByPath(parentObject,["parameters","editMode"],fromEditMode);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);return parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","editConfig","baseSteps"],fromBaseSteps),toObject}function editImageParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>referenceImageAPIInternalToVertex(item))),setValueByPath(toObject,["instances[0]","referenceImages"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&editImageConfigToVertex(fromConfig,toObject),toObject}function editImageResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function embedContentConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["requests[]","taskType"],fromTaskType);let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["requests[]","title"],fromTitle);let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);if(parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["requests[]","outputDimensionality"],fromOutputDimensionality),getValueByPath(fromObject,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function embedContentConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorTaskType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorTaskType===void 0&&(discriminatorTaskType="PREDICT"),discriminatorTaskType==="PREDICT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["instances[]","task_type"],fromTaskType)}else if(discriminatorTaskType==="EMBED_CONTENT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["embedContentConfig","taskType"],fromTaskType)}let discriminatorTitle=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorTitle===void 0&&(discriminatorTitle="PREDICT"),discriminatorTitle==="PREDICT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["instances[]","title"],fromTitle)}else if(discriminatorTitle==="EMBED_CONTENT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["embedContentConfig","title"],fromTitle)}let discriminatorOutputDimensionality=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorOutputDimensionality===void 0&&(discriminatorOutputDimensionality="PREDICT"),discriminatorOutputDimensionality==="PREDICT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["parameters","outputDimensionality"],fromOutputDimensionality)}else if(discriminatorOutputDimensionality==="EMBED_CONTENT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["embedContentConfig","outputDimensionality"],fromOutputDimensionality)}let discriminatorMimeType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorMimeType===void 0&&(discriminatorMimeType="PREDICT"),discriminatorMimeType==="PREDICT"){let fromMimeType=getValueByPath(fromObject,["mimeType"]);parentObject!==void 0&&fromMimeType!=null&&setValueByPath(parentObject,["instances[]","mimeType"],fromMimeType)}let discriminatorAutoTruncate=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAutoTruncate===void 0&&(discriminatorAutoTruncate="PREDICT"),discriminatorAutoTruncate==="PREDICT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["parameters","autoTruncate"],fromAutoTruncate)}else if(discriminatorAutoTruncate==="EMBED_CONTENT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["embedContentConfig","autoTruncate"],fromAutoTruncate)}let discriminatorDocumentOcr=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorDocumentOcr===void 0&&(discriminatorDocumentOcr="PREDICT"),discriminatorDocumentOcr==="EMBED_CONTENT"){let fromDocumentOcr=getValueByPath(fromObject,["documentOcr"]);parentObject!==void 0&&fromDocumentOcr!=null&&setValueByPath(parentObject,["embedContentConfig","documentOcr"],fromDocumentOcr)}let discriminatorAudioTrackExtraction=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAudioTrackExtraction===void 0&&(discriminatorAudioTrackExtraction="PREDICT"),discriminatorAudioTrackExtraction==="EMBED_CONTENT"){let fromAudioTrackExtraction=getValueByPath(fromObject,["audioTrackExtraction"]);parentObject!==void 0&&fromAudioTrackExtraction!=null&&setValueByPath(parentObject,["embedContentConfig","audioTrackExtraction"],fromAudioTrackExtraction)}return toObject}function embedContentParametersPrivateToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["requests[]","content"],transformedList)}let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&contentToMldev$1(tContent(fromContent));let fromConfig=getValueByPath(fromObject,["config"]);fromConfig!=null&&embedContentConfigToMldev(fromConfig,toObject);let fromModelForEmbedContent=getValueByPath(fromObject,["model"]);return fromModelForEmbedContent!==void 0&&setValueByPath(toObject,["requests[]","model"],tModel(apiClient,fromModelForEmbedContent)),toObject}function embedContentParametersPrivateToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let discriminatorContents=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContents===void 0&&(discriminatorContents="PREDICT"),discriminatorContents==="PREDICT"){let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["instances[]","content"],transformedList)}}let discriminatorContent=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContent===void 0&&(discriminatorContent="PREDICT"),discriminatorContent==="EMBED_CONTENT"){let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],contentToVertex$1(tContent(fromContent)))}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&embedContentConfigToVertex(fromConfig,toObject,rootObject),toObject}function embedContentResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(fromObject,["embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);return fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),toObject}function embedContentResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(fromObject,["predictions[]","embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentEmbeddingFromVertex(item))),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);if(fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),rootObject&&getValueByPath(rootObject,["embeddingApiType"])==="EMBED_CONTENT"){let embedding=getValueByPath(fromObject,["embedding"]),usageMetadata=getValueByPath(fromObject,["usageMetadata"]),truncated=getValueByPath(fromObject,["truncated"]);if(embedding){let stats={};usageMetadata&&usageMetadata.promptTokenCount&&(stats.tokenCount=usageMetadata.promptTokenCount),usageMetadata&&usageMetadata.promptTokensDetails&&(stats.tokensDetails=usageMetadata.promptTokensDetails),truncated&&(stats.truncated=truncated),embedding.statistics=stats,setValueByPath(toObject,["embeddings"],[embedding])}}return toObject}function endpointFromVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["endpoint"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDeployedModelId=getValueByPath(fromObject,["deployedModelId"]);return fromDeployedModelId!=null&&setValueByPath(toObject,["deployedModelId"],fromDeployedModelId),toObject}function fileDataToMldev$1(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev$1(fromObject,_rootObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev(fromObject,_rootObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToMldev(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);if(fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema),getValueByPath(fromObject,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$1(item))),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$1(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev(fromToolConfig)),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);if(fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],tSpeechConfig(fromSpeechConfig)),getValueByPath(fromObject,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToMldev(fromImageConfig));let fromEnableEnhancedCivicAnswers=getValueByPath(fromObject,["enableEnhancedCivicAnswers"]);if(fromEnableEnhancedCivicAnswers!=null&&setValueByPath(toObject,["enableEnhancedCivicAnswers"],fromEnableEnhancedCivicAnswers),getValueByPath(fromObject,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToVertex(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToVertex(fromToolConfig));let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);if(fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToVertex(fromImageConfig)),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromModelArmorConfig=getValueByPath(fromObject,["modelArmorConfig"]);return parentObject!==void 0&&fromModelArmorConfig!=null&&setValueByPath(parentObject,["modelArmorConfig"],fromModelArmorConfig),toObject}function generateContentParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToMldev(apiClient,fromConfig,toObject)),toObject}function generateContentParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToVertex(apiClient,fromConfig,toObject)),toObject}function generateContentResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>candidateFromMldev(item))),setValueByPath(toObject,["candidates"],transformedList)}let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata);let fromModelStatus=getValueByPath(fromObject,["modelStatus"]);return fromModelStatus!=null&&setValueByPath(toObject,["modelStatus"],fromModelStatus),toObject}function generateContentResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["candidates"],transformedList)}let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);return fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata),toObject}function generateImagesConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromImageSize=getValueByPath(fromObject,["imageSize"]);parentObject!==void 0&&fromImageSize!=null&&setValueByPath(parentObject,["parameters","sampleImageSize"],fromImageSize);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);return parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),toObject}function generateImagesParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateImagesConfigToVertex(fromConfig,toObject),toObject}function generateImagesResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}let fromPositivePromptSafetyAttributes=getValueByPath(fromObject,["positivePromptSafetyAttributes"]);return fromPositivePromptSafetyAttributes!=null&&setValueByPath(toObject,["positivePromptSafetyAttributes"],safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)),toObject}function generateVideosConfigToMldev(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);if(parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos),getValueByPath(fromObject,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);if(parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds),getValueByPath(fromObject,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);if(parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration),getValueByPath(fromObject,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);if(parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),getValueByPath(fromObject,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToMldev(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToMldev(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}if(getValueByPath(fromObject,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromWebhookConfig=getValueByPath(fromObject,["webhookConfig"]);if(parentObject!==void 0&&fromWebhookConfig!=null&&setValueByPath(parentObject,["webhookConfig"],fromWebhookConfig),getValueByPath(fromObject,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateVideosConfigToVertex(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromFps=getValueByPath(fromObject,["fps"]);parentObject!==void 0&&fromFps!=null&&setValueByPath(parentObject,["parameters","fps"],fromFps);let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromPubsubTopic=getValueByPath(fromObject,["pubsubTopic"]);parentObject!==void 0&&fromPubsubTopic!=null&&setValueByPath(parentObject,["parameters","pubsubTopic"],fromPubsubTopic);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromGenerateAudio=getValueByPath(fromObject,["generateAudio"]);parentObject!==void 0&&fromGenerateAudio!=null&&setValueByPath(parentObject,["parameters","generateAudio"],fromGenerateAudio);let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToVertex(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToVertex(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}let fromMask=getValueByPath(fromObject,["mask"]);parentObject!==void 0&&fromMask!=null&&setValueByPath(parentObject,["instances[0]","mask"],videoGenerationMaskToVertex(fromMask));let fromCompressionQuality=getValueByPath(fromObject,["compressionQuality"]);parentObject!==void 0&&fromCompressionQuality!=null&&setValueByPath(parentObject,["parameters","compressionQuality"],fromCompressionQuality);let fromLabels=getValueByPath(fromObject,["labels"]);if(parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),getValueByPath(fromObject,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromResizeMode=getValueByPath(fromObject,["resizeMode"]);return parentObject!==void 0&&fromResizeMode!=null&&setValueByPath(parentObject,["parameters","resizeMode"],fromResizeMode),toObject}function generateVideosOperationFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev(fromResponse)),toObject}function generateVideosOperationFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex(fromResponse)),toObject}function generateVideosParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["instances[0]","video"],videoToMldev(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToMldev(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToMldev(fromConfig,toObject),toObject}function generateVideosParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["instances[0]","video"],videoToVertex(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToVertex(fromConfig,toObject),toObject}function generateVideosResponseFromMldev(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosSourceToMldev(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToMldev(fromVideo)),toObject}function generateVideosSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToVertex(fromVideo)),toObject}function generatedImageFromVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["_self"]);fromImage!=null&&setValueByPath(toObject,["image"],imageFromVertex(fromImage));let fromRaiFilteredReason=getValueByPath(fromObject,["raiFilteredReason"]);fromRaiFilteredReason!=null&&setValueByPath(toObject,["raiFilteredReason"],fromRaiFilteredReason);let fromSafetyAttributes=getValueByPath(fromObject,["_self"]);fromSafetyAttributes!=null&&setValueByPath(toObject,["safetyAttributes"],safetyAttributesFromVertex(fromSafetyAttributes));let fromEnhancedPrompt=getValueByPath(fromObject,["prompt"]);return fromEnhancedPrompt!=null&&setValueByPath(toObject,["enhancedPrompt"],fromEnhancedPrompt),toObject}function generatedImageMaskFromVertex(fromObject,rootObject){let toObject={},fromMask=getValueByPath(fromObject,["_self"]);fromMask!=null&&setValueByPath(toObject,["mask"],imageFromVertex(fromMask));let fromLabels=getValueByPath(fromObject,["labels"]);if(fromLabels!=null){let transformedList=fromLabels;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["labels"],transformedList)}return toObject}function generatedVideoFromMldev(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev(fromVideo)),toObject}function generatedVideoFromVertex(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex(fromVideo)),toObject}function generationConfigToVertex(fromObject,rootObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex(fromSpeechConfig));let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);if(fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function getModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function getModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function googleMapsToMldev$1(fromObject,rootObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$1(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$1(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function imageConfigToMldev(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);if(fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize),getValueByPath(fromObject,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function imageConfigToVertex(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);fromPersonGeneration!=null&&setValueByPath(toObject,["personGeneration"],fromPersonGeneration);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);fromOutputMimeType!=null&&setValueByPath(toObject,["imageOutputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);fromOutputCompressionQuality!=null&&setValueByPath(toObject,["imageOutputOptions","compressionQuality"],fromOutputCompressionQuality);let fromImageOutputOptions=getValueByPath(fromObject,["imageOutputOptions"]);fromImageOutputOptions!=null&&setValueByPath(toObject,["imageOutputOptions"],fromImageOutputOptions);let fromProminentPeople=getValueByPath(fromObject,["prominentPeople"]);return fromProminentPeople!=null&&setValueByPath(toObject,["prominentPeople"],fromProminentPeople),toObject}function imageFromVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromImageBytes!=null&&setValueByPath(toObject,["imageBytes"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function listModelsConfigToMldev(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsConfigToVertex(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToMldev(apiClient,fromConfig,toObject),toObject}function listModelsParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToVertex(apiClient,fromConfig,toObject),toObject}function listModelsResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromMldev(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function listModelsResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromVertex(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function maskReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromMaskMode=getValueByPath(fromObject,["maskMode"]);fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode);let fromSegmentationClasses=getValueByPath(fromObject,["segmentationClasses"]);fromSegmentationClasses!=null&&setValueByPath(toObject,["maskClasses"],fromSegmentationClasses);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);return fromMaskDilation!=null&&setValueByPath(toObject,["dilation"],fromMaskDilation),toObject}function mcpServerToVertex(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function modelFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["version"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromMldev(fromTunedModelInfo));let fromInputTokenLimit=getValueByPath(fromObject,["inputTokenLimit"]);fromInputTokenLimit!=null&&setValueByPath(toObject,["inputTokenLimit"],fromInputTokenLimit);let fromOutputTokenLimit=getValueByPath(fromObject,["outputTokenLimit"]);fromOutputTokenLimit!=null&&setValueByPath(toObject,["outputTokenLimit"],fromOutputTokenLimit);let fromSupportedActions=getValueByPath(fromObject,["supportedGenerationMethods"]);fromSupportedActions!=null&&setValueByPath(toObject,["supportedActions"],fromSupportedActions);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromMaxTemperature=getValueByPath(fromObject,["maxTemperature"]);fromMaxTemperature!=null&&setValueByPath(toObject,["maxTemperature"],fromMaxTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromThinking=getValueByPath(fromObject,["thinking"]);return fromThinking!=null&&setValueByPath(toObject,["thinking"],fromThinking),toObject}function modelFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["versionId"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromEndpoints=getValueByPath(fromObject,["deployedModels"]);if(fromEndpoints!=null){let transformedList=fromEndpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>endpointFromVertex(item))),setValueByPath(toObject,["endpoints"],transformedList)}let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromVertex(fromTunedModelInfo));let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);fromDefaultCheckpointId!=null&&setValueByPath(toObject,["defaultCheckpointId"],fromDefaultCheckpointId);let fromCheckpoints=getValueByPath(fromObject,["checkpoints"]);if(fromCheckpoints!=null){let transformedList=fromCheckpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["checkpoints"],transformedList)}return toObject}function multiSpeakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeakerVoiceConfigs=getValueByPath(fromObject,["speakerVoiceConfigs"]);if(fromSpeakerVoiceConfigs!=null){let transformedList=fromSpeakerVoiceConfigs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>speakerVoiceConfigToVertex(item))),setValueByPath(toObject,["speakerVoiceConfigs"],transformedList)}return toObject}function partToMldev$1(fromObject,rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$1(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$1(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$1(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function partToVertex$1(fromObject,_rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function productImageToVertex(fromObject,rootObject){let toObject={},fromProductImage=getValueByPath(fromObject,["productImage"]);return fromProductImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromProductImage)),toObject}function recontextImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","baseSteps"],fromBaseSteps);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function recontextImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&recontextImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&recontextImageConfigToVertex(fromConfig,toObject),toObject}function recontextImageResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function recontextImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromPersonImage=getValueByPath(fromObject,["personImage"]);parentObject!==void 0&&fromPersonImage!=null&&setValueByPath(parentObject,["instances[0]","personImage","image"],imageToVertex(fromPersonImage));let fromProductImages=getValueByPath(fromObject,["productImages"]);if(parentObject!==void 0&&fromProductImages!=null){let transformedList=fromProductImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>productImageToVertex(item))),setValueByPath(parentObject,["instances[0]","productImages"],transformedList)}return toObject}function referenceImageAPIInternalToVertex(fromObject,rootObject){let toObject={},fromReferenceImage=getValueByPath(fromObject,["referenceImage"]);fromReferenceImage!=null&&setValueByPath(toObject,["referenceImage"],imageToVertex(fromReferenceImage));let fromReferenceId=getValueByPath(fromObject,["referenceId"]);fromReferenceId!=null&&setValueByPath(toObject,["referenceId"],fromReferenceId);let fromReferenceType=getValueByPath(fromObject,["referenceType"]);fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType);let fromMaskImageConfig=getValueByPath(fromObject,["maskImageConfig"]);fromMaskImageConfig!=null&&setValueByPath(toObject,["maskImageConfig"],maskReferenceConfigToVertex(fromMaskImageConfig));let fromControlImageConfig=getValueByPath(fromObject,["controlImageConfig"]);fromControlImageConfig!=null&&setValueByPath(toObject,["controlImageConfig"],controlReferenceConfigToVertex(fromControlImageConfig));let fromStyleImageConfig=getValueByPath(fromObject,["styleImageConfig"]);fromStyleImageConfig!=null&&setValueByPath(toObject,["styleImageConfig"],fromStyleImageConfig);let fromSubjectImageConfig=getValueByPath(fromObject,["subjectImageConfig"]);return fromSubjectImageConfig!=null&&setValueByPath(toObject,["subjectImageConfig"],fromSubjectImageConfig),toObject}function replicatedVoiceConfigToVertex(fromObject,_rootObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType);let fromVoiceSampleAudio=getValueByPath(fromObject,["voiceSampleAudio"]);if(fromVoiceSampleAudio!=null&&setValueByPath(toObject,["voiceSampleAudio"],fromVoiceSampleAudio),getValueByPath(fromObject,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function safetyAttributesFromVertex(fromObject,_rootObject){let toObject={},fromCategories=getValueByPath(fromObject,["safetyAttributes","categories"]);fromCategories!=null&&setValueByPath(toObject,["categories"],fromCategories);let fromScores=getValueByPath(fromObject,["safetyAttributes","scores"]);fromScores!=null&&setValueByPath(toObject,["scores"],fromScores);let fromContentType=getValueByPath(fromObject,["contentType"]);return fromContentType!=null&&setValueByPath(toObject,["contentType"],fromContentType),toObject}function safetySettingToMldev$1(fromObject,_rootObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function scribbleImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);return fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage)),toObject}function segmentImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromMode=getValueByPath(fromObject,["mode"]);parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode);let fromMaxPredictions=getValueByPath(fromObject,["maxPredictions"]);parentObject!==void 0&&fromMaxPredictions!=null&&setValueByPath(parentObject,["parameters","maxPredictions"],fromMaxPredictions);let fromConfidenceThreshold=getValueByPath(fromObject,["confidenceThreshold"]);parentObject!==void 0&&fromConfidenceThreshold!=null&&setValueByPath(parentObject,["parameters","confidenceThreshold"],fromConfidenceThreshold);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);parentObject!==void 0&&fromMaskDilation!=null&&setValueByPath(parentObject,["parameters","maskDilation"],fromMaskDilation);let fromBinaryColorThreshold=getValueByPath(fromObject,["binaryColorThreshold"]);parentObject!==void 0&&fromBinaryColorThreshold!=null&&setValueByPath(parentObject,["parameters","binaryColorThreshold"],fromBinaryColorThreshold);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function segmentImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&segmentImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&segmentImageConfigToVertex(fromConfig,toObject),toObject}function segmentImageResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedMasks=getValueByPath(fromObject,["predictions"]);if(fromGeneratedMasks!=null){let transformedList=fromGeneratedMasks;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageMaskFromVertex(item))),setValueByPath(toObject,["generatedMasks"],transformedList)}return toObject}function segmentImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromScribbleImage=getValueByPath(fromObject,["scribbleImage"]);return parentObject!==void 0&&fromScribbleImage!=null&&setValueByPath(parentObject,["instances[0]","scribble"],scribbleImageToVertex(fromScribbleImage)),toObject}function speakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeaker=getValueByPath(fromObject,["speaker"]);fromSpeaker!=null&&setValueByPath(toObject,["speaker"],fromSpeaker);let fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);return fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig)),toObject}function speechConfigToVertex(fromObject,rootObject){let toObject={},fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig));let fromLanguageCode=getValueByPath(fromObject,["languageCode"]);fromLanguageCode!=null&&setValueByPath(toObject,["languageCode"],fromLanguageCode);let fromMultiSpeakerVoiceConfig=getValueByPath(fromObject,["multiSpeakerVoiceConfig"]);return fromMultiSpeakerVoiceConfig!=null&&setValueByPath(toObject,["multiSpeakerVoiceConfig"],multiSpeakerVoiceConfigToVertex(fromMultiSpeakerVoiceConfig)),toObject}function toolConfigToMldev(fromObject,rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolConfigToVertex(fromObject,_rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],fromFunctionCallingConfig);let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);if(fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig),getValueByPath(fromObject,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function toolToMldev$1(fromObject,rootObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$1(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$1(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex(fromObject,rootObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tunedModelInfoFromMldev(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function tunedModelInfoFromVertex(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["labels","google-vertex-llm-tuning-base-model-id"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function updateModelConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);return parentObject!==void 0&&fromDefaultCheckpointId!=null&&setValueByPath(parentObject,["defaultCheckpointId"],fromDefaultCheckpointId),toObject}function updateModelConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);return parentObject!==void 0&&fromDefaultCheckpointId!=null&&setValueByPath(parentObject,["defaultCheckpointId"],fromDefaultCheckpointId),toObject}function updateModelParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToMldev(fromConfig,toObject),toObject}function updateModelParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToVertex(fromConfig,toObject),toObject}function upscaleImageAPIConfigInternalToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromEnhanceInputImage=getValueByPath(fromObject,["enhanceInputImage"]);parentObject!==void 0&&fromEnhanceInputImage!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","enhanceInputImage"],fromEnhanceInputImage);let fromImagePreservationFactor=getValueByPath(fromObject,["imagePreservationFactor"]);parentObject!==void 0&&fromImagePreservationFactor!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","imagePreservationFactor"],fromImagePreservationFactor);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromMode=getValueByPath(fromObject,["mode"]);return parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode),toObject}function upscaleImageAPIParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromUpscaleFactor=getValueByPath(fromObject,["upscaleFactor"]);fromUpscaleFactor!=null&&setValueByPath(toObject,["parameters","upscaleConfig","upscaleFactor"],fromUpscaleFactor);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&upscaleImageAPIConfigInternalToVertex(fromConfig,toObject),toObject}function upscaleImageResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function videoFromMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoGenerationMaskToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["_self"],imageToVertex(fromImage));let fromMaskMode=getValueByPath(fromObject,["maskMode"]);return fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode),toObject}function videoGenerationReferenceImageToMldev(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToMldev(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoGenerationReferenceImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoToMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["encodedVideo"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["encoding"],fromMimeType),toObject}function videoToVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["gcsUri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function voiceConfigToVertex(fromObject,rootObject){let toObject={},fromReplicatedVoiceConfig=getValueByPath(fromObject,["replicatedVoiceConfig"]);fromReplicatedVoiceConfig!=null&&setValueByPath(toObject,["replicatedVoiceConfig"],replicatedVoiceConfigToVertex(fromReplicatedVoiceConfig));let fromPrebuiltVoiceConfig=getValueByPath(fromObject,["prebuiltVoiceConfig"]);return fromPrebuiltVoiceConfig!=null&&setValueByPath(toObject,["prebuiltVoiceConfig"],fromPrebuiltVoiceConfig),toObject}var GOOGLE_API_CLIENT_HEADER="x-goog-api-client",SDK_VERSION="2.21.0",LIBRARY_LABEL=`google-genai-sdk/${SDK_VERSION}`;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 t2=yield __await(mcpClient.listTools({cursor}));for(let tool of t2.tools)yield yield __await(tool),numTools++;if(!t2.nextCursor)break;cursor=t2.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}};var DEFAULT_MAX_REMOTE_CALLS=10;function shouldDisableAfc(config){var _a2,_b,_c;if(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.disable)return!0;let callableToolsPresent=!1;for(let tool of(_b=config?.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){callableToolsPresent=!0;break}if(!callableToolsPresent)return!0;let maxCalls=(_c=config?.automaticFunctionCalling)===null||_c===void 0?void 0:_c.maximumRemoteCalls;return maxCalls&&(maxCalls<0||!Number.isInteger(maxCalls))||maxCalls==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",maxCalls),!0):!1}function isCallableTool(tool){return"callTool"in tool&&typeof tool.callTool=="function"}function hasCallableTools(params){var _a2,_b,_c;return(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)===null||_b===void 0?void 0:_b.some(tool=>isCallableTool(tool)))!==null&&_c!==void 0?_c:!1}function findAfcIncompatibleToolIndexes(params){var _a2;let afcIncompatibleToolIndexes=[];return!((_a2=params?.config)===null||_a2===void 0)&&_a2.tools&¶ms.config.tools.forEach((tool,index)=>{if(isCallableTool(tool))return;let geminiTool=tool;geminiTool.functionDeclarations&&geminiTool.functionDeclarations.length>0&&afcIncompatibleToolIndexes.push(index)}),afcIncompatibleToolIndexes}function shouldAppendAfcHistory(config){var _a2;return!(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.ignoreCallHistory)}var Models=class _Models extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.embedContent=async params=>{if(!this.apiClient.isVertexAI())return params.model.includes("gemini-embedding-2")&&(params.contents=tContents(params.contents)),await this.embedContentInternal(params);if(params.model.includes("gemini")&¶ms.model!=="gemini-embedding-001"||params.model.includes("maas")){let contents=tContents(params.contents);if(contents.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let paramsPrivate=Object.assign(Object.assign({},params),{content:contents[0],embeddingApiType:EmbeddingApiType.EMBED_CONTENT});return await this.embedContentInternal(paramsPrivate)}else{let paramsPrivate=Object.assign(Object.assign({},params),{embeddingApiType:EmbeddingApiType.PREDICT});return await this.embedContentInternal(paramsPrivate)}},this.generateContent=async params=>{var _a2,_b,_c,_d,_e;let transformedParams=await this.processParamsMaybeAddMcpUsage(params);if(this.maybeMoveToResponseJsonSchema(params),!hasCallableTools(params)||shouldDisableAfc(params.config))return await this.generateContentInternal(transformedParams);let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`)}let response,functionResponseContent,automaticFunctionCallingHistory=tContents(transformedParams.contents),maxRemoteCalls=(_c=(_b=(_a2=transformedParams.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,remoteCalls=0;for(;remoteCalls<maxRemoteCalls&&(response=await this.generateContentInternal(transformedParams),!(!response.functionCalls||response.functionCalls.length===0));){let responseContent=response.candidates[0].content,functionResponseParts=[];for(let tool of(_e=(_d=params.config)===null||_d===void 0?void 0:_d.tools)!==null&&_e!==void 0?_e:[])if(isCallableTool(tool)){let parts=await tool.callTool(response.functionCalls);functionResponseParts.push(...parts)}remoteCalls++,functionResponseContent={role:"user",parts:functionResponseParts},transformedParams.contents=tContents(transformedParams.contents),transformedParams.contents.push(responseContent),transformedParams.contents.push(functionResponseContent),shouldAppendAfcHistory(transformedParams.config)&&(automaticFunctionCallingHistory.push(responseContent),automaticFunctionCallingHistory.push(functionResponseContent))}return shouldAppendAfcHistory(transformedParams.config)&&(response.automaticFunctionCallingHistory=automaticFunctionCallingHistory),response},this.generateContentStream=async params=>{var _a2,_b,_c,_d,_e;if(this.maybeMoveToResponseJsonSchema(params),shouldDisableAfc(params.config)){let transformedParams=await this.processParamsMaybeAddMcpUsage(params);return await this.generateContentStreamInternal(transformedParams)}let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let streamFunctionCall=(_c=(_b=(_a2=params?.config)===null||_a2===void 0?void 0:_a2.toolConfig)===null||_b===void 0?void 0:_b.functionCallingConfig)===null||_c===void 0?void 0:_c.streamFunctionCallArguments,disableAfc=(_e=(_d=params?.config)===null||_d===void 0?void 0:_d.automaticFunctionCalling)===null||_e===void 0?void 0:_e.disable;if(streamFunctionCall&&!disableAfc)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(params)},this.generateImages=async params=>(_Models.loggedGenerateImagesWarning||(_Models.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(params).then(apiResponse=>{var _a2;let positivePromptSafetyAttributes,generatedImages=[];if(apiResponse?.generatedImages)for(let generatedImage of apiResponse.generatedImages)generatedImage&&generatedImage?.safetyAttributes&&((_a2=generatedImage?.safetyAttributes)===null||_a2===void 0?void 0:_a2.contentType)==="Positive Prompt"?positivePromptSafetyAttributes=generatedImage?.safetyAttributes:generatedImages.push(generatedImage);let response;return positivePromptSafetyAttributes?response={generatedImages,positivePromptSafetyAttributes,sdkHttpResponse:apiResponse.sdkHttpResponse}:response={generatedImages,sdkHttpResponse:apiResponse.sdkHttpResponse},response})),this.list=async params=>{var _a2;let actualParams={config:Object.assign(Object.assign({},{queryBase:!0}),params?.config)};if(this.apiClient.isVertexAI()&&!actualParams.config.queryBase){if(!((_a2=actualParams.config)===null||_a2===void 0)&&_a2.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");actualParams.config.filter="labels.tune-type:*"}return new Pager(PagedItem.PAGED_ITEM_MODELS,x2=>this.listInternal(x2),await this.listInternal(actualParams),actualParams)},this.editImage=async params=>{_Models.loggedEditImageWarning||(_Models.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let paramsInternal={model:params.model,prompt:params.prompt,referenceImages:[],config:params.config};return params.referenceImages&¶ms.referenceImages&&(paramsInternal.referenceImages=params.referenceImages.map(img=>img.toReferenceImageAPI())),await this.editImageInternal(paramsInternal)},this.upscaleImage=async params=>{let apiConfig={numberOfImages:1,mode:"upscale"};params.config&&(apiConfig=Object.assign(Object.assign({},apiConfig),params.config));let apiParams={model:params.model,image:params.image,upscaleFactor:params.upscaleFactor,config:apiConfig};return await this.upscaleImageInternal(apiParams)},this.generateVideos=async params=>{var _a2,_b,_c,_d,_e,_f;if((params.prompt||params.image||params.video)&¶ms.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(params.prompt||params.image||params.video)&&(_Models.loggedGenerateVideosWarning||(_Models.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((_a2=params.video)===null||_a2===void 0)&&_a2.uri&&(!((_b=params.video)===null||_b===void 0)&&_b.videoBytes)?params.video={uri:params.video.uri,mimeType:params.video.mimeType}:!((_d=(_c=params.source)===null||_c===void 0?void 0:_c.video)===null||_d===void 0)&&_d.uri&&(!((_f=(_e=params.source)===null||_e===void 0?void 0:_e.video)===null||_f===void 0)&&_f.videoBytes)&&(params.source.video={uri:params.source.video.uri,mimeType:params.source.video.mimeType})),await this.generateVideosInternal(params)}}maybeMoveToResponseJsonSchema(params){params.config&¶ms.config.responseSchema&&(params.config.responseJsonSchema||Object.keys(params.config.responseSchema).includes("$schema")&&(params.config.responseJsonSchema=params.config.responseSchema,delete params.config.responseSchema))}async processParamsMaybeAddMcpUsage(params){var _a2,_b,_c;let tools=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools;if(!tools)return params;let transformedTools=await Promise.all(tools.map(async tool=>isCallableTool(tool)?await tool.tool():tool)),newParams={model:params.model,contents:params.contents,config:Object.assign(Object.assign({},params.config),{tools:transformedTools})};if(newParams.config.tools=transformedTools,params.config&¶ms.config.tools&&hasMcpToolUsage(params.config.tools)){let headers=(_c=(_b=params.config.httpOptions)===null||_b===void 0?void 0:_b.headers)!==null&&_c!==void 0?_c:{},newHeaders=Object.assign({},headers);Object.keys(newHeaders).length===0&&(newHeaders=this.apiClient.getDefaultHeaders()),setMcpUsageHeader(newHeaders),newParams.config.httpOptions=Object.assign(Object.assign({},params.config.httpOptions),{headers:newHeaders})}return newParams}async initAfcToolsMap(params){var _a2,_b,_c;let afcTools=new Map;for(let tool of(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){let callableTool=tool,toolDeclaration=await callableTool.tool();for(let declaration of(_c=toolDeclaration.functionDeclarations)!==null&&_c!==void 0?_c:[]){if(!declaration.name)throw new Error("Function declaration name is required.");if(afcTools.has(declaration.name))throw new Error(`Duplicate tool declaration name: ${declaration.name}`);afcTools.set(declaration.name,callableTool)}}return afcTools}async processAfcStream(params){var _a2,_b,_c;let maxRemoteCalls=(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,wereFunctionsCalled=!1,remoteCallCount=0,afcToolsMap=await this.initAfcToolsMap(params);return(function(models,afcTools,params2){return __asyncGenerator(this,arguments,function*(){for(var _a3,e_1,_b2,_c2,_d,_e;remoteCallCount<maxRemoteCalls;){wereFunctionsCalled&&(remoteCallCount++,wereFunctionsCalled=!1);let transformedParams=yield __await(models.processParamsMaybeAddMcpUsage(params2)),response=yield __await(models.generateContentStreamInternal(transformedParams)),functionResponses=[],responseContents=[];try{for(var _f=!0,response_1=(e_1=void 0,__asyncValues(response)),response_1_1;response_1_1=yield __await(response_1.next()),_a3=response_1_1.done,!_a3;_f=!0){_c2=response_1_1.value,_f=!1;let chunk=_c2;if(yield yield __await(chunk),chunk.candidates&&(!((_d=chunk.candidates[0])===null||_d===void 0)&&_d.content)){responseContents.push(chunk.candidates[0].content);for(let part of(_e=chunk.candidates[0].content.parts)!==null&&_e!==void 0?_e:[])if(remoteCallCount<maxRemoteCalls&&part.functionCall){if(!part.functionCall.name)throw new Error("Function call name was not returned by the model.");if(afcTools.has(part.functionCall.name)){let responseParts=yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall]));functionResponses.push(...responseParts)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, missing tool: ${part.functionCall.name}`)}}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_f&&!_a3&&(_b2=response_1.return)&&(yield __await(_b2.call(response_1)))}finally{if(e_1)throw e_1.error}}if(functionResponses.length>0){wereFunctionsCalled=!0;let typedResponseChunk=new GenerateContentResponse;typedResponseChunk.candidates=[{content:{role:"user",parts:functionResponses}}],yield yield __await(typedResponseChunk);let newContents=[];newContents.push(...responseContents),newContents.push({role:"user",parts:functionResponses});let updatedContents=tContents(params2.contents).concat(newContents);params2.contents=updatedContents}else break}})})(this,afcToolsMap,params)}async generateContentInternal(params){var _a2,_b,_c,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path,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 path=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=embedContentParametersPrivateToVertex(this.apiClient,params,params),endpointUrl=tIsVertexEmbedContentModel(params.model)?"{model}:embedContent":"{model}:predict";return path=formatMap(endpointUrl,body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{model}:batchEmbedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateImagesParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=editImageParametersInternalToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=upscaleImageAPIParametersInternalToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=recontextImageParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=segmentImageParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=getModelParametersToVertex(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=listModelsParametersToVertex(this.apiClient,params);return path=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateModelParametersToVertex(this.apiClient,params);return path=formatMap("{model}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteModelParametersToVertex(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=countTokensParametersToVertex(this.apiClient,params);return path=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=computeTokensParametersToVertex(this.apiClient,params);return path=formatMap("{model}:computeTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateVideosParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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;function bytesToBase64(u8arr){return btoa(String.fromCodePoint(...u8arr))}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 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 m2=mapper(v);return m2==null||acc.push(m2),acc},[]);return res.length?res:null}function mapDefinedEntries(inp,mapper){let acc=[];for(let[k,v]of inp){if(v==null)continue;let m2=mapper([k,v]);m2!=null&&acc.push(m2)}return acc.length?acc:null}function queryJoin(...args){return args.filter(Boolean).join("&")}function queryEncoder(f3){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)}=`:f3(key,value,opts));return queryJoin(...encoded)}}var encodeFormQuery=queryEncoder(encodeForm);var codeRangeRE$1=new RegExp("^[0-9]xx$","i");var codeRangeRE=new RegExp("^[0-9]xx$","i");var gt=typeof globalThis>"u"?null:globalThis,webWorkerLike=typeof gt=="object"&>!=null&&"importScripts"in gt&&typeof gt.importScripts=="function",isBrowserLike=webWorkerLike||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u";var CR2=13,LF2=10,BOUNDARIES=[[CR2,LF2,CR2,LF2],[CR2,LF2,CR2],[CR2,LF2,LF2],[CR2,CR2,LF2],[LF2,CR2,LF2],[CR2,CR2],[LF2,CR2],[LF2,LF2]],MAX_BOUNDARY_LEN=BOUNDARIES.reduce((m2,b)=>Math.max(m2,b.length),0);var _a;_a=Symbol.toStringTag;var MAX_CHUNK_SIZE=1024*1024*8;var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types3=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types3.includes("object")||types3.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)";function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i2=0;i2<transformed.length;i2++){let msg=transformed[i2];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}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)||/gemini-(?:[4-9]|[1-9]\d)/.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 match=modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(match)return Number.parseInt(match[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(`
|
|
66
|
+
`),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function calculateCost(model,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model.cost,matchedThreshold=-1;for(let tier of model.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost.totalFromProvider=!1,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model){return model.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model,level){let availableLevels=getSupportedThinkingLevels(model);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i2=requestedIndex;i2<EXTENDED_THINKING_LEVELS.length;i2++){let candidate=EXTENDED_THINKING_LEVELS[i2];if(availableLevels.includes(candidate))return candidate}for(let i2=requestedIndex-1;i2>=0;i2--){let candidate=EXTENDED_THINKING_LEVELS[i2];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}var MAX_PROVIDER_ERROR_BODY_CHARS=4e3;function normalizeProviderError(error){if(!(error instanceof Error))return{message:safeJsonStringify(error),messageCarriesBody:!1};let sdkError=error,status=extractStatus(sdkError),body=extractBody(sdkError),messageCarriesBody=body===void 0||error.message.includes(body),message=status===void 0&&body===void 0?withCauseDetail(error):error.message;return{status,body,message,messageCarriesBody}}var MAX_CAUSE_DEPTH=5;function withCauseDetail(error){let deepest,current=error.cause;for(let depth=0;depth<MAX_CAUSE_DEPTH&¤t instanceof Error;depth++)deepest=current,current=current.cause;if(!deepest)return error.message;let detail=(deepest.message||deepest.name).trim(),code=deepest.code;return(typeof code=="string"||typeof code=="number")&&!detail.includes(String(code))&&(detail=detail?`${detail} (${code})`:String(code)),!detail||error.message.includes(detail)?error.message:error.message?`${error.message}: ${detail}`:detail}function extractStatus(error){if(typeof error.statusCode=="number")return error.statusCode;if(typeof error.status=="number")return error.status;if(typeof error.$metadata?.httpStatusCode=="number")return error.$metadata.httpStatusCode;if(typeof error.$response?.statusCode=="number")return error.$response.statusCode}function extractBody(error){let bodyText=pickBodyText(error);if(bodyText===void 0)return;let trimmed=bodyText.trim();if(trimmed.length!==0)return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error){if(typeof error.body=="string")return error.body;if(isPlainNonEmptyObject(error.error))return safeJsonStringify(error.error);let responseBody=error.$response?.body;if(typeof responseBody=="string")return responseBody;if(!isReadableStreamLike(responseBody)&&isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function formatProviderError(norm,prefix){return norm.messageCarriesBody||norm.status===void 0||norm.body===void 0?prefix!==void 0&&norm.status!==void 0?`${prefix} (${norm.status}): ${norm.message}`:norm.message:prefix!==void 0?`${prefix} (${norm.status}): ${norm.body}`:`${norm.status}: ${norm.body}`}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${ownedSlice(text,0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}function headersToRecord(headers){let result={};for(let[key,value]of headers.entries())result[key]=value;return result}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}return merged.size>0?Object.fromEntries(merged.values()):void 0}function isProviderError(error){return!(error instanceof Error)||!("status"in error)||!("headers"in error)?!1:(error.status===void 0||typeof error.status=="number")&&(error.headers===void 0||error.headers instanceof Headers)}function isRetryableProviderError(error){let shouldRetry=error.headers?.get("x-should-retry");return shouldRetry==="true"?!0:shouldRetry==="false"?!1:error.status===void 0?!0:error.status===408||error.status===409||error.status===429||typeof error.status=="number"&&error.status>=500}function validateServerRetryDelayMs(delayMs,maxRetryDelayMs,providerErrorMessage){let maxDelayMs=maxRetryDelayMs??6e4;if(maxDelayMs>0&&delayMs>maxDelayMs)throw new Error(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxDelayMs/1e3)}s). ${providerErrorMessage}`);return delayMs}function getRetryDelayMs(error,retryIndex,maxRetryDelayMs){let retryAfterMs=error.headers?.get("retry-after-ms");if(retryAfterMs){let value=Number.parseFloat(retryAfterMs);if(Number.isFinite(value))return validateServerRetryDelayMs(value,maxRetryDelayMs,error.message)}let retryAfter=error.headers?.get("retry-after");if(retryAfter){let seconds=Number.parseFloat(retryAfter),delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3;if(Number.isFinite(delayMs))return validateServerRetryDelayMs(delayMs,maxRetryDelayMs,error.message)}return Math.min(.5*2**retryIndex,8)*1e3*(1-Math.random()*.25)}function createAbortError(){let error=new Error("Request aborted");return error.name="AbortError",error}function abortableSleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(createAbortError());return}let onAbort=()=>{clearTimeout(timeout),reject(createAbortError())},timeout=setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},Math.max(0,ms));signal?.addEventListener("abort",onAbort,{once:!0})})}async function retryProviderRequest(request,options={}){let maxRetries=options.maxRetries??0,retriesRemaining=maxRetries;for(;;)try{return await request()}catch(error){if(options.signal?.aborted)throw createAbortError();if(retriesRemaining<=0||!isProviderError(error)||!isRetryableProviderError(error)||error.status!==void 0&&options.noRetryStatuses?.includes(error.status))throw error;let retryIndex=maxRetries-retriesRemaining;retriesRemaining--,await abortableSleep(getRetryDelayMs(error,retryIndex,options.maxRetryDelayMs),options.signal)}}function sanitizeSurrogates(text){return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}import{createHash}from"node:crypto";import{arch,platform}from"node:process";var ANTIGRAVITY_CLIENT_VERSION="1.5.9",ANTIGRAVITY_CLIENT_BUILD="1021519450",OS_TYPE=platform==="win32"?"windows":platform,ANTIGRAVITY_USER_AGENT=`antigravity/cli/${ANTIGRAVITY_CLIENT_VERSION} (aidev_client; os_type=${OS_TYPE}; arch=${arch==="x64"?"amd64":arch}; cl=${ANTIGRAVITY_CLIENT_BUILD}; auth_method=consumer)`,ANTIGRAVITY_SESSION_ID=fnv1a64(""),UUID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function antigravityRequestIdentity(sessionId){let requestUuid=crypto.randomUUID();if(!sessionId)return{cascadeId:requestUuid,rootCascadeId:requestUuid,trajectoryId:crypto.randomUUID(),requestUuid};let cascadeId=UUID_PATTERN.test(sessionId)?sessionId:derivedUuid("cascade",sessionId);return{cascadeId,rootCascadeId:cascadeId,trajectoryId:derivedUuid("trajectory",sessionId),requestUuid}}function fnv1a64(seed){let hash=0xcbf29ce484222325n;for(let byte of new TextEncoder().encode(seed))hash=BigInt.asUintN(64,(hash^BigInt(byte))*0x100000001b3n);return BigInt.asIntN(64,hash).toString()}function derivedUuid(scope,key){let bytes=createHash("sha256").update("antigravity/identity/v1\0").update(scope).update("\0").update(key).digest();bytes[6]=bytes[6]&15|128,bytes[8]=bytes[8]&63|128;let hex=bytes.subarray(0,16).toString("hex");return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function antigravityRoutes(model){return model.antigravityRoutes}var PI_OPENING="You are a coding assistant running inside pi, a coding agent harness. Help users inspect files, run commands, and modify code.",ANTIGRAVITY_OPENING=["You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.","You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.","The USER will send you requests, which you must always prioritize addressing. User requests are enclosed within <USER_REQUEST> tags."].join(`
|
|
67
|
+
`),LINE_REPLACEMENTS={tools:new Map([["- read: Read file contents","- read: View the contents of a file"],["- bash: Execute bash commands (ls, grep, find, etc.)","- bash: Run shell commands in the workspace"],["- edit: Make precise file edits with exact text replacement, including multiple disjoint edits in one call","- edit: Apply exact text replacements to an existing file; several separate replacements can be made in one call"],["- write: Create or overwrite files","- write: Create a file or replace its entire contents"],["- grep: Search file contents for patterns (respects .gitignore)","- grep: Search file contents for a pattern; ignored files are skipped"],["- find: Find files by glob pattern (respects .gitignore)","- find: Locate files by glob pattern; ignored files are skipped"],["- ls: List directory contents","- ls: List the entries in a directory"],["- powershell: Execute PowerShell commands","- powershell: Run PowerShell commands in the workspace"],["Additional tools may be available.","Other tools may also be available."]]),rules:new Map([["- Use read to examine files instead of cat or sed.","- Prefer read over cat or sed when viewing files."],["- You can inspect PI_* environment variables for current model and session details.","- Details about the current model and session are available as environment variables; list them with env."],["- Use edit for targeted changes. Batch changes to one file in a single call.","- Use edit for focused changes, grouping all changes to the same file into one call."],["- Each edits[].oldText must exactly and uniquely match the original file. Keep matches short and non-overlapping; merge nearby changes without including large unchanged regions.","- Every edits[].oldText has to match the original file exactly and only once. Keep each match short and separate from the others; combine nearby changes instead of copying large unchanged regions."],["- Use write only for new files or complete rewrites.","- Reserve write for new files or full rewrites."],["- Use bash for file operations like ls, rg, find","- Use bash for file operations such as ls, rg, and find"],["- Use bash or PowerShell for file operations like listing, searching, and finding files","- Use bash or PowerShell to list, search, and locate files"],["- Use PowerShell for file operations like listing, searching, and finding files","- Use PowerShell to list, search, and locate files"],["- Be concise in your responses","- Keep responses concise"],["- Show file paths clearly when working with files","- State file paths clearly when referring to files"]]),project_context:new Map([["Project-specific instructions and guidelines:","Instructions provided for this workspace:"]]),skills:new Map([["The following skills provide specialized instructions for specific tasks.","Skills below contain specialized instructions for particular tasks."],["Use the read tool to load a skill's file when the task matches its description.","When a task matches a skill's description, load that skill's file with the read tool."],["Use bash to load a skill's file when the task matches its description.","When a task matches a skill's description, load that skill's file with bash."],["Load a skill's file when the task matches its description.","When a task matches a skill's description, load that skill's file."],["Resolve relative paths against the skill's directory (parent of SKILL.md). Use absolute paths in tool calls.","Relative paths inside a skill are relative to its directory (the folder containing SKILL.md); use absolute paths in tool calls."]])},DOCS_HEADER="Pi documentation (read only when the user asks about the harness itself, its SDK, extensions, themes, skills, or TUI):",DOCS_RESOLVE="- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory",DOCS_TOPICS="- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md)",DOCS_BEFORE="- Before implementing harness changes, read the relevant docs and examples in full, following related cross-references.",escapeRegExp=text=>text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),DOCS_SECTION=new RegExp(`^<docs>\\n${escapeRegExp(DOCS_HEADER)}\\n- Main documentation: ([^\\n]+)\\n- Additional docs: ([^\\n]+)\\n- Examples: ([^\\n]+) \\(extensions, custom tools, SDK\\)\\n${escapeRegExp(DOCS_RESOLVE)}\\n${escapeRegExp(DOCS_TOPICS)}\\n${escapeRegExp(DOCS_BEFORE)}\\n</docs>$`);function adaptAntigravitySystemPrompt(messages){let current=getCurrentSystemMessage(messages);if(!current)return"";let sections=current.sections?Object.fromEntries(Object.entries(current.sections).map(([name,text])=>[name,text===null?null:adaptSection(name,text)])):void 0,adapted=sections===void 0?current:{...current,sections};return adaptRenderedText(getSystemMessageText(adapted))}function adaptRenderedText(prompt){return rewriteOpening(adaptBuiltinLines(adaptDocsBlock(prompt)))}function adaptSection(name,section){if(name==="preamble")return section===PI_OPENING?ANTIGRAVITY_OPENING:section;if(name==="docs")return adaptDocs(section);let replacements=LINE_REPLACEMENTS[name];return replacements?adaptLines(section,replacements):section}function adaptDocs(section){let match=DOCS_SECTION.exec(section);if(!match)return section;let[,readme,docs,examples]=match;return["<docs>","Agent harness reference (consult only when the user asks about the harness itself: its SDK, extensions, themes, skills, or terminal UI):",`- Overview: ${readme}`,`- Guides: ${docs}`,`- Examples: ${examples}`,"- Resolve docs/... under Guides and examples/... under Examples, not the working directory.","- To find the guide for a topic, list the Guides directory and open the matching file.","- Before changing harness configuration or extensions, read the relevant guides and examples in full, including cross-references.","</docs>"].join(`
|
|
68
|
+
`)}function adaptLines(section,replacements){return section.split(`
|
|
69
|
+
`).map(line=>replacements.get(line)??line).join(`
|
|
70
|
+
`)}function adaptBuiltinLines(text){let adapted=text;for(let replacements of Object.values(LINE_REPLACEMENTS))adapted=adaptLines(adapted,replacements);return adapted}function adaptDocsBlock(text){let start=text.indexOf(`<docs>
|
|
71
|
+
`);if(start===-1)return text;let end=text.indexOf(`
|
|
72
|
+
</docs>`,start);if(end===-1)return text;let blockEnd=end+8,original=text.slice(start,blockEnd),adapted=adaptDocs(original);return adapted===original?text:text.slice(0,start)+adapted+text.slice(blockEnd)}function rewriteOpening(prompt){if(!prompt.startsWith(PI_OPENING))return prompt;let suffix=prompt.slice(PI_OPENING.length);return suffix!==""&&!/^\s/.test(suffix)?prompt:ANTIGRAVITY_OPENING+suffix}var import_p_retry=__toESM(require_p_retry(),1),import_google_auth_library=__toESM(require_src5(),1);var import_stream=__toESM(require_stream(),1),import_extension=__toESM(require_extension(),1),import_permessage_deflate=__toESM(require_permessage_deflate(),1),import_receiver=__toESM(require_receiver(),1),import_sender=__toESM(require_sender(),1),import_subprotocol=__toESM(require_subprotocol(),1),import_websocket=__toESM(require_websocket(),1),import_websocket_server=__toESM(require_websocket_server(),1);var BaseModule=class{};function formatMap(templateString,valueMap){let regex=/\{([^}]+)\}/g;return templateString.replace(regex,(match,key)=>{if(Object.prototype.hasOwnProperty.call(valueMap,key)){let value=valueMap[key];return value!=null?String(value):""}else throw new Error(`Key '${key}' not found in valueMap.`)})}function setValueByPath(data,keys,value){for(let i2=0;i2<keys.length-1;i2++){let key=keys[i2];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(!(keyName in data))if(Array.isArray(value))data[keyName]=Array.from({length:value.length},()=>({}));else throw new Error(`Value must be a list given an array path ${key}`);if(Array.isArray(data[keyName])){let arrayData=data[keyName];if(Array.isArray(value))for(let j=0;j<arrayData.length;j++){let entry=arrayData[j];setValueByPath(entry,keys.slice(i2+1),value[j])}else for(let d of arrayData)setValueByPath(d,keys.slice(i2+1),value)}return}else if(key.endsWith("[0]")){let keyName=key.slice(0,-3);keyName in data||(data[keyName]=[{}]);let arrayData=data[keyName];setValueByPath(arrayData[0],keys.slice(i2+1),value);return}(!data[key]||typeof data[key]!="object")&&(data[key]={}),data=data[key]}let keyToSet=keys[keys.length-1],existingData=data[keyToSet];if(existingData!==void 0){if(!value||typeof value=="object"&&Object.keys(value).length===0||value===existingData)return;if(typeof existingData=="object"&&typeof value=="object"&&existingData!==null&&value!==null)Object.assign(existingData,value);else throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`)}else keyToSet==="_self"&&typeof value=="object"&&value!==null&&!Array.isArray(value)?Object.assign(data,value):data[keyToSet]=value}function getValueByPath(data,keys,defaultValue=void 0){try{if(keys.length===1&&keys[0]==="_self")return data;for(let i2=0;i2<keys.length;i2++){if(typeof data!="object"||data===null)return defaultValue;let key=keys[i2];if(key.endsWith("[]")){let keyName=key.slice(0,-2);if(keyName in data){let arrayData=data[keyName];return Array.isArray(arrayData)?arrayData.map(d=>getValueByPath(d,keys.slice(i2+1),defaultValue)):defaultValue}else return defaultValue}else data=data[key]}return data}catch(error){if(error instanceof TypeError)return defaultValue;throw error}}function tBytes$1(fromBytes){if(typeof fromBytes!="string")throw new Error("fromImageBytes must be a string");return fromBytes}function generateVideosOperationFromMldev$1(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev$1(fromResponse)),toObject}function generateVideosOperationFromVertex$1(fromObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex$1(fromResponse)),toObject}function generateVideosResponseFromMldev$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev$1(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex$1(fromObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex$1(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generatedVideoFromMldev$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev$1(fromVideo)),toObject}function generatedVideoFromVertex$1(fromObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex$1(fromVideo)),toObject}function videoFromMldev$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex$1(fromObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes$1(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}var Outcome;(function(Outcome2){Outcome2.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",Outcome2.OUTCOME_OK="OUTCOME_OK",Outcome2.OUTCOME_FAILED="OUTCOME_FAILED",Outcome2.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(Outcome||(Outcome={}));var Language;(function(Language2){Language2.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",Language2.PYTHON="PYTHON"})(Language||(Language={}));var FunctionResponseScheduling;(function(FunctionResponseScheduling2){FunctionResponseScheduling2.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",FunctionResponseScheduling2.SILENT="SILENT",FunctionResponseScheduling2.WHEN_IDLE="WHEN_IDLE",FunctionResponseScheduling2.INTERRUPT="INTERRUPT"})(FunctionResponseScheduling||(FunctionResponseScheduling={}));var Type;(function(Type2){Type2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",Type2.STRING="STRING",Type2.NUMBER="NUMBER",Type2.INTEGER="INTEGER",Type2.BOOLEAN="BOOLEAN",Type2.ARRAY="ARRAY",Type2.OBJECT="OBJECT",Type2.NULL="NULL"})(Type||(Type={}));var AuthType;(function(AuthType2){AuthType2.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",AuthType2.NO_AUTH="NO_AUTH",AuthType2.API_KEY_AUTH="API_KEY_AUTH",AuthType2.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",AuthType2.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",AuthType2.OAUTH="OAUTH",AuthType2.OIDC_AUTH="OIDC_AUTH"})(AuthType||(AuthType={}));var HttpElementLocation;(function(HttpElementLocation2){HttpElementLocation2.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",HttpElementLocation2.HTTP_IN_QUERY="HTTP_IN_QUERY",HttpElementLocation2.HTTP_IN_HEADER="HTTP_IN_HEADER",HttpElementLocation2.HTTP_IN_PATH="HTTP_IN_PATH",HttpElementLocation2.HTTP_IN_BODY="HTTP_IN_BODY",HttpElementLocation2.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(HttpElementLocation||(HttpElementLocation={}));var ApiSpec;(function(ApiSpec2){ApiSpec2.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",ApiSpec2.SIMPLE_SEARCH="SIMPLE_SEARCH",ApiSpec2.ELASTIC_SEARCH="ELASTIC_SEARCH"})(ApiSpec||(ApiSpec={}));var Environment;(function(Environment2){Environment2.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",Environment2.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",Environment2.ENVIRONMENT_MOBILE="ENVIRONMENT_MOBILE",Environment2.ENVIRONMENT_DESKTOP="ENVIRONMENT_DESKTOP"})(Environment||(Environment={}));var SafetyPolicy;(function(SafetyPolicy2){SafetyPolicy2.SAFETY_POLICY_UNSPECIFIED="SAFETY_POLICY_UNSPECIFIED",SafetyPolicy2.FINANCIAL_TRANSACTIONS="FINANCIAL_TRANSACTIONS",SafetyPolicy2.SENSITIVE_DATA_MODIFICATION="SENSITIVE_DATA_MODIFICATION",SafetyPolicy2.COMMUNICATION_TOOL="COMMUNICATION_TOOL",SafetyPolicy2.ACCOUNT_CREATION="ACCOUNT_CREATION",SafetyPolicy2.DATA_MODIFICATION="DATA_MODIFICATION",SafetyPolicy2.USER_CONSENT_MANAGEMENT="USER_CONSENT_MANAGEMENT",SafetyPolicy2.LEGAL_TERMS_AND_AGREEMENTS="LEGAL_TERMS_AND_AGREEMENTS"})(SafetyPolicy||(SafetyPolicy={}));var PhishBlockThreshold;(function(PhishBlockThreshold2){PhishBlockThreshold2.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",PhishBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",PhishBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",PhishBlockThreshold2.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",PhishBlockThreshold2.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",PhishBlockThreshold2.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",PhishBlockThreshold2.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(PhishBlockThreshold||(PhishBlockThreshold={}));var Behavior;(function(Behavior2){Behavior2.UNSPECIFIED="UNSPECIFIED",Behavior2.BLOCKING="BLOCKING",Behavior2.NON_BLOCKING="NON_BLOCKING"})(Behavior||(Behavior={}));var DynamicRetrievalConfigMode;(function(DynamicRetrievalConfigMode2){DynamicRetrievalConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",DynamicRetrievalConfigMode2.MODE_DYNAMIC="MODE_DYNAMIC"})(DynamicRetrievalConfigMode||(DynamicRetrievalConfigMode={}));var ThinkingLevel;(function(ThinkingLevel2){ThinkingLevel2.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",ThinkingLevel2.MINIMAL="MINIMAL",ThinkingLevel2.LOW="LOW",ThinkingLevel2.MEDIUM="MEDIUM",ThinkingLevel2.HIGH="HIGH"})(ThinkingLevel||(ThinkingLevel={}));var PersonGeneration;(function(PersonGeneration2){PersonGeneration2.DONT_ALLOW="DONT_ALLOW",PersonGeneration2.ALLOW_ADULT="ALLOW_ADULT",PersonGeneration2.ALLOW_ALL="ALLOW_ALL"})(PersonGeneration||(PersonGeneration={}));var ProminentPeople;(function(ProminentPeople2){ProminentPeople2.PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",ProminentPeople2.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",ProminentPeople2.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE"})(ProminentPeople||(ProminentPeople={}));var HarmCategory;(function(HarmCategory2){HarmCategory2.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",HarmCategory2.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",HarmCategory2.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",HarmCategory2.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",HarmCategory2.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",HarmCategory2.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",HarmCategory2.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",HarmCategory2.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",HarmCategory2.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",HarmCategory2.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"})(HarmCategory||(HarmCategory={}));var HarmBlockMethod;(function(HarmBlockMethod2){HarmBlockMethod2.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",HarmBlockMethod2.SEVERITY="SEVERITY",HarmBlockMethod2.PROBABILITY="PROBABILITY"})(HarmBlockMethod||(HarmBlockMethod={}));var HarmBlockThreshold;(function(HarmBlockThreshold2){HarmBlockThreshold2.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",HarmBlockThreshold2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",HarmBlockThreshold2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",HarmBlockThreshold2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",HarmBlockThreshold2.BLOCK_NONE="BLOCK_NONE",HarmBlockThreshold2.OFF="OFF"})(HarmBlockThreshold||(HarmBlockThreshold={}));var FunctionCallingConfigMode;(function(FunctionCallingConfigMode2){FunctionCallingConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",FunctionCallingConfigMode2.AUTO="AUTO",FunctionCallingConfigMode2.ANY="ANY",FunctionCallingConfigMode2.NONE="NONE",FunctionCallingConfigMode2.VALIDATED="VALIDATED"})(FunctionCallingConfigMode||(FunctionCallingConfigMode={}));var FinishReason;(function(FinishReason2){FinishReason2.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",FinishReason2.STOP="STOP",FinishReason2.MAX_TOKENS="MAX_TOKENS",FinishReason2.SAFETY="SAFETY",FinishReason2.RECITATION="RECITATION",FinishReason2.LANGUAGE="LANGUAGE",FinishReason2.OTHER="OTHER",FinishReason2.BLOCKLIST="BLOCKLIST",FinishReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",FinishReason2.SPII="SPII",FinishReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",FinishReason2.IMAGE_SAFETY="IMAGE_SAFETY",FinishReason2.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",FinishReason2.TOO_MANY_TOOL_CALLS="TOO_MANY_TOOL_CALLS",FinishReason2.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",FinishReason2.NO_IMAGE="NO_IMAGE",FinishReason2.IMAGE_RECITATION="IMAGE_RECITATION",FinishReason2.IMAGE_OTHER="IMAGE_OTHER"})(FinishReason||(FinishReason={}));var HarmProbability;(function(HarmProbability2){HarmProbability2.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",HarmProbability2.NEGLIGIBLE="NEGLIGIBLE",HarmProbability2.LOW="LOW",HarmProbability2.MEDIUM="MEDIUM",HarmProbability2.HIGH="HIGH"})(HarmProbability||(HarmProbability={}));var HarmSeverity;(function(HarmSeverity2){HarmSeverity2.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",HarmSeverity2.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",HarmSeverity2.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",HarmSeverity2.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",HarmSeverity2.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(HarmSeverity||(HarmSeverity={}));var UrlRetrievalStatus;(function(UrlRetrievalStatus2){UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",UrlRetrievalStatus2.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(UrlRetrievalStatus||(UrlRetrievalStatus={}));var BlockedReason;(function(BlockedReason2){BlockedReason2.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",BlockedReason2.SAFETY="SAFETY",BlockedReason2.OTHER="OTHER",BlockedReason2.BLOCKLIST="BLOCKLIST",BlockedReason2.PROHIBITED_CONTENT="PROHIBITED_CONTENT",BlockedReason2.IMAGE_SAFETY="IMAGE_SAFETY",BlockedReason2.MODEL_ARMOR="MODEL_ARMOR",BlockedReason2.JAILBREAK="JAILBREAK"})(BlockedReason||(BlockedReason={}));var TrafficType;(function(TrafficType2){TrafficType2.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",TrafficType2.ON_DEMAND="ON_DEMAND",TrafficType2.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",TrafficType2.ON_DEMAND_FLEX="ON_DEMAND_FLEX",TrafficType2.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(TrafficType||(TrafficType={}));var MediaModality;(function(MediaModality2){MediaModality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",MediaModality2.TEXT="TEXT",MediaModality2.IMAGE="IMAGE",MediaModality2.VIDEO="VIDEO",MediaModality2.AUDIO="AUDIO",MediaModality2.DOCUMENT="DOCUMENT"})(MediaModality||(MediaModality={}));var ModelStage;(function(ModelStage2){ModelStage2.MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",ModelStage2.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",ModelStage2.EXPERIMENTAL="EXPERIMENTAL",ModelStage2.PREVIEW="PREVIEW",ModelStage2.STABLE="STABLE",ModelStage2.LEGACY="LEGACY",ModelStage2.DEPRECATED="DEPRECATED",ModelStage2.RETIRED="RETIRED"})(ModelStage||(ModelStage={}));var MediaResolution;(function(MediaResolution2){MediaResolution2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",MediaResolution2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",MediaResolution2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",MediaResolution2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(MediaResolution||(MediaResolution={}));var Modality;(function(Modality2){Modality2.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",Modality2.TEXT="TEXT",Modality2.IMAGE="IMAGE",Modality2.AUDIO="AUDIO",Modality2.VIDEO="VIDEO"})(Modality||(Modality={}));var Delivery;(function(Delivery2){Delivery2.DELIVERY_UNSPECIFIED="DELIVERY_UNSPECIFIED",Delivery2.INLINE="INLINE",Delivery2.URI="URI"})(Delivery||(Delivery={}));var AspectRatio;(function(AspectRatio2){AspectRatio2.ASPECT_RATIO_UNSPECIFIED="ASPECT_RATIO_UNSPECIFIED",AspectRatio2.ASPECT_RATIO_ONE_BY_ONE="ASPECT_RATIO_ONE_BY_ONE",AspectRatio2.ASPECT_RATIO_TWO_BY_THREE="ASPECT_RATIO_TWO_BY_THREE",AspectRatio2.ASPECT_RATIO_THREE_BY_TWO="ASPECT_RATIO_THREE_BY_TWO",AspectRatio2.ASPECT_RATIO_THREE_BY_FOUR="ASPECT_RATIO_THREE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_THREE="ASPECT_RATIO_FOUR_BY_THREE",AspectRatio2.ASPECT_RATIO_FOUR_BY_FIVE="ASPECT_RATIO_FOUR_BY_FIVE",AspectRatio2.ASPECT_RATIO_FIVE_BY_FOUR="ASPECT_RATIO_FIVE_BY_FOUR",AspectRatio2.ASPECT_RATIO_NINE_BY_SIXTEEN="ASPECT_RATIO_NINE_BY_SIXTEEN",AspectRatio2.ASPECT_RATIO_SIXTEEN_BY_NINE="ASPECT_RATIO_SIXTEEN_BY_NINE",AspectRatio2.ASPECT_RATIO_TWENTY_ONE_BY_NINE="ASPECT_RATIO_TWENTY_ONE_BY_NINE",AspectRatio2.ASPECT_RATIO_ONE_BY_EIGHT="ASPECT_RATIO_ONE_BY_EIGHT",AspectRatio2.ASPECT_RATIO_EIGHT_BY_ONE="ASPECT_RATIO_EIGHT_BY_ONE",AspectRatio2.ASPECT_RATIO_ONE_BY_FOUR="ASPECT_RATIO_ONE_BY_FOUR",AspectRatio2.ASPECT_RATIO_FOUR_BY_ONE="ASPECT_RATIO_FOUR_BY_ONE"})(AspectRatio||(AspectRatio={}));var ImageSize;(function(ImageSize2){ImageSize2.IMAGE_SIZE_UNSPECIFIED="IMAGE_SIZE_UNSPECIFIED",ImageSize2.IMAGE_SIZE_FIVE_TWELVE="IMAGE_SIZE_FIVE_TWELVE",ImageSize2.IMAGE_SIZE_ONE_K="IMAGE_SIZE_ONE_K",ImageSize2.IMAGE_SIZE_TWO_K="IMAGE_SIZE_TWO_K",ImageSize2.IMAGE_SIZE_FOUR_K="IMAGE_SIZE_FOUR_K"})(ImageSize||(ImageSize={}));var TuningMode;(function(TuningMode2){TuningMode2.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",TuningMode2.TUNING_MODE_FULL="TUNING_MODE_FULL",TuningMode2.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(TuningMode||(TuningMode={}));var AdapterSize;(function(AdapterSize2){AdapterSize2.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",AdapterSize2.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",AdapterSize2.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",AdapterSize2.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",AdapterSize2.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",AdapterSize2.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",AdapterSize2.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(AdapterSize||(AdapterSize={}));var ResponseParseType;(function(ResponseParseType2){ResponseParseType2.RESPONSE_PARSE_TYPE_UNSPECIFIED="RESPONSE_PARSE_TYPE_UNSPECIFIED",ResponseParseType2.IDENTITY="IDENTITY",ResponseParseType2.REGEX_EXTRACT="REGEX_EXTRACT"})(ResponseParseType||(ResponseParseType={}));var MatchOperation;(function(MatchOperation2){MatchOperation2.MATCH_OPERATION_UNSPECIFIED="MATCH_OPERATION_UNSPECIFIED",MatchOperation2.REGEX_CONTAINS="REGEX_CONTAINS",MatchOperation2.PARTIAL_MATCH="PARTIAL_MATCH",MatchOperation2.EXACT_MATCH="EXACT_MATCH"})(MatchOperation||(MatchOperation={}));var ReinforcementTuningThinkingLevel;(function(ReinforcementTuningThinkingLevel2){ReinforcementTuningThinkingLevel2.REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED="REINFORCEMENT_TUNING_THINKING_LEVEL_UNSPECIFIED",ReinforcementTuningThinkingLevel2.MINIMAL="MINIMAL",ReinforcementTuningThinkingLevel2.HIGH="HIGH"})(ReinforcementTuningThinkingLevel||(ReinforcementTuningThinkingLevel={}));var JobState;(function(JobState2){JobState2.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",JobState2.JOB_STATE_QUEUED="JOB_STATE_QUEUED",JobState2.JOB_STATE_PENDING="JOB_STATE_PENDING",JobState2.JOB_STATE_RUNNING="JOB_STATE_RUNNING",JobState2.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",JobState2.JOB_STATE_FAILED="JOB_STATE_FAILED",JobState2.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",JobState2.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",JobState2.JOB_STATE_PAUSED="JOB_STATE_PAUSED",JobState2.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",JobState2.JOB_STATE_UPDATING="JOB_STATE_UPDATING",JobState2.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(JobState||(JobState={}));var TuningJobState;(function(TuningJobState2){TuningJobState2.TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",TuningJobState2.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",TuningJobState2.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",TuningJobState2.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",TuningJobState2.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING"})(TuningJobState||(TuningJobState={}));var AggregationMetric;(function(AggregationMetric2){AggregationMetric2.AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",AggregationMetric2.AVERAGE="AVERAGE",AggregationMetric2.MODE="MODE",AggregationMetric2.STANDARD_DEVIATION="STANDARD_DEVIATION",AggregationMetric2.VARIANCE="VARIANCE",AggregationMetric2.MINIMUM="MINIMUM",AggregationMetric2.MAXIMUM="MAXIMUM",AggregationMetric2.MEDIAN="MEDIAN",AggregationMetric2.PERCENTILE_P90="PERCENTILE_P90",AggregationMetric2.PERCENTILE_P95="PERCENTILE_P95",AggregationMetric2.PERCENTILE_P99="PERCENTILE_P99"})(AggregationMetric||(AggregationMetric={}));var PairwiseChoice;(function(PairwiseChoice2){PairwiseChoice2.PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",PairwiseChoice2.BASELINE="BASELINE",PairwiseChoice2.CANDIDATE="CANDIDATE",PairwiseChoice2.TIE="TIE"})(PairwiseChoice||(PairwiseChoice={}));var VideoOrientation;(function(VideoOrientation2){VideoOrientation2.VIDEO_ORIENTATION_UNSPECIFIED="VIDEO_ORIENTATION_UNSPECIFIED",VideoOrientation2.LANDSCAPE="LANDSCAPE",VideoOrientation2.PORTRAIT="PORTRAIT"})(VideoOrientation||(VideoOrientation={}));var TuningSpeed;(function(TuningSpeed2){TuningSpeed2.TUNING_SPEED_UNSPECIFIED="TUNING_SPEED_UNSPECIFIED",TuningSpeed2.REGULAR="REGULAR",TuningSpeed2.FAST="FAST"})(TuningSpeed||(TuningSpeed={}));var TuningTask;(function(TuningTask2){TuningTask2.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",TuningTask2.TUNING_TASK_I2V="TUNING_TASK_I2V",TuningTask2.TUNING_TASK_T2V="TUNING_TASK_T2V",TuningTask2.TUNING_TASK_R2V="TUNING_TASK_R2V"})(TuningTask||(TuningTask={}));var DocumentState;(function(DocumentState2){DocumentState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",DocumentState2.STATE_PENDING="STATE_PENDING",DocumentState2.STATE_ACTIVE="STATE_ACTIVE",DocumentState2.STATE_FAILED="STATE_FAILED"})(DocumentState||(DocumentState={}));var ServiceTier;(function(ServiceTier2){ServiceTier2.UNSPECIFIED="unspecified",ServiceTier2.FLEX="flex",ServiceTier2.STANDARD="standard",ServiceTier2.PRIORITY="priority"})(ServiceTier||(ServiceTier={}));var MediaProcessing;(function(MediaProcessing2){MediaProcessing2.MEDIA_PROCESSING_UNSPECIFIED="MEDIA_PROCESSING_UNSPECIFIED",MediaProcessing2.STATIC="STATIC",MediaProcessing2.AGENTIC="AGENTIC"})(MediaProcessing||(MediaProcessing={}));var PartMediaResolutionLevel;(function(PartMediaResolutionLevel2){PartMediaResolutionLevel2.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",PartMediaResolutionLevel2.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",PartMediaResolutionLevel2.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",PartMediaResolutionLevel2.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",PartMediaResolutionLevel2.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(PartMediaResolutionLevel||(PartMediaResolutionLevel={}));var ToolType;(function(ToolType2){ToolType2.TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",ToolType2.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",ToolType2.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",ToolType2.URL_CONTEXT="URL_CONTEXT",ToolType2.GOOGLE_MAPS="GOOGLE_MAPS",ToolType2.FILE_SEARCH="FILE_SEARCH",ToolType2.MEDIA_PROCESSING="MEDIA_PROCESSING"})(ToolType||(ToolType={}));var ResourceScope;(function(ResourceScope2){ResourceScope2.COLLECTION="COLLECTION"})(ResourceScope||(ResourceScope={}));var FeatureSelectionPreference;(function(FeatureSelectionPreference2){FeatureSelectionPreference2.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",FeatureSelectionPreference2.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",FeatureSelectionPreference2.BALANCED="BALANCED",FeatureSelectionPreference2.PRIORITIZE_COST="PRIORITIZE_COST"})(FeatureSelectionPreference||(FeatureSelectionPreference={}));var EmbeddingApiType;(function(EmbeddingApiType2){EmbeddingApiType2.PREDICT="PREDICT",EmbeddingApiType2.EMBED_CONTENT="EMBED_CONTENT"})(EmbeddingApiType||(EmbeddingApiType={}));var SafetyFilterLevel;(function(SafetyFilterLevel2){SafetyFilterLevel2.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",SafetyFilterLevel2.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",SafetyFilterLevel2.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",SafetyFilterLevel2.BLOCK_NONE="BLOCK_NONE"})(SafetyFilterLevel||(SafetyFilterLevel={}));var ImagePromptLanguage;(function(ImagePromptLanguage2){ImagePromptLanguage2.auto="auto",ImagePromptLanguage2.en="en",ImagePromptLanguage2.ja="ja",ImagePromptLanguage2.ko="ko",ImagePromptLanguage2.hi="hi",ImagePromptLanguage2.zh="zh",ImagePromptLanguage2.pt="pt",ImagePromptLanguage2.es="es"})(ImagePromptLanguage||(ImagePromptLanguage={}));var MaskReferenceMode;(function(MaskReferenceMode2){MaskReferenceMode2.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",MaskReferenceMode2.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",MaskReferenceMode2.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",MaskReferenceMode2.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",MaskReferenceMode2.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(MaskReferenceMode||(MaskReferenceMode={}));var ControlReferenceType;(function(ControlReferenceType2){ControlReferenceType2.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",ControlReferenceType2.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",ControlReferenceType2.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",ControlReferenceType2.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(ControlReferenceType||(ControlReferenceType={}));var SubjectReferenceType;(function(SubjectReferenceType2){SubjectReferenceType2.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",SubjectReferenceType2.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",SubjectReferenceType2.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",SubjectReferenceType2.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(SubjectReferenceType||(SubjectReferenceType={}));var EditMode;(function(EditMode2){EditMode2.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",EditMode2.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",EditMode2.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",EditMode2.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",EditMode2.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",EditMode2.EDIT_MODE_STYLE="EDIT_MODE_STYLE",EditMode2.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",EditMode2.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(EditMode||(EditMode={}));var SegmentMode;(function(SegmentMode2){SegmentMode2.FOREGROUND="FOREGROUND",SegmentMode2.BACKGROUND="BACKGROUND",SegmentMode2.PROMPT="PROMPT",SegmentMode2.SEMANTIC="SEMANTIC",SegmentMode2.INTERACTIVE="INTERACTIVE"})(SegmentMode||(SegmentMode={}));var VideoGenerationReferenceType;(function(VideoGenerationReferenceType2){VideoGenerationReferenceType2.ASSET="ASSET",VideoGenerationReferenceType2.STYLE="STYLE"})(VideoGenerationReferenceType||(VideoGenerationReferenceType={}));var VideoGenerationMaskMode;(function(VideoGenerationMaskMode2){VideoGenerationMaskMode2.INSERT="INSERT",VideoGenerationMaskMode2.REMOVE="REMOVE",VideoGenerationMaskMode2.REMOVE_STATIC="REMOVE_STATIC",VideoGenerationMaskMode2.OUTPAINT="OUTPAINT"})(VideoGenerationMaskMode||(VideoGenerationMaskMode={}));var VideoCompressionQuality;(function(VideoCompressionQuality2){VideoCompressionQuality2.OPTIMIZED="OPTIMIZED",VideoCompressionQuality2.LOSSLESS="LOSSLESS"})(VideoCompressionQuality||(VideoCompressionQuality={}));var ImageResizeMode;(function(ImageResizeMode2){ImageResizeMode2.CROP="CROP",ImageResizeMode2.PAD="PAD"})(ImageResizeMode||(ImageResizeMode={}));var TuningMethod;(function(TuningMethod2){TuningMethod2.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",TuningMethod2.PREFERENCE_TUNING="PREFERENCE_TUNING",TuningMethod2.DISTILLATION="DISTILLATION",TuningMethod2.REINFORCEMENT_TUNING="REINFORCEMENT_TUNING"})(TuningMethod||(TuningMethod={}));var FileState;(function(FileState2){FileState2.STATE_UNSPECIFIED="STATE_UNSPECIFIED",FileState2.PROCESSING="PROCESSING",FileState2.ACTIVE="ACTIVE",FileState2.FAILED="FAILED"})(FileState||(FileState={}));var FileSource;(function(FileSource2){FileSource2.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",FileSource2.UPLOADED="UPLOADED",FileSource2.GENERATED="GENERATED",FileSource2.REGISTERED="REGISTERED"})(FileSource||(FileSource={}));var TurnCompleteReason;(function(TurnCompleteReason2){TurnCompleteReason2.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",TurnCompleteReason2.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",TurnCompleteReason2.RESPONSE_REJECTED="RESPONSE_REJECTED",TurnCompleteReason2.NEED_MORE_INPUT="NEED_MORE_INPUT",TurnCompleteReason2.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",TurnCompleteReason2.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",TurnCompleteReason2.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",TurnCompleteReason2.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",TurnCompleteReason2.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",TurnCompleteReason2.INPUT_OTHER="INPUT_OTHER",TurnCompleteReason2.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",TurnCompleteReason2.BLOCKLIST="BLOCKLIST",TurnCompleteReason2.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",TurnCompleteReason2.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",TurnCompleteReason2.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",TurnCompleteReason2.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",TurnCompleteReason2.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",TurnCompleteReason2.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",TurnCompleteReason2.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",TurnCompleteReason2.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",TurnCompleteReason2.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",TurnCompleteReason2.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",TurnCompleteReason2.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",TurnCompleteReason2.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",TurnCompleteReason2.GENERATED_OTHER="GENERATED_OTHER",TurnCompleteReason2.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED"})(TurnCompleteReason||(TurnCompleteReason={}));var InteractionStatus;(function(InteractionStatus2){InteractionStatus2.INTERACTION_STATUS_UNSPECIFIED="INTERACTION_STATUS_UNSPECIFIED",InteractionStatus2.IN_PROGRESS="IN_PROGRESS",InteractionStatus2.REQUIRES_ACTION="REQUIRES_ACTION",InteractionStatus2.IDLE="IDLE"})(InteractionStatus||(InteractionStatus={}));var VadSignalType;(function(VadSignalType2){VadSignalType2.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",VadSignalType2.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",VadSignalType2.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})(VadSignalType||(VadSignalType={}));var VoiceActivityType;(function(VoiceActivityType2){VoiceActivityType2.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",VoiceActivityType2.ACTIVITY_START="ACTIVITY_START",VoiceActivityType2.ACTIVITY_END="ACTIVITY_END"})(VoiceActivityType||(VoiceActivityType={}));var StartSensitivity;(function(StartSensitivity2){StartSensitivity2.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",StartSensitivity2.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",StartSensitivity2.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(StartSensitivity||(StartSensitivity={}));var EndSensitivity;(function(EndSensitivity2){EndSensitivity2.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",EndSensitivity2.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",EndSensitivity2.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(EndSensitivity||(EndSensitivity={}));var ActivityHandling;(function(ActivityHandling2){ActivityHandling2.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",ActivityHandling2.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",ActivityHandling2.NO_INTERRUPTION="NO_INTERRUPTION"})(ActivityHandling||(ActivityHandling={}));var TurnCoverage;(function(TurnCoverage2){TurnCoverage2.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",TurnCoverage2.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",TurnCoverage2.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",TurnCoverage2.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO"})(TurnCoverage||(TurnCoverage={}));var AudioTranscriptionConfigMode;(function(AudioTranscriptionConfigMode2){AudioTranscriptionConfigMode2.MODE_UNSPECIFIED="MODE_UNSPECIFIED",AudioTranscriptionConfigMode2.VERBATIM="VERBATIM",AudioTranscriptionConfigMode2.SMART="SMART"})(AudioTranscriptionConfigMode||(AudioTranscriptionConfigMode={}));var Scale;(function(Scale2){Scale2.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",Scale2.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",Scale2.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",Scale2.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",Scale2.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",Scale2.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",Scale2.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",Scale2.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",Scale2.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",Scale2.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",Scale2.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",Scale2.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",Scale2.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(Scale||(Scale={}));var MusicGenerationMode;(function(MusicGenerationMode2){MusicGenerationMode2.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",MusicGenerationMode2.QUALITY="QUALITY",MusicGenerationMode2.DIVERSITY="DIVERSITY",MusicGenerationMode2.VOCALIZATION="VOCALIZATION"})(MusicGenerationMode||(MusicGenerationMode={}));var LiveMusicPlaybackControl;(function(LiveMusicPlaybackControl2){LiveMusicPlaybackControl2.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",LiveMusicPlaybackControl2.PLAY="PLAY",LiveMusicPlaybackControl2.PAUSE="PAUSE",LiveMusicPlaybackControl2.STOP="STOP",LiveMusicPlaybackControl2.RESET_CONTEXT="RESET_CONTEXT"})(LiveMusicPlaybackControl||(LiveMusicPlaybackControl={}));var GenerateContentResponse=class{get text(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let text="",anyTextPartText=!1,nonTextParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="text"&&fieldName!=="thought"&&fieldName!=="thoughtSignature"&&(fieldValue!==null||fieldValue!==void 0)&&nonTextParts.push(fieldName);if(typeof part.text=="string"){if(typeof part.thought=="boolean"&&part.thought)continue;anyTextPartText=!0,text+=part.text}}return nonTextParts.length>0&&console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),anyTextPartText?text:void 0}get data(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let data="",nonDataParts=[];for(let part of(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)!==null&&_h!==void 0?_h:[]){for(let[fieldName,fieldValue]of Object.entries(part))fieldName!=="inlineData"&&(fieldValue!==null||fieldValue!==void 0)&&nonDataParts.push(fieldName);part.inlineData&&typeof part.inlineData.data=="string"&&(data+=atob(part.inlineData.data))}return nonDataParts.length>0&&console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),data.length>0?btoa(data):void 0}get functionCalls(){var _a2,_b,_c,_d,_e,_f,_g,_h;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let functionCalls=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.functionCall).map(part=>part.functionCall).filter(functionCall=>functionCall!==void 0);if(functionCalls?.length!==0)return functionCalls}get executableCode(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let executableCode=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.executableCode).map(part=>part.executableCode).filter(executableCode2=>executableCode2!==void 0);if(executableCode?.length!==0)return(_j=executableCode?.[0])===null||_j===void 0?void 0:_j.code}get codeExecutionResult(){var _a2,_b,_c,_d,_e,_f,_g,_h,_j;if(((_d=(_c=(_b=(_a2=this.candidates)===null||_a2===void 0?void 0:_a2[0])===null||_b===void 0?void 0:_b.content)===null||_c===void 0?void 0:_c.parts)===null||_d===void 0?void 0:_d.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let codeExecutionResult=(_h=(_g=(_f=(_e=this.candidates)===null||_e===void 0?void 0:_e[0])===null||_f===void 0?void 0:_f.content)===null||_g===void 0?void 0:_g.parts)===null||_h===void 0?void 0:_h.filter(part=>part.codeExecutionResult).map(part=>part.codeExecutionResult).filter(codeExecutionResult2=>codeExecutionResult2!==void 0);if(codeExecutionResult?.length!==0)return(_j=codeExecutionResult?.[0])===null||_j===void 0?void 0:_j.output}},EmbedContentResponse=class{},GenerateImagesResponse=class{},EditImageResponse=class{},UpscaleImageResponse=class{},RecontextImageResponse=class{},SegmentImageResponse=class{},ListModelsResponse=class{},DeleteModelResponse=class{};var CountTokensResponse=class{},ComputeTokensResponse=class{};var GenerateVideosOperation=class _GenerateVideosOperation{_fromAPIResponse({apiResponse,_isVertexAI}){let operation=new _GenerateVideosOperation,response,op=apiResponse;return _isVertexAI?response=generateVideosOperationFromVertex$1(op):response=generateVideosOperationFromMldev$1(op),Object.assign(operation,response),operation}};function tModel(apiClient,model){if(!model||typeof model!="string")throw new Error("model is required and must be a string");if(model.includes("..")||model.includes("?")||model.includes("&"))throw new Error("invalid model parameter");if(apiClient.isVertexAI()){if(model.startsWith("publishers/")||model.startsWith("projects/")||model.startsWith("models/"))return model;if(model.indexOf("/")>=0){let parts=model.split("/",2);return`publishers/${parts[0]}/models/${parts[1]}`}else return`publishers/google/models/${model}`}else return model.startsWith("models/")||model.startsWith("tunedModels/")?model:`models/${model}`}function tPart(origin){if(origin==null)throw new Error("PartUnion is required");if(typeof origin=="object")return origin;if(typeof origin=="string")return{text:origin};throw new Error(`Unsupported part type: ${typeof origin}`)}function tParts(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("PartListUnion is required");return Array.isArray(origin)?origin.map(item=>tPart(item)):[tPart(origin)]}function _isContent(origin){return origin!=null&&typeof origin=="object"&&"parts"in origin&&Array.isArray(origin.parts)}function _isFunctionCallPart(origin){return origin!=null&&typeof origin=="object"&&"functionCall"in origin}function _isFunctionResponsePart(origin){return origin!=null&&typeof origin=="object"&&"functionResponse"in origin}function tContent(origin){if(origin==null)throw new Error("ContentUnion is required");return _isContent(origin)?origin:{role:"user",parts:tParts(origin)}}function tContentsForEmbed(apiClient,origin){if(!origin)return[];if(apiClient.isVertexAI()&&Array.isArray(origin))return origin.flatMap(item=>{let content=tContent(item);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]});if(apiClient.isVertexAI()){let content=tContent(origin);return content.parts&&content.parts.length>0&&content.parts[0].text!==void 0?[content.parts[0].text]:[]}return Array.isArray(origin)?origin.map(item=>tContent(item)):[tContent(origin)]}function tContents(origin){if(origin==null||Array.isArray(origin)&&origin.length===0)throw new Error("contents are required");if(!Array.isArray(origin)){if(_isFunctionCallPart(origin)||_isFunctionResponsePart(origin))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[tContent(origin)]}let result=[],accumulatedParts=[],isContentArray=_isContent(origin[0]);for(let item of origin){let isContent=_isContent(item);if(isContent!=isContentArray)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(isContent)result.push(item);else{if(_isFunctionCallPart(item)||_isFunctionResponsePart(item))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");accumulatedParts.push(item)}}return isContentArray||result.push({role:"user",parts:tParts(accumulatedParts)}),result}function flattenTypeArrayToAnyOf(typeList,resultingSchema){typeList.includes("null")&&(resultingSchema.nullable=!0);let listWithoutNull=typeList.filter(type=>type!=="null");if(listWithoutNull.length===1)resultingSchema.type=Object.values(Type).includes(listWithoutNull[0].toUpperCase())?listWithoutNull[0].toUpperCase():Type.TYPE_UNSPECIFIED;else{resultingSchema.anyOf=[];for(let i2 of listWithoutNull)resultingSchema.anyOf.push({type:Object.values(Type).includes(i2.toUpperCase())?i2.toUpperCase():Type.TYPE_UNSPECIFIED})}}function processJsonSchema(_jsonSchema){let genAISchema={},schemaFieldNames=["items"],listSchemaFieldNames=["anyOf"],dictSchemaFieldNames=["properties"];if(_jsonSchema.type&&_jsonSchema.anyOf)throw new Error("type and anyOf cannot be both populated.");let incomingAnyOf=_jsonSchema.anyOf;incomingAnyOf!=null&&incomingAnyOf.length==2&&(incomingAnyOf[0].type==="null"?(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[1]):incomingAnyOf[1].type==="null"&&(genAISchema.nullable=!0,_jsonSchema=incomingAnyOf[0])),_jsonSchema.type instanceof Array&&flattenTypeArrayToAnyOf(_jsonSchema.type,genAISchema);for(let[fieldName,fieldValue]of Object.entries(_jsonSchema))if(fieldValue!=null)if(fieldName=="type"){if(fieldValue==="null")throw new Error("type: null can not be the only possible type for the field.");if(fieldValue instanceof Array)continue;genAISchema.type=Object.values(Type).includes(fieldValue.toUpperCase())?fieldValue.toUpperCase():Type.TYPE_UNSPECIFIED}else if(schemaFieldNames.includes(fieldName))genAISchema[fieldName]=processJsonSchema(fieldValue);else if(listSchemaFieldNames.includes(fieldName)){let listSchemaFieldValue=[];for(let item of fieldValue){if(item.type=="null"){genAISchema.nullable=!0;continue}listSchemaFieldValue.push(processJsonSchema(item))}genAISchema[fieldName]=listSchemaFieldValue}else if(dictSchemaFieldNames.includes(fieldName)){let dictSchemaFieldValue={};for(let[key,value]of Object.entries(fieldValue))dictSchemaFieldValue[key]=processJsonSchema(value);genAISchema[fieldName]=dictSchemaFieldValue}else{if(fieldName==="additionalProperties")continue;genAISchema[fieldName]=fieldValue}return genAISchema}function tSchema(schema){return processJsonSchema(schema)}function tSpeechConfig(speechConfig){if(typeof speechConfig=="object")return speechConfig;if(typeof speechConfig=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:speechConfig}}};throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`)}function tTool(tool){if(tool.functionDeclarations)for(let functionDeclaration of tool.functionDeclarations)functionDeclaration.parameters&&(Object.keys(functionDeclaration.parameters).includes("$schema")?functionDeclaration.parametersJsonSchema||(functionDeclaration.parametersJsonSchema=functionDeclaration.parameters,delete functionDeclaration.parameters):functionDeclaration.parameters=processJsonSchema(functionDeclaration.parameters)),functionDeclaration.response&&(Object.keys(functionDeclaration.response).includes("$schema")?functionDeclaration.responseJsonSchema||(functionDeclaration.responseJsonSchema=functionDeclaration.response,delete functionDeclaration.response):functionDeclaration.response=processJsonSchema(functionDeclaration.response));return tool}function tTools(tools){if(tools==null)throw new Error("tools is required");if(!Array.isArray(tools))throw new Error("tools is required and must be an array of Tools");let result=[];for(let tool of tools)result.push(tool);return result}function resourceName(client,resourceName2,resourcePrefix,splitsAfterPrefix=1){let shouldAppendPrefix=!resourceName2.startsWith(`${resourcePrefix}/`)&&resourceName2.split("/").length===splitsAfterPrefix;return client.isVertexAI()?resourceName2.startsWith("projects/")?resourceName2:resourceName2.startsWith("locations/")?`projects/${client.getProject()}/${resourceName2}`:resourceName2.startsWith(`${resourcePrefix}/`)?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName2}`:shouldAppendPrefix?`projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName2}`:resourceName2:shouldAppendPrefix?`${resourcePrefix}/${resourceName2}`:resourceName2}function tCachedContentName(apiClient,name){if(typeof name!="string")throw new Error("name must be a string");return resourceName(apiClient,name,"cachedContents")}function tBytes(fromImageBytes){return tBytes$1(fromImageBytes)}function tModelsUrl(apiClient,baseModels){let res;return apiClient.isVertexAI()?res=baseModels?"publishers/google/models":"models":res=baseModels?"models":"tunedModels",res}function tExtractModels(response){for(let key of["models","tunedModels","publisherModels"])if(hasField(response,key))return response[key];return[]}function hasField(data,fieldName){return data!==null&&typeof data=="object"&&fieldName in data}function mcpToGeminiTool(mcpTool,config={}){let mcpToolSchema=mcpTool,functionDeclaration={name:mcpToolSchema.name,description:mcpToolSchema.description,parametersJsonSchema:mcpToolSchema.inputSchema};return mcpToolSchema.outputSchema&&(functionDeclaration.responseJsonSchema=mcpToolSchema.outputSchema),config.behavior&&(functionDeclaration.behavior=config.behavior),{functionDeclarations:[functionDeclaration]}}function mcpToolsToGeminiTool(mcpTools,config={}){let functionDeclarations=[],toolNames=new Set;for(let mcpTool of mcpTools){let mcpToolName=mcpTool.name;if(toolNames.has(mcpToolName))throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);toolNames.add(mcpToolName);let geminiTool=mcpToGeminiTool(mcpTool,config);geminiTool.functionDeclarations&&functionDeclarations.push(...geminiTool.functionDeclarations)}return{functionDeclarations}}function tIsVertexEmbedContentModel(model){return model.includes("gemini")&&model!=="gemini-embedding-001"||model.includes("maas")}var PagedItem;(function(PagedItem2){PagedItem2.PAGED_ITEM_BATCH_JOBS="batchJobs",PagedItem2.PAGED_ITEM_MODELS="models",PagedItem2.PAGED_ITEM_TUNING_JOBS="tuningJobs",PagedItem2.PAGED_ITEM_FILES="files",PagedItem2.PAGED_ITEM_CACHED_CONTENTS="cachedContents",PagedItem2.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",PagedItem2.PAGED_ITEM_DOCUMENTS="documents",PagedItem2.PAGED_ITEM_SKILLS="skills"})(PagedItem||(PagedItem={}));var Pager=class{constructor(name,request,response,params){this.pageInternal=[],this.paramsInternal={},this.requestInternal=request,this.init(name,response,params)}init(name,response,params){var _a2,_b;this.nameInternal=name,this.pageInternal=response[this.nameInternal]||[],this.sdkHttpResponseInternal=response?.sdkHttpResponse,this.idxInternal=0;let requestParams={config:{}};!params||Object.keys(params).length===0?requestParams={config:{}}:typeof params=="object"?requestParams=Object.assign({},params):requestParams=params,requestParams.config&&(requestParams.config.pageToken=response.nextPageToken),this.paramsInternal=requestParams,this.pageInternalSize=(_b=(_a2=requestParams.config)===null||_a2===void 0?void 0:_a2.pageSize)!==null&&_b!==void 0?_b:this.pageInternal.length}initNextPage(response){this.init(this.nameInternal,response,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(index){return this.pageInternal[index]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};let item=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:item,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");let response=await this.requestInternal(this.params);return this.initNextPage(response),this.page}hasNextPage(){var _a2;return((_a2=this.params.config)===null||_a2===void 0?void 0:_a2.pageToken)!==void 0}};function __values(o){var s2=typeof Symbol=="function"&&Symbol.iterator,m2=s2&&o[s2],i2=0;if(m2)return m2.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i2>=o.length&&(o=void 0),{value:o&&o[i2++],done:!o}}};throw new TypeError(s2?"Object is not iterable.":"Symbol.iterator is not defined.")}function __await(v){return this instanceof __await?(this.v=v,this):new __await(v)}function __asyncGenerator(thisArg,_arguments,generator){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var g=generator.apply(thisArg,_arguments||[]),i2,q=[];return i2=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",awaitReturn),i2[Symbol.asyncIterator]=function(){return this},i2;function awaitReturn(f3){return function(v){return Promise.resolve(v).then(f3,reject)}}function verb(n,f3){g[n]&&(i2[n]=function(v){return new Promise(function(a,b){q.push([n,v,a,b])>1||resume(n,v)})},f3&&(i2[n]=f3(i2[n])))}function resume(n,v){try{step(g[n](v))}catch(e2){settle(q[0][3],e2)}}function step(r2){r2.value instanceof __await?Promise.resolve(r2.value.v).then(fulfill,reject):settle(q[0][2],r2)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f3,v){f3(v),q.shift(),q.length&&resume(q[0][0],q[0][1])}}function __asyncValues(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m2=o[Symbol.asyncIterator],i2;return m2?m2.call(o):(o=typeof __values=="function"?__values(o):o[Symbol.iterator](),i2={},verb("next"),verb("throw"),verb("return"),i2[Symbol.asyncIterator]=function(){return this},i2);function verb(n){i2[n]=o[n]&&function(v){return new Promise(function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value)})}}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v2){resolve({value:v2,done:d})},reject)}}function authConfigToMldev$1(fromObject,_rootObject){let toObject={},fromApiKey=getValueByPath(fromObject,["apiKey"]);if(fromApiKey!=null&&setValueByPath(toObject,["apiKey"],fromApiKey),getValueByPath(fromObject,["apiKeyConfig"])!==void 0)throw new Error("apiKeyConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["authType"])!==void 0)throw new Error("authType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["googleServiceAccountConfig"])!==void 0)throw new Error("googleServiceAccountConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["httpBasicAuthConfig"])!==void 0)throw new Error("httpBasicAuthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oauthConfig"])!==void 0)throw new Error("oauthConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["oidcConfig"])!==void 0)throw new Error("oidcConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function blobToMldev$1(fromObject,_rootObject){let toObject={},fromData=getValueByPath(fromObject,["data"]);if(fromData!=null&&setValueByPath(toObject,["data"],fromData),getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function candidateFromMldev(fromObject,rootObject){let toObject={},fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],fromContent);let fromCitationMetadata=getValueByPath(fromObject,["citationMetadata"]);fromCitationMetadata!=null&&setValueByPath(toObject,["citationMetadata"],citationMetadataFromMldev(fromCitationMetadata));let fromTokenCount=getValueByPath(fromObject,["tokenCount"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromFinishReason=getValueByPath(fromObject,["finishReason"]);fromFinishReason!=null&&setValueByPath(toObject,["finishReason"],fromFinishReason);let fromGroundingMetadata=getValueByPath(fromObject,["groundingMetadata"]);fromGroundingMetadata!=null&&setValueByPath(toObject,["groundingMetadata"],fromGroundingMetadata);let fromAvgLogprobs=getValueByPath(fromObject,["avgLogprobs"]);fromAvgLogprobs!=null&&setValueByPath(toObject,["avgLogprobs"],fromAvgLogprobs);let fromIndex=getValueByPath(fromObject,["index"]);fromIndex!=null&&setValueByPath(toObject,["index"],fromIndex);let fromLogprobsResult=getValueByPath(fromObject,["logprobsResult"]);fromLogprobsResult!=null&&setValueByPath(toObject,["logprobsResult"],fromLogprobsResult);let fromSafetyRatings=getValueByPath(fromObject,["safetyRatings"]);if(fromSafetyRatings!=null){let transformedList=fromSafetyRatings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["safetyRatings"],transformedList)}let fromUrlContextMetadata=getValueByPath(fromObject,["urlContextMetadata"]);return fromUrlContextMetadata!=null&&setValueByPath(toObject,["urlContextMetadata"],fromUrlContextMetadata),toObject}function citationMetadataFromMldev(fromObject,_rootObject){let toObject={},fromCitations=getValueByPath(fromObject,["citationSources"]);if(fromCitations!=null){let transformedList=fromCitations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["citations"],transformedList)}return toObject}function computeTokensParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}return toObject}function computeTokensResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTokensInfo=getValueByPath(fromObject,["tokensInfo"]);if(fromTokensInfo!=null){let transformedList=fromTokensInfo;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensInfo"],transformedList)}return toObject}function computerUseToVertex(fromObject,_rootObject){let toObject={},fromEnablePromptInjectionDetection=getValueByPath(fromObject,["enablePromptInjectionDetection"]);fromEnablePromptInjectionDetection!=null&&setValueByPath(toObject,["enablePromptInjectionDetection"],fromEnablePromptInjectionDetection);let fromEnvironment=getValueByPath(fromObject,["environment"]);fromEnvironment!=null&&setValueByPath(toObject,["environment"],fromEnvironment);let fromExcludedPredefinedFunctions=getValueByPath(fromObject,["excludedPredefinedFunctions"]);if(fromExcludedPredefinedFunctions!=null&&setValueByPath(toObject,["excludedPredefinedFunctions"],fromExcludedPredefinedFunctions),getValueByPath(fromObject,["disabledSafetyPolicies"])!==void 0)throw new Error("disabledSafetyPolicies parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function contentEmbeddingFromVertex(fromObject,rootObject){let toObject={},fromValues=getValueByPath(fromObject,["values"]);fromValues!=null&&setValueByPath(toObject,["values"],fromValues);let fromStatistics=getValueByPath(fromObject,["statistics"]);return fromStatistics!=null&&setValueByPath(toObject,["statistics"],contentEmbeddingStatisticsFromVertex(fromStatistics)),toObject}function contentEmbeddingStatisticsFromVertex(fromObject,_rootObject){let toObject={},fromTruncated=getValueByPath(fromObject,["truncated"]);fromTruncated!=null&&setValueByPath(toObject,["truncated"],fromTruncated);let fromTokenCount=getValueByPath(fromObject,["token_count"]);fromTokenCount!=null&&setValueByPath(toObject,["tokenCount"],fromTokenCount);let fromTokensDetails=getValueByPath(fromObject,["tokensDetails"]);if(fromTokensDetails!=null){let transformedList=fromTokensDetails;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["tokensDetails"],transformedList)}return toObject}function contentToMldev$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToMldev$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function contentToVertex$1(fromObject,rootObject){let toObject={},fromParts=getValueByPath(fromObject,["parts"]);if(fromParts!=null){let transformedList=fromParts;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>partToVertex$1(item))),setValueByPath(toObject,["parts"],transformedList)}let fromRole=getValueByPath(fromObject,["role"]);return fromRole!=null&&setValueByPath(toObject,["role"],fromRole),toObject}function controlReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromControlType=getValueByPath(fromObject,["controlType"]);fromControlType!=null&&setValueByPath(toObject,["controlType"],fromControlType);let fromEnableControlImageComputation=getValueByPath(fromObject,["enableControlImageComputation"]);return fromEnableControlImageComputation!=null&&setValueByPath(toObject,["computeControl"],fromEnableControlImageComputation),toObject}function countTokensConfigToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["tools"])!==void 0)throw new Error("tools parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function countTokensConfigToVertex(fromObject,parentObject,rootObject){let toObject={},fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=fromTools;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(item))),setValueByPath(parentObject,["tools"],transformedList)}let fromGenerationConfig=getValueByPath(fromObject,["generationConfig"]);return parentObject!==void 0&&fromGenerationConfig!=null&&setValueByPath(parentObject,["generationConfig"],generationConfigToVertex(fromGenerationConfig)),toObject}function countTokensParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToMldev(fromConfig),toObject}function countTokensParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&countTokensConfigToVertex(fromConfig,toObject),toObject}function countTokensResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens);let fromCachedContentTokenCount=getValueByPath(fromObject,["cachedContentTokenCount"]);return fromCachedContentTokenCount!=null&&setValueByPath(toObject,["cachedContentTokenCount"],fromCachedContentTokenCount),toObject}function countTokensResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromTotalTokens=getValueByPath(fromObject,["totalTokens"]);return fromTotalTokens!=null&&setValueByPath(toObject,["totalTokens"],fromTotalTokens),toObject}function deleteModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function deleteModelResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function deleteModelResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);return fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse),toObject}function editImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromEditMode=getValueByPath(fromObject,["editMode"]);parentObject!==void 0&&fromEditMode!=null&&setValueByPath(parentObject,["parameters","editMode"],fromEditMode);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);return parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","editConfig","baseSteps"],fromBaseSteps),toObject}function editImageParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>referenceImageAPIInternalToVertex(item))),setValueByPath(toObject,["instances[0]","referenceImages"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&editImageConfigToVertex(fromConfig,toObject),toObject}function editImageResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function embedContentConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["requests[]","taskType"],fromTaskType);let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["requests[]","title"],fromTitle);let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);if(parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["requests[]","outputDimensionality"],fromOutputDimensionality),getValueByPath(fromObject,["mimeType"])!==void 0)throw new Error("mimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["documentOcr"])!==void 0)throw new Error("documentOcr parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["audioTrackExtraction"])!==void 0)throw new Error("audioTrackExtraction parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function embedContentConfigToVertex(fromObject,parentObject,rootObject){let toObject={},discriminatorTaskType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorTaskType===void 0&&(discriminatorTaskType="PREDICT"),discriminatorTaskType==="PREDICT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["instances[]","task_type"],fromTaskType)}else if(discriminatorTaskType==="EMBED_CONTENT"){let fromTaskType=getValueByPath(fromObject,["taskType"]);parentObject!==void 0&&fromTaskType!=null&&setValueByPath(parentObject,["embedContentConfig","taskType"],fromTaskType)}let discriminatorTitle=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorTitle===void 0&&(discriminatorTitle="PREDICT"),discriminatorTitle==="PREDICT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["instances[]","title"],fromTitle)}else if(discriminatorTitle==="EMBED_CONTENT"){let fromTitle=getValueByPath(fromObject,["title"]);parentObject!==void 0&&fromTitle!=null&&setValueByPath(parentObject,["embedContentConfig","title"],fromTitle)}let discriminatorOutputDimensionality=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorOutputDimensionality===void 0&&(discriminatorOutputDimensionality="PREDICT"),discriminatorOutputDimensionality==="PREDICT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["parameters","outputDimensionality"],fromOutputDimensionality)}else if(discriminatorOutputDimensionality==="EMBED_CONTENT"){let fromOutputDimensionality=getValueByPath(fromObject,["outputDimensionality"]);parentObject!==void 0&&fromOutputDimensionality!=null&&setValueByPath(parentObject,["embedContentConfig","outputDimensionality"],fromOutputDimensionality)}let discriminatorMimeType=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorMimeType===void 0&&(discriminatorMimeType="PREDICT"),discriminatorMimeType==="PREDICT"){let fromMimeType=getValueByPath(fromObject,["mimeType"]);parentObject!==void 0&&fromMimeType!=null&&setValueByPath(parentObject,["instances[]","mimeType"],fromMimeType)}let discriminatorAutoTruncate=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAutoTruncate===void 0&&(discriminatorAutoTruncate="PREDICT"),discriminatorAutoTruncate==="PREDICT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["parameters","autoTruncate"],fromAutoTruncate)}else if(discriminatorAutoTruncate==="EMBED_CONTENT"){let fromAutoTruncate=getValueByPath(fromObject,["autoTruncate"]);parentObject!==void 0&&fromAutoTruncate!=null&&setValueByPath(parentObject,["embedContentConfig","autoTruncate"],fromAutoTruncate)}let discriminatorDocumentOcr=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorDocumentOcr===void 0&&(discriminatorDocumentOcr="PREDICT"),discriminatorDocumentOcr==="EMBED_CONTENT"){let fromDocumentOcr=getValueByPath(fromObject,["documentOcr"]);parentObject!==void 0&&fromDocumentOcr!=null&&setValueByPath(parentObject,["embedContentConfig","documentOcr"],fromDocumentOcr)}let discriminatorAudioTrackExtraction=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorAudioTrackExtraction===void 0&&(discriminatorAudioTrackExtraction="PREDICT"),discriminatorAudioTrackExtraction==="EMBED_CONTENT"){let fromAudioTrackExtraction=getValueByPath(fromObject,["audioTrackExtraction"]);parentObject!==void 0&&fromAudioTrackExtraction!=null&&setValueByPath(parentObject,["embedContentConfig","audioTrackExtraction"],fromAudioTrackExtraction)}return toObject}function embedContentParametersPrivateToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["requests[]","content"],transformedList)}let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&contentToMldev$1(tContent(fromContent));let fromConfig=getValueByPath(fromObject,["config"]);fromConfig!=null&&embedContentConfigToMldev(fromConfig,toObject);let fromModelForEmbedContent=getValueByPath(fromObject,["model"]);return fromModelForEmbedContent!==void 0&&setValueByPath(toObject,["requests[]","model"],tModel(apiClient,fromModelForEmbedContent)),toObject}function embedContentParametersPrivateToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let discriminatorContents=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContents===void 0&&(discriminatorContents="PREDICT"),discriminatorContents==="PREDICT"){let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContentsForEmbed(apiClient,fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["instances[]","content"],transformedList)}}let discriminatorContent=getValueByPath(rootObject,["embeddingApiType"]);if(discriminatorContent===void 0&&(discriminatorContent="PREDICT"),discriminatorContent==="EMBED_CONTENT"){let fromContent=getValueByPath(fromObject,["content"]);fromContent!=null&&setValueByPath(toObject,["content"],contentToVertex$1(tContent(fromContent)))}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&embedContentConfigToVertex(fromConfig,toObject,rootObject),toObject}function embedContentResponseFromMldev(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(fromObject,["embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);return fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),toObject}function embedContentResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromEmbeddings=getValueByPath(fromObject,["predictions[]","embeddings"]);if(fromEmbeddings!=null){let transformedList=fromEmbeddings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentEmbeddingFromVertex(item))),setValueByPath(toObject,["embeddings"],transformedList)}let fromMetadata=getValueByPath(fromObject,["metadata"]);if(fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata),rootObject&&getValueByPath(rootObject,["embeddingApiType"])==="EMBED_CONTENT"){let embedding=getValueByPath(fromObject,["embedding"]),usageMetadata=getValueByPath(fromObject,["usageMetadata"]),truncated=getValueByPath(fromObject,["truncated"]);if(embedding){let stats={};usageMetadata&&usageMetadata.promptTokenCount&&(stats.tokenCount=usageMetadata.promptTokenCount),usageMetadata&&usageMetadata.promptTokensDetails&&(stats.tokensDetails=usageMetadata.promptTokensDetails),truncated&&(stats.truncated=truncated),embedding.statistics=stats,setValueByPath(toObject,["embeddings"],[embedding])}}return toObject}function endpointFromVertex(fromObject,_rootObject){let toObject={},fromName=getValueByPath(fromObject,["endpoint"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDeployedModelId=getValueByPath(fromObject,["deployedModelId"]);return fromDeployedModelId!=null&&setValueByPath(toObject,["deployedModelId"],fromDeployedModelId),toObject}function fileDataToMldev$1(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["displayName"])!==void 0)throw new Error("displayName parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFileUri=getValueByPath(fromObject,["fileUri"]);fromFileUri!=null&&setValueByPath(toObject,["fileUri"],fromFileUri);let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function functionCallToMldev$1(fromObject,_rootObject){let toObject={},fromArgs=getValueByPath(fromObject,["args"]);fromArgs!=null&&setValueByPath(toObject,["args"],fromArgs);let fromId=getValueByPath(fromObject,["id"]);fromId!=null&&setValueByPath(toObject,["id"],fromId);let fromName=getValueByPath(fromObject,["name"]);if(fromName!=null&&setValueByPath(toObject,["name"],fromName),getValueByPath(fromObject,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["willContinue"])!==void 0)throw new Error("willContinue parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function functionCallingConfigToMldev(fromObject,_rootObject){let toObject={},fromAllowedFunctionNames=getValueByPath(fromObject,["allowedFunctionNames"]);fromAllowedFunctionNames!=null&&setValueByPath(toObject,["allowedFunctionNames"],fromAllowedFunctionNames);let fromMode=getValueByPath(fromObject,["mode"]);if(fromMode!=null&&setValueByPath(toObject,["mode"],fromMode),getValueByPath(fromObject,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToMldev(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToMldev$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);if(fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema),getValueByPath(fromObject,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>safetySettingToMldev$1(item))),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToMldev$1(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);if(parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToMldev(fromToolConfig)),getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);if(fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],tSpeechConfig(fromSpeechConfig)),getValueByPath(fromObject,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToMldev(fromImageConfig));let fromEnableEnhancedCivicAnswers=getValueByPath(fromObject,["enableEnhancedCivicAnswers"]);if(fromEnableEnhancedCivicAnswers!=null&&setValueByPath(toObject,["enableEnhancedCivicAnswers"],fromEnableEnhancedCivicAnswers),getValueByPath(fromObject,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateContentConfigToVertex(apiClient,fromObject,parentObject,rootObject){let toObject={},fromServiceTier=getValueByPath(fromObject,["serviceTier"]);parentObject!==void 0&&fromServiceTier!=null&&setValueByPath(parentObject,["serviceTier"],fromServiceTier);let fromSystemInstruction=getValueByPath(fromObject,["systemInstruction"]);parentObject!==void 0&&fromSystemInstruction!=null&&setValueByPath(parentObject,["systemInstruction"],contentToVertex$1(tContent(fromSystemInstruction)));let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],tSchema(fromResponseSchema));let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromSafetySettings=getValueByPath(fromObject,["safetySettings"]);if(parentObject!==void 0&&fromSafetySettings!=null){let transformedList=fromSafetySettings;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(parentObject,["safetySettings"],transformedList)}let fromTools=getValueByPath(fromObject,["tools"]);if(parentObject!==void 0&&fromTools!=null){let transformedList=tTools(fromTools);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>toolToVertex(tTool(item)))),setValueByPath(parentObject,["tools"],transformedList)}let fromToolConfig=getValueByPath(fromObject,["toolConfig"]);parentObject!==void 0&&fromToolConfig!=null&&setValueByPath(parentObject,["toolConfig"],toolConfigToVertex(fromToolConfig));let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromCachedContent=getValueByPath(fromObject,["cachedContent"]);parentObject!==void 0&&fromCachedContent!=null&&setValueByPath(parentObject,["cachedContent"],tCachedContentName(apiClient,fromCachedContent));let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromImageConfig=getValueByPath(fromObject,["imageConfig"]);if(fromImageConfig!=null&&setValueByPath(toObject,["imageConfig"],imageConfigToVertex(fromImageConfig)),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromModelArmorConfig=getValueByPath(fromObject,["modelArmorConfig"]);return parentObject!==void 0&&fromModelArmorConfig!=null&&setValueByPath(parentObject,["modelArmorConfig"],fromModelArmorConfig),toObject}function generateContentParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToMldev$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToMldev(apiClient,fromConfig,toObject)),toObject}function generateContentParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromContents=getValueByPath(fromObject,["contents"]);if(fromContents!=null){let transformedList=tContents(fromContents);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>contentToVertex$1(item))),setValueByPath(toObject,["contents"],transformedList)}let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&setValueByPath(toObject,["generationConfig"],generateContentConfigToVertex(apiClient,fromConfig,toObject)),toObject}function generateContentResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>candidateFromMldev(item))),setValueByPath(toObject,["candidates"],transformedList)}let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata);let fromModelStatus=getValueByPath(fromObject,["modelStatus"]);return fromModelStatus!=null&&setValueByPath(toObject,["modelStatus"],fromModelStatus),toObject}function generateContentResponseFromVertex(fromObject,_rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromCandidates=getValueByPath(fromObject,["candidates"]);if(fromCandidates!=null){let transformedList=fromCandidates;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["candidates"],transformedList)}let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromModelVersion=getValueByPath(fromObject,["modelVersion"]);fromModelVersion!=null&&setValueByPath(toObject,["modelVersion"],fromModelVersion);let fromPromptFeedback=getValueByPath(fromObject,["promptFeedback"]);fromPromptFeedback!=null&&setValueByPath(toObject,["promptFeedback"],fromPromptFeedback);let fromResponseId=getValueByPath(fromObject,["responseId"]);fromResponseId!=null&&setValueByPath(toObject,["responseId"],fromResponseId);let fromUsageMetadata=getValueByPath(fromObject,["usageMetadata"]);return fromUsageMetadata!=null&&setValueByPath(toObject,["usageMetadata"],fromUsageMetadata),toObject}function generateImagesConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromGuidanceScale=getValueByPath(fromObject,["guidanceScale"]);parentObject!==void 0&&fromGuidanceScale!=null&&setValueByPath(parentObject,["parameters","guidanceScale"],fromGuidanceScale);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeSafetyAttributes=getValueByPath(fromObject,["includeSafetyAttributes"]);parentObject!==void 0&&fromIncludeSafetyAttributes!=null&&setValueByPath(parentObject,["parameters","includeSafetyAttributes"],fromIncludeSafetyAttributes);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromLanguage=getValueByPath(fromObject,["language"]);parentObject!==void 0&&fromLanguage!=null&&setValueByPath(parentObject,["parameters","language"],fromLanguage);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromImageSize=getValueByPath(fromObject,["imageSize"]);parentObject!==void 0&&fromImageSize!=null&&setValueByPath(parentObject,["parameters","sampleImageSize"],fromImageSize);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);return parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),toObject}function generateImagesParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateImagesConfigToVertex(fromConfig,toObject),toObject}function generateImagesResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}let fromPositivePromptSafetyAttributes=getValueByPath(fromObject,["positivePromptSafetyAttributes"]);return fromPositivePromptSafetyAttributes!=null&&setValueByPath(toObject,["positivePromptSafetyAttributes"],safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)),toObject}function generateVideosConfigToMldev(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);if(parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos),getValueByPath(fromObject,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["fps"])!==void 0)throw new Error("fps parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);if(parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds),getValueByPath(fromObject,["seed"])!==void 0)throw new Error("seed parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);if(parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration),getValueByPath(fromObject,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);if(parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt),getValueByPath(fromObject,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToMldev(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToMldev(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}if(getValueByPath(fromObject,["mask"])!==void 0)throw new Error("mask parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["labels"])!==void 0)throw new Error("labels parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromWebhookConfig=getValueByPath(fromObject,["webhookConfig"]);if(parentObject!==void 0&&fromWebhookConfig!=null&&setValueByPath(parentObject,["webhookConfig"],fromWebhookConfig),getValueByPath(fromObject,["resizeMode"])!==void 0)throw new Error("resizeMode parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function generateVideosConfigToVertex(fromObject,parentObject,rootObject){let toObject={},fromNumberOfVideos=getValueByPath(fromObject,["numberOfVideos"]);parentObject!==void 0&&fromNumberOfVideos!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfVideos);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromFps=getValueByPath(fromObject,["fps"]);parentObject!==void 0&&fromFps!=null&&setValueByPath(parentObject,["parameters","fps"],fromFps);let fromDurationSeconds=getValueByPath(fromObject,["durationSeconds"]);parentObject!==void 0&&fromDurationSeconds!=null&&setValueByPath(parentObject,["parameters","durationSeconds"],fromDurationSeconds);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);parentObject!==void 0&&fromAspectRatio!=null&&setValueByPath(parentObject,["parameters","aspectRatio"],fromAspectRatio);let fromResolution=getValueByPath(fromObject,["resolution"]);parentObject!==void 0&&fromResolution!=null&&setValueByPath(parentObject,["parameters","resolution"],fromResolution);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromPubsubTopic=getValueByPath(fromObject,["pubsubTopic"]);parentObject!==void 0&&fromPubsubTopic!=null&&setValueByPath(parentObject,["parameters","pubsubTopic"],fromPubsubTopic);let fromNegativePrompt=getValueByPath(fromObject,["negativePrompt"]);parentObject!==void 0&&fromNegativePrompt!=null&&setValueByPath(parentObject,["parameters","negativePrompt"],fromNegativePrompt);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromGenerateAudio=getValueByPath(fromObject,["generateAudio"]);parentObject!==void 0&&fromGenerateAudio!=null&&setValueByPath(parentObject,["parameters","generateAudio"],fromGenerateAudio);let fromLastFrame=getValueByPath(fromObject,["lastFrame"]);parentObject!==void 0&&fromLastFrame!=null&&setValueByPath(parentObject,["instances[0]","lastFrame"],imageToVertex(fromLastFrame));let fromReferenceImages=getValueByPath(fromObject,["referenceImages"]);if(parentObject!==void 0&&fromReferenceImages!=null){let transformedList=fromReferenceImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>videoGenerationReferenceImageToVertex(item))),setValueByPath(parentObject,["instances[0]","referenceImages"],transformedList)}let fromMask=getValueByPath(fromObject,["mask"]);parentObject!==void 0&&fromMask!=null&&setValueByPath(parentObject,["instances[0]","mask"],videoGenerationMaskToVertex(fromMask));let fromCompressionQuality=getValueByPath(fromObject,["compressionQuality"]);parentObject!==void 0&&fromCompressionQuality!=null&&setValueByPath(parentObject,["parameters","compressionQuality"],fromCompressionQuality);let fromLabels=getValueByPath(fromObject,["labels"]);if(parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),getValueByPath(fromObject,["webhookConfig"])!==void 0)throw new Error("webhookConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromResizeMode=getValueByPath(fromObject,["resizeMode"]);return parentObject!==void 0&&fromResizeMode!=null&&setValueByPath(parentObject,["parameters","resizeMode"],fromResizeMode),toObject}function generateVideosOperationFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response","generateVideoResponse"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromMldev(fromResponse)),toObject}function generateVideosOperationFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromMetadata=getValueByPath(fromObject,["metadata"]);fromMetadata!=null&&setValueByPath(toObject,["metadata"],fromMetadata);let fromDone=getValueByPath(fromObject,["done"]);fromDone!=null&&setValueByPath(toObject,["done"],fromDone);let fromError=getValueByPath(fromObject,["error"]);fromError!=null&&setValueByPath(toObject,["error"],fromError);let fromResponse=getValueByPath(fromObject,["response"]);return fromResponse!=null&&setValueByPath(toObject,["response"],generateVideosResponseFromVertex(fromResponse)),toObject}function generateVideosParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["instances[0]","video"],videoToMldev(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToMldev(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToMldev(fromConfig,toObject),toObject}function generateVideosParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromPrompt=getValueByPath(fromObject,["prompt"]);fromPrompt!=null&&setValueByPath(toObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);fromVideo!=null&&setValueByPath(toObject,["instances[0]","video"],videoToVertex(fromVideo));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&generateVideosSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&generateVideosConfigToVertex(fromConfig,toObject),toObject}function generateVideosResponseFromMldev(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["generatedSamples"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromMldev(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedVideos=getValueByPath(fromObject,["videos"]);if(fromGeneratedVideos!=null){let transformedList=fromGeneratedVideos;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedVideoFromVertex(item))),setValueByPath(toObject,["generatedVideos"],transformedList)}let fromRaiMediaFilteredCount=getValueByPath(fromObject,["raiMediaFilteredCount"]);fromRaiMediaFilteredCount!=null&&setValueByPath(toObject,["raiMediaFilteredCount"],fromRaiMediaFilteredCount);let fromRaiMediaFilteredReasons=getValueByPath(fromObject,["raiMediaFilteredReasons"]);return fromRaiMediaFilteredReasons!=null&&setValueByPath(toObject,["raiMediaFilteredReasons"],fromRaiMediaFilteredReasons),toObject}function generateVideosSourceToMldev(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToMldev(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToMldev(fromVideo)),toObject}function generateVideosSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromVideo=getValueByPath(fromObject,["video"]);return parentObject!==void 0&&fromVideo!=null&&setValueByPath(parentObject,["instances[0]","video"],videoToVertex(fromVideo)),toObject}function generatedImageFromVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["_self"]);fromImage!=null&&setValueByPath(toObject,["image"],imageFromVertex(fromImage));let fromRaiFilteredReason=getValueByPath(fromObject,["raiFilteredReason"]);fromRaiFilteredReason!=null&&setValueByPath(toObject,["raiFilteredReason"],fromRaiFilteredReason);let fromSafetyAttributes=getValueByPath(fromObject,["_self"]);fromSafetyAttributes!=null&&setValueByPath(toObject,["safetyAttributes"],safetyAttributesFromVertex(fromSafetyAttributes));let fromEnhancedPrompt=getValueByPath(fromObject,["prompt"]);return fromEnhancedPrompt!=null&&setValueByPath(toObject,["enhancedPrompt"],fromEnhancedPrompt),toObject}function generatedImageMaskFromVertex(fromObject,rootObject){let toObject={},fromMask=getValueByPath(fromObject,["_self"]);fromMask!=null&&setValueByPath(toObject,["mask"],imageFromVertex(fromMask));let fromLabels=getValueByPath(fromObject,["labels"]);if(fromLabels!=null){let transformedList=fromLabels;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["labels"],transformedList)}return toObject}function generatedVideoFromMldev(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["video"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromMldev(fromVideo)),toObject}function generatedVideoFromVertex(fromObject,rootObject){let toObject={},fromVideo=getValueByPath(fromObject,["_self"]);return fromVideo!=null&&setValueByPath(toObject,["video"],videoFromVertex(fromVideo)),toObject}function generationConfigToVertex(fromObject,rootObject){let toObject={},fromModelSelectionConfig=getValueByPath(fromObject,["modelSelectionConfig"]);fromModelSelectionConfig!=null&&setValueByPath(toObject,["modelConfig"],fromModelSelectionConfig);let fromResponseJsonSchema=getValueByPath(fromObject,["responseJsonSchema"]);fromResponseJsonSchema!=null&&setValueByPath(toObject,["responseJsonSchema"],fromResponseJsonSchema);let fromAudioTranscriptionConfig=getValueByPath(fromObject,["audioTranscriptionConfig"]);fromAudioTranscriptionConfig!=null&&setValueByPath(toObject,["audioTranscriptionConfig"],fromAudioTranscriptionConfig);let fromAudioTimestamp=getValueByPath(fromObject,["audioTimestamp"]);fromAudioTimestamp!=null&&setValueByPath(toObject,["audioTimestamp"],fromAudioTimestamp);let fromCandidateCount=getValueByPath(fromObject,["candidateCount"]);fromCandidateCount!=null&&setValueByPath(toObject,["candidateCount"],fromCandidateCount);let fromEnableAffectiveDialog=getValueByPath(fromObject,["enableAffectiveDialog"]);fromEnableAffectiveDialog!=null&&setValueByPath(toObject,["enableAffectiveDialog"],fromEnableAffectiveDialog);let fromFrequencyPenalty=getValueByPath(fromObject,["frequencyPenalty"]);fromFrequencyPenalty!=null&&setValueByPath(toObject,["frequencyPenalty"],fromFrequencyPenalty);let fromLogprobs=getValueByPath(fromObject,["logprobs"]);fromLogprobs!=null&&setValueByPath(toObject,["logprobs"],fromLogprobs);let fromMaxOutputTokens=getValueByPath(fromObject,["maxOutputTokens"]);fromMaxOutputTokens!=null&&setValueByPath(toObject,["maxOutputTokens"],fromMaxOutputTokens);let fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromPresencePenalty=getValueByPath(fromObject,["presencePenalty"]);fromPresencePenalty!=null&&setValueByPath(toObject,["presencePenalty"],fromPresencePenalty);let fromResponseFormat=getValueByPath(fromObject,["responseFormat"]);if(fromResponseFormat!=null){let transformedList=fromResponseFormat;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["responseFormat"],transformedList)}let fromResponseLogprobs=getValueByPath(fromObject,["responseLogprobs"]);fromResponseLogprobs!=null&&setValueByPath(toObject,["responseLogprobs"],fromResponseLogprobs);let fromResponseMimeType=getValueByPath(fromObject,["responseMimeType"]);fromResponseMimeType!=null&&setValueByPath(toObject,["responseMimeType"],fromResponseMimeType);let fromResponseModalities=getValueByPath(fromObject,["responseModalities"]);fromResponseModalities!=null&&setValueByPath(toObject,["responseModalities"],fromResponseModalities);let fromResponseSchema=getValueByPath(fromObject,["responseSchema"]);fromResponseSchema!=null&&setValueByPath(toObject,["responseSchema"],fromResponseSchema);let fromRoutingConfig=getValueByPath(fromObject,["routingConfig"]);fromRoutingConfig!=null&&setValueByPath(toObject,["routingConfig"],fromRoutingConfig);let fromSeed=getValueByPath(fromObject,["seed"]);fromSeed!=null&&setValueByPath(toObject,["seed"],fromSeed);let fromSpeechConfig=getValueByPath(fromObject,["speechConfig"]);fromSpeechConfig!=null&&setValueByPath(toObject,["speechConfig"],speechConfigToVertex(fromSpeechConfig));let fromStopSequences=getValueByPath(fromObject,["stopSequences"]);fromStopSequences!=null&&setValueByPath(toObject,["stopSequences"],fromStopSequences);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromThinkingConfig=getValueByPath(fromObject,["thinkingConfig"]);fromThinkingConfig!=null&&setValueByPath(toObject,["thinkingConfig"],fromThinkingConfig);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromTopP=getValueByPath(fromObject,["topP"]);if(fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP),getValueByPath(fromObject,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["translationConfig"])!==void 0)throw new Error("translationConfig parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function getModelParametersToMldev(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function getModelParametersToVertex(apiClient,fromObject,_rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);return fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel)),toObject}function googleMapsToMldev$1(fromObject,rootObject){let toObject={},fromAuthConfig=getValueByPath(fromObject,["authConfig"]);fromAuthConfig!=null&&setValueByPath(toObject,["authConfig"],authConfigToMldev$1(fromAuthConfig));let fromEnableWidget=getValueByPath(fromObject,["enableWidget"]);if(fromEnableWidget!=null&&setValueByPath(toObject,["enableWidget"],fromEnableWidget),getValueByPath(fromObject,["groundingTypes"])!==void 0)throw new Error("groundingTypes parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function googleSearchToMldev$1(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromSearchTypes=getValueByPath(fromObject,["searchTypes"]);fromSearchTypes!=null&&setValueByPath(toObject,["searchTypes"],fromSearchTypes);let fromTimeRangeFilter=getValueByPath(fromObject,["timeRangeFilter"]);return fromTimeRangeFilter!=null&&setValueByPath(toObject,["timeRangeFilter"],fromTimeRangeFilter),toObject}function imageConfigToMldev(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);if(fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize),getValueByPath(fromObject,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["imageOutputOptions"])!==void 0)throw new Error("imageOutputOptions parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["prominentPeople"])!==void 0)throw new Error("prominentPeople parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");return toObject}function imageConfigToVertex(fromObject,_rootObject){let toObject={},fromAspectRatio=getValueByPath(fromObject,["aspectRatio"]);fromAspectRatio!=null&&setValueByPath(toObject,["aspectRatio"],fromAspectRatio);let fromImageSize=getValueByPath(fromObject,["imageSize"]);fromImageSize!=null&&setValueByPath(toObject,["imageSize"],fromImageSize);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);fromPersonGeneration!=null&&setValueByPath(toObject,["personGeneration"],fromPersonGeneration);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);fromOutputMimeType!=null&&setValueByPath(toObject,["imageOutputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);fromOutputCompressionQuality!=null&&setValueByPath(toObject,["imageOutputOptions","compressionQuality"],fromOutputCompressionQuality);let fromImageOutputOptions=getValueByPath(fromObject,["imageOutputOptions"]);fromImageOutputOptions!=null&&setValueByPath(toObject,["imageOutputOptions"],fromImageOutputOptions);let fromProminentPeople=getValueByPath(fromObject,["prominentPeople"]);return fromProminentPeople!=null&&setValueByPath(toObject,["prominentPeople"],fromProminentPeople),toObject}function imageFromVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromImageBytes!=null&&setValueByPath(toObject,["imageBytes"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToMldev(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function imageToVertex(fromObject,_rootObject){let toObject={},fromGcsUri=getValueByPath(fromObject,["gcsUri"]);fromGcsUri!=null&&setValueByPath(toObject,["gcsUri"],fromGcsUri);let fromImageBytes=getValueByPath(fromObject,["imageBytes"]);fromImageBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromImageBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function listModelsConfigToMldev(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsConfigToVertex(apiClient,fromObject,parentObject,_rootObject){let toObject={},fromPageSize=getValueByPath(fromObject,["pageSize"]);parentObject!==void 0&&fromPageSize!=null&&setValueByPath(parentObject,["_query","pageSize"],fromPageSize);let fromPageToken=getValueByPath(fromObject,["pageToken"]);parentObject!==void 0&&fromPageToken!=null&&setValueByPath(parentObject,["_query","pageToken"],fromPageToken);let fromFilter=getValueByPath(fromObject,["filter"]);parentObject!==void 0&&fromFilter!=null&&setValueByPath(parentObject,["_query","filter"],fromFilter);let fromQueryBase=getValueByPath(fromObject,["queryBase"]);return parentObject!==void 0&&fromQueryBase!=null&&setValueByPath(parentObject,["_url","models_url"],tModelsUrl(apiClient,fromQueryBase)),toObject}function listModelsParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToMldev(apiClient,fromConfig,toObject),toObject}function listModelsParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&listModelsConfigToVertex(apiClient,fromConfig,toObject),toObject}function listModelsResponseFromMldev(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromMldev(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function listModelsResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromNextPageToken=getValueByPath(fromObject,["nextPageToken"]);fromNextPageToken!=null&&setValueByPath(toObject,["nextPageToken"],fromNextPageToken);let fromModels=getValueByPath(fromObject,["_self"]);if(fromModels!=null){let transformedList=tExtractModels(fromModels);Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>modelFromVertex(item))),setValueByPath(toObject,["models"],transformedList)}return toObject}function maskReferenceConfigToVertex(fromObject,_rootObject){let toObject={},fromMaskMode=getValueByPath(fromObject,["maskMode"]);fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode);let fromSegmentationClasses=getValueByPath(fromObject,["segmentationClasses"]);fromSegmentationClasses!=null&&setValueByPath(toObject,["maskClasses"],fromSegmentationClasses);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);return fromMaskDilation!=null&&setValueByPath(toObject,["dilation"],fromMaskDilation),toObject}function mcpServerToVertex(fromObject,_rootObject){let toObject={};if(getValueByPath(fromObject,["name"])!==void 0)throw new Error("name parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["streamableHttpTransport"])!==void 0)throw new Error("streamableHttpTransport parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function modelFromMldev(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["version"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromMldev(fromTunedModelInfo));let fromInputTokenLimit=getValueByPath(fromObject,["inputTokenLimit"]);fromInputTokenLimit!=null&&setValueByPath(toObject,["inputTokenLimit"],fromInputTokenLimit);let fromOutputTokenLimit=getValueByPath(fromObject,["outputTokenLimit"]);fromOutputTokenLimit!=null&&setValueByPath(toObject,["outputTokenLimit"],fromOutputTokenLimit);let fromSupportedActions=getValueByPath(fromObject,["supportedGenerationMethods"]);fromSupportedActions!=null&&setValueByPath(toObject,["supportedActions"],fromSupportedActions);let fromTemperature=getValueByPath(fromObject,["temperature"]);fromTemperature!=null&&setValueByPath(toObject,["temperature"],fromTemperature);let fromMaxTemperature=getValueByPath(fromObject,["maxTemperature"]);fromMaxTemperature!=null&&setValueByPath(toObject,["maxTemperature"],fromMaxTemperature);let fromTopP=getValueByPath(fromObject,["topP"]);fromTopP!=null&&setValueByPath(toObject,["topP"],fromTopP);let fromTopK=getValueByPath(fromObject,["topK"]);fromTopK!=null&&setValueByPath(toObject,["topK"],fromTopK);let fromThinking=getValueByPath(fromObject,["thinking"]);return fromThinking!=null&&setValueByPath(toObject,["thinking"],fromThinking),toObject}function modelFromVertex(fromObject,rootObject){let toObject={},fromName=getValueByPath(fromObject,["name"]);fromName!=null&&setValueByPath(toObject,["name"],fromName);let fromDisplayName=getValueByPath(fromObject,["displayName"]);fromDisplayName!=null&&setValueByPath(toObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);fromDescription!=null&&setValueByPath(toObject,["description"],fromDescription);let fromVersion=getValueByPath(fromObject,["versionId"]);fromVersion!=null&&setValueByPath(toObject,["version"],fromVersion);let fromEndpoints=getValueByPath(fromObject,["deployedModels"]);if(fromEndpoints!=null){let transformedList=fromEndpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>endpointFromVertex(item))),setValueByPath(toObject,["endpoints"],transformedList)}let fromLabels=getValueByPath(fromObject,["labels"]);fromLabels!=null&&setValueByPath(toObject,["labels"],fromLabels);let fromTunedModelInfo=getValueByPath(fromObject,["_self"]);fromTunedModelInfo!=null&&setValueByPath(toObject,["tunedModelInfo"],tunedModelInfoFromVertex(fromTunedModelInfo));let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);fromDefaultCheckpointId!=null&&setValueByPath(toObject,["defaultCheckpointId"],fromDefaultCheckpointId);let fromCheckpoints=getValueByPath(fromObject,["checkpoints"]);if(fromCheckpoints!=null){let transformedList=fromCheckpoints;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["checkpoints"],transformedList)}return toObject}function multiSpeakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeakerVoiceConfigs=getValueByPath(fromObject,["speakerVoiceConfigs"]);if(fromSpeakerVoiceConfigs!=null){let transformedList=fromSpeakerVoiceConfigs;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>speakerVoiceConfigToVertex(item))),setValueByPath(toObject,["speakerVoiceConfigs"],transformedList)}return toObject}function partToMldev$1(fromObject,rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution);let fromToolCall=getValueByPath(fromObject,["toolCall"]);fromToolCall!=null&&setValueByPath(toObject,["toolCall"],fromToolCall);let fromToolResponse=getValueByPath(fromObject,["toolResponse"]);fromToolResponse!=null&&setValueByPath(toObject,["toolResponse"],fromToolResponse);let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fileDataToMldev$1(fromFileData));let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],functionCallToMldev$1(fromFunctionCall));let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],blobToMldev$1(fromInlineData));let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata);let fromPartMetadata=getValueByPath(fromObject,["partMetadata"]);fromPartMetadata!=null&&setValueByPath(toObject,["partMetadata"],fromPartMetadata);let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function partToVertex$1(fromObject,_rootObject){let toObject={},fromMediaResolution=getValueByPath(fromObject,["mediaResolution"]);if(fromMediaResolution!=null&&setValueByPath(toObject,["mediaResolution"],fromMediaResolution),getValueByPath(fromObject,["toolCall"])!==void 0)throw new Error("toolCall parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["toolResponse"])!==void 0)throw new Error("toolResponse parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromAudioTranscription=getValueByPath(fromObject,["audioTranscription"]);fromAudioTranscription!=null&&setValueByPath(toObject,["audioTranscription"],fromAudioTranscription);let fromCodeExecutionResult=getValueByPath(fromObject,["codeExecutionResult"]);fromCodeExecutionResult!=null&&setValueByPath(toObject,["codeExecutionResult"],fromCodeExecutionResult);let fromExecutableCode=getValueByPath(fromObject,["executableCode"]);fromExecutableCode!=null&&setValueByPath(toObject,["executableCode"],fromExecutableCode);let fromFileData=getValueByPath(fromObject,["fileData"]);fromFileData!=null&&setValueByPath(toObject,["fileData"],fromFileData);let fromFunctionCall=getValueByPath(fromObject,["functionCall"]);fromFunctionCall!=null&&setValueByPath(toObject,["functionCall"],fromFunctionCall);let fromFunctionResponse=getValueByPath(fromObject,["functionResponse"]);fromFunctionResponse!=null&&setValueByPath(toObject,["functionResponse"],fromFunctionResponse);let fromInlineData=getValueByPath(fromObject,["inlineData"]);fromInlineData!=null&&setValueByPath(toObject,["inlineData"],fromInlineData);let fromText=getValueByPath(fromObject,["text"]);fromText!=null&&setValueByPath(toObject,["text"],fromText);let fromThought=getValueByPath(fromObject,["thought"]);fromThought!=null&&setValueByPath(toObject,["thought"],fromThought);let fromThoughtSignature=getValueByPath(fromObject,["thoughtSignature"]);fromThoughtSignature!=null&&setValueByPath(toObject,["thoughtSignature"],fromThoughtSignature);let fromVideoMetadata=getValueByPath(fromObject,["videoMetadata"]);if(fromVideoMetadata!=null&&setValueByPath(toObject,["videoMetadata"],fromVideoMetadata),getValueByPath(fromObject,["partMetadata"])!==void 0)throw new Error("partMetadata parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");let fromMediaProcessing=getValueByPath(fromObject,["mediaProcessing"]);return fromMediaProcessing!=null&&setValueByPath(toObject,["mediaProcessing"],fromMediaProcessing),toObject}function productImageToVertex(fromObject,rootObject){let toObject={},fromProductImage=getValueByPath(fromObject,["productImage"]);return fromProductImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromProductImage)),toObject}function recontextImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromBaseSteps=getValueByPath(fromObject,["baseSteps"]);parentObject!==void 0&&fromBaseSteps!=null&&setValueByPath(parentObject,["parameters","baseSteps"],fromBaseSteps);let fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromSeed=getValueByPath(fromObject,["seed"]);parentObject!==void 0&&fromSeed!=null&&setValueByPath(parentObject,["parameters","seed"],fromSeed);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromAddWatermark=getValueByPath(fromObject,["addWatermark"]);parentObject!==void 0&&fromAddWatermark!=null&&setValueByPath(parentObject,["parameters","addWatermark"],fromAddWatermark);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromEnhancePrompt=getValueByPath(fromObject,["enhancePrompt"]);parentObject!==void 0&&fromEnhancePrompt!=null&&setValueByPath(parentObject,["parameters","enhancePrompt"],fromEnhancePrompt);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function recontextImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&recontextImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&recontextImageConfigToVertex(fromConfig,toObject),toObject}function recontextImageResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function recontextImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromPersonImage=getValueByPath(fromObject,["personImage"]);parentObject!==void 0&&fromPersonImage!=null&&setValueByPath(parentObject,["instances[0]","personImage","image"],imageToVertex(fromPersonImage));let fromProductImages=getValueByPath(fromObject,["productImages"]);if(parentObject!==void 0&&fromProductImages!=null){let transformedList=fromProductImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>productImageToVertex(item))),setValueByPath(parentObject,["instances[0]","productImages"],transformedList)}return toObject}function referenceImageAPIInternalToVertex(fromObject,rootObject){let toObject={},fromReferenceImage=getValueByPath(fromObject,["referenceImage"]);fromReferenceImage!=null&&setValueByPath(toObject,["referenceImage"],imageToVertex(fromReferenceImage));let fromReferenceId=getValueByPath(fromObject,["referenceId"]);fromReferenceId!=null&&setValueByPath(toObject,["referenceId"],fromReferenceId);let fromReferenceType=getValueByPath(fromObject,["referenceType"]);fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType);let fromMaskImageConfig=getValueByPath(fromObject,["maskImageConfig"]);fromMaskImageConfig!=null&&setValueByPath(toObject,["maskImageConfig"],maskReferenceConfigToVertex(fromMaskImageConfig));let fromControlImageConfig=getValueByPath(fromObject,["controlImageConfig"]);fromControlImageConfig!=null&&setValueByPath(toObject,["controlImageConfig"],controlReferenceConfigToVertex(fromControlImageConfig));let fromStyleImageConfig=getValueByPath(fromObject,["styleImageConfig"]);fromStyleImageConfig!=null&&setValueByPath(toObject,["styleImageConfig"],fromStyleImageConfig);let fromSubjectImageConfig=getValueByPath(fromObject,["subjectImageConfig"]);return fromSubjectImageConfig!=null&&setValueByPath(toObject,["subjectImageConfig"],fromSubjectImageConfig),toObject}function replicatedVoiceConfigToVertex(fromObject,_rootObject){let toObject={},fromMimeType=getValueByPath(fromObject,["mimeType"]);fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType);let fromVoiceSampleAudio=getValueByPath(fromObject,["voiceSampleAudio"]);if(fromVoiceSampleAudio!=null&&setValueByPath(toObject,["voiceSampleAudio"],fromVoiceSampleAudio),getValueByPath(fromObject,["consentAudio"])!==void 0)throw new Error("consentAudio parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");if(getValueByPath(fromObject,["voiceConsentSignature"])!==void 0)throw new Error("voiceConsentSignature parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function safetyAttributesFromVertex(fromObject,_rootObject){let toObject={},fromCategories=getValueByPath(fromObject,["safetyAttributes","categories"]);fromCategories!=null&&setValueByPath(toObject,["categories"],fromCategories);let fromScores=getValueByPath(fromObject,["safetyAttributes","scores"]);fromScores!=null&&setValueByPath(toObject,["scores"],fromScores);let fromContentType=getValueByPath(fromObject,["contentType"]);return fromContentType!=null&&setValueByPath(toObject,["contentType"],fromContentType),toObject}function safetySettingToMldev$1(fromObject,_rootObject){let toObject={},fromCategory=getValueByPath(fromObject,["category"]);if(fromCategory!=null&&setValueByPath(toObject,["category"],fromCategory),getValueByPath(fromObject,["method"])!==void 0)throw new Error("method parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromThreshold=getValueByPath(fromObject,["threshold"]);return fromThreshold!=null&&setValueByPath(toObject,["threshold"],fromThreshold),toObject}function scribbleImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);return fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage)),toObject}function segmentImageConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromMode=getValueByPath(fromObject,["mode"]);parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode);let fromMaxPredictions=getValueByPath(fromObject,["maxPredictions"]);parentObject!==void 0&&fromMaxPredictions!=null&&setValueByPath(parentObject,["parameters","maxPredictions"],fromMaxPredictions);let fromConfidenceThreshold=getValueByPath(fromObject,["confidenceThreshold"]);parentObject!==void 0&&fromConfidenceThreshold!=null&&setValueByPath(parentObject,["parameters","confidenceThreshold"],fromConfidenceThreshold);let fromMaskDilation=getValueByPath(fromObject,["maskDilation"]);parentObject!==void 0&&fromMaskDilation!=null&&setValueByPath(parentObject,["parameters","maskDilation"],fromMaskDilation);let fromBinaryColorThreshold=getValueByPath(fromObject,["binaryColorThreshold"]);parentObject!==void 0&&fromBinaryColorThreshold!=null&&setValueByPath(parentObject,["parameters","binaryColorThreshold"],fromBinaryColorThreshold);let fromLabels=getValueByPath(fromObject,["labels"]);return parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels),toObject}function segmentImageParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromSource=getValueByPath(fromObject,["source"]);fromSource!=null&&segmentImageSourceToVertex(fromSource,toObject);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&segmentImageConfigToVertex(fromConfig,toObject),toObject}function segmentImageResponseFromVertex(fromObject,rootObject){let toObject={},fromGeneratedMasks=getValueByPath(fromObject,["predictions"]);if(fromGeneratedMasks!=null){let transformedList=fromGeneratedMasks;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageMaskFromVertex(item))),setValueByPath(toObject,["generatedMasks"],transformedList)}return toObject}function segmentImageSourceToVertex(fromObject,parentObject,rootObject){let toObject={},fromPrompt=getValueByPath(fromObject,["prompt"]);parentObject!==void 0&&fromPrompt!=null&&setValueByPath(parentObject,["instances[0]","prompt"],fromPrompt);let fromImage=getValueByPath(fromObject,["image"]);parentObject!==void 0&&fromImage!=null&&setValueByPath(parentObject,["instances[0]","image"],imageToVertex(fromImage));let fromScribbleImage=getValueByPath(fromObject,["scribbleImage"]);return parentObject!==void 0&&fromScribbleImage!=null&&setValueByPath(parentObject,["instances[0]","scribble"],scribbleImageToVertex(fromScribbleImage)),toObject}function speakerVoiceConfigToVertex(fromObject,rootObject){let toObject={},fromSpeaker=getValueByPath(fromObject,["speaker"]);fromSpeaker!=null&&setValueByPath(toObject,["speaker"],fromSpeaker);let fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);return fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig)),toObject}function speechConfigToVertex(fromObject,rootObject){let toObject={},fromVoiceConfig=getValueByPath(fromObject,["voiceConfig"]);fromVoiceConfig!=null&&setValueByPath(toObject,["voiceConfig"],voiceConfigToVertex(fromVoiceConfig));let fromLanguageCode=getValueByPath(fromObject,["languageCode"]);fromLanguageCode!=null&&setValueByPath(toObject,["languageCode"],fromLanguageCode);let fromMultiSpeakerVoiceConfig=getValueByPath(fromObject,["multiSpeakerVoiceConfig"]);return fromMultiSpeakerVoiceConfig!=null&&setValueByPath(toObject,["multiSpeakerVoiceConfig"],multiSpeakerVoiceConfigToVertex(fromMultiSpeakerVoiceConfig)),toObject}function toolConfigToMldev(fromObject,rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],functionCallingConfigToMldev(fromFunctionCallingConfig));let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig);let fromIncludeServerSideToolInvocations=getValueByPath(fromObject,["includeServerSideToolInvocations"]);return fromIncludeServerSideToolInvocations!=null&&setValueByPath(toObject,["includeServerSideToolInvocations"],fromIncludeServerSideToolInvocations),toObject}function toolConfigToVertex(fromObject,_rootObject){let toObject={},fromFunctionCallingConfig=getValueByPath(fromObject,["functionCallingConfig"]);fromFunctionCallingConfig!=null&&setValueByPath(toObject,["functionCallingConfig"],fromFunctionCallingConfig);let fromRetrievalConfig=getValueByPath(fromObject,["retrievalConfig"]);if(fromRetrievalConfig!=null&&setValueByPath(toObject,["retrievalConfig"],fromRetrievalConfig),getValueByPath(fromObject,["includeServerSideToolInvocations"])!==void 0)throw new Error("includeServerSideToolInvocations parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function toolToMldev$1(fromObject,rootObject){let toObject={};if(getValueByPath(fromObject,["retrieval"])!==void 0)throw new Error("retrieval parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],googleMapsToMldev$1(fromGoogleMaps));let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);if(fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],fromComputerUse),getValueByPath(fromObject,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");if(getValueByPath(fromObject,["exaAiSearch"])!==void 0)throw new Error("exaAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],googleSearchToMldev$1(fromGoogleSearch));let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);if(fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval),getValueByPath(fromObject,["parallelAiSearch"])!==void 0)throw new Error("parallelAiSearch parameter is only supported in Gemini Enterprise Agent Platform mode, not in Gemini Developer API mode.");let fromUrlContext=getValueByPath(fromObject,["urlContext"]);fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext);let fromFileSearch=getValueByPath(fromObject,["fileSearch"]);return fromFileSearch!=null&&setValueByPath(toObject,["fileSearch"],fromFileSearch),toObject}function toolToVertex(fromObject,rootObject){let toObject={},fromRetrieval=getValueByPath(fromObject,["retrieval"]);fromRetrieval!=null&&setValueByPath(toObject,["retrieval"],fromRetrieval);let fromGoogleMaps=getValueByPath(fromObject,["googleMaps"]);fromGoogleMaps!=null&&setValueByPath(toObject,["googleMaps"],fromGoogleMaps);let fromMcpServers=getValueByPath(fromObject,["mcpServers"]);if(fromMcpServers!=null){let transformedList=fromMcpServers;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>mcpServerToVertex(item))),setValueByPath(toObject,["mcpServers"],transformedList)}let fromCodeExecution=getValueByPath(fromObject,["codeExecution"]);fromCodeExecution!=null&&setValueByPath(toObject,["codeExecution"],fromCodeExecution);let fromComputerUse=getValueByPath(fromObject,["computerUse"]);fromComputerUse!=null&&setValueByPath(toObject,["computerUse"],computerUseToVertex(fromComputerUse));let fromEnterpriseWebSearch=getValueByPath(fromObject,["enterpriseWebSearch"]);fromEnterpriseWebSearch!=null&&setValueByPath(toObject,["enterpriseWebSearch"],fromEnterpriseWebSearch);let fromExaAiSearch=getValueByPath(fromObject,["exaAiSearch"]);fromExaAiSearch!=null&&setValueByPath(toObject,["exaAiSearch"],fromExaAiSearch);let fromFunctionDeclarations=getValueByPath(fromObject,["functionDeclarations"]);if(fromFunctionDeclarations!=null){let transformedList=fromFunctionDeclarations;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>item)),setValueByPath(toObject,["functionDeclarations"],transformedList)}let fromGoogleSearch=getValueByPath(fromObject,["googleSearch"]);fromGoogleSearch!=null&&setValueByPath(toObject,["googleSearch"],fromGoogleSearch);let fromGoogleSearchRetrieval=getValueByPath(fromObject,["googleSearchRetrieval"]);fromGoogleSearchRetrieval!=null&&setValueByPath(toObject,["googleSearchRetrieval"],fromGoogleSearchRetrieval);let fromParallelAiSearch=getValueByPath(fromObject,["parallelAiSearch"]);fromParallelAiSearch!=null&&setValueByPath(toObject,["parallelAiSearch"],fromParallelAiSearch);let fromUrlContext=getValueByPath(fromObject,["urlContext"]);if(fromUrlContext!=null&&setValueByPath(toObject,["urlContext"],fromUrlContext),getValueByPath(fromObject,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");return toObject}function tunedModelInfoFromMldev(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["baseModel"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function tunedModelInfoFromVertex(fromObject,_rootObject){let toObject={},fromBaseModel=getValueByPath(fromObject,["labels","google-vertex-llm-tuning-base-model-id"]);fromBaseModel!=null&&setValueByPath(toObject,["baseModel"],fromBaseModel);let fromCreateTime=getValueByPath(fromObject,["createTime"]);fromCreateTime!=null&&setValueByPath(toObject,["createTime"],fromCreateTime);let fromUpdateTime=getValueByPath(fromObject,["updateTime"]);return fromUpdateTime!=null&&setValueByPath(toObject,["updateTime"],fromUpdateTime),toObject}function updateModelConfigToMldev(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);return parentObject!==void 0&&fromDefaultCheckpointId!=null&&setValueByPath(parentObject,["defaultCheckpointId"],fromDefaultCheckpointId),toObject}function updateModelConfigToVertex(fromObject,parentObject,_rootObject){let toObject={},fromDisplayName=getValueByPath(fromObject,["displayName"]);parentObject!==void 0&&fromDisplayName!=null&&setValueByPath(parentObject,["displayName"],fromDisplayName);let fromDescription=getValueByPath(fromObject,["description"]);parentObject!==void 0&&fromDescription!=null&&setValueByPath(parentObject,["description"],fromDescription);let fromDefaultCheckpointId=getValueByPath(fromObject,["defaultCheckpointId"]);return parentObject!==void 0&&fromDefaultCheckpointId!=null&&setValueByPath(parentObject,["defaultCheckpointId"],fromDefaultCheckpointId),toObject}function updateModelParametersToMldev(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","name"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToMldev(fromConfig,toObject),toObject}function updateModelParametersToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&updateModelConfigToVertex(fromConfig,toObject),toObject}function upscaleImageAPIConfigInternalToVertex(fromObject,parentObject,_rootObject){let toObject={},fromOutputGcsUri=getValueByPath(fromObject,["outputGcsUri"]);parentObject!==void 0&&fromOutputGcsUri!=null&&setValueByPath(parentObject,["parameters","storageUri"],fromOutputGcsUri);let fromSafetyFilterLevel=getValueByPath(fromObject,["safetyFilterLevel"]);parentObject!==void 0&&fromSafetyFilterLevel!=null&&setValueByPath(parentObject,["parameters","safetySetting"],fromSafetyFilterLevel);let fromPersonGeneration=getValueByPath(fromObject,["personGeneration"]);parentObject!==void 0&&fromPersonGeneration!=null&&setValueByPath(parentObject,["parameters","personGeneration"],fromPersonGeneration);let fromIncludeRaiReason=getValueByPath(fromObject,["includeRaiReason"]);parentObject!==void 0&&fromIncludeRaiReason!=null&&setValueByPath(parentObject,["parameters","includeRaiReason"],fromIncludeRaiReason);let fromOutputMimeType=getValueByPath(fromObject,["outputMimeType"]);parentObject!==void 0&&fromOutputMimeType!=null&&setValueByPath(parentObject,["parameters","outputOptions","mimeType"],fromOutputMimeType);let fromOutputCompressionQuality=getValueByPath(fromObject,["outputCompressionQuality"]);parentObject!==void 0&&fromOutputCompressionQuality!=null&&setValueByPath(parentObject,["parameters","outputOptions","compressionQuality"],fromOutputCompressionQuality);let fromEnhanceInputImage=getValueByPath(fromObject,["enhanceInputImage"]);parentObject!==void 0&&fromEnhanceInputImage!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","enhanceInputImage"],fromEnhanceInputImage);let fromImagePreservationFactor=getValueByPath(fromObject,["imagePreservationFactor"]);parentObject!==void 0&&fromImagePreservationFactor!=null&&setValueByPath(parentObject,["parameters","upscaleConfig","imagePreservationFactor"],fromImagePreservationFactor);let fromLabels=getValueByPath(fromObject,["labels"]);parentObject!==void 0&&fromLabels!=null&&setValueByPath(parentObject,["labels"],fromLabels);let fromNumberOfImages=getValueByPath(fromObject,["numberOfImages"]);parentObject!==void 0&&fromNumberOfImages!=null&&setValueByPath(parentObject,["parameters","sampleCount"],fromNumberOfImages);let fromMode=getValueByPath(fromObject,["mode"]);return parentObject!==void 0&&fromMode!=null&&setValueByPath(parentObject,["parameters","mode"],fromMode),toObject}function upscaleImageAPIParametersInternalToVertex(apiClient,fromObject,rootObject){let toObject={},fromModel=getValueByPath(fromObject,["model"]);fromModel!=null&&setValueByPath(toObject,["_url","model"],tModel(apiClient,fromModel));let fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["instances[0]","image"],imageToVertex(fromImage));let fromUpscaleFactor=getValueByPath(fromObject,["upscaleFactor"]);fromUpscaleFactor!=null&&setValueByPath(toObject,["parameters","upscaleConfig","upscaleFactor"],fromUpscaleFactor);let fromConfig=getValueByPath(fromObject,["config"]);return fromConfig!=null&&upscaleImageAPIConfigInternalToVertex(fromConfig,toObject),toObject}function upscaleImageResponseFromVertex(fromObject,rootObject){let toObject={},fromSdkHttpResponse=getValueByPath(fromObject,["sdkHttpResponse"]);fromSdkHttpResponse!=null&&setValueByPath(toObject,["sdkHttpResponse"],fromSdkHttpResponse);let fromGeneratedImages=getValueByPath(fromObject,["predictions"]);if(fromGeneratedImages!=null){let transformedList=fromGeneratedImages;Array.isArray(transformedList)&&(transformedList=transformedList.map(item=>generatedImageFromVertex(item))),setValueByPath(toObject,["generatedImages"],transformedList)}return toObject}function videoFromMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["encodedVideo"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["encoding"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoFromVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["gcsUri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["bytesBase64Encoded"]);fromVideoBytes!=null&&setValueByPath(toObject,["videoBytes"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function videoGenerationMaskToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["_self"],imageToVertex(fromImage));let fromMaskMode=getValueByPath(fromObject,["maskMode"]);return fromMaskMode!=null&&setValueByPath(toObject,["maskMode"],fromMaskMode),toObject}function videoGenerationReferenceImageToMldev(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToMldev(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoGenerationReferenceImageToVertex(fromObject,rootObject){let toObject={},fromImage=getValueByPath(fromObject,["image"]);fromImage!=null&&setValueByPath(toObject,["image"],imageToVertex(fromImage));let fromReferenceType=getValueByPath(fromObject,["referenceType"]);return fromReferenceType!=null&&setValueByPath(toObject,["referenceType"],fromReferenceType),toObject}function videoToMldev(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["uri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["encodedVideo"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["encoding"],fromMimeType),toObject}function videoToVertex(fromObject,_rootObject){let toObject={},fromUri=getValueByPath(fromObject,["uri"]);fromUri!=null&&setValueByPath(toObject,["gcsUri"],fromUri);let fromVideoBytes=getValueByPath(fromObject,["videoBytes"]);fromVideoBytes!=null&&setValueByPath(toObject,["bytesBase64Encoded"],tBytes(fromVideoBytes));let fromMimeType=getValueByPath(fromObject,["mimeType"]);return fromMimeType!=null&&setValueByPath(toObject,["mimeType"],fromMimeType),toObject}function voiceConfigToVertex(fromObject,rootObject){let toObject={},fromReplicatedVoiceConfig=getValueByPath(fromObject,["replicatedVoiceConfig"]);fromReplicatedVoiceConfig!=null&&setValueByPath(toObject,["replicatedVoiceConfig"],replicatedVoiceConfigToVertex(fromReplicatedVoiceConfig));let fromPrebuiltVoiceConfig=getValueByPath(fromObject,["prebuiltVoiceConfig"]);return fromPrebuiltVoiceConfig!=null&&setValueByPath(toObject,["prebuiltVoiceConfig"],fromPrebuiltVoiceConfig),toObject}var GOOGLE_API_CLIENT_HEADER="x-goog-api-client",SDK_VERSION="2.21.0",LIBRARY_LABEL=`google-genai-sdk/${SDK_VERSION}`;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 t2=yield __await(mcpClient.listTools({cursor}));for(let tool of t2.tools)yield yield __await(tool),numTools++;if(!t2.nextCursor)break;cursor=t2.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}};var DEFAULT_MAX_REMOTE_CALLS=10;function shouldDisableAfc(config){var _a2,_b,_c;if(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.disable)return!0;let callableToolsPresent=!1;for(let tool of(_b=config?.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){callableToolsPresent=!0;break}if(!callableToolsPresent)return!0;let maxCalls=(_c=config?.automaticFunctionCalling)===null||_c===void 0?void 0:_c.maximumRemoteCalls;return maxCalls&&(maxCalls<0||!Number.isInteger(maxCalls))||maxCalls==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",maxCalls),!0):!1}function isCallableTool(tool){return"callTool"in tool&&typeof tool.callTool=="function"}function hasCallableTools(params){var _a2,_b,_c;return(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)===null||_b===void 0?void 0:_b.some(tool=>isCallableTool(tool)))!==null&&_c!==void 0?_c:!1}function findAfcIncompatibleToolIndexes(params){var _a2;let afcIncompatibleToolIndexes=[];return!((_a2=params?.config)===null||_a2===void 0)&&_a2.tools&¶ms.config.tools.forEach((tool,index)=>{if(isCallableTool(tool))return;let geminiTool=tool;geminiTool.functionDeclarations&&geminiTool.functionDeclarations.length>0&&afcIncompatibleToolIndexes.push(index)}),afcIncompatibleToolIndexes}function shouldAppendAfcHistory(config){var _a2;return!(!((_a2=config?.automaticFunctionCalling)===null||_a2===void 0)&&_a2.ignoreCallHistory)}var Models=class _Models extends BaseModule{constructor(apiClient){super(),this.apiClient=apiClient,this.embedContent=async params=>{if(!this.apiClient.isVertexAI())return params.model.includes("gemini-embedding-2")&&(params.contents=tContents(params.contents)),await this.embedContentInternal(params);if(params.model.includes("gemini")&¶ms.model!=="gemini-embedding-001"||params.model.includes("maas")){let contents=tContents(params.contents);if(contents.length>1)throw new Error("The embedContent API for this model only supports one content at a time.");let paramsPrivate=Object.assign(Object.assign({},params),{content:contents[0],embeddingApiType:EmbeddingApiType.EMBED_CONTENT});return await this.embedContentInternal(paramsPrivate)}else{let paramsPrivate=Object.assign(Object.assign({},params),{embeddingApiType:EmbeddingApiType.PREDICT});return await this.embedContentInternal(paramsPrivate)}},this.generateContent=async params=>{var _a2,_b,_c,_d,_e;let transformedParams=await this.processParamsMaybeAddMcpUsage(params);if(this.maybeMoveToResponseJsonSchema(params),!hasCallableTools(params)||shouldDisableAfc(params.config))return await this.generateContentInternal(transformedParams);let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`)}let response,functionResponseContent,automaticFunctionCallingHistory=tContents(transformedParams.contents),maxRemoteCalls=(_c=(_b=(_a2=transformedParams.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,remoteCalls=0;for(;remoteCalls<maxRemoteCalls&&(response=await this.generateContentInternal(transformedParams),!(!response.functionCalls||response.functionCalls.length===0));){let responseContent=response.candidates[0].content,functionResponseParts=[];for(let tool of(_e=(_d=params.config)===null||_d===void 0?void 0:_d.tools)!==null&&_e!==void 0?_e:[])if(isCallableTool(tool)){let parts=await tool.callTool(response.functionCalls);functionResponseParts.push(...parts)}remoteCalls++,functionResponseContent={role:"user",parts:functionResponseParts},transformedParams.contents=tContents(transformedParams.contents),transformedParams.contents.push(responseContent),transformedParams.contents.push(functionResponseContent),shouldAppendAfcHistory(transformedParams.config)&&(automaticFunctionCallingHistory.push(responseContent),automaticFunctionCallingHistory.push(functionResponseContent))}return shouldAppendAfcHistory(transformedParams.config)&&(response.automaticFunctionCallingHistory=automaticFunctionCallingHistory),response},this.generateContentStream=async params=>{var _a2,_b,_c,_d,_e;if(this.maybeMoveToResponseJsonSchema(params),shouldDisableAfc(params.config)){let transformedParams=await this.processParamsMaybeAddMcpUsage(params);return await this.generateContentStreamInternal(transformedParams)}let incompatibleToolIndexes=findAfcIncompatibleToolIndexes(params);if(incompatibleToolIndexes.length>0){let formattedIndexes=incompatibleToolIndexes.map(index=>`tools[${index}]`).join(", ");throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let streamFunctionCall=(_c=(_b=(_a2=params?.config)===null||_a2===void 0?void 0:_a2.toolConfig)===null||_b===void 0?void 0:_b.functionCallingConfig)===null||_c===void 0?void 0:_c.streamFunctionCallArguments,disableAfc=(_e=(_d=params?.config)===null||_d===void 0?void 0:_d.automaticFunctionCalling)===null||_e===void 0?void 0:_e.disable;if(streamFunctionCall&&!disableAfc)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(params)},this.generateImages=async params=>(_Models.loggedGenerateImagesWarning||(_Models.loggedGenerateImagesWarning=!0,console.warn("The generateImages method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/image-generation#generate-images")),await this.generateImagesInternal(params).then(apiResponse=>{var _a2;let positivePromptSafetyAttributes,generatedImages=[];if(apiResponse?.generatedImages)for(let generatedImage of apiResponse.generatedImages)generatedImage&&generatedImage?.safetyAttributes&&((_a2=generatedImage?.safetyAttributes)===null||_a2===void 0?void 0:_a2.contentType)==="Positive Prompt"?positivePromptSafetyAttributes=generatedImage?.safetyAttributes:generatedImages.push(generatedImage);let response;return positivePromptSafetyAttributes?response={generatedImages,positivePromptSafetyAttributes,sdkHttpResponse:apiResponse.sdkHttpResponse}:response={generatedImages,sdkHttpResponse:apiResponse.sdkHttpResponse},response})),this.list=async params=>{var _a2;let actualParams={config:Object.assign(Object.assign({},{queryBase:!0}),params?.config)};if(this.apiClient.isVertexAI()&&!actualParams.config.queryBase){if(!((_a2=actualParams.config)===null||_a2===void 0)&&_a2.filter)throw new Error("Filtering tuned models list is only supported in Gemini Developer API mode, not in Gemini Enterprise Agent Platform mode.");actualParams.config.filter="labels.tune-type:*"}return new Pager(PagedItem.PAGED_ITEM_MODELS,x2=>this.listInternal(x2),await this.listInternal(actualParams),actualParams)},this.editImage=async params=>{_Models.loggedEditImageWarning||(_Models.loggedEditImageWarning=!0,console.warn("The editImage method is deprecated and will be removed in the next major release (not before Jan. 1 2027). Please use the generateContent method with image models instead. See https://ai.google.dev/gemini-api/docs/deprecations#imagen-models and https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/capabilities/gemini-edit-images#edit-an-image"));let paramsInternal={model:params.model,prompt:params.prompt,referenceImages:[],config:params.config};return params.referenceImages&¶ms.referenceImages&&(paramsInternal.referenceImages=params.referenceImages.map(img=>img.toReferenceImageAPI())),await this.editImageInternal(paramsInternal)},this.upscaleImage=async params=>{let apiConfig={numberOfImages:1,mode:"upscale"};params.config&&(apiConfig=Object.assign(Object.assign({},apiConfig),params.config));let apiParams={model:params.model,image:params.image,upscaleFactor:params.upscaleFactor,config:apiConfig};return await this.upscaleImageInternal(apiParams)},this.generateVideos=async params=>{var _a2,_b,_c,_d,_e,_f;if((params.prompt||params.image||params.video)&¶ms.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return(params.prompt||params.image||params.video)&&(_Models.loggedGenerateVideosWarning||(_Models.loggedGenerateVideosWarning=!0,console.warn("The generateVideos method with prompt/image/video arguments is deprecated and will be removed in a future major release (not before 2026-07-31). Please use the source argument instead."))),this.apiClient.isVertexAI()||(!((_a2=params.video)===null||_a2===void 0)&&_a2.uri&&(!((_b=params.video)===null||_b===void 0)&&_b.videoBytes)?params.video={uri:params.video.uri,mimeType:params.video.mimeType}:!((_d=(_c=params.source)===null||_c===void 0?void 0:_c.video)===null||_d===void 0)&&_d.uri&&(!((_f=(_e=params.source)===null||_e===void 0?void 0:_e.video)===null||_f===void 0)&&_f.videoBytes)&&(params.source.video={uri:params.source.video.uri,mimeType:params.source.video.mimeType})),await this.generateVideosInternal(params)}}maybeMoveToResponseJsonSchema(params){params.config&¶ms.config.responseSchema&&(params.config.responseJsonSchema||Object.keys(params.config.responseSchema).includes("$schema")&&(params.config.responseJsonSchema=params.config.responseSchema,delete params.config.responseSchema))}async processParamsMaybeAddMcpUsage(params){var _a2,_b,_c;let tools=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools;if(!tools)return params;let transformedTools=await Promise.all(tools.map(async tool=>isCallableTool(tool)?await tool.tool():tool)),newParams={model:params.model,contents:params.contents,config:Object.assign(Object.assign({},params.config),{tools:transformedTools})};if(newParams.config.tools=transformedTools,params.config&¶ms.config.tools&&hasMcpToolUsage(params.config.tools)){let headers=(_c=(_b=params.config.httpOptions)===null||_b===void 0?void 0:_b.headers)!==null&&_c!==void 0?_c:{},newHeaders=Object.assign({},headers);Object.keys(newHeaders).length===0&&(newHeaders=this.apiClient.getDefaultHeaders()),setMcpUsageHeader(newHeaders),newParams.config.httpOptions=Object.assign(Object.assign({},params.config.httpOptions),{headers:newHeaders})}return newParams}async initAfcToolsMap(params){var _a2,_b,_c;let afcTools=new Map;for(let tool of(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.tools)!==null&&_b!==void 0?_b:[])if(isCallableTool(tool)){let callableTool=tool,toolDeclaration=await callableTool.tool();for(let declaration of(_c=toolDeclaration.functionDeclarations)!==null&&_c!==void 0?_c:[]){if(!declaration.name)throw new Error("Function declaration name is required.");if(afcTools.has(declaration.name))throw new Error(`Duplicate tool declaration name: ${declaration.name}`);afcTools.set(declaration.name,callableTool)}}return afcTools}async processAfcStream(params){var _a2,_b,_c;let maxRemoteCalls=(_c=(_b=(_a2=params.config)===null||_a2===void 0?void 0:_a2.automaticFunctionCalling)===null||_b===void 0?void 0:_b.maximumRemoteCalls)!==null&&_c!==void 0?_c:DEFAULT_MAX_REMOTE_CALLS,wereFunctionsCalled=!1,remoteCallCount=0,afcToolsMap=await this.initAfcToolsMap(params);return(function(models,afcTools,params2){return __asyncGenerator(this,arguments,function*(){for(var _a3,e_1,_b2,_c2,_d,_e;remoteCallCount<maxRemoteCalls;){wereFunctionsCalled&&(remoteCallCount++,wereFunctionsCalled=!1);let transformedParams=yield __await(models.processParamsMaybeAddMcpUsage(params2)),response=yield __await(models.generateContentStreamInternal(transformedParams)),functionResponses=[],responseContents=[];try{for(var _f=!0,response_1=(e_1=void 0,__asyncValues(response)),response_1_1;response_1_1=yield __await(response_1.next()),_a3=response_1_1.done,!_a3;_f=!0){_c2=response_1_1.value,_f=!1;let chunk=_c2;if(yield yield __await(chunk),chunk.candidates&&(!((_d=chunk.candidates[0])===null||_d===void 0)&&_d.content)){responseContents.push(chunk.candidates[0].content);for(let part of(_e=chunk.candidates[0].content.parts)!==null&&_e!==void 0?_e:[])if(remoteCallCount<maxRemoteCalls&&part.functionCall){if(!part.functionCall.name)throw new Error("Function call name was not returned by the model.");if(afcTools.has(part.functionCall.name)){let responseParts=yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall]));functionResponses.push(...responseParts)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, missing tool: ${part.functionCall.name}`)}}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{!_f&&!_a3&&(_b2=response_1.return)&&(yield __await(_b2.call(response_1)))}finally{if(e_1)throw e_1.error}}if(functionResponses.length>0){wereFunctionsCalled=!0;let typedResponseChunk=new GenerateContentResponse;typedResponseChunk.candidates=[{content:{role:"user",parts:functionResponses}}],yield yield __await(typedResponseChunk);let newContents=[];newContents.push(...responseContents),newContents.push({role:"user",parts:functionResponses});let updatedContents=tContents(params2.contents).concat(newContents);params2.contents=updatedContents}else break}})})(this,afcToolsMap,params)}async generateContentInternal(params){var _a2,_b,_c,_d;let response,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{model}:generateContent",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateContentParametersToVertex(this.apiClient,params);return path=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path,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 path=formatMap("{model}:streamGenerateContent?alt=sse",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.requestStream({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=embedContentParametersPrivateToVertex(this.apiClient,params,params),endpointUrl=tIsVertexEmbedContentModel(params.model)?"{model}:embedContent":"{model}:predict";return path=formatMap(endpointUrl,body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{model}:batchEmbedContents",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateImagesParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=editImageParametersInternalToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=upscaleImageAPIParametersInternalToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=recontextImageParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=segmentImageParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predict",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=getModelParametersToVertex(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=listModelsParametersToVertex(this.apiClient,params);return path=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{models_url}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=updateModelParametersToVertex(this.apiClient,params);return path=formatMap("{model}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=deleteModelParametersToVertex(this.apiClient,params);return path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{name}",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=countTokensParametersToVertex(this.apiClient,params);return path=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{model}:countTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=computeTokensParametersToVertex(this.apiClient,params);return path=formatMap("{model}:computeTokens",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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,path="",queryParams={};if(this.apiClient.isVertexAI()){let body=generateVideosParametersToVertex(this.apiClient,params);return path=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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 path=formatMap("{model}:predictLongRunning",body._url),queryParams=body._query,delete body._url,delete body._query,response=this.apiClient.request({path,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;function bytesToBase64(u8arr){return btoa(String.fromCodePoint(...u8arr))}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 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 m2=mapper(v);return m2==null||acc.push(m2),acc},[]);return res.length?res:null}function mapDefinedEntries(inp,mapper){let acc=[];for(let[k,v]of inp){if(v==null)continue;let m2=mapper([k,v]);m2!=null&&acc.push(m2)}return acc.length?acc:null}function queryJoin(...args){return args.filter(Boolean).join("&")}function queryEncoder(f3){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)}=`:f3(key,value,opts));return queryJoin(...encoded)}}var encodeFormQuery=queryEncoder(encodeForm);var codeRangeRE$1=new RegExp("^[0-9]xx$","i");var codeRangeRE=new RegExp("^[0-9]xx$","i");var gt=typeof globalThis>"u"?null:globalThis,webWorkerLike=typeof gt=="object"&>!=null&&"importScripts"in gt&&typeof gt.importScripts=="function",isBrowserLike=webWorkerLike||typeof navigator<"u"&&"serviceWorker"in navigator||typeof window=="object"&&typeof window.document<"u";var CR2=13,LF2=10,BOUNDARIES=[[CR2,LF2,CR2,LF2],[CR2,LF2,CR2],[CR2,LF2,LF2],[CR2,CR2,LF2],[LF2,CR2,LF2],[CR2,CR2],[LF2,CR2],[LF2,LF2]],MAX_BOUNDARY_LEN=BOUNDARIES.reduce((m2,b)=>Math.max(m2,b.length),0);var _a;_a=Symbol.toStringTag;var MAX_CHUNK_SIZE=1024*1024*8;var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types3=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types3.includes("object")||types3.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(!config||config.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)";function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){return model.input.includes("image")?messages:messages.map(msg=>msg.role==="user"&&Array.isArray(msg.content)?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_USER_IMAGE_PLACEHOLDER)}:msg.role==="toolResult"?{...msg,content:replaceImagesWithPlaceholder(msg.content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)}:msg)}function transformMessages(messages,model,normalizeToolCallId){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),transformed=downgradeUnsupportedImages(normalizedMessages,model).map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking")return isSameModel?block.redacted||block.thinkingSignature?block:!block.thinking||block.thinking.trim()===""?[]:block:[];if(block.type==="text")return isSameModel?block:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall=toolCall;if(!isSameModel&&toolCall.thoughtSignature&&(normalizedToolCall={...toolCall},delete normalizedToolCall.thoughtSignature),!isSameModel&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],pendingToolCalls=[],existingToolResultIds=new Set,heldSystemMessages=[],closePendingToolCalls=()=>{if(pendingToolCalls.length>0){for(let tc of pendingToolCalls)existingToolResultIds.has(tc.id)||result.push({role:"toolResult",toolCallId:tc.id,toolName:tc.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});pendingToolCalls=[],existingToolResultIds=new Set}result.push(...heldSystemMessages),heldSystemMessages.length=0};for(let i2=0;i2<transformed.length;i2++){let msg=transformed[i2];if(msg.role==="assistant"){closePendingToolCalls();let assistantMsg=msg;if(assistantMsg.stopReason==="error"||assistantMsg.stopReason==="aborted")continue;let toolCalls=assistantMsg.content.filter(b=>b.type==="toolCall");toolCalls.length>0&&(pendingToolCalls=toolCalls,existingToolResultIds=new Set),result.push(msg)}else msg.role==="toolResult"?(existingToolResultIds.add(msg.toolCallId),result.push(msg)):msg.role==="system"?pendingToolCalls.length>0?heldSystemMessages.push(msg):result.push(msg):(msg.role==="user"&&closePendingToolCalls(),result.push(msg))}return closePendingToolCalls(),result}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 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 match=modelId.toLowerCase().match(/^gemini(?:-live)?-(\d+)/);if(match)return Number.parseInt(match[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(`
|
|
67
73
|
`),imageContent=model.input.includes("image")?msg.content.filter(c=>c.type==="image"):[],hasText=textResult.trim().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={},constraints={},stringConstant;for(let[key,value]of Object.entries(schema))JSON_SCHEMA_META_DECLARATIONS.has(key)||(key==="const"?typeof value=="string"?stringConstant=value:constraints[key]=value:key==="exclusiveMinimum"||key==="exclusiveMaximum"||key==="patternProperties"?constraints[key]=value:key==="properties"?result[key]=Object.fromEntries(Object.entries(value).map(([name,property])=>[name,sanitizeForOpenApi(property)])):key==="items"?result[key]=sanitizeForOpenApi(value):key==="anyOf"?result[key]=value.map(sanitizeForOpenApi):result[key]=value);if(stringConstant!==void 0&&(result.enum=[stringConstant]),(result.type===void 0||result.type==="string")&&result.enum===void 0&&Array.isArray(result.anyOf)&&result.anyOf.length>0&&result.anyOf.every(variant=>variant.type==="string"&&Array.isArray(variant.enum)&&variant.enum.every(value=>typeof value=="string")&&Object.keys(variant).every(key=>key==="type"||key==="enum"))&&(result.type="string",result.enum=[...new Set(result.anyOf.flatMap(variant=>variant.enum))],delete result.anyOf),Object.keys(constraints).length>0){let instruction=`Must satisfy JSON Schema constraints: ${JSON.stringify(constraints)}`;result.description=result.description?`${result.description}
|
|
68
|
-
${instruction}`:instruction}return result}var JSON_SCHEMA_NAME_MAPS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]),JSON_SCHEMA_SUBSCHEMAS=new Set(["additionalProperties","unevaluatedProperties","propertyNames","items","prefixItems","additionalItems","unevaluatedItems","contains","allOf","anyOf","oneOf","not","if","then","else","contentSchema"]);function rewriteConstAsEnum(schema,isNameMap=!1){if(Array.isArray(schema))return schema.map(item=>rewriteConstAsEnum(item));if(typeof schema!="object"||schema===null)return schema;let result=Object.fromEntries(Object.entries(schema).map(([key,value])=>isNameMap||JSON_SCHEMA_SUBSCHEMAS.has(key)?[key,rewriteConstAsEnum(value)]:JSON_SCHEMA_NAME_MAPS.has(key)?[key,rewriteConstAsEnum(value,!0)]:[key,value]));if(!isNameMap&&"const"in result&&result.enum===void 0){let value=result.const;(typeof value=="string"||typeof value=="number")&&(delete result.const,result.enum=[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:rewriteConstAsEnum(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 mapStopReasonString(reason){switch(reason){case"STOP":return"stop";case"MAX_TOKENS":return"length";default:return"error"}}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify2(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify2(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i2=0;i2<messages.length;i2++){let message=messages[i2];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i2})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i2=usageInfo.index+1;i2<messages.length;i2++)trailingTokens+=estimateMessageTokens(messages[i2]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify2(tools))}var CONTEXT_SAFETY_TOKENS=4096,CONTEXT_SAFETY_RATIO=.15,MIN_OUTPUT_WITH_RATIO_MARGIN=32768,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let input=estimateContextTokens(context).tokens,margin=Math.max(CONTEXT_SAFETY_TOKENS,Math.ceil(input*CONTEXT_SAFETY_RATIO)),room=model.contextWindow-input-margin;return room<MIN_OUTPUT_WITH_RATIO_MARGIN&&(room=Math.min(MIN_OUTPUT_WITH_RATIO_MARGIN,model.contextWindow-input-CONTEXT_SAFETY_TOKENS)),Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,room))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,disableContinuation:options?.disableContinuation,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var MIN_ANSWER_TOKENS=1024,DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let thinkingBudget=thinkingBudgetForLevel(reasoningLevel,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}var DEFAULT_ENDPOINT="https://daily-cloudcode-pa.googleapis.com",stream=(model,context,options)=>{let events=new AssistantMessageEventStream,output={role:"assistant",content:[],api:"google-antigravity",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};return(async()=>{try{if(typeof process<"u"&&process.env.PI_SERVER_MODE==="true")throw new Error("Google Antigravity inference must use pi-server in PI_SERVER_MODE");if(!options?.apiKey)throw new Error("Google Antigravity requires OAuth authentication. Use /login.");let credential=JSON.parse(options.apiKey);if(!credential||typeof credential.token!="string"||typeof credential.projectId!="string")throw new Error("Invalid Google Antigravity credentials. Use /login to authenticate.");let payload=buildRequest(model,context,credential.projectId,options),transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let headers=providerHeadersToRecord({Authorization:`Bearer ${credential.token}`,"Content-Type":"application/json",Accept:"text/event-stream","User-Agent":"antigravity/hub/2.23.0 darwin/arm64",...model.id.startsWith("claude-")&&model.reasoning?{"anthropic-beta":"interleaved-thinking-2025-05-14"}:{}},model.headers,options.headers),body=JSON.stringify(payload),{response,signal}=await retryProviderRequest(async()=>{let timeout=AbortSignal.timeout(options.timeoutMs??6e5),signal2=options.signal?AbortSignal.any([options.signal,timeout]):timeout;signal2.throwIfAborted();let response2;try{response2=await(options.fetch??globalThis.fetch)(`${(model.baseUrl||DEFAULT_ENDPOINT).replace(/\/$/,"")}/v1internal:streamGenerateContent?alt=sse`,{method:"POST",headers,body,signal:signal2})}catch(error){throw Object.assign(error instanceof Error?error:new Error(String(error)),{status:void 0,headers:void 0})}if(await options.onResponse?.({status:response2.status,headers:headersToRecord(response2.headers)},model),!response2.ok)throw Object.assign(new Error("Google Antigravity request failed"),{status:response2.status,headers:response2.headers,body:await response2.text()});return{response:response2,signal:signal2}},{maxRetries:options.maxRetries??2,maxRetryDelayMs:options.maxRetryDelayMs,signal:options.signal});events.push({type:"start",partial:output});let current,endBlock=()=>{if(!current)return;let contentIndex=output.content.length-1;current.type==="text"?events.push({type:"text_end",contentIndex,content:current.text,partial:output}):events.push({type:"thinking_end",contentIndex,content:current.thinking,partial:output}),current=void 0};for await(let chunk of parseStream(response,signal)){if(await options.onProviderStreamEvent?.(chunk,model),chunk.error)throw appendAntigravityFailure(output,chunk.error.code,chunk.error),new Error(chunk.error.message??JSON.stringify(chunk.error));if(!chunk.response)throw new Error("Google Antigravity stream event has no response");let data=chunk.response;output.responseId||=data.responseId,output.responseModel||=data.modelVersion;let candidate=data.candidates?.[0];for(let part of candidate?.content?.parts??[]){if(part.text!==void 0||part.thoughtSignature&&!part.functionCall){let thinking=isThinkingPart(part),signature=current?.type==="thinking"?current.thinkingSignature:current?.textSignature;(!current||(thinking?current.type!=="thinking":current.type!=="text")||signature&&part.thoughtSignature&&signature!==part.thoughtSignature)&&(endBlock(),current=thinking?{type:"thinking",thinking:""}:{type:"text",text:""},output.content.push(current),events.push({type:thinking?"thinking_start":"text_start",contentIndex:output.content.length-1,partial:output}));let delta=part.text??"",contentIndex=output.content.length-1;current.type==="thinking"?(current.thinking+=delta,current.thinkingSignature=retainThoughtSignature(current.thinkingSignature,part.thoughtSignature),events.push({type:"thinking_delta",contentIndex,delta,partial:output})):(current.text+=delta,current.textSignature=retainThoughtSignature(current.textSignature,part.thoughtSignature),events.push({type:"text_delta",contentIndex,delta,partial:output}))}if(part.functionCall){endBlock();let call=part.functionCall;if(!call.name||call.args!==void 0&&(call.args===null||Array.isArray(call.args)||typeof call.args!="object"))throw new Error("Google Antigravity returned an invalid function call");let toolCall={type:"toolCall",id:call.id??`call_${crypto.randomUUID()}`,name:call.name,arguments:call.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}},contentIndex=output.content.length;output.content.push(toolCall),events.push({type:"toolcall_start",contentIndex,partial:output}),events.push({type:"toolcall_delta",contentIndex,delta:JSON.stringify(toolCall.arguments),partial:output}),events.push({type:"toolcall_end",contentIndex,toolCall,partial:output})}}if(candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReasonString(candidate.finishReason),output.stopReason==="stop"&&output.content.some(part=>part.type==="toolCall")&&(output.stopReason="toolUse")),data.usageMetadata){let usage=data.usageMetadata;output.usage.input=(usage.promptTokenCount??0)-(usage.cachedContentTokenCount??0),output.usage.output=(usage.candidatesTokenCount??0)+(usage.thoughtsTokenCount??0),output.usage.cacheRead=usage.cachedContentTokenCount??0,output.usage.reasoning=usage.thoughtsTokenCount??0,output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead,calculateCost(model,output.usage)}}if(endBlock(),signal.throwIfAborted(),output.stopReason==="pending")throw new Error("Google Antigravity stream ended without a finish reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(`Google Antigravity stopped with: ${output.rawStopReason}`);events.push({type:"done",reason:output.stopReason,message:output})}catch(error){output.stopReason=options?.signal?.aborted?"aborted":"error";let failure=normalizeProviderError(error);if(failure.status!==void 0){let upstream;if(failure.body)try{upstream=JSON.parse(failure.body)?.error}catch{}appendAntigravityFailure(output,failure.status,upstream)}output.errorMessage=formatProviderError(failure),events.push({type:"error",reason:output.stopReason,error:output})}events.end()})(),events},RPC_CODE_PATTERN=/^[A-Z][A-Z0-9_]{0,63}$/;function appendAntigravityFailure(message,status,upstream){let details={};if(status!==void 0&&(details.status=status),typeof upstream?.status=="string"&&RPC_CODE_PATTERN.test(upstream.status)&&(details.rpcStatus=upstream.status),Array.isArray(upstream?.details))for(let entry of upstream.details)switch(entry?.["@type"]){case"type.googleapis.com/google.rpc.ErrorInfo":typeof entry.reason=="string"&&RPC_CODE_PATTERN.test(entry.reason)&&(details.reason=entry.reason);break;case"type.googleapis.com/google.rpc.RetryInfo":typeof entry.retryDelay=="string"&&/^\d{1,10}(?:\.\d{1,9})?s$/.test(entry.retryDelay)&&(details.retryDelay=entry.retryDelay);break;case"type.googleapis.com/google.rpc.QuotaFailure":Array.isArray(entry.violations)&&(details.quotaViolations=entry.violations.length);break}appendAssistantMessageDiagnostic(message,{type:"google_antigravity_response_failure",timestamp:Date.now(),details})}var streamSimple=(model,context,options)=>{if(!options?.apiKey)throw new Error("Google Antigravity requires OAuth authentication. Use /login.");let base={...buildBaseOptions(model,context,options),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let level=clampThinkingLevel(model,options.reasoning);if(level==="off")return stream(model,context,{...base,thinking:{enabled:!1}});if(usesGoogleThinkingLevel(model))return stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolveGoogleThinkingLevel(model,level))}});let{maxTokens,thinkingBudget}=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,level,options?.thinkingBudgets);return stream(model,context,{...base,maxTokens,thinking:{enabled:!0,budgetTokens:thinkingBudget}})};function buildRequest(model,context,projectId,options){let tools=getCurrentTools(context.messages),systemPrompt=getCurrentSystemPrompt(context.messages),strict=supportsGoogleStrictToolSampling(model.id),mode=tools.length>0?resolveGoogleFunctionCallingMode(tools,options.toolChoice,strict):void 0,generationConfig={temperature:options.temperature,maxOutputTokens:options.maxTokens};return model.reasoning&&options.thinking&&(generationConfig.thinkingConfig=options.thinking.enabled?{includeThoughts:!0,...options.thinking.level!==void 0?{thinkingLevel:toGoogleSdkThinkingLevel(options.thinking.level)}:{thinkingBudget:options.thinking.budgetTokens}}:getDisabledGoogleThinkingConfig(model)),{project:projectId,model:model.id,requestType:"agent",userAgent:"antigravity",requestId:`agent-${crypto.randomUUID()}`,request:{contents:convertMessages(model,context),sessionId:options.sessionId,generationConfig,...systemPrompt&&{systemInstruction:{parts:[{text:sanitizeSurrogates(systemPrompt)}]}},...tools.length>0&&{tools:convertTools(tools,model.id.startsWith("claude-"),strict)},...mode!==void 0&&{toolConfig:{functionCallingConfig:{mode}}}}}}async function*parseStream(response,signal){if(!response.body)throw new Error("Google Antigravity response has no body");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",data=[],abort=()=>{reader.cancel(signal.reason)};signal.addEventListener("abort",abort,{once:!0});try{for(;;){signal.throwIfAborted();let{value,done}=await reader.read();signal.throwIfAborted(),buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.length>0&&(buffer+=`
|
|
74
|
+
${instruction}`:instruction}return result}var JSON_SCHEMA_NAME_MAPS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]),JSON_SCHEMA_SUBSCHEMAS=new Set(["additionalProperties","unevaluatedProperties","propertyNames","items","prefixItems","additionalItems","unevaluatedItems","contains","allOf","anyOf","oneOf","not","if","then","else","contentSchema"]);function rewriteConstAsEnum(schema,isNameMap=!1){if(Array.isArray(schema))return schema.map(item=>rewriteConstAsEnum(item));if(typeof schema!="object"||schema===null)return schema;let result=Object.fromEntries(Object.entries(schema).map(([key,value])=>isNameMap||JSON_SCHEMA_SUBSCHEMAS.has(key)?[key,rewriteConstAsEnum(value)]:JSON_SCHEMA_NAME_MAPS.has(key)?[key,rewriteConstAsEnum(value,!0)]:[key,value]));if(!isNameMap&&"const"in result&&result.enum===void 0){let value=result.const;(typeof value=="string"||typeof value=="number")&&(delete result.const,result.enum=[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:rewriteConstAsEnum(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 mapStopReasonString(reason){switch(reason){case"STOP":return"stop";case"MAX_TOKENS":return"length";default:return"error"}}var CHARS_PER_TOKEN=3.5,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify2(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:chars+=block.name.length+safeJsonStringify2(block.arguments).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i2=0;i2<messages.length;i2++){let message=messages[i2];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i2})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i2=usageInfo.index+1;i2<messages.length;i2++)trailingTokens+=estimateMessageTokens(messages[i2]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify2(tools))}var CONTEXT_SAFETY_TOKENS=4096,CONTEXT_SAFETY_RATIO=.15,MIN_OUTPUT_WITH_RATIO_MARGIN=32768,MIN_MAX_TOKENS=1;function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Math.max(MIN_MAX_TOKENS,maxTokens);let input=estimateContextTokens(context).tokens,margin=Math.max(CONTEXT_SAFETY_TOKENS,Math.ceil(input*CONTEXT_SAFETY_RATIO)),room=model.contextWindow-input-margin;return room<MIN_OUTPUT_WITH_RATIO_MARGIN&&(room=Math.min(MIN_OUTPUT_WITH_RATIO_MARGIN,model.contextWindow-input-CONTEXT_SAFETY_TOKENS)),Math.min(maxTokens,Math.max(MIN_MAX_TOKENS,room))}function resolveSamplingParams(model,thinkingLevel,requestParams){let effectiveThinkingLevel=clampThinkingLevel(model,thinkingLevel),thinkingLevelParams=model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];return model.samplingParams||thinkingLevelParams||requestParams?{...model.samplingParams,...thinkingLevelParams,...requestParams}:void 0}function buildBaseOptions(model,context,options,apiKey){let samplingParams=resolveSamplingParams(model,options?.reasoning??"off",options?.samplingParams);return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,telemetry:options?.telemetry,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention,sessionId:options?.sessionId,disableContinuation:options?.disableContinuation,headers:options?.headers,identity:options?.identity,onPayload:options?.onPayload,onResponse:options?.onResponse,onProviderStreamEvent:options?.onProviderStreamEvent,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var DEFAULT_ENDPOINT="https://daily-cloudcode-pa.googleapis.com",stream=(model,context,options)=>{let events=new AssistantMessageEventStream,output={role:"assistant",content:[],api:"google-antigravity",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};return(async()=>{try{if(typeof process<"u"&&process.env.PI_SERVER_MODE==="true")throw new Error("Google Antigravity inference must use pi-server in PI_SERVER_MODE");if(!options?.apiKey)throw new Error("Google Antigravity requires OAuth authentication. Use /login.");let credential=JSON.parse(options.apiKey);if(!credential||typeof credential.token!="string"||typeof credential.projectId!="string")throw new Error("Invalid Google Antigravity credentials. Use /login to authenticate.");let payload=buildRequest(model,context,credential.projectId,options),transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let headers=providerHeadersToRecord({Authorization:`Bearer ${credential.token}`,"Content-Type":"application/json","User-Agent":ANTIGRAVITY_USER_AGENT,...model.id.startsWith("claude-")&&model.reasoning?{"anthropic-beta":"interleaved-thinking-2025-05-14"}:{}},model.headers,options.headers),body=JSON.stringify(payload),{response,signal}=await retryProviderRequest(async()=>{let timeout=AbortSignal.timeout(options.timeoutMs??6e5),signal2=options.signal?AbortSignal.any([options.signal,timeout]):timeout;signal2.throwIfAborted();let response2;try{response2=await(options.fetch??globalThis.fetch)(`${(model.baseUrl||DEFAULT_ENDPOINT).replace(/\/$/,"")}/v1internal:streamGenerateContent?alt=sse`,{method:"POST",redirect:"error",headers,body,signal:signal2})}catch(error){throw Object.assign(error instanceof Error?error:new Error(String(error)),{status:void 0,headers:void 0})}if(await options.onResponse?.({status:response2.status,headers:headersToRecord(response2.headers)},model),!response2.ok)throw Object.assign(new Error("Google Antigravity request failed"),{status:response2.status,headers:response2.headers,body:await response2.text()});return{response:response2,signal:signal2}},{maxRetries:options.maxRetries??2,maxRetryDelayMs:options.maxRetryDelayMs,signal:options.signal});events.push({type:"start",partial:output});let current,endBlock=()=>{if(!current)return;let contentIndex=output.content.length-1;current.type==="text"?events.push({type:"text_end",contentIndex,content:current.text,partial:output}):events.push({type:"thinking_end",contentIndex,content:current.thinking,partial:output}),current=void 0};for await(let chunk of parseStream(response,signal)){if(await options.onProviderStreamEvent?.(chunk,model),chunk.error)throw appendAntigravityFailure(output,chunk.error.code,chunk.error),new Error(chunk.error.message??JSON.stringify(chunk.error));if(!chunk.response)throw new Error("Google Antigravity stream event has no response");let data=chunk.response;output.responseId||=data.responseId,output.responseModel||=data.modelVersion;let candidate=data.candidates?.[0];for(let part of candidate?.content?.parts??[]){if(part.text!==void 0||part.thoughtSignature&&!part.functionCall){let thinking=isThinkingPart(part),signature=current?.type==="thinking"?current.thinkingSignature:current?.textSignature;(!current||(thinking?current.type!=="thinking":current.type!=="text")||signature&&part.thoughtSignature&&signature!==part.thoughtSignature)&&(endBlock(),current=thinking?{type:"thinking",thinking:""}:{type:"text",text:""},output.content.push(current),events.push({type:thinking?"thinking_start":"text_start",contentIndex:output.content.length-1,partial:output}));let delta=part.text??"",contentIndex=output.content.length-1;current.type==="thinking"?(current.thinking+=delta,current.thinkingSignature=retainThoughtSignature(current.thinkingSignature,part.thoughtSignature),events.push({type:"thinking_delta",contentIndex,delta,partial:output})):(current.text+=delta,current.textSignature=retainThoughtSignature(current.textSignature,part.thoughtSignature),events.push({type:"text_delta",contentIndex,delta,partial:output}))}if(part.functionCall){endBlock();let call=part.functionCall;if(!call.name||call.args!==void 0&&(call.args===null||Array.isArray(call.args)||typeof call.args!="object"))throw new Error("Google Antigravity returned an invalid function call");let toolCall={type:"toolCall",id:call.id??`call_${crypto.randomUUID()}`,name:call.name,arguments:call.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}},contentIndex=output.content.length;output.content.push(toolCall),events.push({type:"toolcall_start",contentIndex,partial:output}),events.push({type:"toolcall_delta",contentIndex,delta:JSON.stringify(toolCall.arguments),partial:output}),events.push({type:"toolcall_end",contentIndex,toolCall,partial:output})}}if(candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReasonString(candidate.finishReason),output.stopReason==="stop"&&output.content.some(part=>part.type==="toolCall")&&(output.stopReason="toolUse")),data.usageMetadata){let usage=data.usageMetadata;output.usage.input=(usage.promptTokenCount??0)-(usage.cachedContentTokenCount??0),output.usage.output=(usage.candidatesTokenCount??0)+(usage.thoughtsTokenCount??0),output.usage.cacheRead=usage.cachedContentTokenCount??0,output.usage.reasoning=usage.thoughtsTokenCount??0,output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead,calculateCost(model,output.usage)}}if(endBlock(),signal.throwIfAborted(),output.stopReason==="pending")throw new Error("Google Antigravity stream ended without a finish reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(`Google Antigravity stopped with: ${output.rawStopReason}`);events.push({type:"done",reason:output.stopReason,message:output})}catch(error){output.stopReason=options?.signal?.aborted?"aborted":"error";let failure=normalizeProviderError(error);if(failure.status!==void 0){let upstream;if(failure.body)try{upstream=JSON.parse(failure.body)?.error}catch{}appendAntigravityFailure(output,failure.status,upstream)}output.errorMessage=formatProviderError(failure),events.push({type:"error",reason:output.stopReason,error:output})}events.end()})(),events},RPC_CODE_PATTERN=/^[A-Z][A-Z0-9_]{0,63}$/;function appendAntigravityFailure(message,status,upstream){let details={};if(status!==void 0&&(details.status=status),typeof upstream?.status=="string"&&RPC_CODE_PATTERN.test(upstream.status)&&(details.rpcStatus=upstream.status),Array.isArray(upstream?.details))for(let entry of upstream.details)switch(entry?.["@type"]){case"type.googleapis.com/google.rpc.ErrorInfo":typeof entry.reason=="string"&&RPC_CODE_PATTERN.test(entry.reason)&&(details.reason=entry.reason);break;case"type.googleapis.com/google.rpc.RetryInfo":typeof entry.retryDelay=="string"&&/^\d{1,10}(?:\.\d{1,9})?s$/.test(entry.retryDelay)&&(details.retryDelay=entry.retryDelay);break;case"type.googleapis.com/google.rpc.QuotaFailure":Array.isArray(entry.violations)&&(details.quotaViolations=entry.violations.length);break}appendAssistantMessageDiagnostic(message,{type:"google_antigravity_response_failure",timestamp:Date.now(),details})}var streamSimple=(model,context,options)=>{if(!options?.apiKey)throw new Error("Google Antigravity requires OAuth authentication. Use /login.");let base={...buildBaseOptions(model,context,options),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let level=clampThinkingLevel(model,options.reasoning);return level==="off"?stream(model,context,{...base,thinking:{enabled:!1}}):stream(model,context,{...base,thinking:{enabled:!0,level:antigravityThinkingLevel(model,level)}})};function antigravityThinkingLevel(model,level){let mapped=model.thinkingLevelMap?.[level];switch((typeof mapped=="string"?mapped:level).toLowerCase()){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH";case"xhigh":return"XHIGH";default:throw new Error(`Unsupported Antigravity thinking level for ${model.provider}/${model.id}: ${level}`)}}function buildRequest(model,context,projectId,options){let tools=getCurrentTools(context.messages),systemPrompt=adaptAntigravitySystemPrompt(context.messages),strict=supportsGoogleStrictToolSampling(model.id),mode=tools.length>0?resolveGoogleFunctionCallingMode(tools,options.toolChoice,strict):void 0,routes=antigravityRoutes(model),route=(options.thinking?.enabled&&options.thinking.level?routes?.levels[options.thinking.level.toLowerCase()]:void 0)??routes?.default,runtimeId=route?.runtimeId??model.id,contents=convertMessages(model,context);if(runtimeId==="gemini-3.8-flash-low")for(let content of contents)content.parts?.length&&content.parts.every(part=>part.functionResponse!==void 0)&&(content.role="model");let step=Math.max(0,contents.length-1),identity=antigravityRequestIdentity(options.sessionId),timestamp=Date.now(),generationConfig={temperature:options.temperature,maxOutputTokens:options.maxTokens,...options.thinking?.enabled&&options.thinking.level?{thinkingConfig:{includeThoughts:!0,thinkingLevel:options.thinking.level}}:{}};return{project:projectId,model:runtimeId,requestType:"agent",userAgent:"antigravity",requestId:`agent/${identity.cascadeId}/${timestamp}/${identity.requestUuid}/${step}`,request:{contents,sessionId:ANTIGRAVITY_SESSION_ID,generationConfig,...systemPrompt&&{systemInstruction:{role:"user",parts:[{text:sanitizeSurrogates(systemPrompt)}]}},tools:antigravityTools(tools,model.id.startsWith("claude-"),strict),...route&&{labels:antigravityLabels(route.runtimeId,route.modelEnum,identity,step)},...mode!==void 0&&{toolConfig:{functionCallingConfig:{mode}}}}}}function antigravityTools(tools,useParameters,strict){return(convertTools(tools,useParameters,strict)??[]).flatMap(group=>group.functionDeclarations.map(declaration=>({functionDeclarations:[declaration]})))}function antigravityLabels(runtimeId,modelEnum,identity,step){return{cascade_id:identity.cascadeId,root_cascade_id:identity.rootCascadeId,trajectory_id:identity.trajectoryId,request_id:`${identity.requestUuid}-0`,last_step_index:String(step),...modelEnum?{model_enum:modelEnum}:{},used_claude:String(runtimeId.startsWith("claude-")),used_claude_conservative:String(runtimeId.startsWith("claude-")),used_non_gemini_model:String(!runtimeId.startsWith("gemini-"))}}async function*parseStream(response,signal){if(!response.body)throw new Error("Google Antigravity response has no body");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",data=[],abort=()=>{reader.cancel(signal.reason)};signal.addEventListener("abort",abort,{once:!0});try{for(;;){signal.throwIfAborted();let{value,done}=await reader.read();signal.throwIfAborted(),buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.length>0&&(buffer+=`
|
|
69
75
|
`);let end=buffer.indexOf(`
|
|
70
76
|
`);for(;end!==-1;){let line=buffer.slice(0,end).replace(/\r$/,"");buffer=buffer.slice(end+1),line.startsWith("data:")&&data.push(line.slice(5).trimStart()),line===""&&data.length>0&&(yield JSON.parse(data.join(`
|
|
71
77
|
`)),data.length=0),end=buffer.indexOf(`
|