@ai-sdk/react 4.0.169 → 4.0.172

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @ai-sdk/react
2
2
 
3
+ ## 4.0.172
4
+
5
+ ### Patch Changes
6
+
7
+ - 65aa669: add experimental_queue to useChat to queue messages sent while a response is in progress
8
+ - Updated dependencies [65aa669]
9
+ - Updated dependencies [8585d7e]
10
+ - Updated dependencies [88b9575]
11
+ - ai@7.0.168
12
+ - @ai-sdk/mcp@2.0.95
13
+ - @ai-sdk/provider-utils@5.0.78
14
+
15
+ ## 4.0.171
16
+
17
+ ### Patch Changes
18
+
19
+ - Updated dependencies [9f37b45]
20
+ - Updated dependencies [404ce3b]
21
+ - @ai-sdk/provider-utils@5.0.77
22
+ - ai@7.0.167
23
+ - @ai-sdk/mcp@2.0.94
24
+
25
+ ## 4.0.170
26
+
27
+ ### Patch Changes
28
+
29
+ - ai@7.0.166
30
+
3
31
  ## 4.0.169
4
32
 
5
33
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -93,6 +93,7 @@ export declare class Chat<UI_MESSAGE extends UIMessage$1> extends AbstractChat<U
93
93
  '~registerMessagesCallback': (onChange: () => void, throttleWaitMs?: number) => (() => void);
94
94
  '~registerStatusCallback': (onChange: () => void) => (() => void);
95
95
  '~registerErrorCallback': (onChange: () => void) => (() => void);
96
+ '~registerQueuedMessagesCallback': (onChange: () => void) => (() => void);
96
97
  }
97
98
  //#endregion
98
99
  //#region src/use-chat.d.ts
@@ -108,7 +109,7 @@ export type UseChatHelpers<UI_MESSAGE extends UIMessage> = {
108
109
  */
109
110
  setMessages: (messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[])) => void;
110
111
  error: Error | undefined;
111
- } & Pick<AbstractChat<UI_MESSAGE>, 'sendMessage' | 'regenerate' | 'stop' | 'resumeStream' | 'addToolResult' | 'addToolOutput' | 'addToolApprovalResponse' | 'status' | 'messages' | 'clearError'>;
112
+ } & Pick<AbstractChat<UI_MESSAGE>, 'sendMessage' | 'regenerate' | 'stop' | 'resumeStream' | 'addToolResult' | 'addToolOutput' | 'addToolApprovalResponse' | 'status' | 'messages' | 'clearError' | 'experimental_queuedMessages' | 'experimental_removeQueuedMessage' | 'experimental_sendQueuedMessageNow'>;
112
113
  export type UseChatOptions<UI_MESSAGE extends UIMessage> = ({
113
114
  chat: Chat<UI_MESSAGE>;
114
115
  } | ChatInit<UI_MESSAGE>) & {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["UIMessage","RealtimeSessionOptions","UIMessage","RealtimeServerEvent","RealtimeState","AbstractRealtimeSession"],"sources":["../src/use-object.ts","../src/chat.react.ts","../src/use-chat.ts","../src/use-completion.ts","../src/use-realtime.ts","../src/mcp-apps/sandbox.ts","../src/mcp-apps/types.ts","../src/mcp-apps/app-renderer.tsx","../src/mcp-apps/index.ts","../src/index.ts"],"mappings":";;;;;YAsBY,iBAAiB,eAAe,gBAAgB;;;;EAI1D;;;;EAKA,QAAQ;;;;;;EAOR;;;;EAKA,eAAe,YAAY;;;;;EAM3B,QAAQ;;;;EAKR,YAAY;;;;;IAKV,QAAQ;;;;IAKR,OAAO;QACH;;;;EAKN,WAAW,OAAO;;;;;;EAOlB,UAAU,WAAW,yBAAyB;;;;;;EAO9C,cAAc;;YAGJ,iBAAiB,QAAQ;;;;EAInC,SAAS,OAAO;;;;EAKhB,QAAQ,YAAY;;;;EAKpB,OAAO;;;;EAKP;;;;EAKA;;;;EAKA;;wBAOc,UACd,eAAe,gBACf,SAAS,YAAY,SACrB,eAEA,KACA,IACA,QACA,cACA,OACA,SACA,UACA,SACA,eACC,iBAAiB,QAAQ,UAAU,iBAAiB,QAAQ;;;qBCalD,KACX,mBAAmBA,qBACX,aAAa;;EAGT,cAAE,aAAa,QAAQ,SAAS;gCAO1C,sBACA;8BAI2B;6BAGD;;;;YC7JlB,eA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AoB;EACnC,sBAAsB,oBAAoB;EAC1C,sBAAsB;IACpB,MAAM;QACF;IAAU,MAAM;;IAAyB,MAAM;;EACrD,gBAAgB;IAAU;IAAgB;;EAC1C;EACA,qBAAqB;EACrB,SAAS;EACT,WAAW,OAAO;;KAGR;EACV,cAAc;EACd;EACA;EACA,QAAQ;EACR;EACA;EACA;;;;;;EAMA,qBAAqB;;KAcX;EACV,MAAM,WAAW,WAAW;EAC5B,SAAS;EACT,WAAW;EACX,gBAAgB,KAAK,mBAAmB,QAAQ;EAChD,WAAW;EACX;IAAa;IAAc;;EAC3B,cAAc;EACd,WAAW;;;;wBC/DG,iBACd,MACA,SACA,UAAU,cACV,cACA,UACA,UACA,aACA,YACC,kDAAmB,yBAAA,yCAAA,IAAA;;;;;;qBCxBT,oCAA2B;;;;;;qBCc3B,+BAAsB;;;;YAKvB,8BACV,eAAe,gBACf,UACE,iBAAiB,QAAQ;;;;YAKjB,8BAA8B,QAAQ,SAAS,iBACzD,QACA"}
1
+ {"version":3,"file":"index.d.ts","names":["UIMessage","RealtimeSessionOptions","UIMessage","RealtimeServerEvent","RealtimeState","AbstractRealtimeSession"],"sources":["../src/use-object.ts","../src/chat.react.ts","../src/use-chat.ts","../src/use-completion.ts","../src/use-realtime.ts","../src/mcp-apps/sandbox.ts","../src/mcp-apps/types.ts","../src/mcp-apps/app-renderer.tsx","../src/mcp-apps/index.ts","../src/index.ts"],"mappings":";;;;;YAsBY,iBAAiB,eAAe,gBAAgB;;;;EAI1D;;;;EAKA,QAAQ;;;;;;EAOR;;;;EAKA,eAAe,YAAY;;;;;EAM3B,QAAQ;;;;EAKR,YAAY;;;;;IAKV,QAAQ;;;;IAKR,OAAO;QACH;;;;EAKN,WAAW,OAAO;;;;;;EAOlB,UAAU,WAAW,yBAAyB;;;;;;EAO9C,cAAc;;YAGJ,iBAAiB,QAAQ;;;;EAInC,SAAS,OAAO;;;;EAKhB,QAAQ,YAAY;;;;EAKpB,OAAO;;;;EAKP;;;;EAK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wB;;;;;;KChMzB;;;KC5FA;KAEA;EACV;EACA,UAAU;EACV,aAAa;;KAGH;EACV;EACA,cAAc;EACd,wBAAwB;GACvB;;KAGS;EACV;EACA,YAAY;;KAGF;;;;;;EAMV;EACA,YAAY,QAAQ,yBAAyB;EAC7C,gBAAgB;IAAU;QAAkB;EAC5C,iBAAiB,qBAAqB;EACtC,YAAY;IAAU;QAAkB;EACxC,eAAe,oBAAoB;EACnC,sBAAsB,oBAAoB;EAC1C,sBAAsB;IACpB,MAAM;QACF;IAAU,MAAM;;IAAyB,MAAM;;EACrD,gBAAgB;IAAU;IAAgB;;EAC1C;EACA,qBAAqB;EACrB,SAAS;EACT,WAAW,OAAO;;KAGR;EACV,cAAc;EACd;EACA;EACA,QAAQ;EACR;EACA;EACA;;;;;;EAMA,qBAAqB;;KAcX;EACV,MAAM,WAAW,WAAW;EAC5B,SAAS;EACT,WAAW;EACX,gBAAgB,KAAK,mBAAmB,QAAQ;EAChD,WAAW;EACX;IAAa;IAAc;;EAC3B,cAAc;EACd,WAAW;;;;wBC/DG,iBACd,MACA,SACA,UAAU,cACV,cACA,UACA,UACA,aACA,YACC,kDAAmB,yBAAA,yCAAA,IAAA;;;;;;qBCxBT,oCAA2B;;;;;;qBCc3B,+BAAsB;;;;YAKvB,8BACV,eAAe,gBACf,UACE,iBAAiB,QAAQ;;;;YAKjB,8BAA8B,QAAQ,SAAS,iBACzD,QACA"}
package/dist/index.js CHANGED
@@ -114,13 +114,17 @@ var ReactChatState = class {
114
114
  #messages;
115
115
  #status;
116
116
  #error;
117
+ #queuedMessages;
117
118
  #messagesCallbacks;
119
+ #queuedMessagesCallbacks;
118
120
  #statusCallbacks;
119
121
  #errorCallbacks;
120
122
  constructor(initialMessages = []) {
121
123
  this.#status = "ready";
122
124
  this.#error = void 0;
125
+ this.#queuedMessages = [];
123
126
  this.#messagesCallbacks = /* @__PURE__ */ new Set();
127
+ this.#queuedMessagesCallbacks = /* @__PURE__ */ new Set();
124
128
  this.#statusCallbacks = /* @__PURE__ */ new Set();
125
129
  this.#errorCallbacks = /* @__PURE__ */ new Set();
126
130
  this.pushMessage = (message) => {
@@ -168,6 +172,12 @@ var ReactChatState = class {
168
172
  this.#errorCallbacks.delete(onChange);
169
173
  };
170
174
  };
175
+ this["~registerQueuedMessagesCallback"] = (onChange) => {
176
+ this.#queuedMessagesCallbacks.add(onChange);
177
+ return () => {
178
+ this.#queuedMessagesCallbacks.delete(onChange);
179
+ };
180
+ };
171
181
  this.#callMessagesCallbacks = () => {
172
182
  this.#messagesCallbacks.forEach((callback) => callback());
173
183
  };
@@ -193,6 +203,13 @@ var ReactChatState = class {
193
203
  this.#error = newError;
194
204
  this.#callErrorCallbacks();
195
205
  }
206
+ get experimental_queuedMessages() {
207
+ return this.#queuedMessages;
208
+ }
209
+ set experimental_queuedMessages(newQueuedMessages) {
210
+ this.#queuedMessages = newQueuedMessages;
211
+ this.#queuedMessagesCallbacks.forEach((callback) => callback());
212
+ }
196
213
  get messages() {
197
214
  return this.#messages;
198
215
  }
@@ -215,6 +232,7 @@ var Chat = class extends AbstractChat {
215
232
  this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => this.#state["~registerMessagesCallback"](onChange, throttleWaitMs);
216
233
  this["~registerStatusCallback"] = (onChange) => this.#state["~registerStatusCallback"](onChange);
217
234
  this["~registerErrorCallback"] = (onChange) => this.#state["~registerErrorCallback"](onChange);
235
+ this["~registerQueuedMessagesCallback"] = (onChange) => this.#state["~registerQueuedMessagesCallback"](onChange);
218
236
  this.#state = state;
219
237
  }
220
238
  };
@@ -267,11 +285,12 @@ function readChatSnapshot(chat) {
267
285
  chat,
268
286
  messages: chat.messages,
269
287
  status: chat.status,
270
- error: chat.error
288
+ error: chat.error,
289
+ experimental_queuedMessages: chat.experimental_queuedMessages
271
290
  };
272
291
  }
273
292
  function equalChatSnapshots(current, next) {
274
- return current.chat === next.chat && current.messages === next.messages && current.status === next.status && current.error === next.error;
293
+ return current.chat === next.chat && current.messages === next.messages && current.status === next.status && current.error === next.error && current.experimental_queuedMessages === next.experimental_queuedMessages;
275
294
  }
276
295
  function useChat({ throttle, experimental_throttle, resume = false, ...options } = {}) {
277
296
  const throttleWaitMs = throttle ?? experimental_throttle;
@@ -325,7 +344,8 @@ function useChat({ throttle, experimental_throttle, resume = false, ...options }
325
344
  const unsubscribes = [
326
345
  chat["~registerMessagesCallback"](publishSnapshot, throttleWaitMs),
327
346
  chat["~registerStatusCallback"](publishSnapshot),
328
- chat["~registerErrorCallback"](publishSnapshot)
347
+ chat["~registerErrorCallback"](publishSnapshot),
348
+ chat["~registerQueuedMessagesCallback"](publishSnapshot)
329
349
  ];
330
350
  const nextSnapshot = readChatSnapshot(chat);
331
351
  setSnapshot((current) => equalChatSnapshots(current, nextSnapshot) ? current : nextSnapshot);
@@ -334,7 +354,7 @@ function useChat({ throttle, experimental_throttle, resume = false, ...options }
334
354
  unsubscribes.forEach((unsubscribe) => unsubscribe());
335
355
  };
336
356
  }, [chat, throttleWaitMs]);
