@google/genai 1.32.0 → 1.34.0

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/dist/index.cjs CHANGED
@@ -758,21 +758,29 @@ exports.PhishBlockThreshold = void 0;
758
758
  */
759
759
  PhishBlockThreshold["BLOCK_ONLY_EXTREMELY_HIGH"] = "BLOCK_ONLY_EXTREMELY_HIGH";
760
760
  })(exports.PhishBlockThreshold || (exports.PhishBlockThreshold = {}));
761
- /** The level of thoughts tokens that the model should generate. */
761
+ /** The number of thoughts tokens that the model should generate. */
762
762
  exports.ThinkingLevel = void 0;
763
763
  (function (ThinkingLevel) {
764
764
  /**
765
- * Default value.
765
+ * Unspecified thinking level.
766
766
  */
767
767
  ThinkingLevel["THINKING_LEVEL_UNSPECIFIED"] = "THINKING_LEVEL_UNSPECIFIED";
768
768
  /**
769
769
  * Low thinking level.
770
770
  */
771
771
  ThinkingLevel["LOW"] = "LOW";
772
+ /**
773
+ * Medium thinking level.
774
+ */
775
+ ThinkingLevel["MEDIUM"] = "MEDIUM";
772
776
  /**
773
777
  * High thinking level.
774
778
  */
775
779
  ThinkingLevel["HIGH"] = "HIGH";
780
+ /**
781
+ * MINIMAL thinking level.
782
+ */
783
+ ThinkingLevel["MINIMAL"] = "MINIMAL";
776
784
  })(exports.ThinkingLevel || (exports.ThinkingLevel = {}));
777
785
  /** Harm category. */
778
786
  exports.HarmCategory = void 0;
@@ -931,6 +939,14 @@ exports.FinishReason = void 0;
931
939
  * The model was expected to generate an image, but none was generated.
932
940
  */
933
941
  FinishReason["NO_IMAGE"] = "NO_IMAGE";
942
+ /**
943
+ * Image generation stopped because the generated image may be a recitation from a source.
944
+ */
945
+ FinishReason["IMAGE_RECITATION"] = "IMAGE_RECITATION";
946
+ /**
947
+ * Image generation stopped for a reason not otherwise specified.
948
+ */
949
+ FinishReason["IMAGE_OTHER"] = "IMAGE_OTHER";
934
950
  })(exports.FinishReason || (exports.FinishReason = {}));
935
951
  /** Output only. Harm probability levels in the content. */
936
952
  exports.HarmProbability = void 0;
@@ -1235,6 +1251,10 @@ exports.PartMediaResolutionLevel = void 0;
1235
1251
  * Media resolution set to high.
1236
1252
  */
1237
1253
  PartMediaResolutionLevel["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
1254
+ /**
1255
+ * Media resolution set to ultra high.
1256
+ */
1257
+ PartMediaResolutionLevel["MEDIA_RESOLUTION_ULTRA_HIGH"] = "MEDIA_RESOLUTION_ULTRA_HIGH";
1238
1258
  })(exports.PartMediaResolutionLevel || (exports.PartMediaResolutionLevel = {}));
1239
1259
  /** Options for feature selection preference. */
1240
1260
  exports.FeatureSelectionPreference = void 0;
@@ -1553,6 +1573,22 @@ exports.MediaModality = void 0;
1553
1573
  */
1554
1574
  MediaModality["DOCUMENT"] = "DOCUMENT";
1555
1575
  })(exports.MediaModality || (exports.MediaModality = {}));
1576
+ /** The type of the VAD signal. */
1577
+ exports.VadSignalType = void 0;
1578
+ (function (VadSignalType) {
1579
+ /**
1580
+ * The default is VAD_SIGNAL_TYPE_UNSPECIFIED.
1581
+ */
1582
+ VadSignalType["VAD_SIGNAL_TYPE_UNSPECIFIED"] = "VAD_SIGNAL_TYPE_UNSPECIFIED";
1583
+ /**
1584
+ * Start of sentence signal.
1585
+ */
1586
+ VadSignalType["VAD_SIGNAL_TYPE_SOS"] = "VAD_SIGNAL_TYPE_SOS";
1587
+ /**
1588
+ * End of sentence signal.
1589
+ */
1590
+ VadSignalType["VAD_SIGNAL_TYPE_EOS"] = "VAD_SIGNAL_TYPE_EOS";
1591
+ })(exports.VadSignalType || (exports.VadSignalType = {}));
1556
1592
  /** Start of speech sensitivity. */
1557
1593
  exports.StartSensitivity = void 0;
