@ai-sdk/google 3.0.70 → 3.0.72

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.js CHANGED
@@ -27,10 +27,10 @@ __export(index_exports, {
27
27
  module.exports = __toCommonJS(index_exports);
28
28
 
29
29
  // src/google-provider.ts
30
- var import_provider_utils21 = require("@ai-sdk/provider-utils");
30
+ var import_provider_utils23 = require("@ai-sdk/provider-utils");
31
31
 
32
32
  // src/version.ts
33
- var VERSION = true ? "3.0.70" : "0.0.0-test";
33
+ var VERSION = true ? "3.0.72" : "0.0.0-test";
34
34
 
35
35
  // src/google-generative-ai-embedding-model.ts
36
36
  var import_provider = require("@ai-sdk/provider");
@@ -1488,7 +1488,7 @@ var GoogleGenerativeAILanguageModel = class {
1488
1488
  };
1489
1489
  }
1490
1490
  async doGenerate(options) {
1491
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
1491
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
1492
1492
  const { args, warnings, providerOptionsName } = await this.getArgs(options);
1493
1493
  const mergedHeaders = (0, import_provider_utils6.combineHeaders)(
1494
1494
  await (0, import_provider_utils6.resolve)(this.config.headers),
@@ -1556,12 +1556,12 @@ var GoogleGenerativeAILanguageModel = class {
1556
1556
  providerMetadata: thoughtSignatureMetadata
1557
1557
  });
1558
1558
  }
1559
- } else if ("functionCall" in part && part.functionCall.name != null && part.functionCall.args != null) {
1559
+ } else if ("functionCall" in part && part.functionCall.name != null) {
1560
1560
  content.push({
1561
1561
  type: "tool-call",
1562
1562
  toolCallId: this.config.generateId(),
1563
1563
  toolName: part.functionCall.name,
1564
- input: JSON.stringify(part.functionCall.args),
1564
+ input: JSON.stringify((_e = part.functionCall.args) != null ? _e : {}),
1565
1565
  providerMetadata: part.thoughtSignature ? {
1566
1566
  [providerOptionsName]: {
1567
1567
  thoughtSignature: part.thoughtSignature
@@ -1583,13 +1583,13 @@ var GoogleGenerativeAILanguageModel = class {
1583
1583
  } : void 0
1584
1584
  });
1585
1585
  } else if ("toolCall" in part && part.toolCall) {
1586
- const toolCallId = (_e = part.toolCall.id) != null ? _e : this.config.generateId();
1586
+ const toolCallId = (_f = part.toolCall.id) != null ? _f : this.config.generateId();
1587
1587
  lastServerToolCallId = toolCallId;
1588
1588
  content.push({
1589
1589
  type: "tool-call",
1590
1590
  toolCallId,
1591
1591
  toolName: `server:${part.toolCall.toolType}`,
1592
- input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
1592
+ input: JSON.stringify((_g = part.toolCall.args) != null ? _g : {}),
1593
1593
  providerExecuted: true,
1594
1594
  dynamic: true,
1595
1595
  providerMetadata: part.thoughtSignature ? {
@@ -1606,12 +1606,12 @@ var GoogleGenerativeAILanguageModel = class {
1606
1606
  }
1607
1607
  });
1608
1608
  } else if ("toolResponse" in part && part.toolResponse) {
1609
- const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : this.config.generateId();
1609
+ const responseToolCallId = (_h = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _h : this.config.generateId();
1610
1610
  content.push({
1611
1611
  type: "tool-result",
1612
1612
  toolCallId: responseToolCallId,
1613
1613
  toolName: `server:${part.toolResponse.toolType}`,
1614
- result: (_h = part.toolResponse.response) != null ? _h : {},
1614
+ result: (_i = part.toolResponse.response) != null ? _i : {},
1615
1615
  providerMetadata: part.thoughtSignature ? {
1616
1616
  [providerOptionsName]: {
1617
1617
  thoughtSignature: part.thoughtSignature,
@@ -1628,10 +1628,10 @@ var GoogleGenerativeAILanguageModel = class {
1628
1628
  lastServerToolCallId = void 0;
1629
1629
  }
1630
1630
  }
1631
- const sources = (_i = extractSources({
1631
+ const sources = (_j = extractSources({
1632
1632
  groundingMetadata: candidate.groundingMetadata,
1633
1633
  generateId: this.config.generateId
1634
- })) != null ? _i : [];
1634
+ })) != null ? _j : [];
1635
1635
  for (const source of sources) {
1636
1636
  content.push(source);
1637
1637
  }
@@ -1645,19 +1645,19 @@ var GoogleGenerativeAILanguageModel = class {
1645
1645
  (part) => part.type === "tool-call" && !part.providerExecuted
1646
1646
  )
1647
1647
  }),
1648
- raw: (_j = candidate.finishReason) != null ? _j : void 0
1648
+ raw: (_k = candidate.finishReason) != null ? _k : void 0
1649
1649
  },
1650
1650
  usage: convertGoogleGenerativeAIUsage(usageMetadata),
1651
1651
  warnings,
1652
1652
  providerMetadata: {
1653
1653
  [providerOptionsName]: {
1654
- promptFeedback: (_k = response.promptFeedback) != null ? _k : null,
1655
- groundingMetadata: (_l = candidate.groundingMetadata) != null ? _l : null,
1656
- urlContextMetadata: (_m = candidate.urlContextMetadata) != null ? _m : null,
1657
- safetyRatings: (_n = candidate.safetyRatings) != null ? _n : null,
1654
+ promptFeedback: (_l = response.promptFeedback) != null ? _l : null,
1655
+ groundingMetadata: (_m = candidate.groundingMetadata) != null ? _m : null,
1656
+ urlContextMetadata: (_n = candidate.urlContextMetadata) != null ? _n : null,
1657
+ safetyRatings: (_o = candidate.safetyRatings) != null ? _o : null,
1658
1658
  usageMetadata: usageMetadata != null ? usageMetadata : null,
1659
- finishMessage: (_o = candidate.finishMessage) != null ? _o : null,
1660
- serviceTier: (_p = response.serviceTier) != null ? _p : null
1659
+ finishMessage: (_p = candidate.finishMessage) != null ? _p : null,
1660
+ serviceTier: (_q = response.serviceTier) != null ? _q : null
1661
1661
  }
1662
1662
  },
1663
1663
  request: { body: args },
@@ -1916,6 +1916,7 @@ var GoogleGenerativeAILanguageModel = class {
1916
1916
  const isStreamingChunk = part.functionCall.partialArgs != null || part.functionCall.name != null && part.functionCall.willContinue === true;
1917
1917
  const isTerminalChunk = part.functionCall.name == null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue == null;
1918
1918
  const isCompleteCall = part.functionCall.name != null && part.functionCall.args != null && part.functionCall.partialArgs == null;
1919
+ const isNoArgsCompleteCall = part.functionCall.name != null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue !== true;
1919
1920
  if (isStreamingChunk) {
1920
1921
  if (part.functionCall.name != null && part.functionCall.willContinue === true) {
1921
1922
  const toolCallId = generateId3();
@@ -2012,6 +2013,28 @@ var GoogleGenerativeAILanguageModel = class {
2012
2013
  providerMetadata: providerMeta
2013
2014
  });
2014
2015
  hasToolCalls = true;
2016
+ } else if (isNoArgsCompleteCall) {
2017
+ const toolCallId = generateId3();
2018
+ const toolName = part.functionCall.name;
2019
+ controller.enqueue({
2020
+ type: "tool-input-start",
2021
+ id: toolCallId,
2022
+ toolName,
2023
+ providerMetadata: providerMeta
2024
+ });
2025
+ controller.enqueue({
2026
+ type: "tool-input-end",
2027
+ id: toolCallId,
2028
+ providerMetadata: providerMeta
2029
+ });
2030
+ controller.enqueue({
2031
+ type: "tool-call",
2032
+ toolCallId,
2033
+ toolName,
2034
+ input: "{}",
2035
+ providerMetadata: providerMeta
2036
+ });
2037
+ hasToolCalls = true;
2015
2038
  }
2016
2039
  }
2017
2040
  }
@@ -3000,7 +3023,7 @@ var googleVideoModelOptionsSchema = (0, import_provider_utils15.lazySchema)(
3000
3023
  );
3001
3024
 
3002
3025
  // src/interactions/google-interactions-language-model.ts
3003
- var import_provider_utils20 = require("@ai-sdk/provider-utils");
3026
+ var import_provider_utils22 = require("@ai-sdk/provider-utils");
3004
3027
 
3005
3028
  // src/interactions/convert-google-interactions-usage.ts
3006
3029
  function convertGoogleInteractionsUsage(usage) {
@@ -4609,7 +4632,39 @@ function parseGoogleInteractionsOutputs({
4609
4632
  }
4610
4633
 
4611
4634
  // src/interactions/poll-google-interactions.ts
4635
+ var import_provider_utils20 = require("@ai-sdk/provider-utils");
4636
+
4637
+ // src/interactions/cancel-google-interaction.ts
4612
4638
  var import_provider_utils19 = require("@ai-sdk/provider-utils");
4639
+ var getOriginalFetch = () => globalThis.fetch;
4640
+ async function cancelGoogleInteraction({
4641
+ baseURL,
4642
+ interactionId,
4643
+ headers,
4644
+ fetch = getOriginalFetch()
4645
+ }) {
4646
+ if (interactionId == null || interactionId.length === 0) {
4647
+ return;
4648
+ }
4649
+ const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}/cancel`;
4650
+ try {
4651
+ const response = await fetch(url, {
4652
+ method: "POST",
4653
+ headers: (0, import_provider_utils19.withUserAgentSuffix)(
4654
+ (0, import_provider_utils19.combineHeaders)({ "Content-Type": "application/json" }, headers),
4655
+ (0, import_provider_utils19.getRuntimeEnvironmentUserAgent)()
4656
+ ),
4657
+ body: "{}"
4658
+ });
4659
+ try {
4660
+ await response.text();
4661
+ } catch (e) {
4662
+ }
4663
+ } catch (e) {
4664
+ }
4665
+ }
4666
+
4667
+ // src/interactions/poll-google-interactions.ts
4613
4668
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "incomplete"]);
4614
4669
  function isTerminalStatus(status) {
4615
4670
  return status != null && TERMINAL_STATUSES.has(status);
@@ -4635,34 +4690,43 @@ async function pollGoogleInteractionUntilTerminal({
4635
4690
  const startedAt = Date.now();
4636
4691
  let nextDelayMs = initialDelayMs;
4637
4692
  const url = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
4638
- while (true) {
4639
- if (abortSignal == null ? void 0 : abortSignal.aborted) {
4640
- throw new DOMException("Polling was aborted", "AbortError");
4641
- }
4642
- if (Date.now() - startedAt > timeoutMs) {
4643
- throw new Error(
4644
- `google.interactions: timed out polling interaction ${interactionId} after ${timeoutMs}ms.`
4645
- );
4693
+ const cancelOnServer = () => cancelGoogleInteraction({ baseURL, interactionId, headers, fetch });
4694
+ try {
4695
+ while (true) {
4696
+ if (abortSignal == null ? void 0 : abortSignal.aborted) {
4697
+ await cancelOnServer();
4698
+ throw new DOMException("Polling was aborted", "AbortError");
4699
+ }
4700
+ if (Date.now() - startedAt > timeoutMs) {
4701
+ throw new Error(
4702
+ `google.interactions: timed out polling interaction ${interactionId} after ${timeoutMs}ms.`
4703
+ );
4704
+ }
4705
+ await (0, import_provider_utils20.delay)(nextDelayMs, { abortSignal });
4706
+ const {
4707
+ value: response,
4708
+ rawValue: rawResponse,
4709
+ responseHeaders
4710
+ } = await (0, import_provider_utils20.getFromApi)({
4711
+ url,
4712
+ headers,
4713
+ failedResponseHandler: googleFailedResponseHandler,
4714
+ successfulResponseHandler: (0, import_provider_utils20.createJsonResponseHandler)(
4715
+ googleInteractionsResponseSchema
4716
+ ),
4717
+ abortSignal,
4718
+ fetch
4719
+ });
4720
+ if (isTerminalStatus(response.status)) {
4721
+ return { response, rawResponse, responseHeaders };
4722
+ }
4723
+ nextDelayMs = Math.min(nextDelayMs * 2, maxDelayMs);
4646
4724
  }
4647
- await (0, import_provider_utils19.delay)(nextDelayMs, { abortSignal });
4648
- const {
4649
- value: response,
4650
- rawValue: rawResponse,
4651
- responseHeaders
4652
- } = await (0, import_provider_utils19.getFromApi)({
4653
- url,
4654
- headers,
4655
- failedResponseHandler: googleFailedResponseHandler,
4656
- successfulResponseHandler: (0, import_provider_utils19.createJsonResponseHandler)(
4657
- googleInteractionsResponseSchema
4658
- ),
4659
- abortSignal,
4660
- fetch
4661
- });
4662
- if (isTerminalStatus(response.status)) {
4663
- return { response, rawResponse, responseHeaders };
4725
+ } catch (error) {
4726
+ if ((0, import_provider_utils20.isAbortError)(error)) {
4727
+ await cancelOnServer();
4664
4728
  }
4665
- nextDelayMs = Math.min(nextDelayMs * 2, maxDelayMs);
4729
+ throw error;
4666
4730
  }
4667
4731
  }
4668
4732
 
@@ -4814,6 +4878,169 @@ function prepareGoogleInteractionsTools({
4814
4878
  };
4815
4879
  }
4816
4880
 
4881
+ // src/interactions/stream-google-interactions.ts
4882
+ var import_provider_utils21 = require("@ai-sdk/provider-utils");
4883
+ var DEFAULT_MAX_RETRIES = 3;
4884
+ var DEFAULT_RETRY_DELAY_MS = 500;
4885
+ function streamGoogleInteractionEvents({
4886
+ baseURL,
4887
+ interactionId,
4888
+ headers,
4889
+ fetch,
4890
+ abortSignal,
4891
+ maxRetries = DEFAULT_MAX_RETRIES,
4892
+ retryDelayMs = DEFAULT_RETRY_DELAY_MS
4893
+ }) {
4894
+ if (interactionId.length === 0) {
4895
+ throw new Error(
4896
+ "google.interactions: cannot stream a background interaction without an id."
4897
+ );
4898
+ }
4899
+ const eventSourceHeaders = {
4900
+ ...headers,
4901
+ accept: "text/event-stream"
4902
+ };
4903
+ let lastEventId;
4904
+ let complete = false;
4905
+ let attempt = 0;
4906
+ let receivedAnyEventThisAttempt = false;
4907
+ let currentReader;
4908
+ const internalAbort = new AbortController();
4909
+ const upstreamAbortHandler = () => internalAbort.abort();
4910
+ if (abortSignal != null) {
4911
+ if (abortSignal.aborted) {
4912
+ internalAbort.abort();
4913
+ } else {
4914
+ abortSignal.addEventListener("abort", upstreamAbortHandler, {
4915
+ once: true
4916
+ });
4917
+ }
4918
+ }
4919
+ const effectiveSignal = internalAbort.signal;
4920
+ function buildUrl() {
4921
+ const base = `${baseURL}/interactions/${encodeURIComponent(interactionId)}`;
4922
+ const params = new URLSearchParams({ stream: "true" });
4923
+ if (lastEventId != null) {
4924
+ params.set("last_event_id", lastEventId);
4925
+ }
4926
+ return `${base}?${params.toString()}`;
4927
+ }
4928
+ async function openReader() {
4929
+ const { value: stream } = await (0, import_provider_utils21.getFromApi)({
4930
+ url: buildUrl(),
4931
+ headers: eventSourceHeaders,
4932
+ failedResponseHandler: googleFailedResponseHandler,
4933
+ successfulResponseHandler: (0, import_provider_utils21.createEventSourceResponseHandler)(
4934
+ googleInteractionsEventSchema
4935
+ ),
4936
+ abortSignal: effectiveSignal,
4937
+ fetch
4938
+ });
4939
+ return stream.getReader();
4940
+ }
4941
+ return new ReadableStream({
4942
+ async start(controller) {
4943
+ try {
4944
+ while (!complete && !effectiveSignal.aborted) {
4945
+ if (currentReader == null) {
4946
+ try {
4947
+ currentReader = await openReader();
4948
+ receivedAnyEventThisAttempt = false;
4949
+ } catch (error) {
4950
+ if ((0, import_provider_utils21.isAbortError)(error) || effectiveSignal.aborted) {
4951
+ controller.error(error);
4952
+ return;
4953
+ }
4954
+ attempt++;
4955
+ if (attempt >= maxRetries) {
4956
+ controller.error(error);
4957
+ return;
4958
+ }
4959
+ await (0, import_provider_utils21.delay)(retryDelayMs * attempt, {
4960
+ abortSignal: effectiveSignal
4961
+ });
4962
+ continue;
4963
+ }
4964
+ }
4965
+ try {
4966
+ const { done, value } = await currentReader.read();
4967
+ if (done) {
4968
+ currentReader = void 0;
4969
+ if (complete) break;
4970
+ if (!receivedAnyEventThisAttempt) {
4971
+ attempt++;
4972
+ if (attempt >= maxRetries) {
4973
+ controller.error(
4974
+ new Error(
4975
+ "google.interactions: SSE stream closed without producing any events."
4976
+ )
4977
+ );
4978
+ return;
4979
+ }
4980
+ await (0, import_provider_utils21.delay)(retryDelayMs * attempt, {
4981
+ abortSignal: effectiveSignal
4982
+ });
4983
+ } else {
4984
+ attempt = 0;
4985
+ }
4986
+ continue;
4987
+ }
4988
+ receivedAnyEventThisAttempt = true;
4989
+ if (value.success) {
4990
+ const ev = value.value;
4991
+ if (typeof ev.event_id === "string" && ev.event_id.length > 0) {
4992
+ lastEventId = ev.event_id;
4993
+ }
4994
+ if (ev.event_type === "interaction.complete" || ev.event_type === "error") {
4995
+ complete = true;
4996
+ }
4997
+ }
4998
+ controller.enqueue(value);
4999
+ } catch (error) {
5000
+ if ((0, import_provider_utils21.isAbortError)(error) || effectiveSignal.aborted) {
5001
+ controller.error(error);
5002
+ return;
5003
+ }
5004
+ currentReader = void 0;
5005
+ attempt++;
5006
+ if (attempt >= maxRetries) {
5007
+ controller.error(error);
5008
+ return;
5009
+ }
5010
+ await (0, import_provider_utils21.delay)(retryDelayMs * attempt, {
5011
+ abortSignal: effectiveSignal
5012
+ });
5013
+ }
5014
+ }
5015
+ controller.close();
5016
+ } catch (error) {
5017
+ controller.error(error);
5018
+ } finally {
5019
+ if (abortSignal != null) {
5020
+ abortSignal.removeEventListener("abort", upstreamAbortHandler);
5021
+ }
5022
+ currentReader == null ? void 0 : currentReader.cancel().catch(() => {
5023
+ });
5024
+ currentReader = void 0;
5025
+ if (effectiveSignal.aborted && !complete) {
5026
+ await cancelGoogleInteraction({
5027
+ baseURL,
5028
+ interactionId,
5029
+ headers,
5030
+ fetch
5031
+ });
5032
+ }
5033
+ }
5034
+ },
5035
+ cancel() {
5036
+ internalAbort.abort();
5037
+ currentReader == null ? void 0 : currentReader.cancel().catch(() => {
5038
+ });
5039
+ currentReader = void 0;
5040
+ }
5041
+ });
5042
+ }
5043
+
4817
5044
  // src/interactions/synthesize-google-interactions-agent-stream.ts
4818
5045
  function synthesizeGoogleInteractionsAgentStream({
4819
5046
  response,
@@ -4989,7 +5216,7 @@ var GoogleInteractionsLanguageModel = class {
4989
5216
  async getArgs(options) {
4990
5217
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
4991
5218
  const warnings = [];
4992
- const opts = await (0, import_provider_utils20.parseProviderOptions)({
5219
+ const opts = await (0, import_provider_utils22.parseProviderOptions)({
4993
5220
  provider: "google",
4994
5221
  providerOptions: options.providerOptions,
4995
5222
  schema: googleInteractionsLanguageModelOptions
@@ -5127,16 +5354,16 @@ var GoogleInteractionsLanguageModel = class {
5127
5354
  var _a, _b, _c, _d, _e, _f;
5128
5355
  const { args, warnings, isAgent, pollingTimeoutMs } = await this.getArgs(options);
5129
5356
  const url = `${this.config.baseURL}/interactions`;
5130
- const mergedHeaders = (0, import_provider_utils20.combineHeaders)(
5131
- this.config.headers ? await (0, import_provider_utils20.resolve)(this.config.headers) : void 0,
5357
+ const mergedHeaders = (0, import_provider_utils22.combineHeaders)(
5358
+ this.config.headers ? await (0, import_provider_utils22.resolve)(this.config.headers) : void 0,
5132
5359
  options.headers
5133
5360
  );
5134
- const postResult = await (0, import_provider_utils20.postJsonToApi)({
5361
+ const postResult = await (0, import_provider_utils22.postJsonToApi)({
5135
5362
  url,
5136
5363
  headers: mergedHeaders,
5137
5364
  body: args,
5138
5365
  failedResponseHandler: googleFailedResponseHandler,
5139
- successfulResponseHandler: (0, import_provider_utils20.createJsonResponseHandler)(
5366
+ successfulResponseHandler: (0, import_provider_utils22.createJsonResponseHandler)(
5140
5367
  googleInteractionsResponseSchema
5141
5368
  ),
5142
5369
  abortSignal: options.abortSignal,
@@ -5163,7 +5390,7 @@ var GoogleInteractionsLanguageModel = class {
5163
5390
  const interactionId = typeof response.id === "string" && response.id.length > 0 ? response.id : void 0;
5164
5391
  const { content, hasFunctionCall } = parseGoogleInteractionsOutputs({
5165
5392
  outputs: (_b = response.outputs) != null ? _b : null,
5166
- generateId: (_c = this.config.generateId) != null ? _c : import_provider_utils20.generateId,
5393
+ generateId: (_c = this.config.generateId) != null ? _c : import_provider_utils22.generateId,
5167
5394
  interactionId
5168
5395
  });
5169
5396
  const finishReason = {
@@ -5207,12 +5434,12 @@ var GoogleInteractionsLanguageModel = class {
5207
5434
  var _a;
5208
5435
  const { args, warnings, isAgent, pollingTimeoutMs } = await this.getArgs(options);
5209
5436
  const url = `${this.config.baseURL}/interactions`;
5210
- const mergedHeaders = (0, import_provider_utils20.combineHeaders)(
5211
- this.config.headers ? await (0, import_provider_utils20.resolve)(this.config.headers) : void 0,
5437
+ const mergedHeaders = (0, import_provider_utils22.combineHeaders)(
5438
+ this.config.headers ? await (0, import_provider_utils22.resolve)(this.config.headers) : void 0,
5212
5439
  options.headers
5213
5440
  );
5214
5441
  if (isAgent) {
5215
- return this.doStreamAgent({
5442
+ return this.doStreamBackground({
5216
5443
  args,
5217
5444
  warnings,
5218
5445
  url,
@@ -5222,12 +5449,12 @@ var GoogleInteractionsLanguageModel = class {
5222
5449
  });
5223
5450
  }
5224
5451
  const body = { ...args, stream: true };
5225
- const { responseHeaders, value: response } = await (0, import_provider_utils20.postJsonToApi)({
5452
+ const { responseHeaders, value: response } = await (0, import_provider_utils22.postJsonToApi)({
5226
5453
  url,
5227
5454
  headers: mergedHeaders,
5228
5455
  body,
5229
5456
  failedResponseHandler: googleFailedResponseHandler,
5230
- successfulResponseHandler: (0, import_provider_utils20.createEventSourceResponseHandler)(
5457
+ successfulResponseHandler: (0, import_provider_utils22.createEventSourceResponseHandler)(
5231
5458
  googleInteractionsEventSchema
5232
5459
  ),
5233
5460
  abortSignal: options.abortSignal,
@@ -5236,7 +5463,7 @@ var GoogleInteractionsLanguageModel = class {
5236
5463
  const headerServiceTier = responseHeaders == null ? void 0 : responseHeaders["x-gemini-service-tier"];
5237
5464
  const transform = buildGoogleInteractionsStreamTransform({
5238
5465
  warnings,
5239
- generateId: (_a = this.config.generateId) != null ? _a : import_provider_utils20.generateId,
5466
+ generateId: (_a = this.config.generateId) != null ? _a : import_provider_utils22.generateId,
5240
5467
  includeRawChunks: options.includeRawChunks,
5241
5468
  serviceTier: headerServiceTier
5242
5469
  });
@@ -5247,26 +5474,24 @@ var GoogleInteractionsLanguageModel = class {
5247
5474
  };
5248
5475
  }
5249
5476
  /*
5250
- * Drive the streaming surface for agent calls. Agent calls require
5477
+ * Drive the streaming surface for agent calls. Agents require
5251
5478
  * `background: true`, which is incompatible with `stream: true` on POST.
5252
5479
  *
5253
- * In principle the API also exposes `GET /interactions/{id}?stream=true`
5254
- * to replay events as the agent runs. In practice the connection is
5255
- * idle for long stretches while the agent thinks (deep-research can run
5256
- * for a minute or more between SSE events), and undici's default body
5257
- * timeout terminates the request mid-flight with `UND_ERR_BODY_TIMEOUT`.
5258
- * Tuning the timeout per-call would require the caller to thread an
5259
- * `undici.Agent` through `fetch`, which contradicts the AI SDK's
5260
- * pluggable-fetch contract.
5480
+ * Approach:
5481
+ * 1. POST `/interactions` with `background: true`. The response includes
5482
+ * the interaction id and an initial (usually non-terminal) status.
5483
+ * 2. If the POST status is already terminal (rare), synthesize a stream
5484
+ * from the polled outputs and we're done.
5485
+ * 3. Otherwise open `GET /interactions/{id}?stream=true` and pipe the
5486
+ * SSE events through `buildGoogleInteractionsStreamTransform` so the
5487
+ * consumer receives text deltas / thinking summaries / tool events as
5488
+ * they happen instead of all at once at the end.
5261
5489
  *
5262
- * We therefore drive `doStream` exactly like `doGenerate` for agents:
5263
- * POST with `background: true`, poll `GET /interactions/{id}` until
5264
- * terminal, then synthesize the stream from the final outputs. The
5265
- * user-facing surface stays identical -- text-start / text-delta /
5266
- * text-end / finish parts arrive in the same order as a true SSE
5267
- * response, just buffered until the agent completes.
5490
+ * The SSE connection can drop while the agent idles between events
5491
+ * (`UND_ERR_BODY_TIMEOUT`); `streamGoogleInteractionEvents` handles the
5492
+ * reconnect-with-`last_event_id` loop transparently.
5268
5493
  */
5269
- async doStreamAgent({
5494
+ async doStreamBackground({
5270
5495
  args,
5271
5496
  warnings,
5272
5497
  url,
@@ -5275,45 +5500,55 @@ var GoogleInteractionsLanguageModel = class {
5275
5500
  pollingTimeoutMs
5276
5501
  }) {
5277
5502
  var _a, _b;
5278
- const postResult = await (0, import_provider_utils20.postJsonToApi)({
5503
+ const postResult = await (0, import_provider_utils22.postJsonToApi)({
5279
5504
  url,
5280
5505
  headers: mergedHeaders,
5281
5506
  body: args,
5282
5507
  failedResponseHandler: googleFailedResponseHandler,
5283
- successfulResponseHandler: (0, import_provider_utils20.createJsonResponseHandler)(
5508
+ successfulResponseHandler: (0, import_provider_utils22.createJsonResponseHandler)(
5284
5509
  googleInteractionsResponseSchema
5285
5510
  ),
5286
5511
  abortSignal: options.abortSignal,
5287
5512
  fetch: this.config.fetch
5288
5513
  });
5289
- let { responseHeaders: postHeaders, value: postResponse } = postResult;
5514
+ const { responseHeaders: postHeaders, value: postResponse } = postResult;
5290
5515
  const interactionId = postResponse.id;
5291
5516
  if (interactionId == null || interactionId.length === 0) {
5292
5517
  throw new Error(
5293
- "google.interactions: agent POST response did not include an interaction id; cannot poll for the agent result."
5518
+ "google.interactions: background POST response did not include an interaction id; cannot stream the result."
5294
5519
  );
5295
5520
  }
5296
- if (!isTerminalStatus(postResponse.status)) {
5297
- const polled = await pollGoogleInteractionUntilTerminal({
5298
- baseURL: this.config.baseURL,
5299
- interactionId,
5300
- headers: mergedHeaders,
5301
- fetch: this.config.fetch,
5302
- abortSignal: options.abortSignal,
5303
- timeoutMs: pollingTimeoutMs
5521
+ const headerServiceTier = postHeaders == null ? void 0 : postHeaders["x-gemini-service-tier"];
5522
+ if (isTerminalStatus(postResponse.status)) {
5523
+ const synthesized = synthesizeGoogleInteractionsAgentStream({
5524
+ response: postResponse,
5525
+ warnings,
5526
+ generateId: (_a = this.config.generateId) != null ? _a : import_provider_utils22.generateId,
5527
+ includeRawChunks: options.includeRawChunks,
5528
+ headerServiceTier
5304
5529
  });
5305
- postResponse = polled.response;
5306
- postHeaders = (_a = polled.responseHeaders) != null ? _a : postHeaders;
5530
+ return {
5531
+ stream: synthesized,
5532
+ request: { body: args },
5533
+ response: { headers: postHeaders }
5534
+ };
5307
5535
  }
5308
- const stream = synthesizeGoogleInteractionsAgentStream({
5309
- response: postResponse,
5536
+ void pollingTimeoutMs;
5537
+ const events = streamGoogleInteractionEvents({
5538
+ baseURL: this.config.baseURL,
5539
+ interactionId,
5540
+ headers: mergedHeaders,
5541
+ fetch: this.config.fetch,
5542
+ abortSignal: options.abortSignal
5543
+ });
5544
+ const transform = buildGoogleInteractionsStreamTransform({
5310
5545
  warnings,
5311
- generateId: (_b = this.config.generateId) != null ? _b : import_provider_utils20.generateId,
5546
+ generateId: (_b = this.config.generateId) != null ? _b : import_provider_utils22.generateId,
5312
5547
  includeRawChunks: options.includeRawChunks,
5313
- headerServiceTier: postHeaders == null ? void 0 : postHeaders["x-gemini-service-tier"]
5548
+ serviceTier: headerServiceTier
5314
5549
  });
5315
5550
  return {
5316
- stream,
5551
+ stream: events.pipeThrough(transform),
5317
5552
  request: { body: args },
5318
5553
  response: { headers: postHeaders }
5319
5554
  };
@@ -5331,11 +5566,11 @@ function pruneUndefined(obj) {
5331
5566
  // src/google-provider.ts
5332
5567
  function createGoogleGenerativeAI(options = {}) {
5333
5568
  var _a, _b;
5334
- const baseURL = (_a = (0, import_provider_utils21.withoutTrailingSlash)(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
5569
+ const baseURL = (_a = (0, import_provider_utils23.withoutTrailingSlash)(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
5335
5570
  const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
5336
- const getHeaders = () => (0, import_provider_utils21.withUserAgentSuffix)(
5571
+ const getHeaders = () => (0, import_provider_utils23.withUserAgentSuffix)(
5337
5572
  {
5338
- "x-goog-api-key": (0, import_provider_utils21.loadApiKey)({
5573
+ "x-goog-api-key": (0, import_provider_utils23.loadApiKey)({
5339
5574
  apiKey: options.apiKey,
5340
5575
  environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
5341
5576
  description: "Google Generative AI"
@@ -5350,7 +5585,7 @@ function createGoogleGenerativeAI(options = {}) {
5350
5585
  provider: providerName,
5351
5586
  baseURL,
5352
5587
  headers: getHeaders,
5353
- generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils21.generateId,
5588
+ generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils23.generateId,
5354
5589
  supportedUrls: () => ({
5355
5590
  "*": [
5356
5591
  // Google Generative Language "files" endpoint
@@ -5385,7 +5620,7 @@ function createGoogleGenerativeAI(options = {}) {
5385
5620
  baseURL,
5386
5621
  headers: getHeaders,
5387
5622
  fetch: options.fetch,
5388
- generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils21.generateId
5623
+ generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils23.generateId
5389
5624
  });
5390
5625
  };
5391
5626
  const createInteractionsModel = (modelIdOrAgent) => {
@@ -5396,7 +5631,7 @@ function createGoogleGenerativeAI(options = {}) {
5396
5631
  provider: `${providerName}.interactions`,
5397
5632
  baseURL,
5398
5633
  headers: getHeaders,
5399
- generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils21.generateId,
5634
+ generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils23.generateId,
5400
5635
  fetch: options.fetch
5401
5636
  }
5402
5637
  );