337
- const { messages, status, error } = snapshot;
357
+ const { messages, status, error, experimental_queuedMessages } = snapshot;
338
358
  const setMessages = useCallback((messagesParam) => {
339
359
  if (typeof messagesParam === "function") messagesParam = messagesParam(chat.messages);
340
360
  chat.messages = messagesParam;
@@ -363,7 +383,10 @@ function useChat({ throttle, experimental_throttle, resume = false, ...options }
363
383
  */
364
384
  addToolResult: chat.addToolOutput,
365
385
  addToolOutput: chat.addToolOutput,
366
- addToolApprovalResponse: chat.addToolApprovalResponse
386
+ addToolApprovalResponse: chat.addToolApprovalResponse,
387
+ experimental_queuedMessages,
388
+ experimental_removeQueuedMessage: chat.experimental_removeQueuedMessage,
389
+ experimental_sendQueuedMessageNow: chat.experimental_sendQueuedMessageNow
367
390
  };
368
391
  }
369
392
  //#endregion
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["resumableChat","AbstractRealtimeSession"],"sources":["../src/use-object.ts","../src/throttle.ts","../src/chat.react.ts","../src/use-chat.ts","../src/use-completion.ts","../src/use-realtime.ts","../src/mcp-apps/bridge.ts","../src/mcp-apps/sandbox.ts","../src/mcp-apps/utils.ts","../src/mcp-apps/app-frame.tsx","../src/mcp-apps/app-renderer.tsx","../src/mcp-apps/index.ts","../src/index.ts"],"sourcesContent":["import {\n isAbortError,\n resolve,\n normalizeHeaders,\n safeValidateTypes,\n type FetchFunction,\n type FlexibleSchema,\n type InferSchema,\n type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n isDeepEqualData,\n parsePartialJson,\n type DeepPartial,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * Callback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\n * The generated object (typed according to the schema).\n * Can be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\n * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n * Can be a static object, a function that returns headers, or an async function\n * for dynamic auth tokens.\n */\n headers?: Resolvable<Record<string, string> | Headers>;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\ntype ObjectState<RESULT> = {\n object: DeepPartial<RESULT> | undefined;\n};\n\nexport function useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: UseObjectOptions<SCHEMA, RESULT>): UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<ObjectState<RESULT>>(\n [completionId, 'object'],\n null,\n { fallbackData: { object: initialValue } },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n const abortController = new AbortController();\n\n try {\n clearObject();\n\n setIsLoading(true);\n\n abortControllerRef.current = abortController;\n\n // Resolve headers at request time (supports async functions for dynamic auth tokens)\n const resolvedHeaders = await resolve(headers);\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...normalizeHeaders(resolvedHeaders),\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) || 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n if (abortControllerRef.current === abortController) {\n mutate({ object: currentObject });\n }\n }\n },\n\n async close() {\n if (abortControllerRef.current === abortController) {\n setIsLoading(false);\n }\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n await onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n\n if (abortControllerRef.current === abortController) {\n abortControllerRef.current = null;\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n if (abortControllerRef.current === abortController) {\n setIsLoading(false);\n abortControllerRef.current = null;\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate({ object: undefined });\n };\n\n return {\n submit,\n object: data?.object,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n AbstractChat,\n type ChatInit,\n type ChatState,\n type ChatStatus,\n type UIMessage,\n} from 'ai';\nimport { throttle } from './throttle';\n\nfunction cloneMetadata<METADATA>(metadata: METADATA): METADATA {\n if (Array.isArray(metadata)) {\n return [...metadata] as METADATA;\n }\n\n if (\n metadata != null &&\n typeof metadata === 'object' &&\n (Object.getPrototypeOf(metadata) === Object.prototype ||\n Object.getPrototypeOf(metadata) === null)\n ) {\n return { ...metadata } as METADATA;\n }\n\n return metadata;\n}\n\nclass ReactChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => {\n if (\n value == null ||\n typeof value !== 'object' ||\n !('parts' in value) ||\n !Array.isArray(value.parts)\n ) {\n return value;\n }\n\n const message = value as UI_MESSAGE;\n const snapshot = {\n ...message,\n parts: message.parts.map(part => ({ ...part })),\n };\n\n if ('metadata' in message) {\n snapshot.metadata = cloneMetadata(message.metadata);\n }\n\n return snapshot as T;\n };\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import {\n type AbstractChat,\n type ChatInit,\n type ChatTransport,\n type CreateUIMessage,\n type UIMessage,\n DefaultChatTransport,\n} from 'ai';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\n * Custom throttle wait in ms for the chat messages and data updates.\n * Default is undefined, which disables throttling.\n */\n throttle?: number;\n\n /**\n * @deprecated Use `throttle` instead.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to automatically resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\ntype AutomaticResumeState = {\n registrations: Set<object>;\n cleanupVisibilityListener?: () => void;\n pendingVisibilityResume?: Promise<void>;\n};\n\nconst automaticResumeStates = new WeakMap<object, AutomaticResumeState>();\n\ntype AutomaticallyResumableChat = {\n '~resumeStreamIfDisconnected': (options: {\n shouldResume: () => boolean;\n }) => Promise<void>;\n};\n\n/**\n * When the document becomes visible again, resume the chat stream if it was\n * interrupted by a network disconnect while the page was in the background.\n */\nfunction resumeOnVisible<UI_MESSAGE extends UIMessage>({\n chat,\n state,\n}: {\n chat: Chat<UI_MESSAGE>;\n state: AutomaticResumeState;\n}) {\n if (\n document.visibilityState !== 'visible' ||\n state.pendingVisibilityResume != null\n ) {\n return;\n }\n\n const isRegistered = () =>\n automaticResumeStates.get(chat) === state && state.registrations.size > 0;\n\n const clearPendingResume = () => {\n state.pendingVisibilityResume = undefined;\n };\n\n const resumableChat = chat as Chat<UI_MESSAGE> & AutomaticallyResumableChat;\n\n state.pendingVisibilityResume = resumableChat['~resumeStreamIfDisconnected']({\n shouldResume: () =>\n isRegistered() && document.visibilityState === 'visible',\n }).then(clearPendingResume, clearPendingResume);\n}\n\nfunction registerAutomaticResume<UI_MESSAGE extends UIMessage>({\n chat,\n registration,\n}: {\n chat: Chat<UI_MESSAGE>;\n registration: object;\n}) {\n let state = automaticResumeStates.get(chat);\n\n if (state == null) {\n const newState: AutomaticResumeState = { registrations: new Set() };\n automaticResumeStates.set(chat, newState);\n state = newState;\n\n if (typeof document !== 'undefined') {\n const onVisibilityChange = () =>\n resumeOnVisible({ chat, state: newState });\n\n document.addEventListener('visibilitychange', onVisibilityChange);\n newState.cleanupVisibilityListener = () => {\n document.removeEventListener('visibilitychange', onVisibilityChange);\n };\n }\n }\n\n const { registrations } = state;\n const shouldResume = registrations.size === 0;\n registrations.add(registration);\n\n if (\n shouldResume &&\n chat.status !== 'submitted' &&\n chat.status !== 'streaming'\n ) {\n void chat.resumeStream();\n }\n\n return () => {\n registrations.delete(registration);\n\n if (registrations.size === 0) {\n state.cleanupVisibilityListener?.();\n automaticResumeStates.delete(chat);\n }\n };\n}\n\ntype ChatSnapshot<UI_MESSAGE extends UIMessage> = {\n chat: Chat<UI_MESSAGE>;\n messages: UI_MESSAGE[];\n status: Chat<UI_MESSAGE>['status'];\n error: Error | undefined;\n};\n\nfunction readChatSnapshot<UI_MESSAGE extends UIMessage>(\n chat: Chat<UI_MESSAGE>,\n): ChatSnapshot<UI_MESSAGE> {\n return {\n chat,\n messages: chat.messages,\n status: chat.status,\n error: chat.error,\n };\n}\n\nfunction equalChatSnapshots<UI_MESSAGE extends UIMessage>(\n current: ChatSnapshot<UI_MESSAGE>,\n next: ChatSnapshot<UI_MESSAGE>,\n) {\n return (\n current.chat === next.chat &&\n current.messages === next.messages &&\n current.status === next.status &&\n current.error === next.error\n );\n}\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n throttle,\n experimental_throttle,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n const throttleWaitMs = throttle ?? experimental_throttle;\n const automaticResumeRegistration = useRef({});\n // the Chat instance is created once and not recreated when options change,\n // so it would normally keep the callbacks/transport from the first render forever\n\n // keep latest values in a ref that is refreshed on every render,\n // and hand `Chat` stable wrappers that read from it to avoid stale closures\n const latestRef = useRef<\n Partial<\n Pick<\n ChatInit<UI_MESSAGE>,\n | 'onToolCall'\n | 'onData'\n | 'onFinish'\n | 'onError'\n | 'sendAutomaticallyWhen'\n | 'transport'\n >\n >\n >({});\n\n if (!('chat' in options)) {\n latestRef.current = {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen,\n transport: options.transport,\n };\n }\n\n // resolve the latest transport and fallback to a lazily created default transport\n let defaultTransport: ChatTransport<UI_MESSAGE> | undefined;\n const getTransport = (): ChatTransport<UI_MESSAGE> =>\n latestRef.current.transport ??\n (defaultTransport ??= new DefaultChatTransport<UI_MESSAGE>());\n\n // give `Chat` stable wrappers that always read the latest values from `latestRef`\n const chatOptions: typeof options = {\n ...options,\n transport: {\n get resumeStreamIsReplay() {\n return getTransport().resumeStreamIsReplay;\n },\n sendMessages: sendOptions => getTransport().sendMessages(sendOptions),\n reconnectToStream: reconnectOptions =>\n getTransport().reconnectToStream(reconnectOptions),\n },\n onToolCall: arg => latestRef.current.onToolCall?.(arg),\n onData: arg => latestRef.current.onData?.(arg),\n onFinish: arg => latestRef.current.onFinish?.(arg),\n onError: arg => latestRef.current.onError?.(arg),\n sendAutomaticallyWhen: arg =>\n latestRef.current.sendAutomaticallyWhen?.(arg) ?? false,\n };\n\n const chatKey = 'chat' in options ? options.chat : options.id;\n const { chat, isExternallyManaged } = useMemo(\n () => ({\n chat: 'chat' in options ? options.chat : new Chat(chatOptions),\n isExternallyManaged: 'chat' in options,\n }),\n [chatKey],\n );\n\n useEffect(() => {\n if (isExternallyManaged) {\n return;\n }\n\n return () => {\n void chat.stop();\n };\n }, [chat, isExternallyManaged]);\n\n // Chat owns the live state; React owns the snapshot used for rendering.\n // useSyncExternalStore would make streaming updates synchronous and can\n // repeatedly restart navigation renders. Ordinary state updates let React\n // schedule both. Automatically wrapping publication in startTransition can\n // group it with a suspended navigation in the same root, holding back streamed\n // text and local edits.\n // Each consumer subscribes independently, so different throttle intervals can\n // produce different rendered snapshots of the same Chat.\n const [snapshot, setSnapshot] = useState(() => readChatSnapshot(chat));\n\n // React retries this component before rendering children, so they cannot\n // commit the previous Chat's snapshot. Resubscribe only after the swap commits.\n if (snapshot.chat !== chat) {\n setSnapshot(readChatSnapshot(chat));\n }\n\n useEffect(() => {\n let isSubscribed = true;\n const publishSnapshot = () => {\n // A trailing throttled callback can run after cleanup. Check before\n // enqueueing; keep the state updater independent of mutable effect state.\n if (!isSubscribed) {\n return;\n }\n\n const nextSnapshot = readChatSnapshot(chat);\n setSnapshot(current =>\n current.chat !== chat || equalChatSnapshots(current, nextSnapshot)\n ? current\n : nextSnapshot,\n );\n };\n\n // Only message notifications are throttled. Status and error notifications\n // publish the complete snapshot, so ready/error cannot commit beside stale\n // messages even when a throttled message notification is still pending.\n const unsubscribes = [\n chat['~registerMessagesCallback'](publishSnapshot, throttleWaitMs),\n chat['~registerStatusCallback'](publishSnapshot),\n chat['~registerErrorCallback'](publishSnapshot),\n ];\n\n // Catch changes between render and subscription, including updates that\n // arrived before this consumer mounted or while its Chat was being replaced.\n const nextSnapshot = readChatSnapshot(chat);\n setSnapshot(current =>\n equalChatSnapshots(current, nextSnapshot) ? current : nextSnapshot,\n );\n\n return () => {\n isSubscribed = false;\n unsubscribes.forEach(unsubscribe => unsubscribe());\n };\n }, [chat, throttleWaitMs]);\n\n const { messages, status, error } = snapshot;\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chat.messages);\n }\n chat.messages = messagesParam;\n },\n [chat],\n );\n\n useEffect(() => {\n if (resume) {\n return registerAutomaticResume({\n chat,\n registration: automaticResumeRegistration.current,\n });\n }\n }, [resume, chat]);\n\n return {\n get id() {\n return chat.id;\n },\n messages,\n setMessages,\n sendMessage: chat.sendMessage,\n regenerate: chat.regenerate,\n clearError: chat.clearError,\n stop: chat.stop,\n error,\n resumeStream: chat.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chat.addToolOutput,\n addToolOutput: chat.addToolOutput,\n addToolApprovalResponse: chat.addToolApprovalResponse,\n };\n}\n","import {\n callCompletionApi,\n type CompletionRequestOptions,\n type UseCompletionOptions,\n} from 'ai';\nimport { normalizeHeaders } from '@ai-sdk/provider-utils';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers<BODY extends object = object> = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions<BODY>,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion<BODY extends object = object>({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n throttle: throttleWait,\n experimental_throttle,\n}: UseCompletionOptions<NoInfer<BODY>> & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n throttle?: number;\n\n /**\n * @deprecated Use `throttle` instead.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers<BODY> {\n const throttleWaitMs = throttleWait ?? experimental_throttle;\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n const requestIdRef = useRef(0);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions<BODY>) => {\n const requestId = ++requestIdRef.current;\n\n return callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: {\n ...normalizeHeaders(extraMetadataRef.current.headers),\n ...normalizeHeaders(options?.headers),\n },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle((completion: string) => {\n if (requestIdRef.current === requestId) {\n mutate(completion, false);\n }\n }, throttleWaitMs),\n setLoading: mutateLoading,\n setError,\n setAbortController: controller => {\n abortControllerRef.current = controller;\n },\n getAbortController: () => abortControllerRef.current,\n onFinish,\n onError,\n });\n },\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n abortControllerRef.current?.abort();\n }, []);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers<BODY>['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n if (!input) {\n return;\n }\n\n const result = complete(input);\n setInput('');\n return result;\n },\n [input, complete, setInput],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import { secureJsonParse } from '@ai-sdk/provider-utils';\nimport {\n Experimental_AbstractRealtimeSession as AbstractRealtimeSession,\n type Experimental_RealtimeServerEvent as RealtimeServerEvent,\n type Experimental_RealtimeSessionOptions as RealtimeSessionOptions,\n type Experimental_RealtimeState as RealtimeState,\n type Experimental_RealtimeStatus as RealtimeStatus,\n type UIMessage,\n} from 'ai';\nimport {\n useCallback,\n useEffect,\n useInsertionEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\n\ntype UseRealtimeOptions = RealtimeSessionOptions;\n\ntype RealtimeStateKey = keyof RealtimeState;\n\nconst useIsomorphicLayoutEffect =\n typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\nconst RealtimeStore = /* @__PURE__ */ (() =>\n class RealtimeStore extends AbstractRealtimeSession {\n protected state: RealtimeState = {\n status: 'disconnected',\n messages: [],\n events: [],\n isCapturing: false,\n isPlaying: false,\n };\n\n private callbacks: { [K in RealtimeStateKey]-?: Set<() => void> } = {\n status: new Set(),\n messages: new Set(),\n events: new Set(),\n isCapturing: new Set(),\n isPlaying: new Set(),\n session: new Set(),\n };\n\n get status(): RealtimeStatus {\n return this.state.status;\n }\n\n get messages(): UIMessage[] {\n return this.state.messages;\n }\n\n get events(): RealtimeServerEvent[] {\n return this.state.events;\n }\n\n get isCapturing(): boolean {\n return this.state.isCapturing;\n }\n\n get isPlaying(): boolean {\n return this.state.isPlaying;\n }\n\n get session(): RealtimeState['session'] {\n return this.state.session;\n }\n\n subscribe(key: RealtimeStateKey, onChange: () => void): () => void {\n this.callbacks[key].add(onChange);\n\n return () => {\n this.callbacks[key].delete(onChange);\n };\n }\n\n protected setState<K extends RealtimeStateKey>(\n key: K,\n value: RealtimeState[K],\n ): void {\n this.state = { ...this.state, [key]: value };\n this.callbacks[key].forEach(callback => callback());\n }\n })();\n\ntype RealtimeStore = InstanceType<typeof RealtimeStore>;\n\ntype UseRealtimeReturn = {\n status: RealtimeStatus;\n messages: UIMessage[];\n events: RealtimeServerEvent[];\n isCapturing: boolean;\n isPlaying: boolean;\n session?: RealtimeState['session'];\n\n connect: AbstractRealtimeSession['connect'];\n close: AbstractRealtimeSession['close'];\n resumePlayback: () => Promise<void>;\n resumeAudioCapture: () => Promise<void>;\n disconnect: () => void;\n addToolOutput: (callId: string, result: unknown) => void;\n sendEvent: AbstractRealtimeSession['sendEvent'];\n sendTextMessage: (text: string) => void;\n sendAudio: (base64Audio: string) => void;\n commitAudio: () => void;\n clearAudioBuffer: () => void;\n requestResponse: (options?: { modalities?: string[] }) => void;\n cancelResponse: () => void;\n startAudioCapture: (stream: MediaStream) => void;\n stopAudioCapture: () => void;\n stopPlayback: () => void;\n};\n\nfunction useRealtime(options: UseRealtimeOptions): UseRealtimeReturn {\n const ownerRef = useRef<{\n store: RealtimeStore;\n onToolCall: UseRealtimeOptions['onToolCall'];\n onEvent: UseRealtimeOptions['onEvent'];\n onError: UseRealtimeOptions['onError'];\n } | null>(null);\n const {\n model,\n api,\n startupTimeoutMs,\n closeTimeoutMs,\n rtcDisconnectTimeoutMs,\n sessionConfig,\n sampleRate,\n maxEvents,\n maxPlaybackBufferSeconds,\n onToolCall,\n onEvent,\n onError,\n } = options;\n const {\n token,\n websocket,\n session: sessionEndpoint,\n provider: providerEndpoint,\n } = api;\n const protocols = JSON.stringify(api.protocols ?? []);\n\n // Candidates allocate no transports or media; only a committed owner can act.\n const rt = useMemo(() => {\n const store: RealtimeStore = new RealtimeStore({\n model,\n api:\n token != null\n ? { token }\n : providerEndpoint != null\n ? { provider: providerEndpoint }\n : sessionEndpoint != null\n ? { session: sessionEndpoint }\n : {\n websocket: websocket as string,\n protocols: secureJsonParse(protocols) as string[],\n },\n startupTimeoutMs,\n closeTimeoutMs,\n rtcDisconnectTimeoutMs,\n sessionConfig,\n sampleRate,\n maxEvents,\n maxPlaybackBufferSeconds,\n onEvent: (...args) =>\n ownerRef.current?.store === store\n ? ownerRef.current.onEvent?.(...args)\n : undefined,\n onError: (...args) =>\n ownerRef.current?.store === store\n ? ownerRef.current.onError?.(...args)\n : undefined,\n });\n return store;\n }, [\n model,\n token,\n sessionEndpoint,\n providerEndpoint,\n websocket,\n protocols,\n startupTimeoutMs,\n closeTimeoutMs,\n rtcDisconnectTimeoutMs,\n sessionConfig,\n sampleRate,\n maxEvents,\n maxPlaybackBufferSeconds,\n ]);\n\n // Publish before child layout effects; insertion cleanup only revokes refs.\n useInsertionEffect(() => {\n ownerRef.current = { store: rt, onToolCall, onEvent, onError };\n rt.onToolCall =\n onToolCall == null\n ? undefined\n : (...args) =>\n ownerRef.current?.store === rt\n ? ownerRef.current.onToolCall?.(...args)\n : undefined;\n return () => {\n ownerRef.current = null;\n };\n });\n\n // StrictMode replays layout effects, but keeps the insertion-phase owner.\n useIsomorphicLayoutEffect(() => {\n return () => rt.dispose();\n }, [rt]);\n\n const actions = useMemo(() => {\n const current = () => {\n if (ownerRef.current == null)\n throw new Error('Realtime controls require a mounted hook');\n return ownerRef.current.store;\n };\n return {\n connect: async (options?: {\n stream?: MediaStream;\n capture?: boolean;\n }) => {\n const store = current();\n return options == null ? store.connect() : store.connect(options);\n },\n close: async options => current().close(options),\n resumePlayback: async () => current().resumePlayback(),\n resumeAudioCapture: async () => current().resumeAudioCapture(),\n disconnect: () => current().disconnect(),\n addToolOutput: (callId, result) =>\n current().addToolOutput(callId, result),\n sendEvent: event => current().sendEvent(event),\n sendTextMessage: text => current().sendTextMessage(text),\n sendAudio: audio => current().sendAudio(audio),\n commitAudio: () => current().commitAudio(),\n clearAudioBuffer: () => current().clearAudioBuffer(),\n requestResponse: options => current().requestResponse(options),\n cancelResponse: () => current().cancelResponse(),\n startAudioCapture: stream => current().startAudioCapture(stream),\n stopAudioCapture: () => current().stopAudioCapture(),\n stopPlayback: () => current().stopPlayback(),\n } satisfies Omit<UseRealtimeReturn, keyof RealtimeState>;\n }, []);\n\n const status = useSyncExternalStore(\n useCallback(cb => rt.subscribe('status', cb), [rt]),\n () => rt.status,\n () => rt.status,\n );\n\n const messages = useSyncExternalStore(\n useCallback(cb => rt.subscribe('messages', cb), [rt]),\n () => rt.messages,\n () => rt.messages,\n );\n\n const events = useSyncExternalStore(\n useCallback(cb => rt.subscribe('events', cb), [rt]),\n () => rt.events,\n () => rt.events,\n );\n\n const isCapturing = useSyncExternalStore(\n useCallback(cb => rt.subscribe('isCapturing', cb), [rt]),\n () => rt.isCapturing,\n () => rt.isCapturing,\n );\n\n const isPlaying = useSyncExternalStore(\n useCallback(cb => rt.subscribe('isPlaying', cb), [rt]),\n () => rt.isPlaying,\n () => rt.isPlaying,\n );\n\n const session = useSyncExternalStore(\n useCallback(cb => rt.subscribe('session', cb), [rt]),\n () => rt.session,\n () => rt.session,\n );\n\n return {\n status,\n messages,\n events,\n isCapturing,\n isPlaying,\n session,\n ...actions,\n };\n}\n\nexport const experimental_useRealtime = useRealtime;\n\nexport type {\n RealtimeStatus as Experimental_RealtimeStatus,\n UseRealtimeOptions as Experimental_UseRealtimeOptions,\n UseRealtimeReturn as Experimental_UseRealtimeReturn,\n};\n","import { isJSONObject } from '@ai-sdk/provider';\nimport type {\n MCPAppBridgeHandlers,\n MCPAppHostContext,\n MCPAppJsonRpcMessage,\n MCPAppJsonRpcNotification,\n MCPAppJsonRpcRequest,\n MCPAppJsonRpcResponse,\n MCPAppToolCallParams,\n} from './types';\n\nconst MCP_APP_PROTOCOL_VERSION = '2026-01-26';\n\n/**\n * Checks whether an iframe message looks like a JSON-RPC 2.0 message.\n */\nfunction isJsonRpcMessage(value: unknown): value is MCPAppJsonRpcMessage {\n return (\n value != null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n 'jsonrpc' in value &&\n value.jsonrpc === '2.0'\n );\n}\n\n/**\n * Checks whether a JSON-RPC message expects a response.\n */\nfunction isRequest(\n message: MCPAppJsonRpcMessage,\n): message is MCPAppJsonRpcRequest {\n return 'method' in message && 'id' in message;\n}\n\n/**\n * Checks whether a JSON-RPC message is a fire-and-forget notification.\n */\nfunction isNotification(\n message: MCPAppJsonRpcMessage,\n): message is MCPAppJsonRpcNotification {\n return 'method' in message && !('id' in message);\n}\n\n/**\n * Normalizes unknown thrown values into an `Error`.\n */\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\n/**\n * Validates the params for app-initiated `tools/call` requests.\n */\nfunction assertToolCallParams(params: unknown): MCPAppToolCallParams {\n if (!isJSONObject(params) || typeof params.name !== 'string') {\n throw new Error('Invalid tools/call params');\n }\n\n return {\n name: params.name,\n arguments: isJSONObject(params.arguments) ? params.arguments : undefined,\n };\n}\n\n/**\n * Validates `resources/read` params and limits reads to `ui://` app resources.\n */\nfunction assertResourceReadParams(params: unknown): { uri: string } {\n if (!isJSONObject(params) || typeof params.uri !== 'string') {\n throw new Error('Invalid resources/read params');\n }\n if (!params.uri.startsWith('ui://')) {\n throw new Error(\n `resources/read is limited to ui:// resources: ${params.uri}`,\n );\n }\n return { uri: params.uri };\n}\n\n/**\n * Validates `ui/open-link` params and allows only `https:`/`http:`/`mailto:`\n * URLs.\n */\nfunction assertOpenLinkParams(params: unknown): { url: string } {\n if (!isJSONObject(params) || typeof params.url !== 'string') {\n throw new Error('Invalid ui/open-link params');\n }\n\n let scheme: string;\n try {\n scheme = new URL(params.url).protocol;\n } catch {\n throw new Error(`Invalid ui/open-link url: ${params.url}`);\n }\n\n if (scheme !== 'https:' && scheme !== 'http:' && scheme !== 'mailto:') {\n throw new Error(`Disallowed ui/open-link scheme: ${scheme}`);\n }\n\n return { url: params.url };\n}\n\n/**\n * Validates params for `ui/request-display-mode`.\n */\nfunction assertDisplayModeParams(params: unknown): {\n mode: 'inline' | 'fullscreen' | 'pip';\n} {\n if (\n !isJSONObject(params) ||\n (params.mode !== 'inline' &&\n params.mode !== 'fullscreen' &&\n params.mode !== 'pip')\n ) {\n throw new Error('Invalid ui/request-display-mode params');\n }\n return { mode: params.mode };\n}\n\n/**\n * Host-side JSON-RPC bridge for one MCP App iframe.\n *\n * It handles the MCP Apps initialization handshake, sends tool input/result\n * notifications to the iframe, and proxies allowed iframe requests through\n * host-provided callbacks.\n *\n * @example\n * ```ts\n * const bridge = new MCPAppBridge({\n * targetWindow: iframe.contentWindow!,\n * handlers: {\n * allowedTools: ['refreshDashboardData'],\n * callTool: params => client.callTool(params),\n * },\n * });\n *\n * window.addEventListener('message', event => bridge.handleMessage(event));\n * bridge.sendToolInput({ topic: 'usage' });\n * ```\n */\nexport class MCPAppBridge {\n private initialized = false;\n private pendingNotifications: MCPAppJsonRpcNotification[] = [];\n private nextRequestId = 0;\n private pendingResponses = new Map<\n string | number,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n }\n >();\n\n constructor({\n targetWindow,\n targetOrigin = '*',\n handlers = {},\n hostInfo = { name: 'ai-sdk-react', version: '1.0.0' },\n hostContext = { displayMode: 'inline' },\n }: {\n targetWindow: Window;\n targetOrigin?: string;\n handlers?: MCPAppBridgeHandlers;\n hostInfo?: { name: string; version: string };\n hostContext?: MCPAppHostContext;\n }) {\n this.targetWindow = targetWindow;\n this.targetOrigin = targetOrigin;\n this.handlers = handlers;\n this.hostInfo = hostInfo;\n this.hostContext = hostContext;\n }\n\n private targetWindow: Window;\n private targetOrigin: string;\n private handlers: MCPAppBridgeHandlers;\n private hostInfo: { name: string; version: string };\n private hostContext: MCPAppHostContext;\n\n /**\n * Replaces the callbacks used to serve iframe requests.\n */\n setHandlers(handlers: MCPAppBridgeHandlers): void {\n this.handlers = handlers;\n }\n\n /**\n * Updates host context and notifies the iframe after initialization.\n *\n * @example\n * ```ts\n * bridge.setHostContext({ theme: 'dark', displayMode: 'inline' });\n * ```\n */\n setHostContext(hostContext: MCPAppHostContext): void {\n this.hostContext = hostContext;\n this.sendNotification({\n method: 'ui/notifications/host-context-changed',\n params: hostContext,\n });\n }\n\n /**\n * Whether a `message` event came from the expected proxy window and origin.\n * The origin check is skipped only when `targetOrigin` is the `'*'` default.\n * Callers that intercept events before {@link handleMessage} share this check.\n */\n acceptsEvent(event: MessageEvent): boolean {\n return (\n event.source === this.targetWindow &&\n (this.targetOrigin === '*' || event.origin === this.targetOrigin)\n );\n }\n\n /**\n * Processes one `message` event from the sandbox proxy iframe.\n */\n handleMessage(event: MessageEvent): void {\n if (!this.acceptsEvent(event) || !isJsonRpcMessage(event.data)) {\n return;\n }\n\n const message = event.data;\n\n if ('result' in message || 'error' in message) {\n this.handleResponse(message);\n return;\n }\n\n if (isRequest(message)) {\n void this.handleRequest(message);\n return;\n }\n\n if (isNotification(message)) {\n this.handleNotification(message);\n }\n }\n\n /**\n * Sends app HTML and sandbox settings to the sandbox proxy.\n */\n sendSandboxResourceReady(params: unknown): void {\n this.post({\n jsonrpc: '2.0',\n method: 'ui/notifications/sandbox-resource-ready',\n params,\n });\n }\n\n /**\n * Sends final tool arguments to the MCP App.\n */\n sendToolInput(input: unknown): void {\n this.sendNotification({\n method: 'ui/notifications/tool-input',\n params: { arguments: input },\n });\n }\n\n /**\n * Sends a completed MCP tool result to the MCP App.\n */\n sendToolResult(result: unknown): void {\n this.sendNotification({\n method: 'ui/notifications/tool-result',\n params: result,\n });\n }\n\n /**\n * Notifies the MCP App that the related tool call was cancelled.\n */\n sendToolCancelled(reason?: string): void {\n this.sendNotification({\n method: 'ui/notifications/tool-cancelled',\n params: reason != null ? { reason } : {},\n });\n }\n\n /**\n * Requests graceful teardown before the host removes the iframe.\n */\n teardownResource(): Promise<unknown> {\n return this.request('ui/resource-teardown', {});\n }\n\n /**\n * Rejects pending bridge requests and clears queued notifications.\n */\n close(): void {\n for (const pending of this.pendingResponses.values()) {\n pending.reject(new Error('MCP App bridge closed'));\n }\n this.pendingResponses.clear();\n this.pendingNotifications = [];\n }\n\n /**\n * Resolves or rejects a host-initiated request when the iframe responds.\n */\n private handleResponse(response: MCPAppJsonRpcResponse): void {\n const pending = this.pendingResponses.get(response.id);\n if (pending == null) {\n return;\n }\n\n this.pendingResponses.delete(response.id);\n\n if (response.error != null) {\n pending.reject(new Error(response.error.message));\n } else {\n pending.resolve(response.result);\n }\n }\n\n /**\n * Runs a handler for an iframe request and posts the JSON-RPC response.\n */\n private async handleRequest(request: MCPAppJsonRpcRequest): Promise<void> {\n try {\n const result = await this.getRequestResult(request);\n this.post({ jsonrpc: '2.0', id: request.id, result });\n } catch (error) {\n const normalizedError = toError(error);\n this.handlers.onError?.(normalizedError);\n this.post({\n jsonrpc: '2.0',\n id: request.id,\n error: { code: -32603, message: normalizedError.message },\n });\n }\n }\n\n /**\n * Maps supported iframe request methods to host callbacks.\n */\n private async getRequestResult(\n request: MCPAppJsonRpcRequest,\n ): Promise<unknown> {\n switch (request.method) {\n case 'ui/initialize':\n return {\n protocolVersion: MCP_APP_PROTOCOL_VERSION,\n hostCapabilities: {\n ...(this.handlers.callTool != null ? { serverTools: {} } : {}),\n ...(this.handlers.readResource != null\n ? { serverResources: {} }\n : {}),\n ...(this.handlers.onLog != null ? { logging: {} } : {}),\n },\n hostInfo: this.hostInfo,\n hostContext: this.hostContext,\n };\n\n case 'tools/call': {\n if (this.handlers.callTool == null) {\n throw new Error('No tools/call handler configured');\n }\n const params = assertToolCallParams(request.params);\n // Deny-by-default: the (untrusted) MCP App may only invoke tools the\n // host has explicitly allow-listed. Omitting `allowedTools` exposes no\n // tools, rather than forwarding every requested tool to `callTool`.\n if (\n this.handlers.allowedTools == null ||\n !this.handlers.allowedTools.includes(params.name)\n ) {\n throw new Error(`Tool is not app-visible: ${params.name}`);\n }\n return this.handlers.callTool(params);\n }\n\n case 'resources/read':\n if (this.handlers.readResource == null) {\n throw new Error('No resources/read handler configured');\n }\n return this.handlers.readResource(\n assertResourceReadParams(request.params),\n );\n\n case 'resources/list':\n if (this.handlers.listResources == null) {\n throw new Error('No resources/list handler configured');\n }\n return this.handlers.listResources(request.params);\n\n case 'ui/open-link':\n if (this.handlers.openLink == null) {\n throw new Error('No ui/open-link handler configured');\n }\n return this.handlers.openLink(assertOpenLinkParams(request.params));\n\n case 'ui/message':\n return this.handlers.sendMessage?.(request.params) ?? {};\n\n case 'ui/update-model-context':\n return this.handlers.updateModelContext?.(request.params) ?? {};\n\n case 'ui/request-display-mode':\n return (\n this.handlers.requestDisplayMode?.(\n assertDisplayModeParams(request.params),\n ) ?? { mode: this.hostContext.displayMode ?? 'inline' }\n );\n\n default:\n throw new Error(`Unsupported MCP App method: ${request.method}`);\n }\n }\n\n /**\n * Handles iframe lifecycle and telemetry notifications.\n */\n private handleNotification(notification: MCPAppJsonRpcNotification): void {\n switch (notification.method) {\n case 'ui/notifications/initialized':\n this.initialized = true;\n this.flushNotifications();\n this.handlers.onInitialized?.();\n break;\n case 'ui/notifications/size-changed':\n this.handlers.onSizeChange?.(\n notification.params as { width?: number; height?: number },\n );\n break;\n case 'ui/notifications/request-teardown':\n this.handlers.onRequestTeardown?.(notification.params);\n break;\n case 'notifications/message':\n this.handlers.onLog?.(notification.params);\n break;\n }\n }\n\n /**\n * Sends a host-to-iframe notification, queueing it until app initialization.\n */\n private sendNotification(\n notification: Omit<MCPAppJsonRpcNotification, 'jsonrpc'>,\n ) {\n const message = { jsonrpc: '2.0' as const, ...notification };\n if (!this.initialized && !notification.method.includes('sandbox')) {\n this.pendingNotifications.push(message);\n return;\n }\n this.post(message);\n }\n\n /**\n * Sends notifications that were queued before `ui/notifications/initialized`.\n */\n private flushNotifications(): void {\n const notifications = this.pendingNotifications;\n this.pendingNotifications = [];\n for (const notification of notifications) {\n this.post(notification);\n }\n }\n\n /**\n * Sends a host-initiated JSON-RPC request to the iframe.\n */\n private request(method: string, params: unknown): Promise<unknown> {\n const id = this.nextRequestId++;\n this.post({ jsonrpc: '2.0', id, method, params });\n return new Promise((resolve, reject) => {\n this.pendingResponses.set(id, { resolve, reject });\n });\n }\n\n /**\n * Posts a JSON-RPC message to the sandbox proxy iframe.\n */\n private post(message: MCPAppJsonRpcMessage): void {\n this.targetWindow.postMessage(message, this.targetOrigin);\n }\n}\n","import type { MCPAppResourceCSP } from '@ai-sdk/mcp';\n\n// CSP source values come from the (untrusted) MCP server. Rather than\n// denylisting bad characters on the raw string (which an encoding like \"%3B\"\n// can slip past), canonicalize each value: parse it as an absolute URL so any\n// percent-encoding is decoded, keep only https/wss origins, then re-check the\n// decoded origin so a separator that decoded back into \";\" \",\" or whitespace\n// cannot split the directive.\nconst ALLOWED_CSP_SCHEMES = new Set(['https:', 'wss:']);\n\nfunction sanitizeCSPSources(sources?: string[]): string[] {\n const result: string[] = [];\n for (const source of sources ?? []) {\n if (typeof source !== 'string') {\n continue;\n }\n\n let origin: string;\n try {\n const url = new URL(source);\n // Reject non-https/wss, the empty host, and a bare \"*\" host (which would\n // match every origin and defeat the allowlist, like scheme-only \"https:\").\n if (\n !ALLOWED_CSP_SCHEMES.has(url.protocol) ||\n url.host.length === 0 ||\n url.host === '*'\n ) {\n continue;\n }\n origin = url.origin;\n } catch {\n continue;\n }\n\n // Drop separators that split the directive and quotes that could break out\n // of an HTML attribute the policy may be embedded in downstream.\n if (/[\"'`\\s;,]/.test(origin)) {\n continue;\n }\n\n result.push(origin);\n }\n return result;\n}\n\n/**\n * Default sandbox permissions for the outer sandbox proxy iframe.\n */\nexport const MCP_APP_DEFAULT_OUTER_SANDBOX =\n 'allow-scripts allow-same-origin allow-forms';\n\n/**\n * Default sandbox permissions for the inner iframe that runs app HTML.\n */\nexport const MCP_APP_DEFAULT_INNER_SANDBOX = 'allow-scripts allow-forms';\n\n/**\n * Converts MCP App CSP metadata into a Content-Security-Policy string.\n *\n * The returned value is meant to be passed to a sandbox proxy, which can apply\n * it to the inner iframe document.\n *\n * @example\n * ```ts\n * const csp = getMCPAppCSP({\n * connectDomains: ['https://api.example.com'],\n * resourceDomains: ['https://cdn.example.com'],\n * });\n * ```\n */\nexport function getMCPAppCSP(csp?: MCPAppResourceCSP): string | undefined {\n if (csp == null) {\n return undefined;\n }\n\n const connectSrc = [\"'self'\", ...sanitizeCSPSources(csp.connectDomains)];\n const imgSrc = [\n \"'self'\",\n 'data:',\n ...sanitizeCSPSources(csp.resourceDomains),\n ];\n const frameSrc = [\"'self'\", ...sanitizeCSPSources(csp.frameDomains)];\n\n return [\n \"default-src 'none'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n \"script-src 'unsafe-inline'\",\n \"style-src 'unsafe-inline'\",\n `connect-src ${connectSrc.join(' ')}`,\n `img-src ${imgSrc.join(' ')}`,\n `font-src ${imgSrc.join(' ')}`,\n `frame-src ${frameSrc.join(' ')}`,\n ].join('; ');\n}\n\n/**\n * A permission an MCP App may request and a host may allow.\n */\nexport type MCPAppPermission =\n | 'camera'\n | 'microphone'\n | 'geolocation'\n | 'clipboardWrite';\n\nconst MCP_APP_PERMISSION_FEATURES: Record<MCPAppPermission, string> = {\n camera: 'camera',\n microphone: 'microphone',\n geolocation: 'geolocation',\n clipboardWrite: 'clipboard-write',\n};\n\n/**\n * Converts MCP App permission metadata into an iframe `allow` attribute.\n *\n * Deny-by-default: a capability is granted only when it is both requested in\n * `permissions` and present in the host `allowedPermissions` allowlist.\n * Omitting the allowlist grants nothing, mirroring `allowedTools` in the bridge.\n *\n * @example\n * ```ts\n * const allow = getMCPAppAllowAttribute(\n * { microphone: {}, camera: {} },\n * ['microphone'],\n * );\n * // \"microphone\" — camera requested by server but not host-allowed\n * ```\n */\nexport function getMCPAppAllowAttribute(\n permissions?: Record<string, unknown>,\n allowedPermissions?: MCPAppPermission[],\n): string | undefined {\n if (permissions == null || allowedPermissions == null) {\n return undefined;\n }\n\n const allow = allowedPermissions\n .filter(permission => Boolean(permissions[permission]))\n .map(permission => MCP_APP_PERMISSION_FEATURES[permission]);\n\n return allow.length > 0 ? allow.join('; ') : undefined;\n}\n","import { isJSONObject } from '@ai-sdk/provider';\nimport type { MCPAppMetadata, MCPAppRendererProps } from './types';\n\n/**\n * Extracts MCP App metadata from an AI SDK tool UI part.\n *\n * @example\n * ```ts\n * const app = getMCPAppFromToolPart({\n * type: 'dynamic-tool',\n * toolName: 'showDashboard',\n * toolCallId: 'call-1',\n * state: 'input-available',\n * input: { topic: 'usage' },\n * toolMetadata: {\n * app: {\n * resourceUri: 'ui://example/dashboard',\n * mimeType: 'text/html;profile=mcp-app',\n * },\n * },\n * });\n * // { resourceUri: 'ui://example/dashboard', mimeType: 'text/html;profile=mcp-app' }\n * ```\n */\nexport function getMCPAppFromToolPart(\n part: MCPAppRendererProps['part'],\n): MCPAppMetadata | undefined {\n const rawAppMetadata = part.toolMetadata?.app;\n const appMetadata = isJSONObject(rawAppMetadata) ? rawAppMetadata : undefined;\n\n if (\n appMetadata == null ||\n appMetadata.mimeType !== 'text/html;profile=mcp-app' ||\n typeof appMetadata.resourceUri !== 'string' ||\n !appMetadata.resourceUri.startsWith('ui://') ||\n (appMetadata.visibility != null &&\n (!Array.isArray(appMetadata.visibility) ||\n appMetadata.visibility.some(\n value => value !== 'model' && value !== 'app',\n )))\n ) {\n return undefined;\n }\n\n return appMetadata as MCPAppMetadata;\n}\n\n/**\n * Converts an AI SDK tool output into the MCP Apps tool-result shape.\n *\n * MCP Apps expect tool results to have `content` and optional\n * `structuredContent`. MCP tools already return that shape, but typed AI SDK\n * tools may return only structured data. This helper wraps structured-only\n * outputs so the iframe can receive a valid tool result notification.\n *\n * @example\n * ```ts\n * normalizeMCPAppToolResult({ cards: [] });\n * // { content: [], structuredContent: { cards: [] } }\n * ```\n */\nexport function normalizeMCPAppToolResult(output: unknown): {\n content: unknown[];\n structuredContent?: unknown;\n isError?: boolean;\n} {\n if (output != null && typeof output === 'object' && 'content' in output) {\n return output as {\n content: unknown[];\n structuredContent?: unknown;\n isError?: boolean;\n };\n }\n\n return {\n content: [],\n structuredContent: output,\n };\n}\n","import { useEffect, useMemo, useRef } from 'react';\nimport { MCPAppBridge } from './bridge';\nimport {\n MCP_APP_DEFAULT_INNER_SANDBOX,\n MCP_APP_DEFAULT_OUTER_SANDBOX,\n getMCPAppAllowAttribute,\n getMCPAppCSP,\n} from './sandbox';\nimport type { MCPAppFrameProps } from './types';\nimport { normalizeMCPAppToolResult } from './utils';\n\n/**\n * Derives the concrete origin of the sandbox proxy from its URL, so outbound\n * postMessage targets a specific origin instead of `'*'` and inbound messages\n * can be origin-checked. The proxy must be served from a stable, concrete\n * origin (the default outer sandbox keeps `allow-same-origin`). Falls back to\n * the host origin on a malformed URL, never `'*'`.\n */\nfunction deriveTargetOrigin(url: string): string {\n const location = typeof window !== 'undefined' ? window.location : undefined;\n try {\n return new URL(url, location?.href).origin;\n } catch {\n return location?.origin ?? 'null';\n }\n}\n\nfunction sendToolState({\n bridge,\n input,\n output,\n}: {\n bridge?: MCPAppBridge;\n input: unknown;\n output: unknown;\n}) {\n if (bridge == null) {\n return;\n }\n\n if (input !== undefined) {\n bridge.sendToolInput(input);\n }\n\n if (output !== undefined) {\n bridge.sendToolResult(normalizeMCPAppToolResult(output));\n }\n}\n\nexport function MCPAppFrame({\n app,\n resource,\n input,\n output,\n sandbox,\n handlers,\n hostInfo,\n hostContext,\n}: MCPAppFrameProps) {\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const bridgeRef = useRef<MCPAppBridge | undefined>(undefined);\n const inputRef = useRef(input);\n const outputRef = useRef(output);\n const hostContextRef = useRef(hostContext);\n const initializedRef = useRef(false);\n inputRef.current = input;\n outputRef.current = output;\n hostContextRef.current = hostContext;\n const sandboxUrl = String(sandbox.url);\n const targetOrigin = sandbox.targetOrigin ?? deriveTargetOrigin(sandboxUrl);\n const resourceCSP = getMCPAppCSP(resource.meta?.csp);\n const resourceAllow = getMCPAppAllowAttribute(\n resource.meta?.permissions,\n sandbox.allowedPermissions,\n );\n const innerSandbox = sandbox.innerSandbox ?? MCP_APP_DEFAULT_INNER_SANDBOX;\n const bridgeHandlers = useMemo(\n () => ({\n ...handlers,\n onInitialized: () => {\n initializedRef.current = true;\n handlers?.onInitialized?.();\n sendToolState({\n bridge: bridgeRef.current,\n input: inputRef.current,\n output: outputRef.current,\n });\n },\n }),\n [handlers],\n );\n const bridgeHandlersRef = useRef(bridgeHandlers);\n bridgeHandlersRef.current = bridgeHandlers;\n\n useEffect(() => {\n const iframe = iframeRef.current;\n const targetWindow = iframe?.contentWindow;\n if (targetWindow == null) {\n return;\n }\n\n initializedRef.current = false;\n\n const bridge = new MCPAppBridge({\n targetWindow,\n targetOrigin,\n handlers: bridgeHandlersRef.current,\n hostInfo,\n hostContext: hostContextRef.current,\n });\n bridgeRef.current = bridge;\n\n const onMessage = (event: MessageEvent) => {\n // Only handle messages from the proxy window and expected origin.\n if (!bridge.acceptsEvent(event)) {\n return;\n }\n\n if (\n event.data?.jsonrpc === '2.0' &&\n event.data.method === 'ui/notifications/sandbox-proxy-ready'\n ) {\n bridge.sendSandboxResourceReady({\n html: resource.html,\n csp: resourceCSP,\n sandbox: innerSandbox,\n allow: resourceAllow,\n });\n return;\n }\n\n bridge.handleMessage(event);\n };\n\n window.addEventListener('message', onMessage);\n\n return () => {\n initializedRef.current = false;\n window.removeEventListener('message', onMessage);\n void bridge.teardownResource().catch(() => {});\n bridge.close();\n bridgeRef.current = undefined;\n };\n }, [\n hostInfo,\n innerSandbox,\n resource.html,\n resourceAllow,\n resourceCSP,\n sandboxUrl,\n targetOrigin,\n ]);\n\n useEffect(() => {\n bridgeRef.current?.setHandlers(bridgeHandlers);\n }, [bridgeHandlers]);\n\n useEffect(() => {\n if (hostContext != null) {\n bridgeRef.current?.setHostContext(hostContext);\n }\n }, [hostContext]);\n\n useEffect(() => {\n if (initializedRef.current && input !== undefined) {\n bridgeRef.current?.sendToolInput(input);\n }\n }, [input]);\n\n useEffect(() => {\n if (initializedRef.current && output !== undefined) {\n bridgeRef.current?.sendToolResult(normalizeMCPAppToolResult(output));\n }\n }, [output]);\n\n return (\n <iframe\n ref={iframeRef}\n title=\"MCP App\"\n aria-label={sandbox.title ?? app.resourceUri}\n src={sandboxUrl}\n className={sandbox.className}\n style={sandbox.style}\n // Permissions Policy is hierarchical: the outer frame must delegate a\n // feature for the proxy to re-delegate it to the inner app frame.\n allow={resourceAllow}\n sandbox={sandbox.outerSandbox ?? MCP_APP_DEFAULT_OUTER_SANDBOX}\n />\n );\n}\n","import type { MCPAppResource } from '@ai-sdk/mcp';\nimport { useEffect, useState } from 'react';\nimport { MCPAppFrame } from './app-frame';\nimport type { MCPAppMetadata, MCPAppRendererProps } from './types';\nimport { getMCPAppFromToolPart } from './utils';\n\ntype LoadedResourceState = {\n resourceUri: string;\n resource?: MCPAppResource;\n error?: Error;\n};\n\nfunction getToolPartOutput(part: MCPAppRendererProps['part']): unknown {\n return part.state === 'output-available' ? part.output : undefined;\n}\n\nfunction getToolPartInput(part: MCPAppRendererProps['part']): unknown {\n return part.state === 'input-available' || part.state === 'output-available'\n ? part.input\n : undefined;\n}\n\nexport function MCPAppRenderer({\n part,\n sandbox,\n resource: resourceProp,\n loadResource,\n handlers,\n hostInfo,\n hostContext,\n fallback = null,\n}: MCPAppRendererProps) {\n const app = getMCPAppFromToolPart(part);\n const [cachedApp, setCachedApp] = useState<MCPAppMetadata>();\n const [loadedResource, setLoadedResource] = useState<LoadedResourceState>();\n\n useEffect(() => {\n if (app != null) {\n setCachedApp(previous =>\n previous?.resourceUri === app.resourceUri ? previous : app,\n );\n }\n }, [app?.resourceUri]);\n\n const appForRender = app ?? cachedApp;\n\n useEffect(() => {\n if (appForRender == null || resourceProp != null || loadResource == null) {\n return;\n }\n\n let cancelled = false;\n const resourceUri = appForRender.resourceUri;\n\n loadResource(appForRender)\n .then(resource => {\n if (!cancelled) {\n setLoadedResource({ resourceUri, resource });\n }\n })\n .catch(error => {\n if (!cancelled) {\n setLoadedResource({\n resourceUri,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n cancelled = true;\n };\n }, [appForRender?.resourceUri, loadResource, resourceProp]);\n\n const loadedResourceForApp =\n loadedResource?.resourceUri === appForRender?.resourceUri\n ? loadedResource\n : undefined;\n const resource = resourceProp ?? loadedResourceForApp?.resource;\n const error = resourceProp == null ? loadedResourceForApp?.error : undefined;\n\n if (appForRender == null || error != null || resource == null) {\n return fallback;\n }\n\n return (\n <MCPAppFrame\n app={appForRender}\n resource={resource}\n input={getToolPartInput(part)}\n output={getToolPartOutput(part)}\n sandbox={sandbox}\n handlers={handlers}\n hostInfo={hostInfo}\n hostContext={hostContext}\n />\n );\n}\n","import { MCPAppRenderer } from './app-renderer';\n\nexport { MCPAppRenderer } from './app-renderer';\n\n/**\n * @deprecated Use `MCPAppRenderer` instead.\n */\nexport const experimental_MCPAppRenderer = MCPAppRenderer;\n\nexport type { MCPAppPermission } from './sandbox';\nexport type {\n MCPAppBridgeHandlers,\n MCPAppMetadata,\n MCPAppRendererProps,\n MCPAppResource,\n MCPAppSandboxConfig,\n} from './types';\n","import type { FlexibleSchema } from '@ai-sdk/provider-utils';\nimport {\n useObject,\n type UseObjectHelpers,\n type UseObjectOptions,\n} from './use-object';\n\nexport * from './use-chat';\nexport { Chat } from './chat.react';\nexport * from './use-completion';\nexport * from './use-object';\nexport * from './use-realtime';\nexport * from './mcp-apps';\n\n// deprecated aliases\n// note: declared here (instead of export aliases) so that the `@deprecated`\n// tags are preserved in the bundled type declarations\n\n/**\n * @deprecated Use `useObject` instead.\n */\nexport const experimental_useObject = useObject;\n\n/**\n * @deprecated Use `UseObjectOptions` instead.\n */\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = UseObjectOptions<SCHEMA, RESULT>;\n\n/**\n * @deprecated Use `UseObjectHelpers` instead.\n */\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = UseObjectHelpers<\n RESULT,\n INPUT\n>;\n"],"mappings":";;;;;;;;AAoBA,MAAM,yBAAyB;AAuG/B,SAAgB,UAId,EACA,KACA,IACA,QACA,cACA,OACA,SACA,UACA,SACA,eACoE;CAEpE,MAAM,SAAS,MAAM;CAIrB,MAAM,EAAE,MAAM,WAAW,OACvB,CAJmB,MAAM,QAIV,QAAQ,GACvB,MACA,EAAE,cAAc,EAAE,QAAQ,aAAa,EAAE,CAC3C;CAEA,MAAM,CAAC,OAAO,YAAY,SAA4B,KAAA,CAAS;CAC/D,MAAM,CAAC,WAAW,gBAAgB,SAAS,KAAK;CAGhD,MAAM,qBAAqB,OAA+B,IAAI;CAE9D,MAAM,OAAO,kBAAkB;EAC7B,IAAI;GACF,mBAAmB,SAAS,MAAM;EACpC,QAAQ,CACR,UAAU;GACR,aAAa,KAAK;GAClB,mBAAmB,UAAU;EAC/B;CACF,GAAG,CAAC,CAAC;CAEL,MAAM,SAAS,OAAO,UAAiB;EACrC,MAAM,kBAAkB,IAAI,gBAAgB;EAE5C,IAAI;GACF,YAAY;GAEZ,aAAa,IAAI;GAEjB,mBAAmB,UAAU;GAG7B,MAAM,kBAAkB,MAAM,QAAQ,OAAO;GAG7C,MAAM,WAAW,OADG,SAAS,iBAAiB,EAAA,CACX,KAAK;IACtC,QAAQ;IACR,SAAS;KACP,gBAAgB;KAChB,GAAG,iBAAiB,eAAe;IACrC;IACA;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,MAAM,uBACJ,gBAAgB,gBAAgB,cAAc,cAC1C,iBACA,KAAA;CACN,MAAM,WAAW,gBAAgB,sBAAsB;CACvD,MAAM,QAAQ,gBAAgB,OAAO,sBAAsB,QAAQ,KAAA;CAEnE,IAAI,gBAAgB,QAAQ,SAAS,QAAQ,YAAY,MACvD,OAAO;CAGT,OACE,oBAAC,aAAD;EACE,KAAK;EACK;EACV,OAAO,iBAAiB,IAAI;EAC5B,QAAQ,kBAAkB,IAAI;EACrB;EACC;EACA;EACG;CACd,CAAA;AAEL;;;;;;AC1FA,MAAa,8BAA8B;;;;;;ACc3C,MAAa,yBAAyB"}
1
+ {"version":3,"file":"index.js","names":["resumableChat","AbstractRealtimeSession"],"sources":["../src/use-object.ts","../src/throttle.ts","../src/chat.react.ts","../src/use-chat.ts","../src/use-completion.ts","../src/use-realtime.ts","../src/mcp-apps/bridge.ts","../src/mcp-apps/sandbox.ts","../src/mcp-apps/utils.ts","../src/mcp-apps/app-frame.tsx","../src/mcp-apps/app-renderer.tsx","../src/mcp-apps/index.ts","../src/index.ts"],"sourcesContent":["import {\n isAbortError,\n resolve,\n normalizeHeaders,\n safeValidateTypes,\n type FetchFunction,\n type FlexibleSchema,\n type InferSchema,\n type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport {\n asSchema,\n isDeepEqualData,\n parsePartialJson,\n type DeepPartial,\n} from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type UseObjectOptions<SCHEMA extends FlexibleSchema, RESULT> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * Callback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\n * The generated object (typed according to the schema).\n * Can be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\n * Optional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n * Can be a static object, a function that returns headers, or an async function\n * for dynamic auth tokens.\n */\n headers?: Resolvable<Record<string, string> | Headers>;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\ntype ObjectState<RESULT> = {\n object: DeepPartial<RESULT> | undefined;\n};\n\nexport function useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: UseObjectOptions<SCHEMA, RESULT>): UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<ObjectState<RESULT>>(\n [completionId, 'object'],\n null,\n { fallbackData: { object: initialValue } },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n const abortController = new AbortController();\n\n try {\n clearObject();\n\n setIsLoading(true);\n\n abortControllerRef.current = abortController;\n\n // Resolve headers at request time (supports async functions for dynamic auth tokens)\n const resolvedHeaders = await resolve(headers);\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...normalizeHeaders(resolvedHeaders),\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) || 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n if (abortControllerRef.current === abortController) {\n mutate({ object: currentObject });\n }\n }\n },\n\n async close() {\n if (abortControllerRef.current === abortController) {\n setIsLoading(false);\n }\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n await onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n\n if (abortControllerRef.current === abortController) {\n abortControllerRef.current = null;\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n if (abortControllerRef.current === abortController) {\n setIsLoading(false);\n abortControllerRef.current = null;\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate({ object: undefined });\n };\n\n return {\n submit,\n object: data?.object,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n AbstractChat,\n type ChatInit,\n type ChatState,\n type ChatStatus,\n type UIMessage,\n} from 'ai';\nimport { throttle } from './throttle';\n\nfunction cloneMetadata<METADATA>(metadata: METADATA): METADATA {\n if (Array.isArray(metadata)) {\n return [...metadata] as METADATA;\n }\n\n if (\n metadata != null &&\n typeof metadata === 'object' &&\n (Object.getPrototypeOf(metadata) === Object.prototype ||\n Object.getPrototypeOf(metadata) === null)\n ) {\n return { ...metadata } as METADATA;\n }\n\n return metadata;\n}\n\nclass ReactChatState<\n UI_MESSAGE extends UIMessage,\n> implements ChatState<UI_MESSAGE> {\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n #queuedMessages: UI_MESSAGE[] = [];\n\n #messagesCallbacks = new Set<() => void>();\n #queuedMessagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get experimental_queuedMessages(): UI_MESSAGE[] {\n return this.#queuedMessages;\n }\n\n set experimental_queuedMessages(newQueuedMessages: UI_MESSAGE[]) {\n this.#queuedMessages = newQueuedMessages;\n this.#queuedMessagesCallbacks.forEach(callback => callback());\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => {\n if (\n value == null ||\n typeof value !== 'object' ||\n !('parts' in value) ||\n !Array.isArray(value.parts)\n ) {\n return value;\n }\n\n const message = value as UI_MESSAGE;\n const snapshot = {\n ...message,\n parts: message.parts.map(part => ({ ...part })),\n };\n\n if ('metadata' in message) {\n snapshot.metadata = cloneMetadata(message.metadata);\n }\n\n return snapshot as T;\n };\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n '~registerQueuedMessagesCallback' = (onChange: () => void): (() => void) => {\n this.#queuedMessagesCallbacks.add(onChange);\n return () => {\n this.#queuedMessagesCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n\n '~registerQueuedMessagesCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerQueuedMessagesCallback'](onChange);\n}\n","import {\n type AbstractChat,\n type ChatInit,\n type ChatTransport,\n type CreateUIMessage,\n type UIMessage,\n DefaultChatTransport,\n} from 'ai';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n | 'experimental_queuedMessages'\n | 'experimental_removeQueuedMessage'\n | 'experimental_sendQueuedMessageNow'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\n * Custom throttle wait in ms for the chat messages and data updates.\n * Default is undefined, which disables throttling.\n */\n throttle?: number;\n\n /**\n * @deprecated Use `throttle` instead.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to automatically resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\ntype AutomaticResumeState = {\n registrations: Set<object>;\n cleanupVisibilityListener?: () => void;\n pendingVisibilityResume?: Promise<void>;\n};\n\nconst automaticResumeStates = new WeakMap<object, AutomaticResumeState>();\n\ntype AutomaticallyResumableChat = {\n '~resumeStreamIfDisconnected': (options: {\n shouldResume: () => boolean;\n }) => Promise<void>;\n};\n\n/**\n * When the document becomes visible again, resume the chat stream if it was\n * interrupted by a network disconnect while the page was in the background.\n */\nfunction resumeOnVisible<UI_MESSAGE extends UIMessage>({\n chat,\n state,\n}: {\n chat: Chat<UI_MESSAGE>;\n state: AutomaticResumeState;\n}) {\n if (\n document.visibilityState !== 'visible' ||\n state.pendingVisibilityResume != null\n ) {\n return;\n }\n\n const isRegistered = () =>\n automaticResumeStates.get(chat) === state && state.registrations.size > 0;\n\n const clearPendingResume = () => {\n state.pendingVisibilityResume = undefined;\n };\n\n const resumableChat = chat as Chat<UI_MESSAGE> & AutomaticallyResumableChat;\n\n state.pendingVisibilityResume = resumableChat['~resumeStreamIfDisconnected']({\n shouldResume: () =>\n isRegistered() && document.visibilityState === 'visible',\n }).then(clearPendingResume, clearPendingResume);\n}\n\nfunction registerAutomaticResume<UI_MESSAGE extends UIMessage>({\n chat,\n registration,\n}: {\n chat: Chat<UI_MESSAGE>;\n registration: object;\n}) {\n let state = automaticResumeStates.get(chat);\n\n if (state == null) {\n const newState: AutomaticResumeState = { registrations: new Set() };\n automaticResumeStates.set(chat, newState);\n state = newState;\n\n if (typeof document !== 'undefined') {\n const onVisibilityChange = () =>\n resumeOnVisible({ chat, state: newState });\n\n document.addEventListener('visibilitychange', onVisibilityChange);\n newState.cleanupVisibilityListener = () => {\n document.removeEventListener('visibilitychange', onVisibilityChange);\n };\n }\n }\n\n const { registrations } = state;\n const shouldResume = registrations.size === 0;\n registrations.add(registration);\n\n if (\n shouldResume &&\n chat.status !== 'submitted' &&\n chat.status !== 'streaming'\n ) {\n void chat.resumeStream();\n }\n\n return () => {\n registrations.delete(registration);\n\n if (registrations.size === 0) {\n state.cleanupVisibilityListener?.();\n automaticResumeStates.delete(chat);\n }\n };\n}\n\ntype ChatSnapshot<UI_MESSAGE extends UIMessage> = {\n chat: Chat<UI_MESSAGE>;\n messages: UI_MESSAGE[];\n status: Chat<UI_MESSAGE>['status'];\n error: Error | undefined;\n experimental_queuedMessages: UI_MESSAGE[];\n};\n\nfunction readChatSnapshot<UI_MESSAGE extends UIMessage>(\n chat: Chat<UI_MESSAGE>,\n): ChatSnapshot<UI_MESSAGE> {\n return {\n chat,\n messages: chat.messages,\n status: chat.status,\n error: chat.error,\n experimental_queuedMessages: chat.experimental_queuedMessages,\n };\n}\n\nfunction equalChatSnapshots<UI_MESSAGE extends UIMessage>(\n current: ChatSnapshot<UI_MESSAGE>,\n next: ChatSnapshot<UI_MESSAGE>,\n) {\n return (\n current.chat === next.chat &&\n current.messages === next.messages &&\n current.status === next.status &&\n current.error === next.error &&\n current.experimental_queuedMessages === next.experimental_queuedMessages\n );\n}\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n throttle,\n experimental_throttle,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n const throttleWaitMs = throttle ?? experimental_throttle;\n const automaticResumeRegistration = useRef({});\n // the Chat instance is created once and not recreated when options change,\n // so it would normally keep the callbacks/transport from the first render forever\n\n // keep latest values in a ref that is refreshed on every render,\n // and hand `Chat` stable wrappers that read from it to avoid stale closures\n const latestRef = useRef<\n Partial<\n Pick<\n ChatInit<UI_MESSAGE>,\n | 'onToolCall'\n | 'onData'\n | 'onFinish'\n | 'onError'\n | 'sendAutomaticallyWhen'\n | 'transport'\n >\n >\n >({});\n\n if (!('chat' in options)) {\n latestRef.current = {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen,\n transport: options.transport,\n };\n }\n\n // resolve the latest transport and fallback to a lazily created default transport\n let defaultTransport: ChatTransport<UI_MESSAGE> | undefined;\n const getTransport = (): ChatTransport<UI_MESSAGE> =>\n latestRef.current.transport ??\n (defaultTransport ??= new DefaultChatTransport<UI_MESSAGE>());\n\n // give `Chat` stable wrappers that always read the latest values from `latestRef`\n const chatOptions: typeof options = {\n ...options,\n transport: {\n get resumeStreamIsReplay() {\n return getTransport().resumeStreamIsReplay;\n },\n sendMessages: sendOptions => getTransport().sendMessages(sendOptions),\n reconnectToStream: reconnectOptions =>\n getTransport().reconnectToStream(reconnectOptions),\n },\n onToolCall: arg => latestRef.current.onToolCall?.(arg),\n onData: arg => latestRef.current.onData?.(arg),\n onFinish: arg => latestRef.current.onFinish?.(arg),\n onError: arg => latestRef.current.onError?.(arg),\n sendAutomaticallyWhen: arg =>\n latestRef.current.sendAutomaticallyWhen?.(arg) ?? false,\n };\n\n const chatKey = 'chat' in options ? options.chat : options.id;\n const { chat, isExternallyManaged } = useMemo(\n () => ({\n chat: 'chat' in options ? options.chat : new Chat(chatOptions),\n isExternallyManaged: 'chat' in options,\n }),\n [chatKey],\n );\n\n useEffect(() => {\n if (isExternallyManaged) {\n return;\n }\n\n return () => {\n void chat.stop();\n };\n }, [chat, isExternallyManaged]);\n\n // Chat owns the live state; React owns the snapshot used for rendering.\n // useSyncExternalStore would make streaming updates synchronous and can\n // repeatedly restart navigation renders. Ordinary state updates let React\n // schedule both. Automatically wrapping publication in startTransition can\n // group it with a suspended navigation in the same root, holding back streamed\n // text and local edits.\n // Each consumer subscribes independently, so different throttle intervals can\n // produce different rendered snapshots of the same Chat.\n const [snapshot, setSnapshot] = useState(() => readChatSnapshot(chat));\n\n // React retries this component before rendering children, so they cannot\n // commit the previous Chat's snapshot. Resubscribe only after the swap commits.\n if (snapshot.chat !== chat) {\n setSnapshot(readChatSnapshot(chat));\n }\n\n useEffect(() => {\n let isSubscribed = true;\n const publishSnapshot = () => {\n // A trailing throttled callback can run after cleanup. Check before\n // enqueueing; keep the state updater independent of mutable effect state.\n if (!isSubscribed) {\n return;\n }\n\n const nextSnapshot = readChatSnapshot(chat);\n setSnapshot(current =>\n current.chat !== chat || equalChatSnapshots(current, nextSnapshot)\n ? current\n : nextSnapshot,\n );\n };\n\n // Only message notifications are throttled. Status and error notifications\n // publish the complete snapshot, so ready/error cannot commit beside stale\n // messages even when a throttled message notification is still pending.\n const unsubscribes = [\n chat['~registerMessagesCallback'](publishSnapshot, throttleWaitMs),\n chat['~registerStatusCallback'](publishSnapshot),\n chat['~registerErrorCallback'](publishSnapshot),\n chat['~registerQueuedMessagesCallback'](publishSnapshot),\n ];\n\n // Catch changes between render and subscription, including updates that\n // arrived before this consumer mounted or while its Chat was being replaced.\n const nextSnapshot = readChatSnapshot(chat);\n setSnapshot(current =>\n equalChatSnapshots(current, nextSnapshot) ? current : nextSnapshot,\n );\n\n return () => {\n isSubscribed = false;\n unsubscribes.forEach(unsubscribe => unsubscribe());\n };\n }, [chat, throttleWaitMs]);\n\n const { messages, status, error, experimental_queuedMessages } = snapshot;\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chat.messages);\n }\n chat.messages = messagesParam;\n },\n [chat],\n );\n\n useEffect(() => {\n if (resume) {\n return registerAutomaticResume({\n chat,\n registration: automaticResumeRegistration.current,\n });\n }\n }, [resume, chat]);\n\n return {\n get id() {\n return chat.id;\n },\n messages,\n setMessages,\n sendMessage: chat.sendMessage,\n regenerate: chat.regenerate,\n clearError: chat.clearError,\n stop: chat.stop,\n error,\n resumeStream: chat.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chat.addToolOutput,\n addToolOutput: chat.addToolOutput,\n addToolApprovalResponse: chat.addToolApprovalResponse,\n experimental_queuedMessages,\n experimental_removeQueuedMessage: chat.experimental_removeQueuedMessage,\n experimental_sendQueuedMessageNow: chat.experimental_sendQueuedMessageNow,\n };\n}\n","import {\n callCompletionApi,\n type CompletionRequestOptions,\n type UseCompletionOptions,\n} from 'ai';\nimport { normalizeHeaders } from '@ai-sdk/provider-utils';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers<BODY extends object = object> = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions<BODY>,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion<BODY extends object = object>({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n throttle: throttleWait,\n experimental_throttle,\n}: UseCompletionOptions<NoInfer<BODY>> & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n throttle?: number;\n\n /**\n * @deprecated Use `throttle` instead.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers<BODY> {\n const throttleWaitMs = throttleWait ?? experimental_throttle;\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n const requestIdRef = useRef(0);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions<BODY>) => {\n const requestId = ++requestIdRef.current;\n\n return callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: {\n ...normalizeHeaders(extraMetadataRef.current.headers),\n ...normalizeHeaders(options?.headers),\n },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle((completion: string) => {\n if (requestIdRef.current === requestId) {\n mutate(completion, false);\n }\n }, throttleWaitMs),\n setLoading: mutateLoading,\n setError,\n setAbortController: controller => {\n abortControllerRef.current = controller;\n },\n getAbortController: () => abortControllerRef.current,\n onFinish,\n onError,\n });\n },\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n abortControllerRef.current?.abort();\n }, []);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers<BODY>['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n if (!input) {\n return;\n }\n\n const result = complete(input);\n setInput('');\n return result;\n },\n [input, complete, setInput],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import { secureJsonParse } from '@ai-sdk/provider-utils';\nimport {\n Experimental_AbstractRealtimeSession as AbstractRealtimeSession,\n type Experimental_RealtimeServerEvent as RealtimeServerEvent,\n type Experimental_RealtimeSessionOptions as RealtimeSessionOptions,\n type Experimental_RealtimeState as RealtimeState,\n type Experimental_RealtimeStatus as RealtimeStatus,\n type UIMessage,\n} from 'ai';\nimport {\n useCallback,\n useEffect,\n useInsertionEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\n\ntype UseRealtimeOptions = RealtimeSessionOptions;\n\ntype RealtimeStateKey = keyof RealtimeState;\n\nconst useIsomorphicLayoutEffect =\n typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\nconst RealtimeStore = /* @__PURE__ */ (() =>\n class RealtimeStore extends AbstractRealtimeSession {\n protected state: RealtimeState = {\n status: 'disconnected',\n messages: [],\n events: [],\n isCapturing: false,\n isPlaying: false,\n };\n\n private callbacks: { [K in RealtimeStateKey]-?: Set<() => void> } = {\n status: new Set(),\n messages: new Set(),\n events: new Set(),\n isCapturing: new Set(),\n isPlaying: new Set(),\n session: new Set(),\n };\n\n get status(): RealtimeStatus {\n return this.state.status;\n }\n\n get messages(): UIMessage[] {\n return this.state.messages;\n }\n\n get events(): RealtimeServerEvent[] {\n return this.state.events;\n }\n\n get isCapturing(): boolean {\n return this.state.isCapturing;\n }\n\n get isPlaying(): boolean {\n return this.state.isPlaying;\n }\n\n get session(): RealtimeState['session'] {\n return this.state.session;\n }\n\n subscribe(key: RealtimeStateKey, onChange: () => void): () => void {\n this.callbacks[key].add(onChange);\n\n return () => {\n this.callbacks[key].delete(onChange);\n };\n }\n\n protected setState<K extends RealtimeStateKey>(\n key: K,\n value: RealtimeState[K],\n ): void {\n this.state = { ...this.state, [key]: value };\n this.callbacks[key].forEach(callback => callback());\n }\n })();\n\ntype RealtimeStore = InstanceType<typeof RealtimeStore>;\n\ntype UseRealtimeReturn = {\n status: RealtimeStatus;\n messages: UIMessage[];\n events: RealtimeServerEvent[];\n isCapturing: boolean;\n isPlaying: boolean;\n session?: RealtimeState['session'];\n\n connect: AbstractRealtimeSession['connect'];\n close: AbstractRealtimeSession['close'];\n resumePlayback: () => Promise<void>;\n resumeAudioCapture: () => Promise<void>;\n disconnect: () => void;\n addToolOutput: (callId: string, result: unknown) => void;\n sendEvent: AbstractRealtimeSession['sendEvent'];\n sendTextMessage: (text: string) => void;\n sendAudio: (base64Audio: string) => void;\n commitAudio: () => void;\n clearAudioBuffer: () => void;\n requestResponse: (options?: { modalities?: string[] }) => void;\n cancelResponse: () => void;\n startAudioCapture: (stream: MediaStream) => void;\n stopAudioCapture: () => void;\n stopPlayback: () => void;\n};\n\nfunction useRealtime(options: UseRealtimeOptions): UseRealtimeReturn {\n const ownerRef = useRef<{\n store: RealtimeStore;\n onToolCall: UseRealtimeOptions['onToolCall'];\n onEvent: UseRealtimeOptions['onEvent'];\n onError: UseRealtimeOptions['onError'];\n } | null>(null);\n const {\n model,\n api,\n startupTimeoutMs,\n closeTimeoutMs,\n rtcDisconnectTimeoutMs,\n sessionConfig,\n sampleRate,\n maxEvents,\n maxPlaybackBufferSeconds,\n onToolCall,\n onEvent,\n onError,\n } = options;\n const {\n token,\n websocket,\n session: sessionEndpoint,\n provider: providerEndpoint,\n } = api;\n const protocols = JSON.stringify(api.protocols ?? []);\n\n // Candidates allocate no transports or media; only a committed owner can act.\n const rt = useMemo(() => {\n const store: RealtimeStore = new RealtimeStore({\n model,\n api:\n token != null\n ? { token }\n : providerEndpoint != null\n ? { provider: providerEndpoint }\n : sessionEndpoint != null\n ? { session: sessionEndpoint }\n : {\n websocket: websocket as string,\n protocols: secureJsonParse(protocols) as string[],\n },\n startupTimeoutMs,\n closeTimeoutMs,\n rtcDisconnectTimeoutMs,\n sessionConfig,\n sampleRate,\n maxEvents,\n maxPlaybackBufferSeconds,\n onEvent: (...args) =>\n ownerRef.current?.store === store\n ? ownerRef.current.onEvent?.(...args)\n : undefined,\n onError: (...args) =>\n ownerRef.current?.store === store\n ? ownerRef.current.onError?.(...args)\n : undefined,\n });\n return store;\n }, [\n model,\n token,\n sessionEndpoint,\n providerEndpoint,\n websocket,\n protocols,\n startupTimeoutMs,\n closeTimeoutMs,\n rtcDisconnectTimeoutMs,\n sessionConfig,\n sampleRate,\n maxEvents,\n maxPlaybackBufferSeconds,\n ]);\n\n // Publish before child layout effects; insertion cleanup only revokes refs.\n useInsertionEffect(() => {\n ownerRef.current = { store: rt, onToolCall, onEvent, onError };\n rt.onToolCall =\n onToolCall == null\n ? undefined\n : (...args) =>\n ownerRef.current?.store === rt\n ? ownerRef.current.onToolCall?.(...args)\n : undefined;\n return () => {\n ownerRef.current = null;\n };\n });\n\n // StrictMode replays layout effects, but keeps the insertion-phase owner.\n useIsomorphicLayoutEffect(() => {\n return () => rt.dispose();\n }, [rt]);\n\n const actions = useMemo(() => {\n const current = () => {\n if (ownerRef.current == null)\n throw new Error('Realtime controls require a mounted hook');\n return ownerRef.current.store;\n };\n return {\n connect: async (options?: {\n stream?: MediaStream;\n capture?: boolean;\n }) => {\n const store = current();\n return options == null ? store.connect() : store.connect(options);\n },\n close: async options => current().close(options),\n resumePlayback: async () => current().resumePlayback(),\n resumeAudioCapture: async () => current().resumeAudioCapture(),\n disconnect: () => current().disconnect(),\n addToolOutput: (callId, result) =>\n current().addToolOutput(callId, result),\n sendEvent: event => current().sendEvent(event),\n sendTextMessage: text => current().sendTextMessage(text),\n sendAudio: audio => current().sendAudio(audio),\n commitAudio: () => current().commitAudio(),\n clearAudioBuffer: () => current().clearAudioBuffer(),\n requestResponse: options => current().requestResponse(options),\n cancelResponse: () => current().cancelResponse(),\n startAudioCapture: stream => current().startAudioCapture(stream),\n stopAudioCapture: () => current().stopAudioCapture(),\n stopPlayback: () => current().stopPlayback(),\n } satisfies Omit<UseRealtimeReturn, keyof RealtimeState>;\n }, []);\n\n const status = useSyncExternalStore(\n useCallback(cb => rt.subscribe('status', cb), [rt]),\n () => rt.status,\n () => rt.status,\n );\n\n const messages = useSyncExternalStore(\n useCallback(cb => rt.subscribe('messages', cb), [rt]),\n () => rt.messages,\n () => rt.messages,\n );\n\n const events = useSyncExternalStore(\n useCallback(cb => rt.subscribe('events', cb), [rt]),\n () => rt.events,\n () => rt.events,\n );\n\n const isCapturing = useSyncExternalStore(\n useCallback(cb => rt.subscribe('isCapturing', cb), [rt]),\n () => rt.isCapturing,\n () => rt.isCapturing,\n );\n\n const isPlaying = useSyncExternalStore(\n useCallback(cb => rt.subscribe('isPlaying', cb), [rt]),\n () => rt.isPlaying,\n () => rt.isPlaying,\n );\n\n const session = useSyncExternalStore(\n useCallback(cb => rt.subscribe('session', cb), [rt]),\n () => rt.session,\n () => rt.session,\n );\n\n return {\n status,\n messages,\n events,\n isCapturing,\n isPlaying,\n session,\n ...actions,\n };\n}\n\nexport const experimental_useRealtime = useRealtime;\n\nexport type {\n RealtimeStatus as Experimental_RealtimeStatus,\n UseRealtimeOptions as Experimental_UseRealtimeOptions,\n UseRealtimeReturn as Experimental_UseRealtimeReturn,\n};\n","import { isJSONObject } from '@ai-sdk/provider';\nimport type {\n MCPAppBridgeHandlers,\n MCPAppHostContext,\n MCPAppJsonRpcMessage,\n MCPAppJsonRpcNotification,\n MCPAppJsonRpcRequest,\n MCPAppJsonRpcResponse,\n MCPAppToolCallParams,\n} from './types';\n\nconst MCP_APP_PROTOCOL_VERSION = '2026-01-26';\n\n/**\n * Checks whether an iframe message looks like a JSON-RPC 2.0 message.\n */\nfunction isJsonRpcMessage(value: unknown): value is MCPAppJsonRpcMessage {\n return (\n value != null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n 'jsonrpc' in value &&\n value.jsonrpc === '2.0'\n );\n}\n\n/**\n * Checks whether a JSON-RPC message expects a response.\n */\nfunction isRequest(\n message: MCPAppJsonRpcMessage,\n): message is MCPAppJsonRpcRequest {\n return 'method' in message && 'id' in message;\n}\n\n/**\n * Checks whether a JSON-RPC message is a fire-and-forget notification.\n */\nfunction isNotification(\n message: MCPAppJsonRpcMessage,\n): message is MCPAppJsonRpcNotification {\n return 'method' in message && !('id' in message);\n}\n\n/**\n * Normalizes unknown thrown values into an `Error`.\n */\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\n/**\n * Validates the params for app-initiated `tools/call` requests.\n */\nfunction assertToolCallParams(params: unknown): MCPAppToolCallParams {\n if (!isJSONObject(params) || typeof params.name !== 'string') {\n throw new Error('Invalid tools/call params');\n }\n\n return {\n name: params.name,\n arguments: isJSONObject(params.arguments) ? params.arguments : undefined,\n };\n}\n\n/**\n * Validates `resources/read` params and limits reads to `ui://` app resources.\n */\nfunction assertResourceReadParams(params: unknown): { uri: string } {\n if (!isJSONObject(params) || typeof params.uri !== 'string') {\n throw new Error('Invalid resources/read params');\n }\n if (!params.uri.startsWith('ui://')) {\n throw new Error(\n `resources/read is limited to ui:// resources: ${params.uri}`,\n );\n }\n return { uri: params.uri };\n}\n\n/**\n * Validates `ui/open-link` params and allows only `https:`/`http:`/`mailto:`\n * URLs.\n */\nfunction assertOpenLinkParams(params: unknown): { url: string } {\n if (!isJSONObject(params) || typeof params.url !== 'string') {\n throw new Error('Invalid ui/open-link params');\n }\n\n let scheme: string;\n try {\n scheme = new URL(params.url).protocol;\n } catch {\n throw new Error(`Invalid ui/open-link url: ${params.url}`);\n }\n\n if (scheme !== 'https:' && scheme !== 'http:' && scheme !== 'mailto:') {\n throw new Error(`Disallowed ui/open-link scheme: ${scheme}`);\n }\n\n return { url: params.url };\n}\n\n/**\n * Validates params for `ui/request-display-mode`.\n */\nfunction assertDisplayModeParams(params: unknown): {\n mode: 'inline' | 'fullscreen' | 'pip';\n} {\n if (\n !isJSONObject(params) ||\n (params.mode !== 'inline' &&\n params.mode !== 'fullscreen' &&\n params.mode !== 'pip')\n ) {\n throw new Error('Invalid ui/request-display-mode params');\n }\n return { mode: params.mode };\n}\n\n/**\n * Host-side JSON-RPC bridge for one MCP App iframe.\n *\n * It handles the MCP Apps initialization handshake, sends tool input/result\n * notifications to the iframe, and proxies allowed iframe requests through\n * host-provided callbacks.\n *\n * @example\n * ```ts\n * const bridge = new MCPAppBridge({\n * targetWindow: iframe.contentWindow!,\n * handlers: {\n * allowedTools: ['refreshDashboardData'],\n * callTool: params => client.callTool(params),\n * },\n * });\n *\n * window.addEventListener('message', event => bridge.handleMessage(event));\n * bridge.sendToolInput({ topic: 'usage' });\n * ```\n */\nexport class MCPAppBridge {\n private initialized = false;\n private pendingNotifications: MCPAppJsonRpcNotification[] = [];\n private nextRequestId = 0;\n private pendingResponses = new Map<\n string | number,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n }\n >();\n\n constructor({\n targetWindow,\n targetOrigin = '*',\n handlers = {},\n hostInfo = { name: 'ai-sdk-react', version: '1.0.0' },\n hostContext = { displayMode: 'inline' },\n }: {\n targetWindow: Window;\n targetOrigin?: string;\n handlers?: MCPAppBridgeHandlers;\n hostInfo?: { name: string; version: string };\n hostContext?: MCPAppHostContext;\n }) {\n this.targetWindow = targetWindow;\n this.targetOrigin = targetOrigin;\n this.handlers = handlers;\n this.hostInfo = hostInfo;\n this.hostContext = hostContext;\n }\n\n private targetWindow: Window;\n private targetOrigin: string;\n private handlers: MCPAppBridgeHandlers;\n private hostInfo: { name: string; version: string };\n private hostContext: MCPAppHostContext;\n\n /**\n * Replaces the callbacks used to serve iframe requests.\n */\n setHandlers(handlers: MCPAppBridgeHandlers): void {\n this.handlers = handlers;\n }\n\n /**\n * Updates host context and notifies the iframe after initialization.\n *\n * @example\n * ```ts\n * bridge.setHostContext({ theme: 'dark', displayMode: 'inline' });\n * ```\n */\n setHostContext(hostContext: MCPAppHostContext): void {\n this.hostContext = hostContext;\n this.sendNotification({\n method: 'ui/notifications/host-context-changed',\n params: hostContext,\n });\n }\n\n /**\n * Whether a `message` event came from the expected proxy window and origin.\n * The origin check is skipped only when `targetOrigin` is the `'*'` default.\n * Callers that intercept events before {@link handleMessage} share this check.\n */\n acceptsEvent(event: MessageEvent): boolean {\n return (\n event.source === this.targetWindow &&\n (this.targetOrigin === '*' || event.origin === this.targetOrigin)\n );\n }\n\n /**\n * Processes one `message` event from the sandbox proxy iframe.\n */\n handleMessage(event: MessageEvent): void {\n if (!this.acceptsEvent(event) || !isJsonRpcMessage(event.data)) {\n return;\n }\n\n const message = event.data;\n\n if ('result' in message || 'error' in message) {\n this.handleResponse(message);\n return;\n }\n\n if (isRequest(message)) {\n void this.handleRequest(message);\n return;\n }\n\n if (isNotification(message)) {\n this.handleNotification(message);\n }\n }\n\n /**\n * Sends app HTML and sandbox settings to the sandbox proxy.\n */\n sendSandboxResourceReady(params: unknown): void {\n this.post({\n jsonrpc: '2.0',\n method: 'ui/notifications/sandbox-resource-ready',\n params,\n });\n }\n\n /**\n * Sends final tool arguments to the MCP App.\n */\n sendToolInput(input: unknown): void {\n this.sendNotification({\n method: 'ui/notifications/tool-input',\n params: { arguments: input },\n });\n }\n\n /**\n * Sends a completed MCP tool result to the MCP App.\n */\n sendToolResult(result: unknown): void {\n this.sendNotification({\n method: 'ui/notifications/tool-result',\n params: result,\n });\n }\n\n /**\n * Notifies the MCP App that the related tool call was cancelled.\n */\n sendToolCancelled(reason?: string): void {\n this.sendNotification({\n method: 'ui/notifications/tool-cancelled',\n params: reason != null ? { reason } : {},\n });\n }\n\n /**\n * Requests graceful teardown before the host removes the iframe.\n */\n teardownResource(): Promise<unknown> {\n return this.request('ui/resource-teardown', {});\n }\n\n /**\n * Rejects pending bridge requests and clears queued notifications.\n */\n close(): void {\n for (const pending of this.pendingResponses.values()) {\n pending.reject(new Error('MCP App bridge closed'));\n }\n this.pendingResponses.clear();\n this.pendingNotifications = [];\n }\n\n /**\n * Resolves or rejects a host-initiated request when the iframe responds.\n */\n private handleResponse(response: MCPAppJsonRpcResponse): void {\n const pending = this.pendingResponses.get(response.id);\n if (pending == null) {\n return;\n }\n\n this.pendingResponses.delete(response.id);\n\n if (response.error != null) {\n pending.reject(new Error(response.error.message));\n } else {\n pending.resolve(response.result);\n }\n }\n\n /**\n * Runs a handler for an iframe request and posts the JSON-RPC response.\n */\n private async handleRequest(request: MCPAppJsonRpcRequest): Promise<void> {\n try {\n const result = await this.getRequestResult(request);\n this.post({ jsonrpc: '2.0', id: request.id, result });\n } catch (error) {\n const normalizedError = toError(error);\n this.handlers.onError?.(normalizedError);\n this.post({\n jsonrpc: '2.0',\n id: request.id,\n error: { code: -32603, message: normalizedError.message },\n });\n }\n }\n\n /**\n * Maps supported iframe request methods to host callbacks.\n */\n private async getRequestResult(\n request: MCPAppJsonRpcRequest,\n ): Promise<unknown> {\n switch (request.method) {\n case 'ui/initialize':\n return {\n protocolVersion: MCP_APP_PROTOCOL_VERSION,\n hostCapabilities: {\n ...(this.handlers.callTool != null ? { serverTools: {} } : {}),\n ...(this.handlers.readResource != null\n ? { serverResources: {} }\n : {}),\n ...(this.handlers.onLog != null ? { logging: {} } : {}),\n },\n hostInfo: this.hostInfo,\n hostContext: this.hostContext,\n };\n\n case 'tools/call': {\n if (this.handlers.callTool == null) {\n throw new Error('No tools/call handler configured');\n }\n const params = assertToolCallParams(request.params);\n // Deny-by-default: the (untrusted) MCP App may only invoke tools the\n // host has explicitly allow-listed. Omitting `allowedTools` exposes no\n // tools, rather than forwarding every requested tool to `callTool`.\n if (\n this.handlers.allowedTools == null ||\n !this.handlers.allowedTools.includes(params.name)\n ) {\n throw new Error(`Tool is not app-visible: ${params.name}`);\n }\n return this.handlers.callTool(params);\n }\n\n case 'resources/read':\n if (this.handlers.readResource == null) {\n throw new Error('No resources/read handler configured');\n }\n return this.handlers.readResource(\n assertResourceReadParams(request.params),\n );\n\n case 'resources/list':\n if (this.handlers.listResources == null) {\n throw new Error('No resources/list handler configured');\n }\n return this.handlers.listResources(request.params);\n\n case 'ui/open-link':\n if (this.handlers.openLink == null) {\n throw new Error('No ui/open-link handler configured');\n }\n return this.handlers.openLink(assertOpenLinkParams(request.params));\n\n case 'ui/message':\n return this.handlers.sendMessage?.(request.params) ?? {};\n\n case 'ui/update-model-context':\n return this.handlers.updateModelContext?.(request.params) ?? {};\n\n case 'ui/request-display-mode':\n return (\n this.handlers.requestDisplayMode?.(\n assertDisplayModeParams(request.params),\n ) ?? { mode: this.hostContext.displayMode ?? 'inline' }\n );\n\n default:\n throw new Error(`Unsupported MCP App method: ${request.method}`);\n }\n }\n\n /**\n * Handles iframe lifecycle and telemetry notifications.\n */\n private handleNotification(notification: MCPAppJsonRpcNotification): void {\n switch (notification.method) {\n case 'ui/notifications/initialized':\n this.initialized = true;\n this.flushNotifications();\n this.handlers.onInitialized?.();\n break;\n case 'ui/notifications/size-changed':\n this.handlers.onSizeChange?.(\n notification.params as { width?: number; height?: number },\n );\n break;\n case 'ui/notifications/request-teardown':\n this.handlers.onRequestTeardown?.(notification.params);\n break;\n case 'notifications/message':\n this.handlers.onLog?.(notification.params);\n break;\n }\n }\n\n /**\n * Sends a host-to-iframe notification, queueing it until app initialization.\n */\n private sendNotification(\n notification: Omit<MCPAppJsonRpcNotification, 'jsonrpc'>,\n ) {\n const message = { jsonrpc: '2.0' as const, ...notification };\n if (!this.initialized && !notification.method.includes('sandbox')) {\n this.pendingNotifications.push(message);\n return;\n }\n this.post(message);\n }\n\n /**\n * Sends notifications that were queued before `ui/notifications/initialized`.\n */\n private flushNotifications(): void {\n const notifications = this.pendingNotifications;\n this.pendingNotifications = [];\n for (const notification of notifications) {\n this.post(notification);\n }\n }\n\n /**\n * Sends a host-initiated JSON-RPC request to the iframe.\n */\n private request(method: string, params: unknown): Promise<unknown> {\n const id = this.nextRequestId++;\n this.post({ jsonrpc: '2.0', id, method, params });\n return new Promise((resolve, reject) => {\n this.pendingResponses.set(id, { resolve, reject });\n });\n }\n\n /**\n * Posts a JSON-RPC message to the sandbox proxy iframe.\n */\n private post(message: MCPAppJsonRpcMessage): void {\n this.targetWindow.postMessage(message, this.targetOrigin);\n }\n}\n","import type { MCPAppResourceCSP } from '@ai-sdk/mcp';\n\n// CSP source values come from the (untrusted) MCP server. Rather than\n// denylisting bad characters on the raw string (which an encoding like \"%3B\"\n// can slip past), canonicalize each value: parse it as an absolute URL so any\n// percent-encoding is decoded, keep only https/wss origins, then re-check the\n// decoded origin so a separator that decoded back into \";\" \",\" or whitespace\n// cannot split the directive.\nconst ALLOWED_CSP_SCHEMES = new Set(['https:', 'wss:']);\n\nfunction sanitizeCSPSources(sources?: string[]): string[] {\n const result: string[] = [];\n for (const source of sources ?? []) {\n if (typeof source !== 'string') {\n continue;\n }\n\n let origin: string;\n try {\n const url = new URL(source);\n // Reject non-https/wss, the empty host, and a bare \"*\" host (which would\n // match every origin and defeat the allowlist, like scheme-only \"https:\").\n if (\n !ALLOWED_CSP_SCHEMES.has(url.protocol) ||\n url.host.length === 0 ||\n url.host === '*'\n ) {\n continue;\n }\n origin = url.origin;\n } catch {\n continue;\n }\n\n // Drop separators that split the directive and quotes that could break out\n // of an HTML attribute the policy may be embedded in downstream.\n if (/[\"'`\\s;,]/.test(origin)) {\n continue;\n }\n\n result.push(origin);\n }\n return result;\n}\n\n/**\n * Default sandbox permissions for the outer sandbox proxy iframe.\n */\nexport const MCP_APP_DEFAULT_OUTER_SANDBOX =\n 'allow-scripts allow-same-origin allow-forms';\n\n/**\n * Default sandbox permissions for the inner iframe that runs app HTML.\n */\nexport const MCP_APP_DEFAULT_INNER_SANDBOX = 'allow-scripts allow-forms';\n\n/**\n * Converts MCP App CSP metadata into a Content-Security-Policy string.\n *\n * The returned value is meant to be passed to a sandbox proxy, which can apply\n * it to the inner iframe document.\n *\n * @example\n * ```ts\n * const csp = getMCPAppCSP({\n * connectDomains: ['https://api.example.com'],\n * resourceDomains: ['https://cdn.example.com'],\n * });\n * ```\n */\nexport function getMCPAppCSP(csp?: MCPAppResourceCSP): string | undefined {\n if (csp == null) {\n return undefined;\n }\n\n const connectSrc = [\"'self'\", ...sanitizeCSPSources(csp.connectDomains)];\n const imgSrc = [\n \"'self'\",\n 'data:',\n ...sanitizeCSPSources(csp.resourceDomains),\n ];\n const frameSrc = [\"'self'\", ...sanitizeCSPSources(csp.frameDomains)];\n\n return [\n \"default-src 'none'\",\n \"base-uri 'none'\",\n \"form-action 'none'\",\n \"script-src 'unsafe-inline'\",\n \"style-src 'unsafe-inline'\",\n `connect-src ${connectSrc.join(' ')}`,\n `img-src ${imgSrc.join(' ')}`,\n `font-src ${imgSrc.join(' ')}`,\n `frame-src ${frameSrc.join(' ')}`,\n ].join('; ');\n}\n\n/**\n * A permission an MCP App may request and a host may allow.\n */\nexport type MCPAppPermission =\n | 'camera'\n | 'microphone'\n | 'geolocation'\n | 'clipboardWrite';\n\nconst MCP_APP_PERMISSION_FEATURES: Record<MCPAppPermission, string> = {\n camera: 'camera',\n microphone: 'microphone',\n geolocation: 'geolocation',\n clipboardWrite: 'clipboard-write',\n};\n\n/**\n * Converts MCP App permission metadata into an iframe `allow` attribute.\n *\n * Deny-by-default: a capability is granted only when it is both requested in\n * `permissions` and present in the host `allowedPermissions` allowlist.\n * Omitting the allowlist grants nothing, mirroring `allowedTools` in the bridge.\n *\n * @example\n * ```ts\n * const allow = getMCPAppAllowAttribute(\n * { microphone: {}, camera: {} },\n * ['microphone'],\n * );\n * // \"microphone\" — camera requested by server but not host-allowed\n * ```\n */\nexport function getMCPAppAllowAttribute(\n permissions?: Record<string, unknown>,\n allowedPermissions?: MCPAppPermission[],\n): string | undefined {\n if (permissions == null || allowedPermissions == null) {\n return undefined;\n }\n\n const allow = allowedPermissions\n .filter(permission => Boolean(permissions[permission]))\n .map(permission => MCP_APP_PERMISSION_FEATURES[permission]);\n\n return allow.length > 0 ? allow.join('; ') : undefined;\n}\n","import { isJSONObject } from '@ai-sdk/provider';\nimport type { MCPAppMetadata, MCPAppRendererProps } from './types';\n\n/**\n * Extracts MCP App metadata from an AI SDK tool UI part.\n *\n * @example\n * ```ts\n * const app = getMCPAppFromToolPart({\n * type: 'dynamic-tool',\n * toolName: 'showDashboard',\n * toolCallId: 'call-1',\n * state: 'input-available',\n * input: { topic: 'usage' },\n * toolMetadata: {\n * app: {\n * resourceUri: 'ui://example/dashboard',\n * mimeType: 'text/html;profile=mcp-app',\n * },\n * },\n * });\n * // { resourceUri: 'ui://example/dashboard', mimeType: 'text/html;profile=mcp-app' }\n * ```\n */\nexport function getMCPAppFromToolPart(\n part: MCPAppRendererProps['part'],\n): MCPAppMetadata | undefined {\n const rawAppMetadata = part.toolMetadata?.app;\n const appMetadata = isJSONObject(rawAppMetadata) ? rawAppMetadata : undefined;\n\n if (\n appMetadata == null ||\n appMetadata.mimeType !== 'text/html;profile=mcp-app' ||\n typeof appMetadata.resourceUri !== 'string' ||\n !appMetadata.resourceUri.startsWith('ui://') ||\n (appMetadata.visibility != null &&\n (!Array.isArray(appMetadata.visibility) ||\n appMetadata.visibility.some(\n value => value !== 'model' && value !== 'app',\n )))\n ) {\n return undefined;\n }\n\n return appMetadata as MCPAppMetadata;\n}\n\n/**\n * Converts an AI SDK tool output into the MCP Apps tool-result shape.\n *\n * MCP Apps expect tool results to have `content` and optional\n * `structuredContent`. MCP tools already return that shape, but typed AI SDK\n * tools may return only structured data. This helper wraps structured-only\n * outputs so the iframe can receive a valid tool result notification.\n *\n * @example\n * ```ts\n * normalizeMCPAppToolResult({ cards: [] });\n * // { content: [], structuredContent: { cards: [] } }\n * ```\n */\nexport function normalizeMCPAppToolResult(output: unknown): {\n content: unknown[];\n structuredContent?: unknown;\n isError?: boolean;\n} {\n if (output != null && typeof output === 'object' && 'content' in output) {\n return output as {\n content: unknown[];\n structuredContent?: unknown;\n isError?: boolean;\n };\n }\n\n return {\n content: [],\n structuredContent: output,\n };\n}\n","import { useEffect, useMemo, useRef } from 'react';\nimport { MCPAppBridge } from './bridge';\nimport {\n MCP_APP_DEFAULT_INNER_SANDBOX,\n MCP_APP_DEFAULT_OUTER_SANDBOX,\n getMCPAppAllowAttribute,\n getMCPAppCSP,\n} from './sandbox';\nimport type { MCPAppFrameProps } from './types';\nimport { normalizeMCPAppToolResult } from './utils';\n\n/**\n * Derives the concrete origin of the sandbox proxy from its URL, so outbound\n * postMessage targets a specific origin instead of `'*'` and inbound messages\n * can be origin-checked. The proxy must be served from a stable, concrete\n * origin (the default outer sandbox keeps `allow-same-origin`). Falls back to\n * the host origin on a malformed URL, never `'*'`.\n */\nfunction deriveTargetOrigin(url: string): string {\n const location = typeof window !== 'undefined' ? window.location : undefined;\n try {\n return new URL(url, location?.href).origin;\n } catch {\n return location?.origin ?? 'null';\n }\n}\n\nfunction sendToolState({\n bridge,\n input,\n output,\n}: {\n bridge?: MCPAppBridge;\n input: unknown;\n output: unknown;\n}) {\n if (bridge == null) {\n return;\n }\n\n if (input !== undefined) {\n bridge.sendToolInput(input);\n }\n\n if (output !== undefined) {\n bridge.sendToolResult(normalizeMCPAppToolResult(output));\n }\n}\n\nexport function MCPAppFrame({\n app,\n resource,\n input,\n output,\n sandbox,\n handlers,\n hostInfo,\n hostContext,\n}: MCPAppFrameProps) {\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const bridgeRef = useRef<MCPAppBridge | undefined>(undefined);\n const inputRef = useRef(input);\n const outputRef = useRef(output);\n const hostContextRef = useRef(hostContext);\n const initializedRef = useRef(false);\n inputRef.current = input;\n outputRef.current = output;\n hostContextRef.current = hostContext;\n const sandboxUrl = String(sandbox.url);\n const targetOrigin = sandbox.targetOrigin ?? deriveTargetOrigin(sandboxUrl);\n const resourceCSP = getMCPAppCSP(resource.meta?.csp);\n const resourceAllow = getMCPAppAllowAttribute(\n resource.meta?.permissions,\n sandbox.allowedPermissions,\n );\n const innerSandbox = sandbox.innerSandbox ?? MCP_APP_DEFAULT_INNER_SANDBOX;\n const bridgeHandlers = useMemo(\n () => ({\n ...handlers,\n onInitialized: () => {\n initializedRef.current = true;\n handlers?.onInitialized?.();\n sendToolState({\n bridge: bridgeRef.current,\n input: inputRef.current,\n output: outputRef.current,\n });\n },\n }),\n [handlers],\n );\n const bridgeHandlersRef = useRef(bridgeHandlers);\n bridgeHandlersRef.current = bridgeHandlers;\n\n useEffect(() => {\n const iframe = iframeRef.current;\n const targetWindow = iframe?.contentWindow;\n if (targetWindow == null) {\n return;\n }\n\n initializedRef.current = false;\n\n const bridge = new MCPAppBridge({\n targetWindow,\n targetOrigin,\n handlers: bridgeHandlersRef.current,\n hostInfo,\n hostContext: hostContextRef.current,\n });\n bridgeRef.current = bridge;\n\n const onMessage = (event: MessageEvent) => {\n // Only handle messages from the proxy window and expected origin.\n if (!bridge.acceptsEvent(event)) {\n return;\n }\n\n if (\n event.data?.jsonrpc === '2.0' &&\n event.data.method === 'ui/notifications/sandbox-proxy-ready'\n ) {\n bridge.sendSandboxResourceReady({\n html: resource.html,\n csp: resourceCSP,\n sandbox: innerSandbox,\n allow: resourceAllow,\n });\n return;\n }\n\n bridge.handleMessage(event);\n };\n\n window.addEventListener('message', onMessage);\n\n return () => {\n initializedRef.current = false;\n window.removeEventListener('message', onMessage);\n void bridge.teardownResource().catch(() => {});\n bridge.close();\n bridgeRef.current = undefined;\n };\n }, [\n hostInfo,\n innerSandbox,\n resource.html,\n resourceAllow,\n resourceCSP,\n sandboxUrl,\n targetOrigin,\n ]);\n\n useEffect(() => {\n bridgeRef.current?.setHandlers(bridgeHandlers);\n }, [bridgeHandlers]);\n\n useEffect(() => {\n if (hostContext != null) {\n bridgeRef.current?.setHostContext(hostContext);\n }\n }, [hostContext]);\n\n useEffect(() => {\n if (initializedRef.current && input !== undefined) {\n bridgeRef.current?.sendToolInput(input);\n }\n }, [input]);\n\n useEffect(() => {\n if (initializedRef.current && output !== undefined) {\n bridgeRef.current?.sendToolResult(normalizeMCPAppToolResult(output));\n }\n }, [output]);\n\n return (\n <iframe\n ref={iframeRef}\n title=\"MCP App\"\n aria-label={sandbox.title ?? app.resourceUri}\n src={sandboxUrl}\n className={sandbox.className}\n style={sandbox.style}\n // Permissions Policy is hierarchical: the outer frame must delegate a\n // feature for the proxy to re-delegate it to the inner app frame.\n allow={resourceAllow}\n sandbox={sandbox.outerSandbox ?? MCP_APP_DEFAULT_OUTER_SANDBOX}\n />\n );\n}\n","import type { MCPAppResource } from '@ai-sdk/mcp';\nimport { useEffect, useState } from 'react';\nimport { MCPAppFrame } from './app-frame';\nimport type { MCPAppMetadata, MCPAppRendererProps } from './types';\nimport { getMCPAppFromToolPart } from './utils';\n\ntype LoadedResourceState = {\n resourceUri: string;\n resource?: MCPAppResource;\n error?: Error;\n};\n\nfunction getToolPartOutput(part: MCPAppRendererProps['part']): unknown {\n return part.state === 'output-available' ? part.output : undefined;\n}\n\nfunction getToolPartInput(part: MCPAppRendererProps['part']): unknown {\n return part.state === 'input-available' || part.state === 'output-available'\n ? part.input\n : undefined;\n}\n\nexport function MCPAppRenderer({\n part,\n sandbox,\n resource: resourceProp,\n loadResource,\n handlers,\n hostInfo,\n hostContext,\n fallback = null,\n}: MCPAppRendererProps) {\n const app = getMCPAppFromToolPart(part);\n const [cachedApp, setCachedApp] = useState<MCPAppMetadata>();\n const [loadedResource, setLoadedResource] = useState<LoadedResourceState>();\n\n useEffect(() => {\n if (app != null) {\n setCachedApp(previous =>\n previous?.resourceUri === app.resourceUri ? previous : app,\n );\n }\n }, [app?.resourceUri]);\n\n const appForRender = app ?? cachedApp;\n\n useEffect(() => {\n if (appForRender == null || resourceProp != null || loadResource == null) {\n return;\n }\n\n let cancelled = false;\n const resourceUri = appForRender.resourceUri;\n\n loadResource(appForRender)\n .then(resource => {\n if (!cancelled) {\n setLoadedResource({ resourceUri, resource });\n }\n })\n .catch(error => {\n if (!cancelled) {\n setLoadedResource({\n resourceUri,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n cancelled = true;\n };\n }, [appForRender?.resourceUri, loadResource, resourceProp]);\n\n const loadedResourceForApp =\n loadedResource?.resourceUri === appForRender?.resourceUri\n ? loadedResource\n : undefined;\n const resource = resourceProp ?? loadedResourceForApp?.resource;\n const error = resourceProp == null ? loadedResourceForApp?.error : undefined;\n\n if (appForRender == null || error != null || resource == null) {\n return fallback;\n }\n\n return (\n <MCPAppFrame\n app={appForRender}\n resource={resource}\n input={getToolPartInput(part)}\n output={getToolPartOutput(part)}\n sandbox={sandbox}\n handlers={handlers}\n hostInfo={hostInfo}\n hostContext={hostContext}\n />\n );\n}\n","import { MCPAppRenderer } from './app-renderer';\n\nexport { MCPAppRenderer } from './app-renderer';\n\n/**\n * @deprecated Use `MCPAppRenderer` instead.\n */\nexport const experimental_MCPAppRenderer = MCPAppRenderer;\n\nexport type { MCPAppPermission } from './sandbox';\nexport type {\n MCPAppBridgeHandlers,\n MCPAppMetadata,\n MCPAppRendererProps,\n MCPAppResource,\n MCPAppSandboxConfig,\n} from './types';\n","import type { FlexibleSchema } from '@ai-sdk/provider-utils';\nimport {\n useObject,\n type UseObjectHelpers,\n type UseObjectOptions,\n} from './use-object';\n\nexport * from './use-chat';\nexport { Chat } from './chat.react';\nexport * from './use-completion';\nexport * from './use-object';\nexport * from './use-realtime';\nexport * from './mcp-apps';\n\n// deprecated aliases\n// note: declared here (instead of export aliases) so that the `@deprecated`\n// tags are preserved in the bundled type declarations\n\n/**\n * @deprecated Use `useObject` instead.\n */\nexport const experimental_useObject = useObject;\n\n/**\n * @deprecated Use `UseObjectOptions` instead.\n */\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = UseObjectOptions<SCHEMA, RESULT>;\n\n/**\n * @deprecated Use `UseObjectHelpers` instead.\n */\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = UseObjectHelpers<\n RESULT,\n INPUT\n>;\n"],"mappings":";;;;;;;;AAoBA,MAAM,yBAAyB;AAuG/B,SAAgB,UAId,EACA,KACA,IACA,QACA,cACA,OACA,SACA,UACA,SACA,eACoE;CAEpE,MAAM,SAAS,MAAM;CAIrB,MAAM,EAAE,MAAM,WAAW,OACvB,CAJmB,MAAM,QAIV,QAAQ,GACvB,MACA,EAAE,cAAc,EAAE,QAAQ,aAAa,EAAE,CAC3C;CAEA,MAAM,CAAC,OAAO,YAAY,SAA4B,KAAA,CAAS;CAC/D,MAAM,CAAC,WAAW,gBAAgB,SAAS,KAAK;CAGhD,MAAM,qBAAqB,OAA+B,IAAI;CAE9D,MAAM,OAAO,kBAAkB;EAC7B,IAAI;GACF,mBAAmB,SAAS,MAAM;EACpC,QAAQ,CACR,UAAU;GACR,aAAa,KAAK;GAClB,mBAAmB,UAAU;EAC/B;CACF,GAAG,CAAC,CAAC;CAEL,MAAM,SAAS,OAAO,UAAiB;EACrC,MAAM,kBAAkB,IAAI,gBAAgB;EAE5C,IAAI;GACF,YAAY;GAEZ,aAAa,IAAI;GAEjB,mBAAmB,UAAU;GAG7B,MAAM,kBAAkB,MAAM,QAAQ,OAAO;GAG7C,MAAM,WAAW,OADG,SAAS,iBAAiB,EAAA,CACX,KAAK;IACtC,QAAQ;IACR,SAAS;KACP,gBAAgB;KAChB,GAAG,iBAAiB,eAAe;IACrC;IACA;IACA,QAAQ,g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,WAAW,GACzD;CAEJ,GAAG,CAAC,KAAK,WAAW,CAAC;CAErB,MAAM,eAAe,OAAO;CAE5B,gBAAgB;EACd,IAAI,gBAAgB,QAAQ,gBAAgB,QAAQ,gBAAgB,MAClE;EAGF,IAAI,YAAY;EAChB,MAAM,cAAc,aAAa;EAEjC,aAAa,YAAY,CAAC,CACvB,MAAK,aAAY;GAChB,IAAI,CAAC,WACH,kBAAkB;IAAE;IAAa;GAAS,CAAC;EAE/C,CAAC,CAAC,CACD,OAAM,UAAS;GACd,IAAI,CAAC,WACH,kBAAkB;IAChB;IACA,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;GACjE,CAAC;EAEL,CAAC;EAEH,aAAa;GACX,YAAY;EACd;CACF,GAAG;EAAC,cAAc;EAAa;EAAc;CAAY,CAAC;CAE1D,MAAM,uBACJ,gBAAgB,gBAAgB,cAAc,cAC1C,iBACA,KAAA;CACN,MAAM,WAAW,gBAAgB,sBAAsB;CACvD,MAAM,QAAQ,gBAAgB,OAAO,sBAAsB,QAAQ,KAAA;CAEnE,IAAI,gBAAgB,QAAQ,SAAS,QAAQ,YAAY,MACvD,OAAO;CAGT,OACE,oBAAC,aAAD;EACE,KAAK;EACK;EACV,OAAO,iBAAiB,IAAI;EAC5B,QAAQ,kBAAkB,IAAI;EACrB;EACC;EACA;EACG;CACd,CAAA;AAEL;;;;;;AC1FA,MAAa,8BAA8B;;;;;;ACc3C,MAAa,yBAAyB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/react",
3
- "version": "4.0.169",
3
+ "version": "4.0.172",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -26,10 +26,10 @@
26
26
  "README.md"
27
27
  ],