1558
1594
  (function (StartSensitivity) {
@@ -6223,6 +6259,18 @@ PERFORMANCE OF THIS SOFTWARE.
6223
6259
  /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
6224
6260
 
6225
6261
 
6262
+ function __rest(s, e) {
6263
+ var t = {};
6264
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
6265
+ t[p] = s[p];
6266
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6267
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
6268
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
6269
+ t[p[i]] = s[p[i]];
6270
+ }
6271
+ return t;
6272
+ }
6273
+
6226
6274
  function __values(o) {
6227
6275
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
6228
6276
  if (m) return m.call(o);
@@ -6849,7 +6897,7 @@ const CONTENT_TYPE_HEADER = 'Content-Type';
6849
6897
  const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
6850
6898
  const USER_AGENT_HEADER = 'User-Agent';
6851
6899
  const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
6852
- const SDK_VERSION = '1.32.0'; // x-release-please-version
6900
+ const SDK_VERSION = '1.34.0'; // x-release-please-version
6853
6901
  const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
6854
6902
  const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
6855
6903
  const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
@@ -6923,6 +6971,11 @@ class ApiClient {
6923
6971
  getLocation() {
6924
6972
  return this.clientOptions.location;
6925
6973
  }
6974
+ async getAuthHeaders() {
6975
+ const headers = new Headers();
6976
+ await this.clientOptions.auth.addAuthHeaders(headers);
6977
+ return headers;
6978
+ }
6926
6979
  getApiVersion() {
6927
6980
  if (this.clientOptions.httpOptions &&
6928
6981
  this.clientOptions.httpOptions.apiVersion !== undefined) {
@@ -7581,7 +7634,7 @@ async function uploadBlobInternal(file, uploadUrl, apiClient) {
7581
7634
  break;
7582
7635
  }
7583
7636
  retryCount++;
7584
- await sleep(currentDelayMs);
7637
+ await sleep$1(currentDelayMs);
7585
7638
  currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;
7586
7639
  }
7587
7640
  offset += chunkSize;
@@ -7602,7 +7655,7 @@ async function getBlobStat(file) {
7602
7655
  const fileStat = { size: file.size, type: file.type };
7603
7656
  return fileStat;
7604
7657
  }
7605
- function sleep(ms) {
7658
+ function sleep$1(ms) {
7606
7659
  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
7607
7660
  }
7608
7661
 
@@ -8272,218 +8325,2210 @@ class FileSearchStores extends BaseModule {
8272
8325
  return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName, params.file, params.config);
8273
8326
  }
8274
8327
  /**
8275
- * Creates a File Search Store.
8276
- *
8277
- * @param params - The parameters for creating a File Search Store.
8278
- * @return FileSearchStore.
8328
+ * Creates a File Search Store.
8329
+ *
8330
+ * @param params - The parameters for creating a File Search Store.
8331
+ * @return FileSearchStore.
8332
+ */
8333
+ async create(params) {
8334
+ var _a, _b;
8335
+ let response;
8336
+ let path = '';
8337
+ let queryParams = {};
8338
+ if (this.apiClient.isVertexAI()) {
8339
+ throw new Error('This method is only supported by the Gemini Developer API.');
8340
+ }
8341
+ else {
8342
+ const body = createFileSearchStoreParametersToMldev(params);
8343
+ path = formatMap('fileSearchStores', body['_url']);
8344
+ queryParams = body['_query'];
8345
+ delete body['_url'];
8346
+ delete body['_query'];
8347
+ response = this.apiClient
8348
+ .request({
8349
+ path: path,
8350
+ queryParams: queryParams,
8351
+ body: JSON.stringify(body),
8352
+ httpMethod: 'POST',
8353
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8354
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8355
+ })
8356
+ .then((httpResponse) => {
8357
+ return httpResponse.json();
8358
+ });
8359
+ return response.then((resp) => {
8360
+ return resp;
8361
+ });
8362
+ }
8363
+ }
8364
+ /**
8365
+ * Gets a File Search Store.
8366
+ *
8367
+ * @param params - The parameters for getting a File Search Store.
8368
+ * @return FileSearchStore.
8369
+ */
8370
+ async get(params) {
8371
+ var _a, _b;
8372
+ let response;
8373
+ let path = '';
8374
+ let queryParams = {};
8375
+ if (this.apiClient.isVertexAI()) {
8376
+ throw new Error('This method is only supported by the Gemini Developer API.');
8377
+ }
8378
+ else {
8379
+ const body = getFileSearchStoreParametersToMldev(params);
8380
+ path = formatMap('{name}', body['_url']);
8381
+ queryParams = body['_query'];
8382
+ delete body['_url'];
8383
+ delete body['_query'];
8384
+ response = this.apiClient
8385
+ .request({
8386
+ path: path,
8387
+ queryParams: queryParams,
8388
+ body: JSON.stringify(body),
8389
+ httpMethod: 'GET',
8390
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8391
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8392
+ })
8393
+ .then((httpResponse) => {
8394
+ return httpResponse.json();
8395
+ });
8396
+ return response.then((resp) => {
8397
+ return resp;
8398
+ });
8399
+ }
8400
+ }
8401
+ /**
8402
+ * Deletes a File Search Store.
8403
+ *
8404
+ * @param params - The parameters for deleting a File Search Store.
8405
+ */
8406
+ async delete(params) {
8407
+ var _a, _b;
8408
+ let path = '';
8409
+ let queryParams = {};
8410
+ if (this.apiClient.isVertexAI()) {
8411
+ throw new Error('This method is only supported by the Gemini Developer API.');
8412
+ }
8413
+ else {
8414
+ const body = deleteFileSearchStoreParametersToMldev(params);
8415
+ path = formatMap('{name}', body['_url']);
8416
+ queryParams = body['_query'];
8417
+ delete body['_url'];
8418
+ delete body['_query'];
8419
+ await this.apiClient.request({
8420
+ path: path,
8421
+ queryParams: queryParams,
8422
+ body: JSON.stringify(body),
8423
+ httpMethod: 'DELETE',
8424
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8425
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8426
+ });
8427
+ }
8428
+ }
8429
+ async listInternal(params) {
8430
+ var _a, _b;
8431
+ let response;
8432
+ let path = '';
8433
+ let queryParams = {};
8434
+ if (this.apiClient.isVertexAI()) {
8435
+ throw new Error('This method is only supported by the Gemini Developer API.');
8436
+ }
8437
+ else {
8438
+ const body = listFileSearchStoresParametersToMldev(params);
8439
+ path = formatMap('fileSearchStores', body['_url']);
8440
+ queryParams = body['_query'];
8441
+ delete body['_url'];
8442
+ delete body['_query'];
8443
+ response = this.apiClient
8444
+ .request({
8445
+ path: path,
8446
+ queryParams: queryParams,
8447
+ body: JSON.stringify(body),
8448
+ httpMethod: 'GET',
8449
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8450
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8451
+ })
8452
+ .then((httpResponse) => {
8453
+ return httpResponse.json();
8454
+ });
8455
+ return response.then((apiResponse) => {
8456
+ const resp = listFileSearchStoresResponseFromMldev(apiResponse);
8457
+ const typedResp = new ListFileSearchStoresResponse();
8458
+ Object.assign(typedResp, resp);
8459
+ return typedResp;
8460
+ });
8461
+ }
8462
+ }
8463
+ async uploadToFileSearchStoreInternal(params) {
8464
+ var _a, _b;
8465
+ let response;
8466
+ let path = '';
8467
+ let queryParams = {};
8468
+ if (this.apiClient.isVertexAI()) {
8469
+ throw new Error('This method is only supported by the Gemini Developer API.');
8470
+ }
8471
+ else {
8472
+ const body = uploadToFileSearchStoreParametersToMldev(params);
8473
+ path = formatMap('upload/v1beta/{file_search_store_name}:uploadToFileSearchStore', body['_url']);
8474
+ queryParams = body['_query'];
8475
+ delete body['_url'];
8476
+ delete body['_query'];
8477
+ response = this.apiClient
8478
+ .request({
8479
+ path: path,
8480
+ queryParams: queryParams,
8481
+ body: JSON.stringify(body),
8482
+ httpMethod: 'POST',
8483
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8484
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8485
+ })
8486
+ .then((httpResponse) => {
8487
+ return httpResponse.json();
8488
+ });
8489
+ return response.then((apiResponse) => {
8490
+ const resp = uploadToFileSearchStoreResumableResponseFromMldev(apiResponse);
8491
+ const typedResp = new UploadToFileSearchStoreResumableResponse();
8492
+ Object.assign(typedResp, resp);
8493
+ return typedResp;
8494
+ });
8495
+ }
8496
+ }
8497
+ /**
8498
+ * Imports a File from File Service to a FileSearchStore.
8499
+ *
8500
+ * This is a long-running operation, see aip.dev/151
8501
+ *
8502
+ * @param params - The parameters for importing a file to a file search store.
8503
+ * @return ImportFileOperation.
8504
+ */
8505
+ async importFile(params) {
8506
+ var _a, _b;
8507
+ let response;
8508
+ let path = '';
8509
+ let queryParams = {};
8510
+ if (this.apiClient.isVertexAI()) {
8511
+ throw new Error('This method is only supported by the Gemini Developer API.');
8512
+ }
8513
+ else {
8514
+ const body = importFileParametersToMldev(params);
8515
+ path = formatMap('{file_search_store_name}:importFile', body['_url']);
8516
+ queryParams = body['_query'];
8517
+ delete body['_url'];
8518
+ delete body['_query'];
8519
+ response = this.apiClient
8520
+ .request({
8521
+ path: path,
8522
+ queryParams: queryParams,
8523
+ body: JSON.stringify(body),
8524
+ httpMethod: 'POST',
8525
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8526
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8527
+ })
8528
+ .then((httpResponse) => {
8529
+ return httpResponse.json();
8530
+ });
8531
+ return response.then((apiResponse) => {
8532
+ const resp = importFileOperationFromMldev(apiResponse);
8533
+ const typedResp = new ImportFileOperation();
8534
+ Object.assign(typedResp, resp);
8535
+ return typedResp;
8536
+ });
8537
+ }
8538
+ }
8539
+ }
8540
+
8541
+ /**
8542
+ * @license
8543
+ * Copyright 2025 Google LLC
8544
+ * SPDX-License-Identifier: Apache-2.0
8545
+ */
8546
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8547
+ /**
8548
+ * https://stackoverflow.com/a/2117523
8549
+ */
8550
+ let uuid4Internal = function () {
8551
+ const { crypto } = globalThis;
8552
+ if (crypto === null || crypto === void 0 ? void 0 : crypto.randomUUID) {
8553
+ uuid4Internal = crypto.randomUUID.bind(crypto);
8554
+ return crypto.randomUUID();
8555
+ }
8556
+ const u8 = new Uint8Array(1);
8557
+ const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff;
8558
+ return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16));
8559
+ };
8560
+ const uuid4 = () => uuid4Internal();
8561
+
8562
+ /**
8563
+ * @license
8564
+ * Copyright 2025 Google LLC
8565
+ * SPDX-License-Identifier: Apache-2.0
8566
+ */
8567
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8568
+ function isAbortError(err) {
8569
+ return (typeof err === 'object' &&
8570
+ err !== null &&
8571
+ // Spec-compliant fetch implementations
8572
+ (('name' in err && err.name === 'AbortError') ||
8573
+ // Expo fetch
8574
+ ('message' in err && String(err.message).includes('FetchRequestCanceledException'))));
8575
+ }
8576
+ const castToError = (err) => {
8577
+ if (err instanceof Error)
8578
+ return err;
8579
+ if (typeof err === 'object' && err !== null) {
8580
+ try {
8581
+ if (Object.prototype.toString.call(err) === '[object Error]') {
8582
+ // @ts-ignore - not all envs have native support for cause yet
8583
+ const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
8584
+ if (err.stack)
8585
+ error.stack = err.stack;
8586
+ // @ts-ignore - not all envs have native support for cause yet
8587
+ if (err.cause && !error.cause)
8588
+ error.cause = err.cause;
8589
+ if (err.name)
8590
+ error.name = err.name;
8591
+ return error;
8592
+ }
8593
+ }
8594
+ catch (_a) { }
8595
+ try {
8596
+ return new Error(JSON.stringify(err));
8597
+ }
8598
+ catch (_b) { }
8599
+ }
8600
+ return new Error(err);
8601
+ };
8602
+
8603
+ /**
8604
+ * @license
8605
+ * Copyright 2025 Google LLC
8606
+ * SPDX-License-Identifier: Apache-2.0
8607
+ */
8608
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8609
+ class GeminiNextGenAPIClientError extends Error {
8610
+ }
8611
+ class APIError extends GeminiNextGenAPIClientError {
8612
+ constructor(status, error, message, headers) {
8613
+ super(`${APIError.makeMessage(status, error, message)}`);
8614
+ this.status = status;
8615
+ this.headers = headers;
8616
+ this.error = error;
8617
+ }
8618
+ static makeMessage(status, error, message) {
8619
+ const msg = (error === null || error === void 0 ? void 0 : error.message) ?
8620
+ typeof error.message === 'string' ?
8621
+ error.message
8622
+ : JSON.stringify(error.message)
8623
+ : error ? JSON.stringify(error)
8624
+ : message;
8625
+ if (status && msg) {
8626
+ return `${status} ${msg}`;
8627
+ }
8628
+ if (status) {
8629
+ return `${status} status code (no body)`;
8630
+ }
8631
+ if (msg) {
8632
+ return msg;
8633
+ }
8634
+ return '(no status code or body)';
8635
+ }
8636
+ static generate(status, errorResponse, message, headers) {
8637
+ if (!status || !headers) {
8638
+ return new APIConnectionError({ message, cause: castToError(errorResponse) });
8639
+ }
8640
+ const error = errorResponse;
8641
+ if (status === 400) {
8642
+ return new BadRequestError(status, error, message, headers);
8643
+ }
8644
+ if (status === 401) {
8645
+ return new AuthenticationError(status, error, message, headers);
8646
+ }
8647
+ if (status === 403) {
8648
+ return new PermissionDeniedError(status, error, message, headers);
8649
+ }
8650
+ if (status === 404) {
8651
+ return new NotFoundError(status, error, message, headers);
8652
+ }
8653
+ if (status === 409) {
8654
+ return new ConflictError(status, error, message, headers);
8655
+ }
8656
+ if (status === 422) {
8657
+ return new UnprocessableEntityError(status, error, message, headers);
8658
+ }
8659
+ if (status === 429) {
8660
+ return new RateLimitError(status, error, message, headers);
8661
+ }
8662
+ if (status >= 500) {
8663
+ return new InternalServerError(status, error, message, headers);
8664
+ }
8665
+ return new APIError(status, error, message, headers);
8666
+ }
8667
+ }
8668
+ class APIUserAbortError extends APIError {
8669
+ constructor({ message } = {}) {
8670
+ super(undefined, undefined, message || 'Request was aborted.', undefined);
8671
+ }
8672
+ }
8673
+ class APIConnectionError extends APIError {
8674
+ constructor({ message, cause }) {
8675
+ super(undefined, undefined, message || 'Connection error.', undefined);
8676
+ // in some environments the 'cause' property is already declared
8677
+ // @ts-ignore
8678
+ if (cause)
8679
+ this.cause = cause;
8680
+ }
8681
+ }
8682
+ class APIConnectionTimeoutError extends APIConnectionError {
8683
+ constructor({ message } = {}) {
8684
+ super({ message: message !== null && message !== void 0 ? message : 'Request timed out.' });
8685
+ }
8686
+ }
8687
+ class BadRequestError extends APIError {
8688
+ }
8689
+ class AuthenticationError extends APIError {
8690
+ }
8691
+ class PermissionDeniedError extends APIError {
8692
+ }
8693
+ class NotFoundError extends APIError {
8694
+ }
8695
+ class ConflictError extends APIError {
8696
+ }
8697
+ class UnprocessableEntityError extends APIError {
8698
+ }
8699
+ class RateLimitError extends APIError {
8700
+ }
8701
+ class InternalServerError extends APIError {
8702
+ }
8703
+
8704
+ /**
8705
+ * @license
8706
+ * Copyright 2025 Google LLC
8707
+ * SPDX-License-Identifier: Apache-2.0
8708
+ */
8709
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8710
+ // https://url.spec.whatwg.org/#url-scheme-string
8711
+ const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
8712
+ const isAbsoluteURL = (url) => {
8713
+ return startsWithSchemeRegexp.test(url);
8714
+ };
8715
+ let isArrayInternal = (val) => ((isArrayInternal = Array.isArray), isArrayInternal(val));
8716
+ const isArray = isArrayInternal;
8717
+ let isReadonlyArrayInternal = isArray;
8718
+ const isReadonlyArray = isReadonlyArrayInternal;
8719
+ // https://stackoverflow.com/a/34491287
8720
+ function isEmptyObj(obj) {
8721
+ if (!obj)
8722
+ return true;
8723
+ for (const _k in obj)
8724
+ return false;
8725
+ return true;
8726
+ }
8727
+ // https://eslint.org/docs/latest/rules/no-prototype-builtins
8728
+ function hasOwn(obj, key) {
8729
+ return Object.prototype.hasOwnProperty.call(obj, key);
8730
+ }
8731
+ const validatePositiveInteger = (name, n) => {
8732
+ if (typeof n !== 'number' || !Number.isInteger(n)) {
8733
+ throw new GeminiNextGenAPIClientError(`${name} must be an integer`);
8734
+ }
8735
+ if (n < 0) {
8736
+ throw new GeminiNextGenAPIClientError(`${name} must be a positive integer`);
8737
+ }
8738
+ return n;
8739
+ };
8740
+ const safeJSON = (text) => {
8741
+ try {
8742
+ return JSON.parse(text);
8743
+ }
8744
+ catch (err) {
8745
+ return undefined;
8746
+ }
8747
+ };
8748
+
8749
+ /**
8750
+ * @license
8751
+ * Copyright 2025 Google LLC
8752
+ * SPDX-License-Identifier: Apache-2.0
8753
+ */
8754
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8755
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8756
+
8757
+ /**
8758
+ * @license
8759
+ * Copyright 2025 Google LLC
8760
+ * SPDX-License-Identifier: Apache-2.0
8761
+ */
8762
+ const VERSION = '0.0.1';
8763
+
8764
+ /**
8765
+ * @license
8766
+ * Copyright 2025 Google LLC
8767
+ * SPDX-License-Identifier: Apache-2.0
8768
+ */
8769
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8770
+ /**
8771
+ * Note this does not detect 'browser'; for that, use getBrowserInfo().
8772
+ */
8773
+ function getDetectedPlatform() {
8774
+ if (typeof Deno !== 'undefined' && Deno.build != null) {
8775
+ return 'deno';
8776
+ }
8777
+ if (typeof EdgeRuntime !== 'undefined') {
8778
+ return 'edge';
8779
+ }
8780
+ if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') {
8781
+ return 'node';
8782
+ }
8783
+ return 'unknown';
8784
+ }
8785
+ const getPlatformProperties = () => {
8786
+ var _a, _b, _c, _d, _e;
8787
+ const detectedPlatform = getDetectedPlatform();
8788
+ if (detectedPlatform === 'deno') {
8789
+ return {
8790
+ 'X-Stainless-Lang': 'js',
8791
+ 'X-Stainless-Package-Version': VERSION,
8792
+ 'X-Stainless-OS': normalizePlatform(Deno.build.os),
8793
+ 'X-Stainless-Arch': normalizeArch(Deno.build.arch),
8794
+ 'X-Stainless-Runtime': 'deno',
8795
+ 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : (_b = (_a = Deno.version) === null || _a === void 0 ? void 0 : _a.deno) !== null && _b !== void 0 ? _b : 'unknown',
8796
+ };
8797
+ }
8798
+ if (typeof EdgeRuntime !== 'undefined') {
8799
+ return {
8800
+ 'X-Stainless-Lang': 'js',
8801
+ 'X-Stainless-Package-Version': VERSION,
8802
+ 'X-Stainless-OS': 'Unknown',
8803
+ 'X-Stainless-Arch': `other:${EdgeRuntime}`,
8804
+ 'X-Stainless-Runtime': 'edge',
8805
+ 'X-Stainless-Runtime-Version': globalThis.process.version,
8806
+ };
8807
+ }
8808
+ // Check if Node.js
8809
+ if (detectedPlatform === 'node') {
8810
+ return {
8811
+ 'X-Stainless-Lang': 'js',
8812
+ 'X-Stainless-Package-Version': VERSION,
8813
+ 'X-Stainless-OS': normalizePlatform((_c = globalThis.process.platform) !== null && _c !== void 0 ? _c : 'unknown'),
8814
+ 'X-Stainless-Arch': normalizeArch((_d = globalThis.process.arch) !== null && _d !== void 0 ? _d : 'unknown'),
8815
+ 'X-Stainless-Runtime': 'node',
8816
+ 'X-Stainless-Runtime-Version': (_e = globalThis.process.version) !== null && _e !== void 0 ? _e : 'unknown',
8817
+ };
8818
+ }
8819
+ const browserInfo = getBrowserInfo();
8820
+ if (browserInfo) {
8821
+ return {
8822
+ 'X-Stainless-Lang': 'js',
8823
+ 'X-Stainless-Package-Version': VERSION,
8824
+ 'X-Stainless-OS': 'Unknown',
8825
+ 'X-Stainless-Arch': 'unknown',
8826
+ 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
8827
+ 'X-Stainless-Runtime-Version': browserInfo.version,
8828
+ };
8829
+ }
8830
+ // TODO add support for Cloudflare workers, etc.
8831
+ return {
8832
+ 'X-Stainless-Lang': 'js',
8833
+ 'X-Stainless-Package-Version': VERSION,
8834
+ 'X-Stainless-OS': 'Unknown',
8835
+ 'X-Stainless-Arch': 'unknown',
8836
+ 'X-Stainless-Runtime': 'unknown',
8837
+ 'X-Stainless-Runtime-Version': 'unknown',
8838
+ };
8839
+ };
8840
+ // Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
8841
+ function getBrowserInfo() {
8842
+ if (typeof navigator === 'undefined' || !navigator) {
8843
+ return null;
8844
+ }
8845
+ // NOTE: The order matters here!
8846
+ const browserPatterns = [
8847
+ { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
8848
+ { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
8849
+ { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
8850
+ { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
8851
+ { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
8852
+ { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
8853
+ ];
8854
+ // Find the FIRST matching browser
8855
+ for (const { key, pattern } of browserPatterns) {
8856
+ const match = pattern.exec(navigator.userAgent);
8857
+ if (match) {
8858
+ const major = match[1] || 0;
8859
+ const minor = match[2] || 0;
8860
+ const patch = match[3] || 0;
8861
+ return { browser: key, version: `${major}.${minor}.${patch}` };
8862
+ }
8863
+ }
8864
+ return null;
8865
+ }
8866
+ const normalizeArch = (arch) => {
8867
+ // Node docs:
8868
+ // - https://nodejs.org/api/process.html#processarch
8869
+ // Deno docs:
8870
+ // - https://doc.deno.land/deno/stable/~/Deno.build
8871
+ if (arch === 'x32')
8872
+ return 'x32';
8873
+ if (arch === 'x86_64' || arch === 'x64')
8874
+ return 'x64';
8875
+ if (arch === 'arm')
8876
+ return 'arm';
8877
+ if (arch === 'aarch64' || arch === 'arm64')
8878
+ return 'arm64';
8879
+ if (arch)
8880
+ return `other:${arch}`;
8881
+ return 'unknown';
8882
+ };
8883
+ const normalizePlatform = (platform) => {
8884
+ // Node platforms:
8885
+ // - https://nodejs.org/api/process.html#processplatform
8886
+ // Deno platforms:
8887
+ // - https://doc.deno.land/deno/stable/~/Deno.build
8888
+ // - https://github.com/denoland/deno/issues/14799
8889
+ platform = platform.toLowerCase();
8890
+ // NOTE: this iOS check is untested and may not work
8891
+ // Node does not work natively on IOS, there is a fork at
8892
+ // https://github.com/nodejs-mobile/nodejs-mobile
8893
+ // however it is unknown at the time of writing how to detect if it is running
8894
+ if (platform.includes('ios'))
8895
+ return 'iOS';
8896
+ if (platform === 'android')
8897
+ return 'Android';
8898
+ if (platform === 'darwin')
8899
+ return 'MacOS';
8900
+ if (platform === 'win32')
8901
+ return 'Windows';
8902
+ if (platform === 'freebsd')
8903
+ return 'FreeBSD';
8904
+ if (platform === 'openbsd')
8905
+ return 'OpenBSD';
8906
+ if (platform === 'linux')
8907
+ return 'Linux';
8908
+ if (platform)
8909
+ return `Other:${platform}`;
8910
+ return 'Unknown';
8911
+ };
8912
+ let _platformHeaders;
8913
+ const getPlatformHeaders = () => {
8914
+ return (_platformHeaders !== null && _platformHeaders !== void 0 ? _platformHeaders : (_platformHeaders = getPlatformProperties()));
8915
+ };
8916
+
8917
+ /**
8918
+ * @license
8919
+ * Copyright 2025 Google LLC
8920
+ * SPDX-License-Identifier: Apache-2.0
8921
+ */
8922
+ function getDefaultFetch() {
8923
+ if (typeof fetch !== 'undefined') {
8924
+ return fetch;
8925
+ }
8926
+ throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`');
8927
+ }
8928
+ function makeReadableStream(...args) {
8929
+ const ReadableStream = globalThis.ReadableStream;
8930
+ if (typeof ReadableStream === 'undefined') {
8931
+ // Note: All of the platforms / runtimes we officially support already define
8932
+ // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.
8933
+ throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`');
8934
+ }
8935
+ return new ReadableStream(...args);
8936
+ }
8937
+ function ReadableStreamFrom(iterable) {
8938
+ let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
8939
+ return makeReadableStream({
8940
+ start() { },
8941
+ async pull(controller) {
8942
+ const { done, value } = await iter.next();
8943
+ if (done) {
8944
+ controller.close();
8945
+ }
8946
+ else {
8947
+ controller.enqueue(value);
8948
+ }
8949
+ },
8950
+ async cancel() {
8951
+ var _a;
8952
+ await ((_a = iter.return) === null || _a === void 0 ? void 0 : _a.call(iter));
8953
+ },
8954
+ });
8955
+ }
8956
+ /**
8957
+ * Most browsers don't yet have async iterable support for ReadableStream,
8958
+ * and Node has a very different way of reading bytes from its "ReadableStream".
8959
+ *
8960
+ * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
8961
+ */
8962
+ function ReadableStreamToAsyncIterable(stream) {
8963
+ if (stream[Symbol.asyncIterator])
8964
+ return stream;
8965
+ const reader = stream.getReader();
8966
+ return {
8967
+ async next() {
8968
+ try {
8969
+ const result = await reader.read();
8970
+ if (result === null || result === void 0 ? void 0 : result.done)
8971
+ reader.releaseLock(); // release lock when stream becomes closed
8972
+ return result;
8973
+ }
8974
+ catch (e) {
8975
+ reader.releaseLock(); // release lock when stream becomes errored
8976
+ throw e;
8977
+ }
8978
+ },
8979
+ async return() {
8980
+ const cancelPromise = reader.cancel();
8981
+ reader.releaseLock();
8982
+ await cancelPromise;
8983
+ return { done: true, value: undefined };
8984
+ },
8985
+ [Symbol.asyncIterator]() {
8986
+ return this;
8987
+ },
8988
+ };
8989
+ }
8990
+ /**
8991
+ * Cancels a ReadableStream we don't need to consume.
8992
+ * See https://undici.nodejs.org/#/?id=garbage-collection
8993
+ */
8994
+ async function CancelReadableStream(stream) {
8995
+ var _a, _b;
8996
+ if (stream === null || typeof stream !== 'object')
8997
+ return;
8998
+ if (stream[Symbol.asyncIterator]) {
8999
+ await ((_b = (_a = stream[Symbol.asyncIterator]()).return) === null || _b === void 0 ? void 0 : _b.call(_a));
9000
+ return;
9001
+ }
9002
+ const reader = stream.getReader();
9003
+ const cancelPromise = reader.cancel();
9004
+ reader.releaseLock();
9005
+ await cancelPromise;
9006
+ }
9007
+
9008
+ /**
9009
+ * @license
9010
+ * Copyright 2025 Google LLC
9011
+ * SPDX-License-Identifier: Apache-2.0
9012
+ */
9013
+ const FallbackEncoder = ({ headers, body }) => {
9014
+ return {
9015
+ bodyHeaders: {
9016
+ 'content-type': 'application/json',
9017
+ },
9018
+ body: JSON.stringify(body),
9019
+ };
9020
+ };
9021
+
9022
+ /**
9023
+ * @license
9024
+ * Copyright 2025 Google LLC
9025
+ * SPDX-License-Identifier: Apache-2.0
9026
+ */
9027
+ const checkFileSupport = () => {
9028
+ var _a;
9029
+ if (typeof File === 'undefined') {
9030
+ const { process } = globalThis;
9031
+ const isOldNode = typeof ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) === 'string' && parseInt(process.versions.node.split('.')) < 20;
9032
+ throw new Error('`File` is not defined as a global, which is required for file uploads.' +
9033
+ (isOldNode ?
9034
+ " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`."
9035
+ : ''));
9036
+ }
9037
+ };
9038
+ /**
9039
+ * Construct a `File` instance. This is used to ensure a helpful error is thrown
9040
+ * for environments that don't define a global `File` yet.
9041
+ */
9042
+ function makeFile(fileBits, fileName, options) {
9043
+ checkFileSupport();
9044
+ return new File(fileBits, fileName !== null && fileName !== void 0 ? fileName : 'unknown_file', options);
9045
+ }
9046
+ function getName(value) {
9047
+ return (((typeof value === 'object' &&
9048
+ value !== null &&
9049
+ (('name' in value && value.name && String(value.name)) ||
9050
+ ('url' in value && value.url && String(value.url)) ||
9051
+ ('filename' in value && value.filename && String(value.filename)) ||
9052
+ ('path' in value && value.path && String(value.path)))) ||
9053
+ '')
9054
+ .split(/[\\/]/)
9055
+ .pop() || undefined);
9056
+ }
9057
+ const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
9058
+
9059
+ /**
9060
+ * @license
9061
+ * Copyright 2025 Google LLC
9062
+ * SPDX-License-Identifier: Apache-2.0
9063
+ */
9064
+ /**
9065
+ * This check adds the arrayBuffer() method type because it is available and used at runtime
9066
+ */
9067
+ const isBlobLike = (value) => value != null &&
9068
+ typeof value === 'object' &&
9069
+ typeof value.size === 'number' &&
9070
+ typeof value.type === 'string' &&
9071
+ typeof value.text === 'function' &&
9072
+ typeof value.slice === 'function' &&
9073
+ typeof value.arrayBuffer === 'function';
9074
+ /**
9075
+ * This check adds the arrayBuffer() method type because it is available and used at runtime
9076
+ */
9077
+ const isFileLike = (value) => value != null &&
9078
+ typeof value === 'object' &&
9079
+ typeof value.name === 'string' &&
9080
+ typeof value.lastModified === 'number' &&
9081
+ isBlobLike(value);
9082
+ const isResponseLike = (value) => value != null &&
9083
+ typeof value === 'object' &&
9084
+ typeof value.url === 'string' &&
9085
+ typeof value.blob === 'function';
9086
+ /**
9087
+ * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
9088
+ * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts
9089
+ * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
9090
+ * @param {Object=} options additional properties
9091
+ * @param {string=} options.type the MIME type of the content
9092
+ * @param {number=} options.lastModified the last modified timestamp
9093
+ * @returns a {@link File} with the given properties
9094
+ */
9095
+ async function toFile(value, name, options) {
9096
+ checkFileSupport();
9097
+ // If it's a promise, resolve it.
9098
+ value = await value;
9099
+ // If we've been given a `File` we don't need to do anything
9100
+ if (isFileLike(value)) {
9101
+ if (value instanceof File) {
9102
+ return value;
9103
+ }
9104
+ return makeFile([await value.arrayBuffer()], value.name);
9105
+ }
9106
+ if (isResponseLike(value)) {
9107
+ const blob = await value.blob();
9108
+ name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
9109
+ return makeFile(await getBytes(blob), name, options);
9110
+ }
9111
+ const parts = await getBytes(value);
9112
+ name || (name = getName(value));
9113
+ if (!(options === null || options === void 0 ? void 0 : options.type)) {
9114
+ const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);
9115
+ if (typeof type === 'string') {
9116
+ options = Object.assign(Object.assign({}, options), { type });
9117
+ }
9118
+ }
9119
+ return makeFile(parts, name, options);
9120
+ }
9121
+ async function getBytes(value) {
9122
+ var _a, e_1, _b, _c;
9123
+ var _d;
9124
+ let parts = [];
9125
+ if (typeof value === 'string' ||
9126
+ ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
9127
+ value instanceof ArrayBuffer) {
9128
+ parts.push(value);
9129
+ }
9130
+ else if (isBlobLike(value)) {
9131
+ parts.push(value instanceof Blob ? value : await value.arrayBuffer());
9132
+ }
9133
+ else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc.
9134
+ ) {
9135
+ try {
9136
+ for (var _e = true, value_1 = __asyncValues(value), value_1_1; value_1_1 = await value_1.next(), _a = value_1_1.done, !_a; _e = true) {
9137
+ _c = value_1_1.value;
9138
+ _e = false;
9139
+ const chunk = _c;
9140
+ parts.push(...(await getBytes(chunk))); // TODO, consider validating?
9141
+ }
9142
+ }
9143
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
9144
+ finally {
9145
+ try {
9146
+ if (!_e && !_a && (_b = value_1.return)) await _b.call(value_1);
9147
+ }
9148
+ finally { if (e_1) throw e_1.error; }
9149
+ }
9150
+ }
9151
+ else {
9152
+ const constructor = (_d = value === null || value === void 0 ? void 0 : value.constructor) === null || _d === void 0 ? void 0 : _d.name;
9153
+ throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`);
9154
+ }
9155
+ return parts;
9156
+ }
9157
+ function propsForError(value) {
9158
+ if (typeof value !== 'object' || value === null)
9159
+ return '';
9160
+ const props = Object.getOwnPropertyNames(value);
9161
+ return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`;
9162
+ }
9163
+
9164
+ /**
9165
+ * @license
9166
+ * Copyright 2025 Google LLC
9167
+ * SPDX-License-Identifier: Apache-2.0
9168
+ */
9169
+ class APIResource {
9170
+ constructor(client) {
9171
+ this._client = client;
9172
+ }
9173
+ }
9174
+ /**
9175
+ * The key path from the client. For example, a resource accessible as `client.resource.subresource` would
9176
+ * have a property `static override readonly _key = Object.freeze(['resource', 'subresource'] as const);`.
9177
+ */
9178
+ APIResource._key = [];
9179
+
9180
+ /**
9181
+ * @license
9182
+ * Copyright 2025 Google LLC
9183
+ * SPDX-License-Identifier: Apache-2.0
9184
+ */
9185
+ /**
9186
+ * Percent-encode everything that isn't safe to have in a path without encoding safe chars.
9187
+ *
9188
+ * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3:
9189
+ * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
9190
+ * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
9191
+ * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
9192
+ */
9193
+ function encodeURIPath(str) {
9194
+ return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
9195
+ }
9196
+ const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
9197
+ const createPathTagFunction = (pathEncoder = encodeURIPath) => (function path(statics, ...params) {
9198
+ // If there are no params, no processing is needed.
9199
+ if (statics.length === 1)
9200
+ return statics[0];
9201
+ let postPath = false;
9202
+ const invalidSegments = [];
9203
+ const path = statics.reduce((previousValue, currentValue, index) => {
9204
+ var _a, _b, _c;
9205
+ if (/[?#]/.test(currentValue)) {
9206
+ postPath = true;
9207
+ }
9208
+ const value = params[index];
9209
+ let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);
9210
+ if (index !== params.length &&
9211
+ (value == null ||
9212
+ (typeof value === 'object' &&
9213
+ // handle values from other realms
9214
+ value.toString ===
9215
+ ((_c = Object.getPrototypeOf((_b = Object.getPrototypeOf((_a = value.hasOwnProperty) !== null && _a !== void 0 ? _a : EMPTY)) !== null && _b !== void 0 ? _b : EMPTY)) === null || _c === void 0 ? void 0 : _c.toString)))) {
9216
+ encoded = value + '';
9217
+ invalidSegments.push({
9218
+ start: previousValue.length + currentValue.length,
9219
+ length: encoded.length,
9220
+ error: `Value of type ${Object.prototype.toString
9221
+ .call(value)
9222
+ .slice(8, -1)} is not a valid path parameter`,
9223
+ });
9224
+ }
9225
+ return previousValue + currentValue + (index === params.length ? '' : encoded);
9226
+ }, '');
9227
+ const pathOnly = path.split(/[?#]/, 1)[0];
9228
+ const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
9229
+ let match;
9230
+ // Find all invalid segments
9231
+ while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
9232
+ invalidSegments.push({
9233
+ start: match.index,
9234
+ length: match[0].length,
9235
+ error: `Value "${match[0]}" can\'t be safely passed as a path parameter`,
9236
+ });
9237
+ }
9238
+ invalidSegments.sort((a, b) => a.start - b.start);
9239
+ if (invalidSegments.length > 0) {
9240
+ let lastEnd = 0;
9241
+ const underline = invalidSegments.reduce((acc, segment) => {
9242
+ const spaces = ' '.repeat(segment.start - lastEnd);
9243
+ const arrows = '^'.repeat(segment.length);
9244
+ lastEnd = segment.start + segment.length;
9245
+ return acc + spaces + arrows;
9246
+ }, '');
9247
+ throw new GeminiNextGenAPIClientError(`Path parameters result in path with invalid segments:\n${invalidSegments
9248
+ .map((e) => e.error)
9249
+ .join('\n')}\n${path}\n${underline}`);
9250
+ }
9251
+ return path;
9252
+ });
9253
+ /**
9254
+ * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced.
9255
+ */
9256
+ const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
9257
+
9258
+ /**
9259
+ * @license
9260
+ * Copyright 2025 Google LLC
9261
+ * SPDX-License-Identifier: Apache-2.0
9262
+ */
9263
+ class BaseInteractions extends APIResource {
9264
+ create(params, options) {
9265
+ var _a;
9266
+ const { api_version = this._client.apiVersion } = params, body = __rest(params, ["api_version"]);
9267
+ if ('model' in body && 'agent_config' in body) {
9268
+ throw new GeminiNextGenAPIClientError(`Invalid request: specified \`model\` and \`agent_config\`. If specifying \`model\`, use \`generation_config\`.`);
9269
+ }
9270
+ if ('agent' in body && 'generation_config' in body) {
9271
+ throw new GeminiNextGenAPIClientError(`Invalid request: specified \`agent\` and \`generation_config\`. If specifying \`agent\`, use \`agent_config\`.`);
9272
+ }
9273
+ return this._client.post(path `/${api_version}/interactions`, Object.assign(Object.assign({ body }, options), { stream: (_a = params.stream) !== null && _a !== void 0 ? _a : false }));
9274
+ }
9275
+ /**
9276
+ * Deletes the interaction by id.
9277
+ *
9278
+ * @example
9279
+ * ```ts
9280
+ * const interaction = await client.interactions.delete('id');
9281
+ * ```
9282
+ */
9283
+ delete(id, params = {}, options) {
9284
+ const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
9285
+ return this._client.delete(path `/${api_version}/interactions/${id}`, options);
9286
+ }
9287
+ /**
9288
+ * Cancels an interaction by id. This only applies to background interactions that are still running.
9289
+ *
9290
+ * @example
9291
+ * ```ts
9292
+ * const interaction = await client.interactions.cancel('id');
9293
+ * ```
9294
+ */
9295
+ cancel(id, params = {}, options) {
9296
+ const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
9297
+ return this._client.post(path `/${api_version}/interactions/${id}/cancel`, options);
9298
+ }
9299
+ get(id, params = {}, options) {
9300
+ var _a;
9301
+ const _b = params !== null && params !== void 0 ? params : {}, { api_version = this._client.apiVersion } = _b, query = __rest(_b, ["api_version"]);
9302
+ return this._client.get(path `/${api_version}/interactions/${id}`, Object.assign(Object.assign({ query }, options), { stream: (_a = params === null || params === void 0 ? void 0 : params.stream) !== null && _a !== void 0 ? _a : false }));
9303
+ }
9304
+ }
9305
+ BaseInteractions._key = Object.freeze(['interactions']);
9306
+ class Interactions extends BaseInteractions {
9307
+ }
9308
+
9309
+ /**
9310
+ * @license
9311
+ * Copyright 2025 Google LLC
9312
+ * SPDX-License-Identifier: Apache-2.0
9313
+ */
9314
+ function concatBytes(buffers) {
9315
+ let length = 0;
9316
+ for (const buffer of buffers) {
9317
+ length += buffer.length;
9318
+ }
9319
+ const output = new Uint8Array(length);
9320
+ let index = 0;
9321
+ for (const buffer of buffers) {
9322
+ output.set(buffer, index);
9323
+ index += buffer.length;
9324
+ }
9325
+ return output;
9326
+ }
9327
+ let encodeUTF8_;
9328
+ function encodeUTF8(str) {
9329
+ let encoder;
9330
+ return (encodeUTF8_ !== null && encodeUTF8_ !== void 0 ? encodeUTF8_ : ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str);
9331
+ }
9332
+ let decodeUTF8_;
9333
+ function decodeUTF8(bytes) {
9334
+ let decoder;
9335
+ return (decodeUTF8_ !== null && decodeUTF8_ !== void 0 ? decodeUTF8_ : ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes);
9336
+ }
9337
+
9338
+ /**
9339
+ * @license
9340
+ * Copyright 2025 Google LLC
9341
+ * SPDX-License-Identifier: Apache-2.0
9342
+ */
9343
+ /**
9344
+ * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
9345
+ * reading lines from text.
9346
+ *
9347
+ * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
9348
+ */
9349
+ class LineDecoder {
9350
+ constructor() {
9351
+ this.buffer = new Uint8Array();
9352
+ this.carriageReturnIndex = null;
9353
+ }
9354
+ decode(chunk) {
9355
+ if (chunk == null) {
9356
+ return [];
9357
+ }
9358
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
9359
+ : typeof chunk === 'string' ? encodeUTF8(chunk)
9360
+ : chunk;
9361
+ this.buffer = concatBytes([this.buffer, binaryChunk]);
9362
+ const lines = [];
9363
+ let patternIndex;
9364
+ while ((patternIndex = findNewlineIndex(this.buffer, this.carriageReturnIndex)) != null) {
9365
+ if (patternIndex.carriage && this.carriageReturnIndex == null) {
9366
+ // skip until we either get a corresponding `\n`, a new `\r` or nothing
9367
+ this.carriageReturnIndex = patternIndex.index;
9368
+ continue;
9369
+ }
9370
+ // we got double \r or \rtext\n
9371
+ if (this.carriageReturnIndex != null &&
9372
+ (patternIndex.index !== this.carriageReturnIndex + 1 || patternIndex.carriage)) {
9373
+ lines.push(decodeUTF8(this.buffer.subarray(0, this.carriageReturnIndex - 1)));
9374
+ this.buffer = this.buffer.subarray(this.carriageReturnIndex);
9375
+ this.carriageReturnIndex = null;
9376
+ continue;
9377
+ }
9378
+ const endIndex = this.carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
9379
+ const line = decodeUTF8(this.buffer.subarray(0, endIndex));
9380
+ lines.push(line);
9381
+ this.buffer = this.buffer.subarray(patternIndex.index);
9382
+ this.carriageReturnIndex = null;
9383
+ }
9384
+ return lines;
9385
+ }
9386
+ flush() {
9387
+ if (!this.buffer.length) {
9388
+ return [];
9389
+ }
9390
+ return this.decode('\n');
9391
+ }
9392
+ }
9393
+ // prettier-ignore
9394
+ LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
9395
+ LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
9396
+ /**
9397
+ * This function searches the buffer for the end patterns, (\r or \n)
9398
+ * and returns an object with the index preceding the matched newline and the
9399
+ * index after the newline char. `null` is returned if no new line is found.
9400
+ *
9401
+ * ```ts
9402
+ * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
9403
+ * ```
9404
+ */
9405
+ function findNewlineIndex(buffer, startIndex) {
9406
+ const newline = 0x0a; // \n
9407
+ const carriage = 0x0d; // \r
9408
+ for (let i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < buffer.length; i++) {
9409
+ if (buffer[i] === newline) {
9410
+ return { preceding: i, index: i + 1, carriage: false };
9411
+ }
9412
+ if (buffer[i] === carriage) {
9413
+ return { preceding: i, index: i + 1, carriage: true };
9414
+ }
9415
+ }
9416
+ return null;
9417
+ }
9418
+ function findDoubleNewlineIndex(buffer) {
9419
+ // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
9420
+ // and returns the index right after the first occurrence of any pattern,
9421
+ // or -1 if none of the patterns are found.
9422
+ const newline = 0x0a; // \n
9423
+ const carriage = 0x0d; // \r
9424
+ for (let i = 0; i < buffer.length - 1; i++) {
9425
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
9426
+ // \n\n
9427
+ return i + 2;
9428
+ }
9429
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
9430
+ // \r\r
9431
+ return i + 2;
9432
+ }
9433
+ if (buffer[i] === carriage &&
9434
+ buffer[i + 1] === newline &&
9435
+ i + 3 < buffer.length &&
9436
+ buffer[i + 2] === carriage &&
9437
+ buffer[i + 3] === newline) {
9438
+ // \r\n\r\n
9439
+ return i + 4;
9440
+ }
9441
+ }
9442
+ return -1;
9443
+ }
9444
+
9445
+ /**
9446
+ * @license
9447
+ * Copyright 2025 Google LLC
9448
+ * SPDX-License-Identifier: Apache-2.0
9449
+ */
9450
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9451
+ const levelNumbers = {
9452
+ off: 0,
9453
+ error: 200,
9454
+ warn: 300,
9455
+ info: 400,
9456
+ debug: 500,
9457
+ };
9458
+ const parseLogLevel = (maybeLevel, sourceName, client) => {
9459
+ if (!maybeLevel) {
9460
+ return undefined;
9461
+ }
9462
+ if (hasOwn(levelNumbers, maybeLevel)) {
9463
+ return maybeLevel;
9464
+ }
9465
+ loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
9466
+ return undefined;
9467
+ };
9468
+ function noop() { }
9469
+ function makeLogFn(fnLevel, logger, logLevel) {
9470
+ if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
9471
+ return noop;
9472
+ }
9473
+ else {
9474
+ // Don't wrap logger functions, we want the stacktrace intact!
9475
+ return logger[fnLevel].bind(logger);
9476
+ }
9477
+ }
9478
+ const noopLogger = {
9479
+ error: noop,
9480
+ warn: noop,
9481
+ info: noop,
9482
+ debug: noop,
9483
+ };
9484
+ let cachedLoggers = /* @__PURE__ */ new WeakMap();
9485
+ function loggerFor(client) {
9486
+ var _a;
9487
+ const logger = client.logger;
9488
+ const logLevel = (_a = client.logLevel) !== null && _a !== void 0 ? _a : 'off';
9489
+ if (!logger) {
9490
+ return noopLogger;
9491
+ }
9492
+ const cachedLogger = cachedLoggers.get(logger);
9493
+ if (cachedLogger && cachedLogger[0] === logLevel) {
9494
+ return cachedLogger[1];
9495
+ }
9496
+ const levelLogger = {
9497
+ error: makeLogFn('error', logger, logLevel),
9498
+ warn: makeLogFn('warn', logger, logLevel),
9499
+ info: makeLogFn('info', logger, logLevel),
9500
+ debug: makeLogFn('debug', logger, logLevel),
9501
+ };
9502
+ cachedLoggers.set(logger, [logLevel, levelLogger]);
9503
+ return levelLogger;
9504
+ }
9505
+ const formatRequestDetails = (details) => {
9506
+ if (details.options) {
9507
+ details.options = Object.assign({}, details.options);
9508
+ delete details.options['headers']; // redundant + leaks internals
9509
+ }
9510
+ if (details.headers) {
9511
+ details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
9512
+ name,
9513
+ (name.toLowerCase() === 'x-goog-api-key' ||
9514
+ name.toLowerCase() === 'authorization' ||
9515
+ name.toLowerCase() === 'cookie' ||
9516
+ name.toLowerCase() === 'set-cookie') ?
9517
+ '***'
9518
+ : value,
9519
+ ]));
9520
+ }
9521
+ if ('retryOfRequestLogID' in details) {
9522
+ if (details.retryOfRequestLogID) {
9523
+ details.retryOf = details.retryOfRequestLogID;
9524
+ }
9525
+ delete details.retryOfRequestLogID;
9526
+ }
9527
+ return details;
9528
+ };
9529
+
9530
+ /**
9531
+ * @license
9532
+ * Copyright 2025 Google LLC
9533
+ * SPDX-License-Identifier: Apache-2.0
9534
+ */
9535
+ class Stream {
9536
+ constructor(iterator, controller, client) {
9537
+ this.iterator = iterator;
9538
+ this.controller = controller;
9539
+ this.client = client;
9540
+ }
9541
+ static fromSSEResponse(response, controller, client) {
9542
+ let consumed = false;
9543
+ const logger = client ? loggerFor(client) : console;
9544
+ function iterator() {
9545
+ return __asyncGenerator(this, arguments, function* iterator_1() {
9546
+ var _a, e_1, _b, _c;
9547
+ if (consumed) {
9548
+ throw new GeminiNextGenAPIClientError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
9549
+ }
9550
+ consumed = true;
9551
+ let done = false;
9552
+ try {
9553
+ try {
9554
+ for (var _d = true, _e = __asyncValues(_iterSSEMessages(response, controller)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
9555
+ _c = _f.value;
9556
+ _d = false;
9557
+ const sse = _c;
9558
+ if (done)
9559
+ continue;
9560
+ if (sse.data.startsWith('[DONE]')) {
9561
+ done = true;
9562
+ continue;
9563
+ }
9564
+ else {
9565
+ try {
9566
+ // @ts-ignore
9567
+ yield yield __await(JSON.parse(sse.data));
9568
+ }
9569
+ catch (e) {
9570
+ logger.error(`Could not parse message into JSON:`, sse.data);
9571
+ logger.error(`From chunk:`, sse.raw);
9572
+ throw e;
9573
+ }
9574
+ }
9575
+ }
9576
+ }
9577
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
9578
+ finally {
9579
+ try {
9580
+ if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
9581
+ }
9582
+ finally { if (e_1) throw e_1.error; }
9583
+ }
9584
+ done = true;
9585
+ }
9586
+ catch (e) {
9587
+ // If the user calls `stream.controller.abort()`, we should exit without throwing.
9588
+ if (isAbortError(e))
9589
+ return yield __await(void 0);
9590
+ throw e;
9591
+ }
9592
+ finally {
9593
+ // If the user `break`s, abort the ongoing request.
9594
+ if (!done)
9595
+ controller.abort();
9596
+ }
9597
+ });
9598
+ }
9599
+ return new Stream(iterator, controller, client);
9600
+ }
9601
+ /**
9602
+ * Generates a Stream from a newline-separated ReadableStream
9603
+ * where each item is a JSON value.
9604
+ */
9605
+ static fromReadableStream(readableStream, controller, client) {
9606
+ let consumed = false;
9607
+ function iterLines() {
9608
+ return __asyncGenerator(this, arguments, function* iterLines_1() {
9609
+ var _a, e_2, _b, _c;
9610
+ const lineDecoder = new LineDecoder();
9611
+ const iter = ReadableStreamToAsyncIterable(readableStream);
9612
+ try {
9613
+ for (var _d = true, iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = yield __await(iter_1.next()), _a = iter_1_1.done, !_a; _d = true) {
9614
+ _c = iter_1_1.value;
9615
+ _d = false;
9616
+ const chunk = _c;
9617
+ for (const line of lineDecoder.decode(chunk)) {
9618
+ yield yield __await(line);
9619
+ }
9620
+ }
9621
+ }
9622
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
9623
+ finally {
9624
+ try {
9625
+ if (!_d && !_a && (_b = iter_1.return)) yield __await(_b.call(iter_1));
9626
+ }
9627
+ finally { if (e_2) throw e_2.error; }
9628
+ }
9629
+ for (const line of lineDecoder.flush()) {
9630
+ yield yield __await(line);
9631
+ }
9632
+ });
9633
+ }
9634
+ function iterator() {
9635
+ return __asyncGenerator(this, arguments, function* iterator_2() {
9636
+ var _a, e_3, _b, _c;
9637
+ if (consumed) {
9638
+ throw new GeminiNextGenAPIClientError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
9639
+ }
9640
+ consumed = true;
9641
+ let done = false;
9642
+ try {
9643
+ try {
9644
+ for (var _d = true, _e = __asyncValues(iterLines()), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
9645
+ _c = _f.value;
9646
+ _d = false;
9647
+ const line = _c;
9648
+ if (done)
9649
+ continue;
9650
+ // @ts-ignore
9651
+ if (line)
9652
+ yield yield __await(JSON.parse(line));
9653
+ }
9654
+ }
9655
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
9656
+ finally {
9657
+ try {
9658
+ if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
9659
+ }
9660
+ finally { if (e_3) throw e_3.error; }
9661
+ }
9662
+ done = true;
9663
+ }
9664
+ catch (e) {
9665
+ // If the user calls `stream.controller.abort()`, we should exit without throwing.
9666
+ if (isAbortError(e))
9667
+ return yield __await(void 0);
9668
+ throw e;
9669
+ }
9670
+ finally {
9671
+ // If the user `break`s, abort the ongoing request.
9672
+ if (!done)
9673
+ controller.abort();
9674
+ }
9675
+ });
9676
+ }
9677
+ return new Stream(iterator, controller, client);
9678
+ }
9679
+ [Symbol.asyncIterator]() {
9680
+ return this.iterator();
9681
+ }
9682
+ /**
9683
+ * Splits the stream into two streams which can be
9684
+ * independently read from at different speeds.
9685
+ */
9686
+ tee() {
9687
+ const left = [];
9688
+ const right = [];
9689
+ const iterator = this.iterator();
9690
+ const teeIterator = (queue) => {
9691
+ return {
9692
+ next: () => {
9693
+ if (queue.length === 0) {
9694
+ const result = iterator.next();
9695
+ left.push(result);
9696
+ right.push(result);
9697
+ }
9698
+ return queue.shift();
9699
+ },
9700
+ };
9701
+ };
9702
+ return [
9703
+ new Stream(() => teeIterator(left), this.controller, this.client),
9704
+ new Stream(() => teeIterator(right), this.controller, this.client),
9705
+ ];
9706
+ }
9707
+ /**
9708
+ * Converts this stream to a newline-separated ReadableStream of
9709
+ * JSON stringified values in the stream
9710
+ * which can be turned back into a Stream with `Stream.fromReadableStream()`.
9711
+ */
9712
+ toReadableStream() {
9713
+ const self = this;
9714
+ let iter;
9715
+ return makeReadableStream({
9716
+ async start() {
9717
+ iter = self[Symbol.asyncIterator]();
9718
+ },
9719
+ async pull(ctrl) {
9720
+ try {
9721
+ const { value, done } = await iter.next();
9722
+ if (done)
9723
+ return ctrl.close();
9724
+ const bytes = encodeUTF8(JSON.stringify(value) + '\n');
9725
+ ctrl.enqueue(bytes);
9726
+ }
9727
+ catch (err) {
9728
+ ctrl.error(err);
9729
+ }
9730
+ },
9731
+ async cancel() {
9732
+ var _a;
9733
+ await ((_a = iter.return) === null || _a === void 0 ? void 0 : _a.call(iter));
9734
+ },
9735
+ });
9736
+ }
9737
+ }
9738
+ function _iterSSEMessages(response, controller) {
9739
+ return __asyncGenerator(this, arguments, function* _iterSSEMessages_1() {
9740
+ var _a, e_4, _b, _c;
9741
+ if (!response.body) {
9742
+ controller.abort();
9743
+ if (typeof globalThis.navigator !== 'undefined' &&
9744
+ globalThis.navigator.product === 'ReactNative') {
9745
+ throw new GeminiNextGenAPIClientError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
9746
+ }
9747
+ throw new GeminiNextGenAPIClientError(`Attempted to iterate over a response with no body`);
9748
+ }
9749
+ const sseDecoder = new SSEDecoder();
9750
+ const lineDecoder = new LineDecoder();
9751
+ const iter = ReadableStreamToAsyncIterable(response.body);
9752
+ try {
9753
+ for (var _d = true, _e = __asyncValues(iterSSEChunks(iter)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
9754
+ _c = _f.value;
9755
+ _d = false;
9756
+ const sseChunk = _c;
9757
+ for (const line of lineDecoder.decode(sseChunk)) {
9758
+ const sse = sseDecoder.decode(line);
9759
+ if (sse)
9760
+ yield yield __await(sse);
9761
+ }
9762
+ }
9763
+ }
9764
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
9765
+ finally {
9766
+ try {
9767
+ if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
9768
+ }
9769
+ finally { if (e_4) throw e_4.error; }
9770
+ }
9771
+ for (const line of lineDecoder.flush()) {
9772
+ const sse = sseDecoder.decode(line);
9773
+ if (sse)
9774
+ yield yield __await(sse);
9775
+ }
9776
+ });
9777
+ }
9778
+ /**
9779
+ * Given an async iterable iterator, iterates over it and yields full
9780
+ * SSE chunks, i.e. yields when a double new-line is encountered.
9781
+ */
9782
+ function iterSSEChunks(iterator) {
9783
+ return __asyncGenerator(this, arguments, function* iterSSEChunks_1() {
9784
+ var _a, e_5, _b, _c;
9785
+ let data = new Uint8Array();
9786
+ try {
9787
+ for (var _d = true, iterator_3 = __asyncValues(iterator), iterator_3_1; iterator_3_1 = yield __await(iterator_3.next()), _a = iterator_3_1.done, !_a; _d = true) {
9788
+ _c = iterator_3_1.value;
9789
+ _d = false;
9790
+ const chunk = _c;
9791
+ if (chunk == null) {
9792
+ continue;
9793
+ }
9794
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
9795
+ : typeof chunk === 'string' ? encodeUTF8(chunk)
9796
+ : chunk;
9797
+ let newData = new Uint8Array(data.length + binaryChunk.length);
9798
+ newData.set(data);
9799
+ newData.set(binaryChunk, data.length);
9800
+ data = newData;
9801
+ let patternIndex;
9802
+ while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
9803
+ yield yield __await(data.slice(0, patternIndex));
9804
+ data = data.slice(patternIndex);
9805
+ }
9806
+ }
9807
+ }
9808
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
9809
+ finally {
9810
+ try {
9811
+ if (!_d && !_a && (_b = iterator_3.return)) yield __await(_b.call(iterator_3));
9812
+ }
9813
+ finally { if (e_5) throw e_5.error; }
9814
+ }
9815
+ if (data.length > 0) {
9816
+ yield yield __await(data);
9817
+ }
9818
+ });
9819
+ }
9820
+ class SSEDecoder {
9821
+ constructor() {
9822
+ this.event = null;
9823
+ this.data = [];
9824
+ this.chunks = [];
9825
+ }
9826
+ decode(line) {
9827
+ if (line.endsWith('\r')) {
9828
+ line = line.substring(0, line.length - 1);
9829
+ }
9830
+ if (!line) {
9831
+ // empty line and we didn't previously encounter any messages
9832
+ if (!this.event && !this.data.length)
9833
+ return null;
9834
+ const sse = {
9835
+ event: this.event,
9836
+ data: this.data.join('\n'),
9837
+ raw: this.chunks,
9838
+ };
9839
+ this.event = null;
9840
+ this.data = [];
9841
+ this.chunks = [];
9842
+ return sse;
9843
+ }
9844
+ this.chunks.push(line);
9845
+ if (line.startsWith(':')) {
9846
+ return null;
9847
+ }
9848
+ let [fieldname, _, value] = partition(line, ':');
9849
+ if (value.startsWith(' ')) {
9850
+ value = value.substring(1);
9851
+ }
9852
+ if (fieldname === 'event') {
9853
+ this.event = value;
9854
+ }
9855
+ else if (fieldname === 'data') {
9856
+ this.data.push(value);
9857
+ }
9858
+ return null;
9859
+ }
9860
+ }
9861
+ function partition(str, delimiter) {
9862
+ const index = str.indexOf(delimiter);
9863
+ if (index !== -1) {
9864
+ return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
9865
+ }
9866
+ return [str, '', ''];
9867
+ }
9868
+
9869
+ /**
9870
+ * @license
9871
+ * Copyright 2025 Google LLC
9872
+ * SPDX-License-Identifier: Apache-2.0
9873
+ */
9874
+ async function defaultParseResponse(client, props) {
9875
+ const { response, requestLogID, retryOfRequestLogID, startTime } = props;
9876
+ const body = await (async () => {
9877
+ var _a;
9878
+ if (props.options.stream) {
9879
+ loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);
9880
+ // Note: there is an invariant here that isn't represented in the type system
9881
+ // that if you set `stream: true` the response type must also be `Stream<T>`
9882
+ if (props.options.__streamClass) {
9883
+ return props.options.__streamClass.fromSSEResponse(response, props.controller, client);
9884
+ }
9885
+ return Stream.fromSSEResponse(response, props.controller, client);
9886
+ }
9887
+ // fetch refuses to read the body when the status code is 204.
9888
+ if (response.status === 204) {
9889
+ return null;
9890
+ }
9891
+ if (props.options.__binaryResponse) {
9892
+ return response;
9893
+ }
9894
+ const contentType = response.headers.get('content-type');
9895
+ const mediaType = (_a = contentType === null || contentType === void 0 ? void 0 : contentType.split(';')[0]) === null || _a === void 0 ? void 0 : _a.trim();
9896
+ const isJSON = (mediaType === null || mediaType === void 0 ? void 0 : mediaType.includes('application/json')) || (mediaType === null || mediaType === void 0 ? void 0 : mediaType.endsWith('+json'));
9897
+ if (isJSON) {
9898
+ const json = await response.json();
9899
+ return json;
9900
+ }
9901
+ const text = await response.text();
9902
+ return text;
9903
+ })();
9904
+ loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
9905
+ retryOfRequestLogID,
9906
+ url: response.url,
9907
+ status: response.status,
9908
+ body,
9909
+ durationMs: Date.now() - startTime,
9910
+ }));
9911
+ return body;
9912
+ }
9913
+
9914
+ /**
9915
+ * @license
9916
+ * Copyright 2025 Google LLC
9917
+ * SPDX-License-Identifier: Apache-2.0
9918
+ */
9919
+ /**
9920
+ * A subclass of `Promise` providing additional helper methods
9921
+ * for interacting with the SDK.
9922
+ */
9923
+ class APIPromise extends Promise {
9924
+ constructor(client, responsePromise, parseResponse = defaultParseResponse) {
9925
+ super((resolve) => {
9926
+ // this is maybe a bit weird but this has to be a no-op to not implicitly
9927
+ // parse the response body; instead .then, .catch, .finally are overridden
9928
+ // to parse the response
9929
+ resolve(null);
9930
+ });
9931
+ this.responsePromise = responsePromise;
9932
+ this.parseResponse = parseResponse;
9933
+ this.client = client;
9934
+ }
9935
+ _thenUnwrap(transform) {
9936
+ return new APIPromise(this.client, this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props));
9937
+ }
9938
+ /**
9939
+ * Gets the raw `Response` instance instead of parsing the response
9940
+ * data.
9941
+ *
9942
+ * If you want to parse the response body but still get the `Response`
9943
+ * instance, you can use {@link withResponse()}.
9944
+ *
9945
+ * 👋 Getting the wrong TypeScript type for `Response`?
9946
+ * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
9947
+ * to your `tsconfig.json`.
9948
+ */
9949
+ asResponse() {
9950
+ return this.responsePromise.then((p) => p.response);
9951
+ }
9952
+ /**
9953
+ * Gets the parsed response data and the raw `Response` instance.
9954
+ *
9955
+ * If you just want to get the raw `Response` instance without parsing it,
9956
+ * you can use {@link asResponse()}.
9957
+ *
9958
+ * 👋 Getting the wrong TypeScript type for `Response`?
9959
+ * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
9960
+ * to your `tsconfig.json`.
9961
+ */
9962
+ async withResponse() {
9963
+ const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
9964
+ return { data, response };
9965
+ }
9966
+ parse() {
9967
+ if (!this.parsedPromise) {
9968
+ this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(this.client, data));
9969
+ }
9970
+ return this.parsedPromise;
9971
+ }
9972
+ then(onfulfilled, onrejected) {
9973
+ return this.parse().then(onfulfilled, onrejected);
9974
+ }
9975
+ catch(onrejected) {
9976
+ return this.parse().catch(onrejected);
9977
+ }
9978
+ finally(onfinally) {
9979
+ return this.parse().finally(onfinally);
9980
+ }
9981
+ }
9982
+
9983
+ /**
9984
+ * @license
9985
+ * Copyright 2025 Google LLC
9986
+ * SPDX-License-Identifier: Apache-2.0
9987
+ */
9988
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9989
+ const brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders');
9990
+ function* iterateHeaders(headers) {
9991
+ if (!headers)
9992
+ return;
9993
+ if (brand_privateNullableHeaders in headers) {
9994
+ const { values, nulls } = headers;
9995
+ yield* values.entries();
9996
+ for (const name of nulls) {
9997
+ yield [name, null];
9998
+ }
9999
+ return;
10000
+ }
10001
+ let shouldClear = false;
10002
+ let iter;
10003
+ if (headers instanceof Headers) {
10004
+ iter = headers.entries();
10005
+ }
10006
+ else if (isReadonlyArray(headers)) {
10007
+ iter = headers;
10008
+ }
10009
+ else {
10010
+ shouldClear = true;
10011
+ iter = Object.entries(headers !== null && headers !== void 0 ? headers : {});
10012
+ }
10013
+ for (let row of iter) {
10014
+ const name = row[0];
10015
+ if (typeof name !== 'string')
10016
+ throw new TypeError('expected header name to be a string');
10017
+ const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
10018
+ let didClear = false;
10019
+ for (const value of values) {
10020
+ if (value === undefined)
10021
+ continue;
10022
+ // Objects keys always overwrite older headers, they never append.
10023
+ // Yield a null to clear the header before adding the new values.
10024
+ if (shouldClear && !didClear) {
10025
+ didClear = true;
10026
+ yield [name, null];
10027
+ }
10028
+ yield [name, value];
10029
+ }
10030
+ }
10031
+ }
10032
+ const buildHeaders = (newHeaders) => {
10033
+ const targetHeaders = new Headers();
10034
+ const nullHeaders = new Set();
10035
+ for (const headers of newHeaders) {
10036
+ const seenHeaders = new Set();
10037
+ for (const [name, value] of iterateHeaders(headers)) {
10038
+ const lowerName = name.toLowerCase();
10039
+ if (!seenHeaders.has(lowerName)) {
10040
+ targetHeaders.delete(name);
10041
+ seenHeaders.add(lowerName);
10042
+ }
10043
+ if (value === null) {
10044
+ targetHeaders.delete(name);
10045
+ nullHeaders.add(lowerName);
10046
+ }
10047
+ else {
10048
+ targetHeaders.append(name, value);
10049
+ nullHeaders.delete(lowerName);
10050
+ }
10051
+ }
10052
+ }
10053
+ return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
10054
+ };
10055
+
10056
+ /**
10057
+ * @license
10058
+ * Copyright 2025 Google LLC
10059
+ * SPDX-License-Identifier: Apache-2.0
10060
+ */
10061
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
10062
+ /**
10063
+ * Read an environment variable.
10064
+ *
10065
+ * Trims beginning and trailing whitespace.
10066
+ *
10067
+ * Will return undefined if the environment variable doesn't exist or cannot be accessed.
10068
+ */
10069
+ const readEnv = (env) => {
10070
+ var _a, _b, _c, _d, _e, _f;
10071
+ if (typeof globalThis.process !== 'undefined') {
10072
+ return (_c = (_b = (_a = globalThis.process.env) === null || _a === void 0 ? void 0 : _a[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : undefined;
10073
+ }
10074
+ if (typeof globalThis.Deno !== 'undefined') {
10075
+ return (_f = (_e = (_d = globalThis.Deno.env) === null || _d === void 0 ? void 0 : _d.get) === null || _e === void 0 ? void 0 : _e.call(_d, env)) === null || _f === void 0 ? void 0 : _f.trim();
10076
+ }
10077
+ return undefined;
10078
+ };
10079
+
10080
+ /**
10081
+ * @license
10082
+ * Copyright 2025 Google LLC
10083
+ * SPDX-License-Identifier: Apache-2.0
10084
+ */
10085
+ var _a;
10086
+ /**
10087
+ * Base class for Gemini Next Gen API API clients.
10088
+ */
10089
+ class BaseGeminiNextGenAPIClient {
10090
+ /**
10091
+ * API Client for interfacing with the Gemini Next Gen API API.
10092
+ *
10093
+ * @param {string | null | undefined} [opts.apiKey=process.env['GEMINI_API_KEY'] ?? null]
10094
+ * @param {string | undefined} [opts.apiVersion=v1beta]
10095
+ * @param {string} [opts.baseURL=process.env['GEMINI_NEXT_GEN_API_BASE_URL'] ?? https://generativelanguage.googleapis.com] - Override the default base URL for the API.
10096
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
10097
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
10098
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
10099
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
10100
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
10101
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
10102
+ */
10103
+ constructor(_b) {
10104
+ var _c, _d, _e, _f, _g, _h, _j;
10105
+ var { baseURL = readEnv('GEMINI_NEXT_GEN_API_BASE_URL'), apiKey = (_c = readEnv('GEMINI_API_KEY')) !== null && _c !== void 0 ? _c : null, apiVersion = 'v1beta' } = _b, opts = __rest(_b, ["baseURL", "apiKey", "apiVersion"]);
10106
+ const options = Object.assign(Object.assign({ apiKey,
10107
+ apiVersion }, opts), { baseURL: baseURL || `https://generativelanguage.googleapis.com` });
10108
+ this.baseURL = options.baseURL;
10109
+ this.timeout = (_d = options.timeout) !== null && _d !== void 0 ? _d : BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT /* 1 minute */;
10110
+ this.logger = (_e = options.logger) !== null && _e !== void 0 ? _e : console;
10111
+ const defaultLogLevel = 'warn';
10112
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
10113
+ this.logLevel = defaultLogLevel;
10114
+ this.logLevel =
10115
+ (_g = (_f = parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this)) !== null && _f !== void 0 ? _f : parseLogLevel(readEnv('GEMINI_NEXT_GEN_API_LOG'), "process.env['GEMINI_NEXT_GEN_API_LOG']", this)) !== null && _g !== void 0 ? _g : defaultLogLevel;
10116
+ this.fetchOptions = options.fetchOptions;
10117
+ this.maxRetries = (_h = options.maxRetries) !== null && _h !== void 0 ? _h : 2;
10118
+ this.fetch = (_j = options.fetch) !== null && _j !== void 0 ? _j : getDefaultFetch();
10119
+ this.encoder = FallbackEncoder;
10120
+ this._options = options;
10121
+ this.apiKey = apiKey;
10122
+ this.apiVersion = apiVersion;
10123
+ this.clientAdapter = options.clientAdapter;
10124
+ }
10125
+ /**
10126
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
10127
+ */
10128
+ withOptions(options) {
10129
+ const client = new this.constructor(Object.assign(Object.assign(Object.assign({}, this._options), { baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, apiVersion: this.apiVersion }), options));
10130
+ return client;
10131
+ }
10132
+ /**
10133
+ * Check whether the base URL is set to its default.
10134
+ */
10135
+ baseURLOverridden() {
10136
+ return this.baseURL !== 'https://generativelanguage.googleapis.com';
10137
+ }
10138
+ defaultQuery() {
10139
+ return this._options.defaultQuery;
10140
+ }
10141
+ validateHeaders({ values, nulls }) {
10142
+ // The headers object handles case insensitivity.
10143
+ if (values.has('authorization') || values.has('x-goog-api-key')) {
10144
+ return;
10145
+ }
10146
+ if (this.apiKey && values.get('x-goog-api-key')) {
10147
+ return;
10148
+ }
10149
+ if (nulls.has('x-goog-api-key')) {
10150
+ return;
10151
+ }
10152
+ throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted');
10153
+ }
10154
+ async authHeaders(opts) {
10155
+ const existingHeaders = buildHeaders([opts.headers]);
10156
+ if (existingHeaders.values.has('authorization') || existingHeaders.values.has('x-goog-api-key')) {
10157
+ return undefined;
10158
+ }
10159
+ if (this.apiKey) {
10160
+ return buildHeaders([{ 'x-goog-api-key': this.apiKey }]);
10161
+ }
10162
+ if (this.clientAdapter.isVertexAI()) {
10163
+ return buildHeaders([await this.clientAdapter.getAuthHeaders()]);
10164
+ }
10165
+ return undefined;
10166
+ }
10167
+ /**
10168
+ * Basic re-implementation of `qs.stringify` for primitive types.
8279
10169
  */
8280
- async create(params) {
8281
- var _a, _b;
8282
- let response;
8283
- let path = '';
8284
- let queryParams = {};
8285
- if (this.apiClient.isVertexAI()) {
8286
- throw new Error('This method is only supported by the Gemini Developer API.');
10170
+ stringifyQuery(query) {
10171
+ return Object.entries(query)
10172
+ .filter(([_, value]) => typeof value !== 'undefined')
10173
+ .map(([key, value]) => {
10174
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
10175
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
10176
+ }
10177
+ if (value === null) {
10178
+ return `${encodeURIComponent(key)}=`;
10179
+ }
10180
+ throw new GeminiNextGenAPIClientError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
10181
+ })
10182
+ .join('&');
10183
+ }
10184
+ getUserAgent() {
10185
+ return `${this.constructor.name}/JS ${VERSION}`;
10186
+ }
10187
+ defaultIdempotencyKey() {
10188
+ return `stainless-node-retry-${uuid4()}`;
10189
+ }
10190
+ makeStatusError(status, error, message, headers) {
10191
+ return APIError.generate(status, error, message, headers);
10192
+ }
10193
+ buildURL(path, query, defaultBaseURL) {
10194
+ const baseURL = (!this.baseURLOverridden() && defaultBaseURL) || this.baseURL;
10195
+ const url = isAbsoluteURL(path) ?
10196
+ new URL(path)
10197
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
10198
+ const defaultQuery = this.defaultQuery();
10199
+ if (!isEmptyObj(defaultQuery)) {
10200
+ query = Object.assign(Object.assign({}, defaultQuery), query);
8287
10201
  }
8288
- else {
8289
- const body = createFileSearchStoreParametersToMldev(params);
8290
- path = formatMap('fileSearchStores', body['_url']);
8291
- queryParams = body['_query'];
8292
- delete body['_url'];
8293
- delete body['_query'];
8294
- response = this.apiClient
8295
- .request({
8296
- path: path,
8297
- queryParams: queryParams,
8298
- body: JSON.stringify(body),
8299
- httpMethod: 'POST',
8300
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8301
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8302
- })
8303
- .then((httpResponse) => {
8304
- return httpResponse.json();
8305
- });
8306
- return response.then((resp) => {
8307
- return resp;
8308
- });
10202
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
10203
+ url.search = this.stringifyQuery(query);
8309
10204
  }
10205
+ return url.toString();
8310
10206
  }
8311
10207
  /**
8312
- * Gets a File Search Store.
8313
- *
8314
- * @param params - The parameters for getting a File Search Store.
8315
- * @return FileSearchStore.
10208
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
10209
+
8316
10210
  */
8317
- async get(params) {
8318
- var _a, _b;
8319
- let response;
8320
- let path = '';
8321
- let queryParams = {};
8322
- if (this.apiClient.isVertexAI()) {
8323
- throw new Error('This method is only supported by the Gemini Developer API.');
8324
- }
8325
- else {
8326
- const body = getFileSearchStoreParametersToMldev(params);
8327
- path = formatMap('{name}', body['_url']);
8328
- queryParams = body['_query'];
8329
- delete body['_url'];
8330
- delete body['_query'];
8331
- response = this.apiClient
8332
- .request({
8333
- path: path,
8334
- queryParams: queryParams,
8335
- body: JSON.stringify(body),
8336
- httpMethod: 'GET',
8337
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8338
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8339
- })
8340
- .then((httpResponse) => {
8341
- return httpResponse.json();
8342
- });
8343
- return response.then((resp) => {
8344
- return resp;
8345
- });
10211
+ async prepareOptions(options) {
10212
+ if (this.clientAdapter &&
10213
+ this.clientAdapter.isVertexAI() &&
10214
+ !options.path.startsWith(`/${this.apiVersion}/projects/`)) {
10215
+ const oldPath = options.path.slice(this.apiVersion.length + 1);
10216
+ options.path = `/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${oldPath}`;
8346
10217
  }
8347
10218
  }
8348
10219
  /**
8349
- * Deletes a File Search Store.
10220
+ * Used as a callback for mutating the given `RequestInit` object.
8350
10221
  *
8351
- * @param params - The parameters for deleting a File Search Store.
10222
+ * This is useful for cases where you want to add certain headers based off of
10223
+ * the request properties, e.g. `method` or `url`.
8352
10224
  */
8353
- async delete(params) {
8354
- var _a, _b;
8355
- let path = '';
8356
- let queryParams = {};
8357
- if (this.apiClient.isVertexAI()) {
8358
- throw new Error('This method is only supported by the Gemini Developer API.');
10225
+ async prepareRequest(request, { url, options }) { }
10226
+ get(path, opts) {
10227
+ return this.methodRequest('get', path, opts);
10228
+ }
10229
+ post(path, opts) {
10230
+ return this.methodRequest('post', path, opts);
10231
+ }
10232
+ patch(path, opts) {
10233
+ return this.methodRequest('patch', path, opts);
10234
+ }
10235
+ put(path, opts) {
10236
+ return this.methodRequest('put', path, opts);
10237
+ }
10238
+ delete(path, opts) {
10239
+ return this.methodRequest('delete', path, opts);
10240
+ }
10241
+ methodRequest(method, path, opts) {
10242
+ return this.request(Promise.resolve(opts).then((opts) => {
10243
+ return Object.assign({ method, path }, opts);
10244
+ }));
10245
+ }
10246
+ request(options, remainingRetries = null) {
10247
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
10248
+ }
10249
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
10250
+ var _b, _c, _d;
10251
+ const options = await optionsInput;
10252
+ const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
10253
+ if (retriesRemaining == null) {
10254
+ retriesRemaining = maxRetries;
8359
10255
  }
8360
- else {
8361
- const body = deleteFileSearchStoreParametersToMldev(params);
8362
- path = formatMap('{name}', body['_url']);
8363
- queryParams = body['_query'];
8364
- delete body['_url'];
8365
- delete body['_query'];
8366
- await this.apiClient.request({
8367
- path: path,
8368
- queryParams: queryParams,
8369
- body: JSON.stringify(body),
8370
- httpMethod: 'DELETE',
8371
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8372
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8373
- });
10256
+ await this.prepareOptions(options);
10257
+ const { req, url, timeout } = await this.buildRequest(options, {
10258
+ retryCount: maxRetries - retriesRemaining,
10259
+ });
10260
+ await this.prepareRequest(req, { url, options });
10261
+ /** Not an API request ID, just for correlating local log entries. */
10262
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
10263
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
10264
+ const startTime = Date.now();
10265
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
10266
+ retryOfRequestLogID,
10267
+ method: options.method,
10268
+ url,
10269
+ options,
10270
+ headers: req.headers,
10271
+ }));
10272
+ if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
10273
+ throw new APIUserAbortError();
10274
+ }
10275
+ const controller = new AbortController();
10276
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
10277
+ const headersTime = Date.now();
10278
+ if (response instanceof globalThis.Error) {
10279
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
10280
+ if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) {
10281
+ throw new APIUserAbortError();
10282
+ }
10283
+ // detect native connection timeout errors
10284
+ // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
10285
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
10286
+ // others do not provide enough information to distinguish timeouts from other connection errors
10287
+ const isTimeout = isAbortError(response) ||
10288
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
10289
+ if (retriesRemaining) {
10290
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
10291
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
10292
+ retryOfRequestLogID,
10293
+ url,
10294
+ durationMs: headersTime - startTime,
10295
+ message: response.message,
10296
+ }));
10297
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID);
10298
+ }
10299
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
10300
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
10301
+ retryOfRequestLogID,
10302
+ url,
10303
+ durationMs: headersTime - startTime,
10304
+ message: response.message,
10305
+ }));
10306
+ if (isTimeout) {
10307
+ throw new APIConnectionTimeoutError();
10308
+ }
10309
+ throw new APIConnectionError({ cause: response });
10310
+ }
10311
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
10312
+ if (!response.ok) {
10313
+ const shouldRetry = await this.shouldRetry(response);
10314
+ if (retriesRemaining && shouldRetry) {
10315
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
10316
+ // We don't need the body of this response.
10317
+ await CancelReadableStream(response.body);
10318
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
10319
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
10320
+ retryOfRequestLogID,
10321
+ url: response.url,
10322
+ status: response.status,
10323
+ headers: response.headers,
10324
+ durationMs: headersTime - startTime,
10325
+ }));
10326
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID, response.headers);
10327
+ }
10328
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
10329
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
10330
+ const errText = await response.text().catch((err) => castToError(err).message);
10331
+ const errJSON = safeJSON(errText);
10332
+ const errMessage = errJSON ? undefined : errText;
10333
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
10334
+ retryOfRequestLogID,
10335
+ url: response.url,
10336
+ status: response.status,
10337
+ headers: response.headers,
10338
+ message: errMessage,
10339
+ durationMs: Date.now() - startTime,
10340
+ }));
10341
+ // @ts-ignore
10342
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
10343
+ throw err;
10344
+ }
10345
+ loggerFor(this).info(responseInfo);
10346
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
10347
+ retryOfRequestLogID,
10348
+ url: response.url,
10349
+ status: response.status,
10350
+ headers: response.headers,
10351
+ durationMs: headersTime - startTime,
10352
+ }));
10353
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
10354
+ }
10355
+ async fetchWithTimeout(url, init, ms, controller) {
10356
+ const _b = init || {}, { signal, method } = _b, options = __rest(_b, ["signal", "method"]);
10357
+ if (signal)
10358
+ signal.addEventListener('abort', () => controller.abort());
10359
+ const timeout = setTimeout(() => controller.abort(), ms);
10360
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
10361
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
10362
+ const fetchOptions = Object.assign(Object.assign(Object.assign({ signal: controller.signal }, (isReadableBody ? { duplex: 'half' } : {})), { method: 'GET' }), options);
10363
+ if (method) {
10364
+ // Custom methods like 'patch' need to be uppercased
10365
+ // See https://github.com/nodejs/undici/issues/2294
10366
+ fetchOptions.method = method.toUpperCase();
8374
10367
  }
8375
- }
8376
- async listInternal(params) {
8377
- var _a, _b;
8378
- let response;
8379
- let path = '';
8380
- let queryParams = {};
8381
- if (this.apiClient.isVertexAI()) {
8382
- throw new Error('This method is only supported by the Gemini Developer API.');
10368
+ try {
10369
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
10370
+ return await this.fetch.call(undefined, url, fetchOptions);
8383
10371
  }
8384
- else {
8385
- const body = listFileSearchStoresParametersToMldev(params);
8386
- path = formatMap('fileSearchStores', body['_url']);
8387
- queryParams = body['_query'];
8388
- delete body['_url'];
8389
- delete body['_query'];
8390
- response = this.apiClient
8391
- .request({
8392
- path: path,
8393
- queryParams: queryParams,
8394
- body: JSON.stringify(body),
8395
- httpMethod: 'GET',
8396
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8397
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8398
- })
8399
- .then((httpResponse) => {
8400
- return httpResponse.json();
8401
- });
8402
- return response.then((apiResponse) => {
8403
- const resp = listFileSearchStoresResponseFromMldev(apiResponse);
8404
- const typedResp = new ListFileSearchStoresResponse();
8405
- Object.assign(typedResp, resp);
8406
- return typedResp;
8407
- });
10372
+ finally {
10373
+ clearTimeout(timeout);
8408
10374
  }
8409
10375
  }
8410
- async uploadToFileSearchStoreInternal(params) {
8411
- var _a, _b;
8412
- let response;
8413
- let path = '';
8414
- let queryParams = {};
8415
- if (this.apiClient.isVertexAI()) {
8416
- throw new Error('This method is only supported by the Gemini Developer API.');
10376
+ async shouldRetry(response) {
10377
+ // Note this is not a standard header.
10378
+ const shouldRetryHeader = response.headers.get('x-should-retry');
10379
+ // If the server explicitly says whether or not to retry, obey.
10380
+ if (shouldRetryHeader === 'true')
10381
+ return true;
10382
+ if (shouldRetryHeader === 'false')
10383
+ return false;
10384
+ // Retry on request timeouts.
10385
+ if (response.status === 408)
10386
+ return true;
10387
+ // Retry on lock timeouts.
10388
+ if (response.status === 409)
10389
+ return true;
10390
+ // Retry on rate limits.
10391
+ if (response.status === 429)
10392
+ return true;
10393
+ // Retry internal errors.
10394
+ if (response.status >= 500)
10395
+ return true;
10396
+ return false;
10397
+ }
10398
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
10399
+ var _b;
10400
+ let timeoutMillis;
10401
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
10402
+ const retryAfterMillisHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get('retry-after-ms');
10403
+ if (retryAfterMillisHeader) {
10404
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
10405
+ if (!Number.isNaN(timeoutMs)) {
10406
+ timeoutMillis = timeoutMs;
10407
+ }
8417
10408
  }
8418
- else {
8419
- const body = uploadToFileSearchStoreParametersToMldev(params);
8420
- path = formatMap('upload/v1beta/{file_search_store_name}:uploadToFileSearchStore', body['_url']);
8421
- queryParams = body['_query'];
8422
- delete body['_url'];
8423
- delete body['_query'];
8424
- response = this.apiClient
8425
- .request({
8426
- path: path,
8427
- queryParams: queryParams,
8428
- body: JSON.stringify(body),
8429
- httpMethod: 'POST',
8430
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8431
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8432
- })
8433
- .then((httpResponse) => {
8434
- return httpResponse.json();
8435
- });
8436
- return response.then((apiResponse) => {
8437
- const resp = uploadToFileSearchStoreResumableResponseFromMldev(apiResponse);
8438
- const typedResp = new UploadToFileSearchStoreResumableResponse();
8439
- Object.assign(typedResp, resp);
8440
- return typedResp;
8441
- });
10409
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
10410
+ const retryAfterHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get('retry-after');
10411
+ if (retryAfterHeader && !timeoutMillis) {
10412
+ const timeoutSeconds = parseFloat(retryAfterHeader);
10413
+ if (!Number.isNaN(timeoutSeconds)) {
10414
+ timeoutMillis = timeoutSeconds * 1000;
10415
+ }
10416
+ else {
10417
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
10418
+ }
8442
10419
  }
8443
- }
8444
- /**
8445
- * Imports a File from File Service to a FileSearchStore.
8446
- *
8447
- * This is a long-running operation, see aip.dev/151
8448
- *
8449
- * @param params - The parameters for importing a file to a file search store.
8450
- * @return ImportFileOperation.
8451
- */
8452
- async importFile(params) {
8453
- var _a, _b;
8454
- let response;
8455
- let path = '';
8456
- let queryParams = {};
8457
- if (this.apiClient.isVertexAI()) {
8458
- throw new Error('This method is only supported by the Gemini Developer API.');
10420
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
10421
+ // just do what it says, but otherwise calculate a default
10422
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
10423
+ const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
10424
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
10425
+ }
10426
+ await sleep(timeoutMillis);
10427
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
10428
+ }
10429
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
10430
+ const initialRetryDelay = 0.5;
10431
+ const maxRetryDelay = 8.0;
10432
+ const numRetries = maxRetries - retriesRemaining;
10433
+ // Apply exponential backoff, but not more than the max.
10434
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
10435
+ // Apply some jitter, take up to at most 25 percent of the retry time.
10436
+ const jitter = 1 - Math.random() * 0.25;
10437
+ return sleepSeconds * jitter * 1000;
10438
+ }
10439
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
10440
+ var _b, _c, _d;
10441
+ const options = Object.assign({}, inputOptions);
10442
+ const { method, path, query, defaultBaseURL } = options;
10443
+ const url = this.buildURL(path, query, defaultBaseURL);
10444
+ if ('timeout' in options)
10445
+ validatePositiveInteger('timeout', options.timeout);
10446
+ options.timeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : this.timeout;
10447
+ const { bodyHeaders, body } = this.buildBody({ options });
10448
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
10449
+ const req = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ method, headers: reqHeaders }, (options.signal && { signal: options.signal })), (globalThis.ReadableStream &&
10450
+ body instanceof globalThis.ReadableStream && { duplex: 'half' })), (body && { body })), ((_c = this.fetchOptions) !== null && _c !== void 0 ? _c : {})), ((_d = options.fetchOptions) !== null && _d !== void 0 ? _d : {}));
10451
+ return { req, url, timeout: options.timeout };
10452
+ }
10453
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
10454
+ let idempotencyHeaders = {};
10455
+ if (this.idempotencyHeader && method !== 'get') {
10456
+ if (!options.idempotencyKey)
10457
+ options.idempotencyKey = this.defaultIdempotencyKey();
10458
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
10459
+ }
10460
+ const authHeaders = await this.authHeaders(options);
10461
+ let headers = buildHeaders([
10462
+ idempotencyHeaders,
10463
+ Object.assign(Object.assign({ Accept: 'application/json', 'User-Agent': this.getUserAgent(), 'X-Stainless-Retry-Count': String(retryCount) }, (options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {})), getPlatformHeaders()),
10464
+ this._options.defaultHeaders,
10465
+ bodyHeaders,
10466
+ options.headers,
10467
+ authHeaders,
10468
+ ]);
10469
+ this.validateHeaders(headers);
10470
+ return headers.values;
10471
+ }
10472
+ buildBody({ options: { body, headers: rawHeaders } }) {
10473
+ if (!body) {
10474
+ return { bodyHeaders: undefined, body: undefined };
10475
+ }
10476
+ const headers = buildHeaders([rawHeaders]);
10477
+ if (
10478
+ // Pass raw type verbatim
10479
+ ArrayBuffer.isView(body) ||
10480
+ body instanceof ArrayBuffer ||
10481
+ body instanceof DataView ||
10482
+ (typeof body === 'string' &&
10483
+ // Preserve legacy string encoding behavior for now
10484
+ headers.values.has('content-type')) ||
10485
+ // `Blob` is superset of `File`
10486
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
10487
+ // `FormData` -> `multipart/form-data`
10488
+ body instanceof FormData ||
10489
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
10490
+ body instanceof URLSearchParams ||
10491
+ // Send chunked stream (each chunk has own `length`)
10492
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
10493
+ return { bodyHeaders: undefined, body: body };
10494
+ }
10495
+ else if (typeof body === 'object' &&
10496
+ (Symbol.asyncIterator in body ||
10497
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
10498
+ return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
8459
10499
  }
8460
10500
  else {
8461
- const body = importFileParametersToMldev(params);
8462
- path = formatMap('{file_search_store_name}:importFile', body['_url']);
8463
- queryParams = body['_query'];
8464
- delete body['_url'];
8465
- delete body['_query'];
8466
- response = this.apiClient
8467
- .request({
8468
- path: path,
8469
- queryParams: queryParams,
8470
- body: JSON.stringify(body),
8471
- httpMethod: 'POST',
8472
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8473
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8474
- })
8475
- .then((httpResponse) => {
8476
- return httpResponse.json();
8477
- });
8478
- return response.then((apiResponse) => {
8479
- const resp = importFileOperationFromMldev(apiResponse);
8480
- const typedResp = new ImportFileOperation();
8481
- Object.assign(typedResp, resp);
8482
- return typedResp;
8483
- });
10501
+ return this.encoder({ body, headers });
8484
10502
  }
8485
10503
  }
8486
10504
  }
