ai 7.0.178 → 7.0.180

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.
@@ -1,4 +1,4 @@
1
- import { $c as LanguageModelCallOptions, Al as addLanguageModelUsage, Ao as ToolApprovalStatus, Ba as GenerateTextOnEndCallback, Bl as LanguageModelResponseMetadata, Ca as TelemetryDispatcher, El as Warning, Eo as ResolvedToolCallers, Ga as GenerateTextOnStepFinishCallback, Go as StaticToolOutputDenied, Ha as GenerateTextOnStartCallback, Hl as LanguageModelRequestMetadata, Jl as ToolChoice, Js as ContentPart, Ka as GenerateTextOnStepStartCallback, Kl as FinishReason, Ks as StepResult, Ml as createNullLanguageModelUsage, Pc as ToolModelMessage$1, So as ToolCallRepairFunction, Ua as GenerateTextOnStepEndCallback, Vl as ResponseMessage, Vo as ToolOrder, Wa as GenerateTextOnStepErrorCallback, Ws as DefaultStepResult, Xs as StaticToolResult, Ys as DynamicToolResult, Zo as createAsyncIterableStream, Zs as TypedToolResult, _a as LanguageModelStreamPart, _c as StandardizedPrompt, _l as DownloadFunction, _o as OnToolExecutionEndCallback, ac as TypedToolCall, dc as IncludedContext, fc as IncludedToolsContext, ga as GenerateTextResult, gc as Callback, ic as StaticToolCall, jl as asLanguageModelUsage, kl as LanguageModelUsage, ko as ToolApprovalConfiguration, mo as ToolInputRefinement, nc as ToolApprovalRequestOutput, oc as ReasoningFileOutput, pc as TelemetryOptions, po as ToolsContextSettings, ql as LanguageModel, qo as InferCompleteOutput, rc as DynamicToolCall, sc as ReasoningOutput, tc as ToolApprovalResponseOutput, to as Output, uc as GeneratedFile, vc as standardizePrompt, vl as createDefaultDownloadFunction, vo as OnToolExecutionStartCallback, wc as AssistantModelMessage$1, wl as logWarnings, wo as InvalidToolInputError, xo as ToolOutput, za as GenerateTextOnAbortCallback, zc as Instructions } from "../index-kb5wF2kk.js";
1
+ import { $c as LanguageModelCallOptions, Al as addLanguageModelUsage, Ao as ToolApprovalStatus, Ba as GenerateTextOnEndCallback, Bl as LanguageModelResponseMetadata, Ca as TelemetryDispatcher, El as Warning, Eo as ResolvedToolCallers, Ga as GenerateTextOnStepFinishCallback, Go as StaticToolOutputDenied, Ha as GenerateTextOnStartCallback, Hl as LanguageModelRequestMetadata, Jl as ToolChoice, Js as ContentPart, Ka as GenerateTextOnStepStartCallback, Kl as FinishReason, Ks as StepResult, Ml as createNullLanguageModelUsage, Pc as ToolModelMessage$1, So as ToolCallRepairFunction, Ua as GenerateTextOnStepEndCallback, Vl as ResponseMessage, Vo as ToolOrder, Wa as GenerateTextOnStepErrorCallback, Ws as DefaultStepResult, Xs as StaticToolResult, Ys as DynamicToolResult, Zo as createAsyncIterableStream, Zs as TypedToolResult, _a as LanguageModelStreamPart, _c as StandardizedPrompt, _l as DownloadFunction, _o as OnToolExecutionEndCallback, ac as TypedToolCall, dc as IncludedContext, fc as IncludedToolsContext, ga as GenerateTextResult, gc as Callback, ic as StaticToolCall, jl as asLanguageModelUsage, kl as LanguageModelUsage, ko as ToolApprovalConfiguration, mo as ToolInputRefinement, nc as ToolApprovalRequestOutput, oc as ReasoningFileOutput, pc as TelemetryOptions, po as ToolsContextSettings, ql as LanguageModel, qo as InferCompleteOutput, rc as DynamicToolCall, sc as ReasoningOutput, tc as ToolApprovalResponseOutput, to as Output, uc as GeneratedFile, vc as standardizePrompt, vl as createDefaultDownloadFunction, vo as OnToolExecutionStartCallback, wc as AssistantModelMessage$1, wl as logWarnings, wo as InvalidToolInputError, xo as ToolOutput, za as GenerateTextOnAbortCallback, zc as Instructions } from "../index-CM_8u8gB.js";
2
2
  import { Arrayable, Context, Experimental_SandboxSession, FlexibleSchema, IdGenerator, InferToolSetContext, ModelMessage, RetryFunction, ShouldRetryFunction, Tool, ToolApprovalRequest, ToolApprovalResponse, ToolResultOutput, ToolResultPart, ToolSet, convertAsyncIteratorToReadableStream } from "@ai-sdk/provider-utils";