28
28
  "dependencies": {
29
- "@ai-sdk/mcp": "2.0.93",
29
+ "@ai-sdk/mcp": "2.0.95",
30
30
  "@ai-sdk/provider": "4.0.37",
31
- "@ai-sdk/provider-utils": "5.0.76",
32
- "ai": "7.0.165",
31
+ "@ai-sdk/provider-utils": "5.0.78",
32
+ "ai": "7.0.168",
33
33
  "swr": "^2.4.1",
34
34
  "throttleit": "2.1.0"
35
35
  },
package/src/chat.react.ts CHANGED
@@ -30,8 +30,10 @@ class ReactChatState<
30
30
  #messages: UI_MESSAGE[];
31
31
  #status: ChatStatus = 'ready';
32
32
  #error: Error | undefined = undefined;
33
+ #queuedMessages: UI_MESSAGE[] = [];
33
34
 
34
35
  #messagesCallbacks = new Set<() => void>();
36
+ #queuedMessagesCallbacks = new Set<() => void>();
35
37
  #statusCallbacks = new Set<() => void>();
36
38
  #errorCallbacks = new Set<() => void>();
37
39
 
@@ -57,6 +59,15 @@ class ReactChatState<
57
59
  this.#callErrorCallbacks();
58
60
  }
59
61
 