10505
+ BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT = 60000; // 1 minute
10506
+ /**
10507
+ * API Client for interfacing with the Gemini Next Gen API API.
10508
+ */
10509
+ class GeminiNextGenAPIClient extends BaseGeminiNextGenAPIClient {
10510
+ constructor() {
10511
+ super(...arguments);
10512
+ this.interactions = new Interactions(this);
10513
+ }
10514
+ }
10515
+ _a = GeminiNextGenAPIClient;
10516
+ GeminiNextGenAPIClient.GeminiNextGenAPIClient = _a;
10517
+ GeminiNextGenAPIClient.GeminiNextGenAPIClientError = GeminiNextGenAPIClientError;
10518
+ GeminiNextGenAPIClient.APIError = APIError;
10519
+ GeminiNextGenAPIClient.APIConnectionError = APIConnectionError;
10520
+ GeminiNextGenAPIClient.APIConnectionTimeoutError = APIConnectionTimeoutError;
10521
+ GeminiNextGenAPIClient.APIUserAbortError = APIUserAbortError;
10522
+ GeminiNextGenAPIClient.NotFoundError = NotFoundError;
10523
+ GeminiNextGenAPIClient.ConflictError = ConflictError;
10524
+ GeminiNextGenAPIClient.RateLimitError = RateLimitError;
10525
+ GeminiNextGenAPIClient.BadRequestError = BadRequestError;
10526
+ GeminiNextGenAPIClient.AuthenticationError = AuthenticationError;
10527
+ GeminiNextGenAPIClient.InternalServerError = InternalServerError;
10528
+ GeminiNextGenAPIClient.PermissionDeniedError = PermissionDeniedError;
10529
+ GeminiNextGenAPIClient.UnprocessableEntityError = UnprocessableEntityError;
10530
+ GeminiNextGenAPIClient.toFile = toFile;
10531
+ GeminiNextGenAPIClient.Interactions = Interactions;
8487
10532
 