3
3
  import { EmbeddingModelV4, Experimental_DecisionModelV4, Experimental_ExtractionModelV4, Experimental_SpeechTranslationModelV4, Experimental_VideoModelV4, ImageModelV4, LanguageModelV4, LanguageModelV4Content, LanguageModelV4FunctionTool, LanguageModelV4Prompt, LanguageModelV4ProviderTool, LanguageModelV4ToolCall, LanguageModelV4ToolChoice, LanguageModelV4ToolResultOutput, RerankingModelV4, SharedV4Warning, SpeechModelV4, TranscriptionModelV4 } from "@ai-sdk/provider";
4
4
  //#region src/prompt/convert-to-language-model-prompt.d.ts
@@ -1,3 +1,3 @@
1
- import { $ as convertToLanguageModelPrompt, B as setAbortTimeout, C as resolveToolApproval, E as DefaultGenerateTextResult, Et as logWarnings, G as addLanguageModelUsage, H as mergeAbortSignals, J as standardizePrompt, K as asLanguageModelUsage, O as validateToolContext, P as convertLanguageModelContent, Q as createToolModelOutput, R as collectToolApprovals, S as filterIncludedContext, V as prepareRetries, X as prepareToolChoice, Y as prepareTools, Z as prepareLanguageModelCallOptions, _ as createTelemetryDispatcher, a as createAsyncIterableStream, c as validateApprovedToolApprovals, d as verifyToolApprovalSignature, et as downloadAssets, g as DefaultStepResult, h as createRestrictedTelemetryDispatcher, ht as resolveLanguageModel, k as createToolSearchState, n as logDefaultStopConditionWarning, o as mapWithConcurrency, ot as mergeObjects, p as toResponseMessages, q as createNullLanguageModelUsage, r as isOutputChunk, s as prepareToolCallConcurrency, st as createDefaultDownloadFunction, tt as mapToolResultOutput, u as signToolApproval, w as parseToolCall, x as mergeCallbacks, z as calculateTokensPerSecond } from "../default-stop-condition-BskNu2xj.js";
1
+ import { $ as convertToLanguageModelPrompt, B as setAbortTimeout, C as resolveToolApproval, E as DefaultGenerateTextResult, Et as logWarnings, G as addLanguageModelUsage, H as mergeAbortSignals, J as standardizePrompt, K as asLanguageModelUsage, O as validateToolContext, P as convertLanguageModelContent, Q as createToolModelOutput, R as collectToolApprovals, S as filterIncludedContext, V as prepareRetries, X as prepareToolChoice, Y as prepareTools, Z as prepareLanguageModelCallOptions, _ as createTelemetryDispatcher, a as createAsyncIterableStream, c as validateApprovedToolApprovals, d as verifyToolApprovalSignature, et as downloadAssets, g as DefaultStepResult, h as createRestrictedTelemetryDispatcher, ht as resolveLanguageModel, k as createToolSearchState, n as logDefaultStopConditionWarning, o as mapWithConcurrency, ot as mergeObjects, p as toResponseMessages, q as createNullLanguageModelUsage, r as isOutputChunk, s as prepareToolCallConcurrency, st as createDefaultDownloadFunction, tt as mapToolResultOutput, u as signToolApproval, w as parseToolCall, x as mergeCallbacks, z as calculateTokensPerSecond } from "../default-stop-condition-vtYEJcnz.js";
2
2
  import { convertAsyncIteratorToReadableStream } from "@ai-sdk/provider-utils";