62
+ get experimental_queuedMessages(): UI_MESSAGE[] {
63
+ return this.#queuedMessages;
64
+ }
65
+
66
+ set experimental_queuedMessages(newQueuedMessages: UI_MESSAGE[]) {
67
+ this.#queuedMessages = newQueuedMessages;
68
+ this.#queuedMessagesCallbacks.forEach(callback => callback());
69
+ }
70
+
60
71
  get messages(): UI_MESSAGE[] {
61
72
  return this.#messages;
62
73
  }
@@ -135,6 +146,13 @@ class ReactChatState<
135
146
  };
136
147
  };
137
148
 
149
+ '~registerQueuedMessagesCallback' = (onChange: () => void): (() => void) => {
150
+ this.#queuedMessagesCallbacks.add(onChange);
151
+ return () => {
152
+ this.#queuedMessagesCallbacks.delete(onChange);
153
+ };
154
+ };
155
+
138
156
  #callMessagesCallbacks = () => {
139
157
  this.#messagesCallbacks.forEach(callback => callback());
140
158
  };
@@ -170,4 +188,7 @@ export class Chat<
170
188
 
171
189
  '~registerErrorCallback' = (onChange: () => void): (() => void) =>
172
190
  this.#state['~registerErrorCallback'](onChange);
191
+
192
+ '~registerQueuedMessagesCallback' = (onChange: () => void): (() => void) =>
193
+ this.#state['~registerQueuedMessagesCallback'](onChange);
173
194
  }