8488
10533
  /**
8489
10534
  * @license
@@ -8691,7 +10736,7 @@ function generationConfigToVertex$1(fromObject) {
8691
10736
  }
8692
10737
  const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
8693
10738
  if (fromSpeechConfig != null) {
8694
- setValueByPath(toObject, ['speechConfig'], speechConfigToVertex$1(fromSpeechConfig));
10739
+ setValueByPath(toObject, ['speechConfig'], fromSpeechConfig);
8695
10740
  }
8696
10741
  const fromStopSequences = getValueByPath(fromObject, [
8697
10742
  'stopSequences',
@@ -8858,6 +10903,9 @@ function liveConnectConfigToMldev$1(fromObject, parentObject) {
8858
10903
  if (parentObject !== undefined && fromProactivity != null) {
8859
10904
  setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
8860
10905
  }
10906
+ if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {
10907
+ throw new Error('explicitVadSignal parameter is not supported in Gemini API.');
10908
+ }
8861
10909
  return toObject;
8862
10910
  }
8863
10911
  function liveConnectConfigToVertex(fromObject, parentObject) {
@@ -8904,7 +10952,7 @@ function liveConnectConfigToVertex(fromObject, parentObject) {
8904
10952
  }
8905
10953
  const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
8906
10954
  if (parentObject !== undefined && fromSpeechConfig != null) {
8907
- setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)));
10955
+ setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], tLiveSpeechConfig(fromSpeechConfig));
8908
10956
  }
8909
10957
  const fromThinkingConfig = getValueByPath(fromObject, [
8910
10958
  'thinkingConfig',
@@ -8968,6 +11016,12 @@ function liveConnectConfigToVertex(fromObject, parentObject) {
8968
11016
  if (parentObject !== undefined && fromProactivity != null) {
8969
11017
  setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
8970
11018
  }
11019
+ const fromExplicitVadSignal = getValueByPath(fromObject, [
11020
+ 'explicitVadSignal',
11021
+ ]);
11022
+ if (parentObject !== undefined && fromExplicitVadSignal != null) {
11023
+ setValueByPath(parentObject, ['setup', 'explicitVadSignal'], fromExplicitVadSignal);
11024
+ }
8971
11025
  return toObject;
8972
11026
  }
8973
11027
  function liveConnectParametersToMldev(apiClient, fromObject) {
@@ -9144,6 +11198,12 @@ function liveServerMessageFromVertex(fromObject) {
9144
11198
  if (fromSessionResumptionUpdate != null) {
9145
11199
  setValueByPath(toObject, ['sessionResumptionUpdate'], fromSessionResumptionUpdate);
9146
11200
  }
11201
+ const fromVoiceActivityDetectionSignal = getValueByPath(fromObject, [
11202
+ 'voiceActivityDetectionSignal',
11203
+ ]);
11204
+ if (fromVoiceActivityDetectionSignal != null) {
11205
+ setValueByPath(toObject, ['voiceActivityDetectionSignal'], fromVoiceActivityDetectionSignal);
11206
+ }
9147
11207
  return toObject;
9148
11208
  }
9149
11209
  function partToMldev$2(fromObject) {
@@ -9217,21 +11277,6 @@ function sessionResumptionConfigToMldev$1(fromObject) {
9217
11277
  }
9218
11278
  return toObject;
9219
11279
  }
9220
- function speechConfigToVertex$1(fromObject) {
9221
- const toObject = {};
9222
- const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']);
9223
- if (fromVoiceConfig != null) {
9224
- setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);
9225
- }
9226
- const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
9227
- if (fromLanguageCode != null) {
9228
- setValueByPath(toObject, ['languageCode'], fromLanguageCode);
9229
- }
9230
- if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) {
9231
- throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.');
9232
- }
9233
- return toObject;
9234
- }
9235
11280
  function toolToMldev$2(fromObject) {
9236
11281
  const toObject = {};
9237
11282
  const fromFunctionDeclarations = getValueByPath(fromObject, [
@@ -10474,7 +12519,7 @@ function generateContentConfigToVertex(apiClient, fromObject, parentObject) {
10474
12519
  }
10475
12520
  const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
10476
12521
  if (fromSpeechConfig != null) {
10477
- setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));
12522
+ setValueByPath(toObject, ['speechConfig'], tSpeechConfig(fromSpeechConfig));
10478
12523
  }
10479
12524
  const fromAudioTimestamp = getValueByPath(fromObject, [
10480
12525
  'audioTimestamp',
@@ -11420,7 +13465,7 @@ function generationConfigToVertex(fromObject) {
11420
13465
  }
11421
13466
  const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
11422
13467
  if (fromSpeechConfig != null) {
11423
- setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(fromSpeechConfig));
13468
+ setValueByPath(toObject, ['speechConfig'], fromSpeechConfig);
11424
13469
  }
11425
13470
  const fromStopSequences = getValueByPath(fromObject, [
11426
13471
  'stopSequences',
@@ -12222,21 +14267,6 @@ function segmentImageSourceToVertex(fromObject, parentObject) {
12222
14267
  }
12223
14268
  return toObject;
12224
14269
  }
12225
- function speechConfigToVertex(fromObject) {
12226
- const toObject = {};
12227
- const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']);
12228
- if (fromVoiceConfig != null) {
12229
- setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);
12230
- }
12231
- const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
12232
- if (fromLanguageCode != null) {
12233
- setValueByPath(toObject, ['languageCode'], fromLanguageCode);
12234
- }
12235
- if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) {
12236
- throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.');
12237
- }
12238
- return toObject;
12239
- }
12240
14270
  function toolConfigToMldev(fromObject) {
12241
14271
  const toObject = {};
12242
14272
  const fromFunctionCallingConfig = getValueByPath(fromObject, [
@@ -15526,6 +17556,9 @@ function liveConnectConfigToMldev(fromObject, parentObject) {
15526
17556
  if (parentObject !== undefined && fromProactivity != null) {
15527
17557
  setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
15528
17558
  }
17559
+ if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {
17560
+ throw new Error('explicitVadSignal parameter is not supported in Gemini API.');
17561
+ }
15529
17562
  return toObject;
15530
17563
  }
15531
17564
  function liveConnectConstraintsToMldev(apiClient, fromObject) {
@@ -17069,6 +19102,30 @@ const LANGUAGE_LABEL_PREFIX = 'gl-node/';
17069
19102
  *
17070
19103
  */
17071
19104
  class GoogleGenAI {
19105
+ get interactions() {
19106
+ if (this._interactions !== undefined) {
19107
+ return this._interactions;
19108
+ }
19109
+ console.warn('GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.');
19110
+ if (this.vertexai) {
19111
+ throw new Error('This version of the GenAI SDK does not support Vertex AI API for interactions.');
19112
+ }
19113
+ const httpOpts = this.httpOptions;
19114
+ // Unsupported Options Warnings
19115
+ if (httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.extraBody) {
19116
+ console.warn('GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.');
19117
+ }
19118
+ const nextGenClient = new GeminiNextGenAPIClient({
19119
+ baseURL: this.apiClient.getBaseUrl(),
19120
+ apiKey: this.apiKey,
19121
+ apiVersion: this.apiClient.getApiVersion(),
19122
+ clientAdapter: this.apiClient,
19123
+ defaultHeaders: this.apiClient.getDefaultHeaders(),
19124
+ timeout: httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.timeout,
19125
+ });
19126
+ this._interactions = nextGenClient.interactions;
19127
+ return this._interactions;
19128
+ }
17072
19129
  constructor(options) {
17073
19130
  var _a;
17074
19131
  if (options.apiKey == null) {