3
3
  export { DefaultGenerateTextResult, DefaultStepResult, addLanguageModelUsage, asLanguageModelUsage, calculateTokensPerSecond, collectToolApprovals, convertAsyncIteratorToReadableStream, convertLanguageModelContent, convertToLanguageModelPrompt, createAsyncIterableStream, createDefaultDownloadFunction, createNullLanguageModelUsage, createRestrictedTelemetryDispatcher, createTelemetryDispatcher, createToolModelOutput, createToolSearchState, downloadAssets, filterIncludedContext, isOutputChunk, logDefaultStopConditionWarning, logWarnings, mapToolResultOutput, mapWithConcurrency, mergeAbortSignals, mergeCallbacks, mergeObjects, parseToolCall, prepareLanguageModelCallOptions as prepareCallSettings, prepareLanguageModelCallOptions, prepareRetries, prepareToolCallConcurrency, prepareToolChoice, prepareTools, resolveLanguageModel, resolveToolApproval, setAbortTimeout, signToolApproval, standardizePrompt, toResponseMessages, validateApprovedToolApprovals, validateToolContext, verifyToolApprovalSignature };
@@ -71,14 +71,15 @@ A model can return several tool calls in one response. `generateText`, `streamTe
71
71
  `opaPolicy` therefore evaluates every tool call after the first one of a response twice, unless the first evaluation already denies it:
72
72
 
73
73
  1. With `messages` as they were sent to the model.
74
- 2. With the earlier tool calls of the same response appended as an assistant message. Tool calls that the policy denied are followed by a tool message with their `execution-denied` result. The other tool calls have no result yet.
74
+ 2. With the earlier tool calls of the same response appended as an assistant message. Tool calls that are denied are followed by a tool message with their `execution-denied` result. The other tool calls have no result yet.
75
75
 
76
76
  The more restrictive decision applies: `deny` before `requires-approval`, before no matching rule, before `allow`.
77
77
 
78
78
  - A limit such as a budget, a quota, or "only one delete per conversation" counts the earlier tool calls of the same response.
79
79
  - A rule that allows a tool call only after another one, such as "deploy only after the tests ran", is not satisfied by a tool call of the same response, because that call has not run yet.
80
+ - Check a prerequisite through the earlier tool's result in history, not through the presence of its tool call. A tool call does not prove that the tool ran or succeeded. This also matters when an approved tool call is evaluated again before it runs: the history then contains the response with the tool calls, but not their results.
80
81
  - Base a limit that must hold within one response on tool calls, not on tool results. The earlier tool calls of a response have no results when the policy is evaluated.
81
- - OPA receives two queries for such a tool call, so it appears twice in OPA decision logs. A custom `toInput` is called twice as well. When it returns the same input both times, for example because it does not use `messages`, the policy is evaluated once.
82
+ - OPA receives two queries for such a tool call, so it appears twice in OPA decision logs. A custom `toInput` is called twice as well. When it returns the same input both times, for example because it does not use `messages`, the policy is evaluated once. With `wrapMcpTools` in hard allowlist mode (`default: 'denied'`), a tool call whose first evaluation is `not-applicable` is treated as denied by the fallback and evaluated once.
82
83
  - `opaPolicy` recognizes the tool calls of one response by the `messages` array they are evaluated with. `generateText`, `streamText`, and `ToolLoopAgent` pass the same array for all tool calls of a response and a new array for every response. When a caller passes a separate array for each tool call, `opaPolicy` evaluates each tool call once, with `messages` as passed. A caller must not pass one array for several responses: the tool calls of the earlier responses would count as earlier tool calls of the later ones.
83
84
 
84
85
  ### Tool calls that a user approved
@@ -350,6 +351,8 @@ Defaults for uncovered tools:
350
351
  - `'denied'`: hard allowlist mode. The policy enumerates what is allowed; everything else is rejected.
351
352
  - `'approved'`: allow. Only when the discovery source is fully trusted.
352
353
 
354
+ When the approval is an `opaPolicy` approval, the fallback is applied to each policy evaluation for a tool call, before the evaluations are compared. This holds when you pass `opaPolicy(...)` or `shadow(opaPolicy(...))` directly. A custom wrapper function around it hides the fallback from the policy, so the fallback then applies to the combined decision only.
355
+
353
356
  Despite the name, it works on any `Record<string, Tool>`.
354
357
 
355
358
  ## Allow-all when no policy is configured
@@ -218,6 +218,65 @@ const mcpClient = await createMCPClient({
218
218
 
219
219
  You can also bring your own transport by implementing the `MCPTransport` interface for specific requirements not covered by the standard transports.
220
220
 
221
+ ### WebMCP Transport
222
+
223
+ `Experimental_WebMCPTransport` (aliased below as `WebMCPTransport`) adapts tools
224
+ registered with the browser's
225
+ [`document.modelContext`](https://webmachinelearning.github.io/webmcp/) to the
226
+ existing MCP client:
227
+
228
+ ```ts
229
+ import {
230
+ createMCPClient,
231
+ Experimental_WebMCPTransport as WebMCPTransport,
232
+ } from '@ai-sdk/mcp';
233
+
234
+ // Run in a browser with WebMCP enabled, after checking API availability.
235
+ const client = await createMCPClient({
236
+ transport: new WebMCPTransport({ modelContext: document.modelContext }),
237
+ });
238
+
239
+ const tools = await client.tools();
240
+ ```
241
+
242
+ The required `modelContext` provides WebMCP's `getTools` and `executeTool`
243
+ methods. The optional `fromOrigins: string[]` constructor option discovers tools
244
+ exposed by additional frame origins, subject to browser permissions. The package
245
+ exports structural `Experimental_WebMCPModelContext` and
246
+ `Experimental_WebMCPTool` types; use browser API
247
+ typings such as `webmcp-types` to declare `document.modelContext`.
248
+
249
+ Use the tool names returned by `listTools` or `tools`: duplicate names across
250
+ frames receive stable aliases such as `getCart_2`. Results include text `content`
251
+ and parsed `structuredContent`. WebMCP `OperationError` failures become tool
252
+ results with `isError: true`; other failures reject the request.
253
+
254
+ WebMCP is an experimental browser API, not an HTTP MCP endpoint. Tool discovery
255
+ and execution happen in the page. To keep model inference on your backend, send
256
+ tool definitions to your API route, then execute the returned calls in
257
+ [`useChat.onToolCall`](/docs/ai-sdk-ui/chatbot-tool-usage) and return results with
258
+ `addToolOutput`. On the backend,
259
+ [`createMCPTools`](/docs/reference/ai-sdk-core/create-mcp-tools) validates and
260
+ converts those definitions into model-facing tools without `execute` functions:
261
+
262
+ ```ts
263
+ import { createMCPTools } from '@ai-sdk/mcp';
264
+
265
+ const { messages, tools: definitions } = await request.json();
266
+ const tools = createMCPTools(definitions);
267
+ ```
268
+
269
+ Pass `tools` to `streamText` and to `convertToModelMessages(messages, { tools })`
270
+ so returned MCP results are converted to model content. The
271
+ [shopping cart example](https://github.com/vercel/ai/tree/main/examples/ai-e2e-next/app/chat/webmcp)
272
+ demonstrates this flow with live page state. Follow the
273
+ [WebMCP shopping cart recipe](/cookbook/next/webmcp-tools) to build it.
274
+
275
+ Tool lists are snapshots. List tools again when the page's available tools change,
276
+ and close the client when the consuming component or browser connection is
277
+ disposed. Cancellation is forwarded to tool execution. Closing the client aborts
278
+ pending calls without unregistering the page's tools.
279
+
221
280
  <Note>
222
281
  The client returned by the `createMCPClient` function is a
223
282
  lightweight client intended for use in tool conversion. It currently does not
@@ -30,7 +30,9 @@ The typical flow is:
30
30
  1. Tool calls are handled by your application with `onToolCall`.
31
31
 
32
32
  For continuous **OpenAI Live** conversations, use an application-owned WebSocket
33
- relay or optional WebRTC via `api.session`. Live uses client delegation: your
33
+ relay or optional WebRTC via `api.session`. With
34
+ [AI Gateway](/providers/ai-sdk-providers/ai-gateway#live-models), the browser can
35
+ also connect straight to the Gateway with a token from `api.token`. Live uses client delegation: your
34
36
  application handles delegated work and submits context rather than using the
35
37
  turn-based tool loop below. See the
36
38
  [`experimental_useRealtime` reference](/docs/reference/ai-sdk-ui/use-realtime)
@@ -417,8 +417,8 @@ try {
417
417
  | [Deepgram](/providers/ai-sdk-providers/deepgram#transcription-models) | `nova-2` (+ variants) |
418
418
  | [Deepgram](/providers/ai-sdk-providers/deepgram#transcription-models) | `nova-3` (+ variants) |
419
419
  | [Gladia](/providers/ai-sdk-providers/gladia#transcription-models) | `default` |
420
- | [AssemblyAI](/providers/ai-sdk-providers/assemblyai#transcription-models) | `universal-3-5-pro` |
421
- | [AssemblyAI](/providers/ai-sdk-providers/assemblyai#transcription-models) | `universal-3-pro` |
420
+ | [AssemblyAI](/providers/ai-sdk-providers/assemblyai#transcription-models) | `assemblyai-stt-3-7` |
421
+ | [AssemblyAI](/providers/ai-sdk-providers/assemblyai#transcription-models) | `universal-2` |
422
422
  | [Fal](/providers/ai-sdk-providers/fal#transcription-models) | `whisper` |
423
423
  | [Fal](/providers/ai-sdk-providers/fal#transcription-models) | `wizper` |
424
424
  | [Google Vertex](/providers/ai-sdk-providers/google-vertex#transcription-models) | `chirp_2` |
@@ -255,5 +255,6 @@ try {
255
255
  | [Fish Audio](/providers/ai-sdk-providers/fish-audio#speech-models) | `s1` |
256
256
  | [Fish Audio](/providers/ai-sdk-providers/fish-audio#speech-models) | `s2-pro` |
257
257
  | [Fish Audio](/providers/ai-sdk-providers/fish-audio#speech-models) | `s2.1-pro` |
258
+ | [AssemblyAI](/providers/ai-sdk-providers/assemblyai#speech-models) | `assemblyai-tts-1` |
258
259
 
259
260
  Above are a small subset of the speech models supported by the AI SDK providers. For more, see the respective provider documentation.
@@ -0,0 +1,65 @@
1
+ ---
2
+ title: createMCPTools
3
+ description: Convert MCP tool definitions into AI SDK tools without a connection.
4
+ ---
5
+
6
+ # `createMCPTools()`
7
+
8
+ Converts an array of MCP tool definitions into AI SDK dynamic tools without
9
+ `execute` functions. Use it when the model runs on your backend and tools execute
10
+ elsewhere, such as in a browser using
11
+ [`Experimental_WebMCPTransport`](/docs/ai-sdk-core/mcp-tools#webmcp-transport).
12
+
13
+ ```ts
14
+ import { createMCPTools } from '@ai-sdk/mcp';
15
+ import { convertToModelMessages, streamText } from 'ai';
16
+
17
+ // In your API route, after applying application-specific request policies:
18
+ const { messages, tools: definitions } = await request.json();
19
+ const tools = createMCPTools(definitions);
20
+
21
+ const result = streamText({
22
+ model,
23
+ messages: await convertToModelMessages(messages, { tools }),
24
+ tools,
25
+ });
26
+ ```
27
+
28
+ The browser obtains the definitions using `const { tools } = await client.listTools()`
29
+ and sends that array with the chat request. It handles returned calls through
30
+ `useChat.onToolCall` and submits results with `addToolOutput`. The helper does not
31
+ connect to a browser or create an MCP client.
32
+
33
+ ## Parameters
34
+
35
+ - **`definitions: unknown`** (required): an array in the format of
36
+ `listTools().tools`. Each item must contain `name` and `inputSchema` and can
37
+ include MCP fields such as `description`, `title`, `annotations`, and `_meta`.
38
+ Deserialized request data can be passed directly.
39
+
40
+ ## Returns
41
+
42
+ A record of tool names to AI SDK dynamic tools. The helper:
43
+
44
+ - Validates the MCP definition structure and rejects duplicate names.
45
+ - Converts input schemas using the same automatic schema conversion as
46
+ `client.tools()`, including defaulting `properties` to `{}` and setting
47
+ `additionalProperties: false`.
48
+ - Preserves titles, standard MCP annotations, MCP App metadata, and `_meta`.
49
+ - Adds `toModelOutput` to convert returned MCP text and image content into model
50
+ content. Pass `{ tools }` to `convertToModelMessages` to use this conversion
51
+ for browser tool results in chat history.
52
+ - Leaves `execute` unset. The application forwards calls and returns results.
53
+
54
+ As with `client.tools()` in automatic schema mode, declared MCP output schemas
55
+ are not used to validate results.
56
+
57
+ ## Errors
58
+
59
+ Throws `MCPClientError` for malformed definitions or duplicate names. API routes
60
+ can catch it and return HTTP 400. Validation checks the MCP definition structure;
61
+ it does not establish trust, enforce application limits, or fully validate JSON
62
+ Schema documents. Apply your own authentication and tool policies to requests.
63
+
64
+ To execute tools over an MCP connection in the same runtime as the model, use
65
+ [`client.tools()`](/docs/reference/ai-sdk-core/create-mcp-client) instead.
@@ -83,8 +83,12 @@ function LiveConversation() {
83
83
  }
84
84
  ```