package/src/use-chat.ts CHANGED
@@ -39,6 +39,9 @@ export type UseChatHelpers<UI_MESSAGE extends UIMessage> = {
39
39
  | 'status'
40
40
  | 'messages'
41
41
  | 'clearError'
42
+ | 'experimental_queuedMessages'
43
+ | 'experimental_removeQueuedMessage'
44
+ | 'experimental_sendQueuedMessageNow'
42
45
  >;
43
46
 
44
47
  export type UseChatOptions<UI_MESSAGE extends UIMessage> = (
@@ -161,6 +164,7 @@ type ChatSnapshot<UI_MESSAGE extends UIMessage> = {
161
164
  messages: UI_MESSAGE[];
162
165
  status: Chat<UI_MESSAGE>['status'];
163
166
  error: Error | undefined;
167
+ experimental_queuedMessages: UI_MESSAGE[];
164
168
  };
165
169
 
166
170
  function readChatSnapshot<UI_MESSAGE extends UIMessage>(
@@ -171,6 +175,7 @@ function readChatSnapshot<UI_MESSAGE extends UIMessage>(
171
175
  messages: chat.messages,
172
176
  status: chat.status,
173
177
  error: chat.error,
178
+ experimental_queuedMessages: chat.experimental_queuedMessages,
174
179
  };
175
180
  }
176
181
 
@@ -182,7 +187,8 @@ function equalChatSnapshots<UI_MESSAGE extends UIMessage>(
182
187
  current.chat === next.chat &&
183
188
  current.messages === next.messages &&
184
189
  current.status === next.status &&
185
- current.error === next.error
190
+ current.error === next.error &&
191
+ current.experimental_queuedMessages === next.experimental_queuedMessages
186
192
  );
187
193
  }
188
194
 
@@ -308,6 +314,7 @@ export function useChat<UI_MESSAGE extends UIMessage = UIMessage>({
308
314
  chat['~registerMessagesCallback'](publishSnapshot, throttleWaitMs),
309
315
  chat['~registerStatusCallback'](publishSnapshot),
310
316
  chat['~registerErrorCallback'](publishSnapshot),
317
+ chat['~registerQueuedMessagesCallback'](publishSnapshot),
311
318
  ];
312
319
 
313
320
  // Catch changes between render and subscription, including updates that
@@ -323,7 +330,7 @@ export function useChat<UI_MESSAGE extends UIMessage = UIMessage>({
323
330
  };
324
331
  }, [chat, throttleWaitMs]);
325
332
 
326
- const { messages, status, error } = snapshot;
333
+ const { messages, status, error, experimental_queuedMessages } = snapshot;
327
334
 
328
335
  const setMessages = useCallback(
329
336
  (
@@ -365,5 +372,8 @@ export function useChat<UI_MESSAGE extends UIMessage = UIMessage>({
365
372
  addToolResult: chat.addToolOutput,
366
373
  addToolOutput: chat.addToolOutput,
367
374
  addToolApprovalResponse: chat.addToolApprovalResponse,
375
+ experimental_queuedMessages,
376
+ experimental_removeQueuedMessage: chat.experimental_removeQueuedMessage,
377
+ experimental_sendQueuedMessageNow: chat.experimental_sendQueuedMessageNow,
368
378
  };
369
379
  }