85
85
 
86
- The current continuous browser runtime supports a JSON/PCM16 WebSocket relay media
87
- profile. Continuous conversation semantics alone do not guarantee support for every
86
+ The current continuous browser runtime supports a JSON/PCM16 WebSocket media
87
+ profile, through an application relay (`api.websocket`) or, for models that declare
88
+ the `client-secret-websocket` connection, straight to the provider with a
89
+ short-lived token (`api.token`). AI Gateway Live models support the token flow; see
90
+ [AI Gateway Live models](/providers/ai-sdk-providers/ai-gateway#live-models).
91
+ Continuous conversation semantics alone do not guarantee support for every
88
92
  codec or transport. Applications with their own audio pipeline can use the low-level
89
93
  provider for other supported codecs. OpenAI-specific settings
90
94
  live under `providerOptions.openai` and use camelCase fields; the provider converts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai",
3
- "version": "7.0.178",
3
+ "version": "7.0.180",
4
4
  "type": "module",
5
5
  "description": "AI SDK by Vercel - build apps like ChatGPT, Claude, Gemini, and more with a single interface for any model using the Vercel AI Gateway or go direct to OpenAI, Anthropic, Google, or any other model provider.",
6
6
  "license": "Apache-2.0",
@@ -43,14 +43,14 @@
43
43
  }
44
44
  },
45
45
  "dependencies": {
46
- "@ai-sdk/gateway": "4.0.151",
46
+ "@ai-sdk/gateway": "4.0.153",
47
47
  "@ai-sdk/provider": "4.0.39",
48
48
  "@ai-sdk/provider-utils": "5.0.83"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@ai-sdk/amazon-bedrock": "5.0.146",
52
52
  "@ai-sdk/deepseek": "3.0.89",
53
- "@ai-sdk/google": "4.0.123",
53
+ "@ai-sdk/google": "4.0.124",
54
54
  "@ai-sdk/groq": "4.0.86",
55
55
  "@ai-sdk/huggingface": "2.0.95",
56
56
  "@ai-sdk/moonshotai": "3.0.95",
@@ -8,7 +8,7 @@ import type {
8
8
  import { BrowserRealtimeAudio } from './browser-realtime-audio';
9
9
  import { BrowserRealtimeTransport } from './browser-realtime-transport';
10
10
 
11
- /** Continuous PCM16 audio-chunk media for an application-owned WebSocket relay. */
11
+ /** Continuous PCM16 audio-chunk media over a WebSocket relay or client-secret connection. */
12
12
  export class BrowserRealtimeLiveWebSocket {
13
13
  private readonly transport: BrowserRealtimeTransport;
14
14
  private readonly audio: BrowserRealtimeAudio;
@@ -84,9 +84,20 @@ export class BrowserRealtimeLiveWebSocket {
84
84
  stream?: MediaStream;
85
85
  capture?: boolean;
86
86
  }): void {
87
+ const generation = this.prepare(options);
88
+ if (generation !== this.generation) return;
89
+ this.open({
90
+ mode: 'relay',
91
+ url: options.url,
92
+ protocols: options.protocols,
93
+ });
94
+ }
95
+
96
+ /** Resets media and primes playback; call while still in the user gesture. */
97
+ prepare(options: { stream?: MediaStream; capture?: boolean }): number {
87
98
  const generation = this.generation + 1;
88
99
  this.dispose();
89
- if (generation !== this.generation) return;
100
+ if (generation !== this.generation) return generation;
90
101
  for (const format of [
91
102
  this.config.inputAudioFormat,
92
103
  this.config.outputAudioFormat,
@@ -111,10 +122,17 @@ export class BrowserRealtimeLiveWebSocket {
111
122
  void this.audio.resumePlayback().catch(error => {
112
123
  if (generation === this.generation) this.options.onError(error);
113
124
  });
125
+ return generation;
126
+ }
127
+
128
+ /** Opens the socket through an application relay or with a client secret. */
129
+ open(
130
+ connection:
131
+ | { mode: 'relay'; url: string; protocols?: string[] }
132
+ | { mode: 'client-secret'; url: string; token: string },
133
+ ): void {
114
134
  this.transport.connect({
115
- mode: 'relay',
116
- url: options.url,
117
- protocols: options.protocols,
135
+ ...connection,
118
136
  onOpen: () => {
119
137
  return this.transport.sendEvent({
120
138
  type: this.options.model.capabilities?.startup ?? 'session-update',
@@ -175,9 +175,14 @@ export abstract class AbstractRealtimeSession {
175
175
  throw new Error('Realtime model does not support WebRTC configuration');
176
176
  return;
177
177
  }
178
- if (this.continuous && api.websocket == null)
178
+ // Continuous token sessions need an explicit declaration, not the legacy default.
179
+ if (
180
+ this.continuous &&
181
+ api.token != null &&
182
+ !model.capabilities?.connections?.includes('client-secret-websocket')
183
+ )
179
184
  throw new Error(
180
- 'Continuous PCM sessions require an application WebSocket relay',
185
+ 'Realtime model does not support client-secret-websocket',
181
186
  );
182
187
  if (api.token != null && model.getWebSocketConfig == null)
183
188
  throw new Error(
@@ -340,44 +345,55 @@ export abstract class AbstractRealtimeSession {
340
345
  capture: connectOptions?.capture,
341
346
  timeoutMs: this.options.startupTimeoutMs ?? 30_000,
342
347
  });
343
- } else if (
344
- api.websocket != null &&
345
- model.capabilities?.conversation === 'continuous'
346
- ) {
347
- this.pcm = new BrowserRealtimeLiveWebSocket({
348
+ } else if (this.continuous) {
349
+ const pcm = new BrowserRealtimeLiveWebSocket({
348
350
  ...callbacks,
349
351
  sessionConfig,
350
352
  sampleRate: this.options.sampleRate,
351
353
  maxPlaybackBufferSeconds: this.options.maxPlaybackBufferSeconds,
352
354
  });
353
- this.pcm.connect({
354
- url: api.websocket,
355
- protocols: api.protocols,
356
- stream: connectOptions?.stream,
357
- capture: connectOptions?.capture,
358
- });
355
+ this.pcm = pcm;
356
+ if (api.websocket != null) {
357
+ pcm.connect({
358
+ url: api.websocket,
359
+ protocols: api.protocols,
360
+ stream: connectOptions?.stream,
361
+ capture: connectOptions?.capture,
362
+ });
363
+ } else if (api.token != null) {
364
+ pcm.prepare({
365
+ stream: connectOptions?.stream,
366
+ capture: connectOptions?.capture,
367
+ });
368
+ const setup = await this.fetchRealtimeSetup(
369
+ api.token,
370
+ sessionConfig,
371
+ attempt,
372
+ );
373
+ if (setup == null || !current() || this.pcm !== pcm) return;
374
+ if (setup.tools != null && setup.tools.length > 0)
375
+ throw new UnsupportedFunctionalityError({
376
+ functionality:
377
+ 'Realtime setup tools for continuous sessions; client delegation is application-owned',
378
+ });
379
+ pcm.open({
380
+ mode: 'client-secret',
381
+ token: setup.token,
382
+ url: setup.url,
383
+ });
384
+ }
359
385
  } else {
360
386
  this.ensureAudio();
361
387
  let config: RealtimeSessionConfig = sessionConfig ?? {};
362
388
  let token: string | undefined;
363
389
  let url = api.websocket;
364
390
  if (api.token != null) {
365
- const response = await fetch(api.token, {
366
- method: 'POST',
367
- headers: { 'Content-Type': 'application/json' },
368
- body: JSON.stringify({ sessionConfig }),
369
- signal: attempt.abort.signal,
370
- });
371
- if (!current()) return;
372
- if (!response.ok)
373
- throw new Error(
374
- `Failed to fetch realtime setup: ${response.status}`,
375
- );
376
- const payload: unknown = await response.json().catch(() => {
377
- throw new Error('Invalid realtime setup response');
378
- });
379
- if (!current() || attempt.closing) return;
380
- const setup = validateRealtimeSetup(payload);
391
+ const setup = await this.fetchRealtimeSetup(
392
+ api.token,
393
+ sessionConfig,
394
+ attempt,
395
+ );
396
+ if (setup == null) return;
381
397
  token = setup.token;
382
398
  url = setup.url;
383
399
  config = {
@@ -418,6 +434,29 @@ export abstract class AbstractRealtimeSession {
418
434
  }
419
435
  }
420
436
 
437
+ /** Fetches the application's token setup; undefined when the attempt ended. */
438
+ private async fetchRealtimeSetup(
439
+ endpoint: string,
440
+ sessionConfig: Partial<RealtimeSessionConfig> | undefined,
441
+ attempt: RealtimeAttempt,
442
+ ) {
443
+ const current = () => this.attempt === attempt && attempt.active;
444
+ const response = await fetch(endpoint, {
445
+ method: 'POST',
446
+ headers: { 'Content-Type': 'application/json' },
447
+ body: JSON.stringify({ sessionConfig }),
448
+ signal: attempt.abort.signal,
449
+ });
450
+ if (!current()) return undefined;
451
+ if (!response.ok)
452
+ throw new Error(`Failed to fetch realtime setup: ${response.status}`);
453
+ const payload: unknown = await response.json().catch(() => {
454
+ throw new Error('Invalid realtime setup response');
455
+ });
456
+ if (!current() || attempt.closing) return undefined;
457
+ return validateRealtimeSetup(payload);
458
+ }
459
+
421
460
  private fail(error: unknown, drain?: Promise<void>, report = true): void {
422
461
  const attempt = this.attempt;
423
462
  if (attempt == null || !attempt.active || attempt.cause != null) return;