@assistant-ui/ai-sdk 0.0.9 → 0.0.11

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.
Files changed (35) hide show
  1. package/dist/converters/convertMessage.d.ts.map +1 -1
  2. package/dist/converters/convertMessage.js +59 -6
  3. package/dist/converters/convertMessage.js.map +1 -1
  4. package/dist/converters/toCreateMessage.d.ts.map +1 -1
  5. package/dist/converters/toCreateMessage.js +2 -1
  6. package/dist/converters/toCreateMessage.js.map +1 -1
  7. package/dist/converters/toolApprovalAnswers.d.ts +3 -0
  8. package/dist/converters/toolApprovalAnswers.d.ts.map +1 -0
  9. package/dist/converters/toolApprovalAnswers.js +17 -0
  10. package/dist/converters/toolApprovalAnswers.js.map +1 -0
  11. package/dist/runtime/AISDKChat.js.map +1 -1
  12. package/dist/runtime/AISDKThreads.js.map +1 -1
  13. package/dist/runtime/sdkIdentity.js +1 -1
  14. package/dist/runtime/useAISDKRuntime.js.map +1 -1
  15. package/dist/runtime/useChatRuntime.js.map +1 -1
  16. package/dist/runtime/useExternalHistory.d.ts.map +1 -1
  17. package/dist/runtime/useExternalHistory.js +4 -0
  18. package/dist/runtime/useExternalHistory.js.map +1 -1
  19. package/dist/runtime/useResourceCleanup.js.map +1 -1
  20. package/dist/runtime/useStreamingTiming.js.map +1 -1
  21. package/dist/tools/generativeTools.d.ts.map +1 -1
  22. package/dist/tools/generativeTools.js +12 -1
  23. package/dist/tools/generativeTools.js.map +1 -1
  24. package/dist/transport/resumable.js.map +1 -1
  25. package/dist/usage.js.map +1 -1
  26. package/package.json +12 -11
  27. package/src/converters/convertMessage.test.ts +266 -0
  28. package/src/converters/convertMessage.ts +97 -4
  29. package/src/converters/toCreateMessage.test.ts +13 -0
  30. package/src/converters/toCreateMessage.ts +1 -0
  31. package/src/converters/toolApprovalAnswers.ts +27 -0
  32. package/src/runtime/useExternalHistory.test.ts +94 -0
  33. package/src/runtime/useExternalHistory.ts +4 -0
  34. package/src/tools/generativeTools.test.ts +189 -1
  35. package/src/tools/generativeTools.ts +23 -2
@@ -1 +1 @@
1
- {"version":3,"file":"useAISDKRuntime.js","names":["c","_c","useCallback","useEffect","useInsertionEffect","useMemo","useRef","useState","UIMessage","useChat","CreateUIMessage","UseChatHelpers","isToolUIPart","generateId","getToolName","useExternalStoreRuntime","useRuntimeAdapters","JoinStrategy","useReplaySafeEffect","SuggestionAdapter","ThreadSuggestion","ToolExecutionStatus","ExternalStoreAdapter","ExternalStoreSharedOptions","ThreadHistoryAdapter","AssistantRuntime","ThreadMessage","MessageFormatAdapter","MessageFormatItem","MessageFormatRepository","AppendMessage","RunConfig","McpAppMetadata","RespondToToolApprovalOptions","Unstable_ToolInteractionLog","getExternalStoreMessages","pickExternalStoreSharedOptions","appendToolInteraction","consumeSuggestionResult","MessageRepository","ReadonlyJSONObject","AssistantError","sliceMessagesUntil","toCreateMessage","vercelAttachmentAdapter","getVercelAIMessages","AISDKMessageConverter","AISDKMessageConverterMetadata","wrapModelContentEnvelope","AISDKStorageFormat","aiSDKV6FormatAdapter","useExternalHistory","toExportedMessageRepository","useStreamingTiming","aiSDKExtras","CustomToCreateMessageFunction","message","UI_MESSAGE","toUIMessage","createMessage","fallbackRole","id","role","toVoiceTranscriptUIMessage","parts","content","filter","part","type","map","text","metadata","modality","Object","keys","custom","length","AISDKRuntimeAdapter","adapters","NonNullable","history","suggestion","unstable_messageRepositoryInstance","unstable_hostApprovalOwner","cancelPendingToolCallsOnSend","onResume","onResumeToolCall","onRespondToToolApproval","response","context","toolCallId","toolName","respondViaAISDK","Promise","joinStrategy","messageRepository","unstable_onBranchChange","EMPTY_SUGGESTIONS","useGeneratedSuggestions","suggestionAdapter","messages","isRunning","$","suggestions","setSuggestions","controllerRef","wasRunningRef","messagesRef","t0","t1","current","adapterRef","t2","t3","hasAdapter","t4","clearSuggestions","abort","_temp","adapter","currentMessages","last","at","status","controller","AbortController","signal","promiseOrGenerator","generate","onUpdate","t5","t6","t7","Symbol","for","NO_CANCELLED_MESSAGE_IDS","ReadonlySet","Set","NO_SUPERSEDED_APPROVAL_PROJECTION","freeze","approvalIds","statusMessageIds","NO_TOOL_APPROVAL_RESPONSES","ReadonlyMap","Map","OwnedApproval","hostToolApprovalsByChat","WeakMap","toApprovalResponses","owned","size","entry","hostApprovalListenersByChat","subscribeToHostApprovals","owner","listener","listeners","get","set","add","delete","notifyHostApprovals","getSupersededApprovalProjection","hostApprovalIds","lastIndex","lastAssistant","hasSupersededApproval","previousWasVoice","flush","hasOpenToolPart","some","state","approval","resolution","descriptor","undefined","index","isVoice","approvalId","has","findRawToolMessageIndex","messageId","containsToolCall","messageIndex","findIndex","start","end","toChatError","error","Error","code","name","useAISDKRuntime","chatHelpers","ReturnType","customToCreateMessage","customOnRespondToToolApproval","contextAdapters","toolStatuses","setToolStatuses","Record","cancelledMessages","setCancelledMessages","chatId","ids","approvalOwner","ownedApprovals","created","toolApprovalResponses","setToolApprovalResponses","toolArtifactEpoch","setToolArtifactEpoch","toolInteractionEpoch","setToolInteractionEpoch","toolApprovalResponsesRef","ownedApprovalIdsRef","hostApprovalIdsRef","sync","prev","next","unchanged","every","unsubscribe","lastApprovalOwnerRef","toolArgsKeyOrderCacheRef","toolLastInputCacheRef","toolArgsTextCacheRef","mcpAppMetadataCacheRef","toolArtifactsRef","toolInteractionsRef","lastRunConfigRef","markToolArtifactsChanged","epoch","markToolInteractionsChanged","hasExecutingTools","values","s","providerIsRunning","wasProviderRunningRef","messageTiming","lastMessage","optimisticMessageId","cancelledMessageIds","supportsRichToolApprovalResponses","supersededApprovalProjectionRef","supersededApprovalProjection","projection","previous","toThreadMessages","sourceMessages","toolArtifacts","toolInteractions","retractCancellation","resumedMessageId","wasProviderRunning","useThreadMessages","toolArgsKeyOrderCache","toolArgsTextCache","toolLastInputCache","mcpAppMetadataCache","cancelledToolApprovalIds","cancelledStatusMessageIds","exportedMessageRepository","converted","generatedSuggestions","runtimeRef","runtime","isLoading","deleteMessage","deleteHistoryMessage","persistToolInteractions","persistToolApprovalResponses","setMessages","chatMessages","chatStatus","extras","provide","chat","completePendingToolCalls","hasChanges","messageChanged","_approval","rest","const","errorText","approved","reason","resolve","addToolApprovalResponse","options","respondViaHost","onRespond","requested","flatMap","find","startedWith","startedOwner","startedResponses","isApplied","applyResponse","applied","remainsApplied","hasSeededRepositoryRef","shouldFeedRepository","unstable_persistsHistory","unstable_enableToolInvocations","Boolean","flat","onImport","onVoiceTranscript","onExportExternalState","exported","thread","export","expandedMessages","lastInnerIdMap","item","innerMessages","parentId","innerMessage","push","getId","result","headId","onLoadExternalState","repo","exportedRepo","import","onCancel","cancelledId","liveIds","m","kept","stop","onNew","startRun","runConfig","sendMessage","onEdit","onDelete","threadMessages","getState","removedToolArtifact","removedToolInteractions","removedToolApprovalResponse","removedHostApprovalId","deleteIds","onReload","config","newMessages","regenerate","onAddToolResult","isError","artifact","modelContent","targetIndex","JSON","stringify","output","target","targetPart","preliminary","targetMessageId","_preliminary","finalPart","addToolOutput","tool","reject","unstable_onRecordToolInteraction","interaction","attachments","setMessagesRef","tempRepo","getMessages"],"sources":["../../src/runtime/useAISDKRuntime.ts"],"sourcesContent":["\"use client\";\n\nimport {\n useCallback,\n useEffect,\n useInsertionEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type {\n UIMessage,\n useChat,\n CreateUIMessage,\n UseChatHelpers,\n} from \"@ai-sdk/react\";\nimport { isToolUIPart, generateId, getToolName } from \"ai\";\nimport {\n useExternalStoreRuntime,\n useRuntimeAdapters,\n type JoinStrategy,\n} from \"@assistant-ui/core/react\";\nimport { useReplaySafeEffect } from \"@assistant-ui/store/internal\";\nimport type {\n SuggestionAdapter,\n ThreadSuggestion,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type {\n ExternalStoreAdapter,\n ExternalStoreSharedOptions,\n ThreadHistoryAdapter,\n AssistantRuntime,\n ThreadMessage,\n MessageFormatAdapter,\n MessageFormatItem,\n MessageFormatRepository,\n AppendMessage,\n RunConfig,\n McpAppMetadata,\n RespondToToolApprovalOptions,\n Unstable_ToolInteractionLog,\n} from \"@assistant-ui/core\";\nimport {\n getExternalStoreMessages,\n pickExternalStoreSharedOptions,\n} from \"@assistant-ui/core\";\nimport {\n appendToolInteraction,\n consumeSuggestionResult,\n MessageRepository,\n} from \"@assistant-ui/core/internal\";\nimport type { ReadonlyJSONObject } from \"assistant-stream/utils\";\nimport type { AssistantError } from \"@assistant-ui/core\";\nimport { sliceMessagesUntil } from \"../utils/sliceMessagesUntil\";\nimport { toCreateMessage } from \"../converters/toCreateMessage\";\nimport { vercelAttachmentAdapter } from \"../adapters/vercelAttachmentAdapter\";\nimport { getVercelAIMessages } from \"../utils/getVercelAIMessages\";\nimport {\n AISDKMessageConverter,\n type AISDKMessageConverterMetadata,\n} from \"../converters/convertMessage\";\nimport { wrapModelContentEnvelope } from \"../converters/modelContentEnvelope\";\nimport {\n type AISDKStorageFormat,\n aiSDKV6FormatAdapter,\n} from \"../adapters/aiSDKFormatAdapter\";\nimport {\n useExternalHistory,\n toExportedMessageRepository,\n} from \"./useExternalHistory\";\nimport { useStreamingTiming } from \"./useStreamingTiming\";\nimport { aiSDKExtras } from \"../aiSDKExtras\";\n\nexport type CustomToCreateMessageFunction = <\n UI_MESSAGE extends UIMessage = UIMessage,\n>(\n message: AppendMessage,\n) => CreateUIMessage<UI_MESSAGE>;\n\nconst toUIMessage = <UI_MESSAGE extends UIMessage>(\n createMessage: CreateUIMessage<UI_MESSAGE>,\n fallbackRole: UI_MESSAGE[\"role\"],\n): UI_MESSAGE =>\n ({\n ...createMessage,\n id: createMessage.id ?? generateId(),\n role: createMessage.role ?? fallbackRole,\n }) as UI_MESSAGE;\n\nconst toVoiceTranscriptUIMessage = <UI_MESSAGE extends UIMessage>(\n message: ThreadMessage,\n): UI_MESSAGE =>\n ({\n id: message.id,\n role: message.role,\n parts: message.content\n .filter((part) => part.type === \"text\")\n .map((part) => ({ type: \"text\", text: part.text })),\n metadata: {\n ...(message.metadata.modality && { modality: message.metadata.modality }),\n ...(Object.keys(message.metadata.custom).length > 0 && {\n custom: message.metadata.custom,\n }),\n },\n }) as UI_MESSAGE;\n\nexport type AISDKRuntimeAdapter<UI_MESSAGE extends UIMessage = UIMessage> =\n ExternalStoreSharedOptions & {\n adapters?:\n | (NonNullable<ExternalStoreAdapter[\"adapters\"]> & {\n history?: ThreadHistoryAdapter | undefined;\n suggestion?: SuggestionAdapter | undefined;\n })\n | undefined;\n toCreateMessage?: CustomToCreateMessageFunction;\n unstable_messageRepositoryInstance?: MessageRepository | undefined;\n /**\n * The object a host answer belongs to, normally the `Chat` the runtime\n * renders. A host answer never reaches the `useChat` messages, so without\n * an owner it lives only as long as this runtime. With an owner, it\n * survives runtime remounts over the same chat.\n */\n unstable_hostApprovalOwner?: object | undefined;\n /**\n * Whether to automatically cancel pending interactive tool calls when the user sends a new message.\n *\n * When enabled (default), the pending tool calls will be marked as failed with an error message\n * indicating the user cancelled the tool call by sending a new message.\n *\n * @default true\n */\n cancelPendingToolCallsOnSend?: boolean | undefined;\n /**\n * Called when `runtime.thread.resumeRun(config)` is invoked.\n *\n * When omitted, `resumeRun` throws `\"Runtime does not support resuming runs.\"`.\n * Provide this to bridge resume invocations into a custom replay channel\n * (for example, an SSE reconnect endpoint keyed by turn id).\n */\n onResume?: ExternalStoreAdapter[\"onResume\"];\n /**\n * Called when `runtime.thread.resumeToolCall(options)` is invoked for a tool call the in-process tracker does not own.\n *\n * When omitted, `resumeToolCall` throws `\"Tool call ${toolCallId} is not waiting for resume.\"`.\n * Provide this to bridge resume-tool-call invocations into a custom handler.\n */\n onResumeToolCall?: ExternalStoreAdapter[\"onResumeToolCall\"];\n /**\n * Answers tool approval requests through a host-owned channel instead of the AI SDK's `addToolApprovalResponse`.\n *\n * Called for every approval request in the thread with the complete response, including option and free-form answers. Hand requests the host does not own to `respondViaAISDK`, which is what runs when this option is omitted. The answer applies to the approval when the handler starts and is removed if it throws. It is never written into the `useChat` messages, so `sendAutomaticallyWhen` cannot forward it. With a history adapter, the answer is stored with its message once the handler resolves and returns on reload. With `unstable_hostApprovalOwner`, in-memory answers survive runtime remounts over the same chat; without an owner or history adapter, they last only as long as the runtime. Bring the resumed run back into the chat, for example with `resumeStream`, and have the endpoint refuse a second resume.\n *\n * While a handler is set, an approval's `display`, `allowFreeform`, `dismissible` and `options` reach the renderer, because the handler can receive answers the AI SDK cannot carry. A stream declares them through the `approvalDescriptor` of its `tool-approval-request` chunk, the one approval field the AI SDK keeps opaque; the converter reads the request and answer fields from that descriptor when the approval itself lacks them.\n */\n onRespondToToolApproval?:\n | ((\n response: RespondToToolApprovalOptions,\n context: {\n toolCallId: string;\n toolName: string;\n /** Sends this response through the AI SDK's `addToolApprovalResponse`, which carries only `approved` and `reason`. */\n respondViaAISDK: () => Promise<void>;\n },\n ) => Promise<void> | void)\n | undefined;\n /**\n * How consecutive assistant messages are rendered.\n *\n * `\"concat-content\"` (the default) merges them into a single thread message.\n * `\"none\"` keeps each assistant message as its own thread message, which is\n * useful when a backend persists proactive or consecutive assistant messages\n * as separate entries.\n */\n joinStrategy?: JoinStrategy | undefined;\n /**\n * A branch-aware AI SDK message tree seeded once when `useChat` is empty.\n * After that seed, live updates come only from `useChat`. A later empty\n * chat or a new object identity does not reload the tree.\n */\n messageRepository?: MessageFormatRepository<UI_MESSAGE>;\n /**\n * Called after an explicit `switchToBranch` (for example a BranchPicker\n * click). Complements `setMessages` and does not enable switching by itself.\n *\n * @deprecated This API is still under active development and might change without notice.\n */\n unstable_onBranchChange?: ExternalStoreAdapter[\"unstable_onBranchChange\"];\n };\n\nconst EMPTY_SUGGESTIONS: readonly ThreadSuggestion[] = [];\n\nconst useGeneratedSuggestions = (\n suggestionAdapter: SuggestionAdapter | undefined,\n messages: readonly ThreadMessage[],\n isRunning: boolean,\n): readonly ThreadSuggestion[] => {\n const [suggestions, setSuggestions] =\n useState<readonly ThreadSuggestion[]>(EMPTY_SUGGESTIONS);\n const controllerRef = useRef<AbortController | null>(null);\n const wasRunningRef = useRef(false);\n const messagesRef = useRef(messages);\n useInsertionEffect(() => {\n messagesRef.current = messages;\n }, [messages]);\n const adapterRef = useRef(suggestionAdapter);\n useInsertionEffect(() => {\n adapterRef.current = suggestionAdapter;\n }, [suggestionAdapter]);\n const hasAdapter = suggestionAdapter != null;\n\n useEffect(() => {\n const clearSuggestions = () => {\n controllerRef.current?.abort();\n controllerRef.current = null;\n setSuggestions((prev) => (prev.length === 0 ? prev : EMPTY_SUGGESTIONS));\n };\n\n const adapter = adapterRef.current;\n if (!adapter) {\n clearSuggestions();\n wasRunningRef.current = isRunning;\n return;\n }\n\n if (isRunning) {\n if (!wasRunningRef.current) {\n clearSuggestions();\n }\n wasRunningRef.current = true;\n return;\n }\n\n if (!wasRunningRef.current) return;\n wasRunningRef.current = false;\n\n const currentMessages = messagesRef.current;\n const last = currentMessages.at(-1);\n if (last?.role !== \"assistant\") return;\n if (last.status?.type === \"requires-action\") return;\n\n const controller = new AbortController();\n controllerRef.current = controller;\n const { signal } = controller;\n\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: currentMessages,\n signal,\n });\n\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: setSuggestions,\n });\n } catch {}\n })();\n }, [hasAdapter, isRunning]);\n\n useReplaySafeEffect(() => {\n return () => {\n controllerRef.current?.abort();\n };\n }, []);\n\n return suggestions;\n};\n\nconst NO_CANCELLED_MESSAGE_IDS: ReadonlySet<string> = new Set();\n\nconst NO_SUPERSEDED_APPROVAL_PROJECTION = Object.freeze({\n approvalIds: Object.freeze(new Set<string>()),\n statusMessageIds: Object.freeze(new Set<string>()),\n});\n\nconst NO_TOOL_APPROVAL_RESPONSES: ReadonlyMap<\n string,\n RespondToToolApprovalOptions\n> = new Map();\n\n/**\n * A host answer is deliberately kept out of the `useChat` messages, so nothing\n * in the chat records it. Held in runtime state it would die with the runtime,\n * and a runtime mounted again over the same chat would show the request open\n * and take a second answer. Keyed on the chat instead, the answer lives as\n * long as the chat it belongs to, and is collected with it.\n */\ntype OwnedApproval = {\n response: RespondToToolApprovalOptions;\n};\n\nconst hostToolApprovalsByChat = new WeakMap<\n object,\n Map<string, OwnedApproval>\n>();\n\nconst toApprovalResponses = (\n owned: ReadonlyMap<string, OwnedApproval> | undefined,\n): ReadonlyMap<string, RespondToToolApprovalOptions> =>\n owned && owned.size > 0\n ? new Map([...owned].map(([id, entry]) => [id, entry.response]))\n : NO_TOOL_APPROVAL_RESPONSES;\n\n/**\n * The answers live on the owner, but each mounted runtime renders them from\n * its own state, so a write has to be announced: the runtime that performed it\n * may already be unmounted (a rollback resolving after a remount), and another\n * runtime may be mounted over the same owner.\n */\nconst hostApprovalListenersByChat = new WeakMap<object, Set<() => void>>();\n\nconst subscribeToHostApprovals = (owner: object, listener: () => void) => {\n const listeners = hostApprovalListenersByChat.get(owner) ?? new Set();\n hostApprovalListenersByChat.set(owner, listeners);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n};\n\nconst notifyHostApprovals = (owner: object) => {\n for (const listener of [...(hostApprovalListenersByChat.get(owner) ?? [])]) {\n listener();\n }\n};\n\nconst getSupersededApprovalProjection = <UI_MESSAGE extends UIMessage>(\n messages: readonly UI_MESSAGE[],\n hostApprovalIds: ReadonlySet<string>,\n joinStrategy: JoinStrategy | undefined,\n isRunning: boolean,\n) => {\n const approvalIds = new Set<string>();\n const statusMessageIds = new Set<string>();\n const lastIndex = messages.length - 1;\n let lastAssistant: UI_MESSAGE | undefined;\n let hasSupersededApproval = false;\n let previousWasVoice = false;\n\n const flush = () => {\n const hasOpenToolPart =\n lastAssistant === messages[lastIndex] &&\n lastAssistant?.parts?.some((part) => {\n if (\n !isToolUIPart(part) ||\n part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\"\n )\n return false;\n\n const approval = (\n part as {\n approval?: {\n resolution?: unknown;\n descriptor?: unknown;\n };\n }\n ).approval;\n const resolution =\n approval?.resolution ??\n (approval?.descriptor as { resolution?: unknown } | undefined)\n ?.resolution;\n return resolution !== \"cancelled\" && resolution !== \"expired\";\n });\n if (\n lastAssistant &&\n hasSupersededApproval &&\n !hasOpenToolPart &&\n !(isRunning && lastAssistant === messages[lastIndex])\n ) {\n statusMessageIds.add(lastAssistant.id);\n }\n lastAssistant = undefined;\n hasSupersededApproval = false;\n previousWasVoice = false;\n };\n\n for (let index = 0; index < messages.length; index++) {\n const message = messages[index]!;\n if (message.role !== \"assistant\") {\n flush();\n } else {\n const isVoice =\n (message.metadata as { modality?: unknown } | undefined)?.modality ===\n \"voice\";\n if (isVoice || previousWasVoice || joinStrategy === \"none\") flush();\n lastAssistant = message;\n previousWasVoice = isVoice;\n }\n\n for (const part of message.parts ?? []) {\n if (!isToolUIPart(part) || part.state !== \"approval-requested\") continue;\n\n const approval = part.approval;\n if (!approval) continue;\n\n const approvalId = approval.id;\n if (hostApprovalIds.has(approvalId)) continue;\n\n const resolution =\n (approval as { resolution?: unknown }).resolution ??\n (approval.descriptor as { resolution?: unknown } | null | undefined)\n ?.resolution;\n if (resolution === \"cancelled\" || resolution === \"expired\") continue;\n\n if (index !== lastIndex) {\n approvalIds.add(approvalId);\n if (message.role === \"assistant\") hasSupersededApproval = true;\n }\n }\n }\n flush();\n\n if (approvalIds.size === 0 && statusMessageIds.size === 0)\n return NO_SUPERSEDED_APPROVAL_PROJECTION;\n\n return { approvalIds, statusMessageIds };\n};\n\nconst findRawToolMessageIndex = <UI_MESSAGE extends UIMessage>(\n messages: readonly UI_MESSAGE[],\n messageId: string,\n toolCallId: string,\n joinStrategy: JoinStrategy | undefined,\n) => {\n const containsToolCall = (message: UI_MESSAGE) =>\n message.parts?.some(\n (part) => isToolUIPart(part) && part.toolCallId === toolCallId,\n ) === true;\n\n const messageIndex = messages.findIndex(\n (message) => message.id === messageId,\n );\n if (messageIndex === -1) return -1;\n if (containsToolCall(messages[messageIndex]!)) return messageIndex;\n if (joinStrategy === \"none\" || messages[messageIndex]?.role !== \"assistant\")\n return -1;\n\n let start = messageIndex;\n while (start > 0 && messages[start - 1]?.role === \"assistant\") start--;\n\n let end = messageIndex;\n while (end + 1 < messages.length && messages[end + 1]?.role === \"assistant\")\n end++;\n\n for (let index = start; index <= end; index++) {\n if (containsToolCall(messages[index]!)) return index;\n }\n return -1;\n};\n\nconst toChatError = (error: Error): AssistantError => {\n const code = (error as { code?: unknown }).code;\n return {\n code:\n typeof code === \"string\"\n ? code\n : error.name !== \"Error\"\n ? error.name\n : \"unknown\",\n message: error.message,\n };\n};\n\nexport const useAISDKRuntime = <UI_MESSAGE extends UIMessage = UIMessage>(\n chatHelpers: ReturnType<typeof useChat<UI_MESSAGE>>,\n adapter: AISDKRuntimeAdapter<UI_MESSAGE> = {},\n) => {\n const {\n adapters,\n toCreateMessage: customToCreateMessage,\n cancelPendingToolCallsOnSend = true,\n onResume,\n onResumeToolCall,\n onRespondToToolApproval: customOnRespondToToolApproval,\n joinStrategy,\n messageRepository,\n unstable_onBranchChange,\n } = adapter;\n const suggestionAdapter = adapters?.suggestion;\n const contextAdapters = useRuntimeAdapters();\n const [toolStatuses, setToolStatuses] = useState<\n Record<string, ToolExecutionStatus>\n >({});\n const [cancelledMessages, setCancelledMessages] = useState<{\n chatId: string;\n ids: ReadonlySet<string>;\n } | null>(null);\n // Set by hosts that own the chat across runtime lifetimes, so a host answer\n // outlives a remount over that same chat.\n const approvalOwner = adapter.unstable_hostApprovalOwner;\n const ownedApprovals = approvalOwner\n ? (hostToolApprovalsByChat.get(approvalOwner) ??\n (() => {\n const created = new Map<string, OwnedApproval>();\n hostToolApprovalsByChat.set(approvalOwner, created);\n return created;\n })())\n : undefined;\n const [toolApprovalResponses, setToolApprovalResponses] = useState<\n ReadonlyMap<string, RespondToToolApprovalOptions>\n >(() => toApprovalResponses(ownedApprovals));\n const [toolArtifactEpoch, setToolArtifactEpoch] = useState(0);\n const [toolInteractionEpoch, setToolInteractionEpoch] = useState(0);\n const toolApprovalResponsesRef = useRef(\n new Map(toApprovalResponses(ownedApprovals)),\n );\n const ownedApprovalIdsRef = useRef(new Set(ownedApprovals?.keys()));\n const hostApprovalIdsRef = useRef(new Set<string>(ownedApprovals?.keys()));\n\n // The owner's record is shared, so this runtime re-reads it whenever it is\n // written rather than only at mount: the write may come from a runtime that\n // has since unmounted, or from another runtime mounted over the same owner.\n useEffect(() => {\n if (!approvalOwner || !ownedApprovals) return undefined;\n const sync = () => {\n for (const id of ownedApprovalIdsRef.current)\n toolApprovalResponsesRef.current.delete(id);\n for (const [id, entry] of ownedApprovals)\n toolApprovalResponsesRef.current.set(id, entry.response);\n ownedApprovalIdsRef.current = new Set(ownedApprovals.keys());\n hostApprovalIdsRef.current = new Set(\n toolApprovalResponsesRef.current.keys(),\n );\n setToolApprovalResponses((prev) => {\n const next = new Map(toolApprovalResponsesRef.current);\n const unchanged =\n prev.size === next.size &&\n [...next].every(([id, response]) => prev.get(id) === response);\n return unchanged ? prev : next;\n });\n };\n const unsubscribe = subscribeToHostApprovals(approvalOwner, sync);\n // The state was seeded during render, so a write landing between then and\n // this subscription would otherwise never be seen.\n sync();\n return unsubscribe;\n }, [approvalOwner, ownedApprovals]);\n\n // A runtime kept mounted across a change of owner must not carry the\n // previous chat's answers: a reused approval id would render as already\n // answered and reject a genuine response.\n const lastApprovalOwnerRef = useRef(approvalOwner);\n if (lastApprovalOwnerRef.current !== approvalOwner) {\n lastApprovalOwnerRef.current = approvalOwner;\n hostApprovalIdsRef.current = new Set<string>(ownedApprovals?.keys());\n toolApprovalResponsesRef.current = new Map(\n toApprovalResponses(ownedApprovals),\n );\n ownedApprovalIdsRef.current = new Set(ownedApprovals?.keys());\n setToolApprovalResponses(new Map(toolApprovalResponsesRef.current));\n }\n const toolArgsKeyOrderCacheRef = useRef<Map<string, Map<string, string[]>>>(\n new Map(),\n );\n const toolLastInputCacheRef = useRef<Map<string, ReadonlyJSONObject>>(\n new Map(),\n );\n const toolArgsTextCacheRef = useRef<\n WeakMap<ReadonlyJSONObject, Map<string, string>>\n >(new WeakMap());\n const mcpAppMetadataCacheRef = useRef<Map<string, McpAppMetadata>>(new Map());\n const toolArtifactsRef = useRef<Map<string, unknown>>(new Map());\n const toolInteractionsRef = useRef<Map<string, Unstable_ToolInteractionLog>>(\n new Map(),\n );\n const lastRunConfigRef = useRef<RunConfig | undefined>(undefined);\n const markToolArtifactsChanged = useCallback(() => {\n setToolArtifactEpoch((epoch) => epoch + 1);\n }, []);\n const markToolInteractionsChanged = useCallback(() => {\n setToolInteractionEpoch((epoch) => epoch + 1);\n }, []);\n\n const hasExecutingTools = Object.values(toolStatuses).some(\n (s) => s?.type === \"executing\",\n );\n const providerIsRunning =\n chatHelpers.status === \"submitted\" || chatHelpers.status === \"streaming\";\n const isRunning = providerIsRunning || hasExecutingTools;\n const wasProviderRunningRef = useRef(providerIsRunning);\n\n const messageTiming = useStreamingTiming(chatHelpers.messages, isRunning);\n\n // Flag the streaming message optimistic: its id can be swapped for a server\n // id mid-run, and the repository then drops the orphaned pre-swap id (#4037).\n const lastMessage = chatHelpers.messages.at(-1);\n const optimisticMessageId =\n isRunning && lastMessage?.role === \"assistant\" ? lastMessage.id : undefined;\n\n const cancelledMessageIds =\n cancelledMessages?.chatId === chatHelpers.id\n ? cancelledMessages.ids\n : NO_CANCELLED_MESSAGE_IDS;\n const supportsRichToolApprovalResponses =\n customOnRespondToToolApproval != null;\n const supersededApprovalProjectionRef = useRef(\n NO_SUPERSEDED_APPROVAL_PROJECTION,\n );\n const supersededApprovalProjection = useMemo(\n () => {\n const projection = getSupersededApprovalProjection(\n chatHelpers.messages,\n hostApprovalIdsRef.current,\n joinStrategy,\n isRunning,\n );\n const previous = supersededApprovalProjectionRef.current;\n if (\n projection.approvalIds.size === previous.approvalIds.size &&\n projection.statusMessageIds.size === previous.statusMessageIds.size &&\n [...projection.approvalIds].every((id) =>\n previous.approvalIds.has(id),\n ) &&\n [...projection.statusMessageIds].every((id) =>\n previous.statusMessageIds.has(id),\n )\n )\n return previous;\n\n supersededApprovalProjectionRef.current = projection;\n return projection;\n },\n // oxlint-disable-next-line react/exhaustive-deps -- hostApprovalIdsRef changes alongside toolApprovalResponses, which invalidates the projection\n [chatHelpers.messages, joinStrategy, isRunning, toolApprovalResponses],\n );\n\n const toThreadMessages = useCallback(\n (sourceMessages: UI_MESSAGE[]) => {\n const metadata: AISDKMessageConverterMetadata = {\n supportsRichToolApprovalResponses,\n toolArtifacts: toolArtifactsRef.current,\n toolInteractions: toolInteractionsRef.current,\n toolApprovalResponses: toolApprovalResponsesRef.current,\n };\n return AISDKMessageConverter.toThreadMessages(\n sourceMessages,\n false,\n metadata,\n );\n },\n [supportsRichToolApprovalResponses],\n );\n\n const retractCancellation = useCallback(\n (chatId: string, messageId: string) => {\n setCancelledMessages((prev) => {\n if (prev?.chatId !== chatId || !prev.ids.has(messageId)) return prev;\n const ids = new Set(prev.ids);\n ids.delete(messageId);\n return { chatId, ids };\n });\n },\n [],\n );\n\n // A provider run that resumes the stopped response retracts its cancellation;\n // a run that starts a new response leaves the stopped one marked.\n const resumedMessageId =\n providerIsRunning && lastMessage?.role === \"assistant\"\n ? lastMessage.id\n : undefined;\n\n useEffect(() => {\n const wasProviderRunning = wasProviderRunningRef.current;\n wasProviderRunningRef.current = providerIsRunning;\n if (wasProviderRunning || !resumedMessageId) return;\n retractCancellation(chatHelpers.id, resumedMessageId);\n }, [\n providerIsRunning,\n resumedMessageId,\n chatHelpers.id,\n retractCancellation,\n ]);\n\n const messages = AISDKMessageConverter.useThreadMessages({\n isRunning,\n messages: chatHelpers.messages,\n joinStrategy,\n metadata: useMemo<AISDKMessageConverterMetadata>(\n () => ({\n toolStatuses,\n messageTiming,\n toolArgsKeyOrderCache: toolArgsKeyOrderCacheRef.current,\n toolArgsTextCache: toolArgsTextCacheRef.current,\n toolLastInputCache: toolLastInputCacheRef.current,\n mcpAppMetadataCache: mcpAppMetadataCacheRef.current,\n toolArtifacts: toolArtifactsRef.current,\n toolInteractions: toolInteractionsRef.current,\n supportsRichToolApprovalResponses,\n cancelledToolApprovalIds: supersededApprovalProjection.approvalIds,\n cancelledStatusMessageIds:\n supersededApprovalProjection.statusMessageIds,\n ...(optimisticMessageId && { optimisticMessageId }),\n ...(chatHelpers.error && {\n error: toChatError(chatHelpers.error),\n }),\n ...(cancelledMessageIds.size > 0 && { cancelledMessageIds }),\n ...(toolApprovalResponses.size > 0 && { toolApprovalResponses }),\n }),\n [\n toolStatuses,\n messageTiming,\n optimisticMessageId,\n chatHelpers.error,\n cancelledMessageIds,\n toolApprovalResponses,\n supportsRichToolApprovalResponses,\n supersededApprovalProjection,\n toolArtifactEpoch,\n toolInteractionEpoch,\n ],\n ),\n });\n\n const exportedMessageRepository = useMemo(() => {\n if (!messageRepository) return undefined;\n const converted = toExportedMessageRepository(\n toThreadMessages,\n messageRepository,\n );\n return converted.messages.length > 0 ? converted : undefined;\n }, [messageRepository, toThreadMessages]);\n\n const generatedSuggestions = useGeneratedSuggestions(\n suggestionAdapter,\n messages,\n isRunning,\n );\n\n const [runtimeRef] = useState(() => ({\n get current(): AssistantRuntime {\n return runtime;\n },\n }));\n\n const {\n isLoading,\n deleteMessage: deleteHistoryMessage,\n persistToolInteractions,\n persistToolApprovalResponses,\n } = useExternalHistory(\n runtimeRef,\n adapters?.history ?? contextAdapters?.history,\n toThreadMessages,\n aiSDKV6FormatAdapter as MessageFormatAdapter<\n UI_MESSAGE,\n AISDKStorageFormat\n >,\n (messages) => {\n chatHelpers.setMessages(messages);\n },\n toolArtifactsRef.current,\n markToolArtifactsChanged,\n toolInteractionsRef.current,\n markToolInteractionsChanged,\n toolApprovalResponsesRef.current,\n () => {\n for (const [id, entry] of ownedApprovals ?? []) {\n toolApprovalResponsesRef.current.set(id, entry.response);\n }\n hostApprovalIdsRef.current = new Set(\n toolApprovalResponsesRef.current.keys(),\n );\n setToolApprovalResponses(new Map(toolApprovalResponsesRef.current));\n },\n );\n\n const {\n id: chatId,\n messages: chatMessages,\n status: chatStatus,\n error,\n } = chatHelpers;\n const extras = useMemo(\n () =>\n aiSDKExtras.provide({\n chat: chatHelpers as unknown as UseChatHelpers<UIMessage>,\n error,\n }),\n // oxlint-disable-next-line react/exhaustive-deps -- keyed on the chat's identity and reactive snapshots; useChat re-mints the helpers object every render while its remaining fields are instance-bound methods, and a render-stable extras identity is what lets the external-store core dedupe adapter updates\n [chatId, chatMessages, chatStatus, error],\n );\n\n const completePendingToolCalls = async () => {\n if (!cancelPendingToolCallsOnSend) return;\n\n // The runtime auto-aborts in-flight tool invocations when a new run\n // is dispatched (append() / startRun()), so this only has to mark the\n // abandoned tools cancelled in the UI message list. Every non-terminal\n // tool call qualifies wherever it sits: the run that produced it is over,\n // and a staged `startRun: false` message can sit between it and the tail.\n // Uses setMessages to avoid triggering sendAutomaticallyWhen.\n chatHelpers.setMessages((messages) => {\n let hasChanges = false;\n\n const next = messages.map((message) => {\n if (message.role !== \"assistant\") return message;\n\n let messageChanged = false;\n const parts = message.parts?.map((part) => {\n if (!isToolUIPart(part)) return part;\n if (\n part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\"\n )\n return part;\n\n messageChanged = true;\n const { approval: _approval, ...rest } = part;\n return {\n ...rest,\n state: \"output-error\" as const,\n errorText: \"User cancelled tool call by sending a new message.\",\n };\n });\n\n if (!messageChanged) return message;\n hasChanges = true;\n return { ...message, parts };\n });\n\n if (!hasChanges) return messages;\n return next;\n });\n };\n\n const respondViaAISDK = ({\n approvalId,\n approved,\n reason,\n }: RespondToToolApprovalOptions) =>\n Promise.resolve(\n chatHelpers.addToolApprovalResponse({\n id: approvalId,\n approved,\n ...(reason != null && { reason }),\n options: { metadata: lastRunConfigRef.current },\n }),\n );\n\n const respondViaHost = async (\n onRespond: NonNullable<AISDKRuntimeAdapter[\"onRespondToToolApproval\"]>,\n response: RespondToToolApprovalOptions,\n ) => {\n const { approvalId } = response;\n const requested = chatHelpers.messages\n .flatMap((message) =>\n message.parts.flatMap((part) =>\n isToolUIPart(part) ? [{ messageId: message.id, part }] : [],\n ),\n )\n .find(\n ({ part }) =>\n part.state === \"approval-requested\" &&\n part.approval?.id === approvalId,\n );\n if (!requested || hostApprovalIdsRef.current.has(approvalId))\n throw new Error(\n `Tool approval ${approvalId} is not waiting for a response.`,\n );\n\n // A host answer stays out of the useChat messages, where sendAutomaticallyWhen would forward it to the chat route.\n // The owner can change while a response is in flight, and the id set is a\n // ref that is reseeded when it does. Both writes are therefore scoped to\n // the record this response started under, so a rollback never reaches a\n // different chat's state.\n const startedWith = ownedApprovals;\n const startedOwner = approvalOwner;\n const startedResponses = toolApprovalResponsesRef.current;\n // Whether this response is currently applied, tracked here rather than\n // read back from the id ref: that ref follows the chat on screen and is\n // reseeded when the owner changes, so it cannot answer for this response.\n let isApplied = false;\n const applyResponse = (applied: boolean) => {\n isApplied = applied;\n // The captured record is always corrected, so a rollback reaches the\n // chat the response belongs to even after the owner moved on.\n if (applied)\n startedWith?.set(approvalId, {\n response,\n });\n else startedWith?.delete(approvalId);\n\n if (startedOwner) {\n // Every runtime mounted over that owner re-reads the record, including\n // one mounted after this response started.\n notifyHostApprovals(startedOwner);\n return;\n }\n\n if (lastApprovalOwnerRef.current !== startedOwner) return;\n if (applied) hostApprovalIdsRef.current.add(approvalId);\n else hostApprovalIdsRef.current.delete(approvalId);\n if (applied) toolApprovalResponsesRef.current.set(approvalId, response);\n else toolApprovalResponsesRef.current.delete(approvalId);\n setToolApprovalResponses(new Map(toolApprovalResponsesRef.current));\n };\n\n applyResponse(true);\n try {\n await onRespond(response, {\n toolCallId: requested.part.toolCallId,\n toolName: getToolName(requested.part),\n respondViaAISDK: async () => {\n try {\n await respondViaAISDK(response);\n } finally {\n applyResponse(false);\n }\n },\n });\n } catch (error) {\n if (isApplied) applyResponse(false);\n throw error;\n }\n const remainsApplied =\n startedWith?.has(approvalId) ?? startedResponses.has(approvalId);\n if (isApplied && remainsApplied) {\n await persistToolApprovalResponses(requested.messageId);\n }\n };\n\n const hasSeededRepositoryRef = useRef(false);\n const shouldFeedRepository =\n exportedMessageRepository != null &&\n !hasSeededRepositoryRef.current &&\n messages.length === 0;\n\n const runtime = useExternalStoreRuntime({\n unstable_persistsHistory: true,\n isRunning: providerIsRunning,\n ...(shouldFeedRepository\n ? { messageRepository: exportedMessageRepository }\n : { messages }),\n unstable_enableToolInvocations: true,\n setToolStatuses,\n setMessages: (messages) =>\n chatHelpers.setMessages(\n messages\n .map(getVercelAIMessages<UI_MESSAGE>)\n .filter(Boolean)\n .flat(),\n ),\n onImport: (messages) =>\n chatHelpers.setMessages(\n messages\n .map(getVercelAIMessages<UI_MESSAGE>)\n .filter(Boolean)\n .flat(),\n ),\n onVoiceTranscript: (message: ThreadMessage) =>\n chatHelpers.setMessages((current) => [\n ...current,\n toVoiceTranscriptUIMessage<UI_MESSAGE>(message),\n ]),\n onExportExternalState: (): MessageFormatRepository<UI_MESSAGE> => {\n const exported = runtimeRef.current.thread.export();\n\n const expandedMessages: MessageFormatItem<UI_MESSAGE>[] = [];\n const lastInnerIdMap = new Map<string, string>();\n\n for (const item of exported.messages) {\n const innerMessages = getExternalStoreMessages<UI_MESSAGE>(\n item.message,\n );\n let parentId =\n item.parentId != null\n ? (lastInnerIdMap.get(item.parentId) ?? item.parentId)\n : null;\n for (const innerMessage of innerMessages) {\n expandedMessages.push({ parentId, message: innerMessage });\n parentId = aiSDKV6FormatAdapter.getId(innerMessage as UIMessage);\n }\n if (innerMessages.length > 0) {\n lastInnerIdMap.set(\n item.message.id,\n aiSDKV6FormatAdapter.getId(\n innerMessages[innerMessages.length - 1]! as UIMessage,\n ),\n );\n }\n }\n\n const result: MessageFormatRepository<UI_MESSAGE> = {\n messages: expandedMessages,\n };\n\n if (exported.headId != null) {\n result.headId = lastInnerIdMap.get(exported.headId) ?? exported.headId;\n }\n\n return result;\n },\n onLoadExternalState: (repo: MessageFormatRepository<UI_MESSAGE>) => {\n // Convert MessageFormatRepository to ExportedMessageRepository\n const exportedRepo = toExportedMessageRepository(toThreadMessages, repo);\n\n // Import into the thread's MessageRepository\n runtimeRef.current.thread.import(exportedRepo);\n },\n onCancel: async () => {\n const message = chatHelpers.messages.at(-1);\n const cancelledId =\n isRunning && message?.role === \"assistant\" ? message.id : undefined;\n if (cancelledId) {\n const liveIds = new Set(chatHelpers.messages.map((m) => m.id));\n setCancelledMessages((prev) => {\n const kept =\n prev?.chatId === chatHelpers.id\n ? [...prev.ids].filter((id) => liveIds.has(id))\n : [];\n return {\n chatId: chatHelpers.id,\n ids: new Set([...kept, cancelledId]),\n };\n });\n }\n try {\n await chatHelpers.stop();\n } catch (error) {\n if (!(error instanceof Error && error.name === \"AbortError\")) {\n if (cancelledId) retractCancellation(chatHelpers.id, cancelledId);\n throw error;\n }\n }\n },\n onNew: async (message) => {\n const createMessage = (\n customToCreateMessage ?? toCreateMessage\n )<UI_MESSAGE>(message);\n\n if (!(message.startRun ?? message.role === \"user\")) {\n chatHelpers.setMessages((current) => [\n ...current,\n toUIMessage<UI_MESSAGE>(createMessage, message.role),\n ]);\n return;\n }\n\n lastRunConfigRef.current = message.runConfig;\n await completePendingToolCalls();\n await chatHelpers.sendMessage(createMessage, {\n metadata: message.runConfig,\n });\n },\n onEdit: async (message) => {\n const createMessage = (\n customToCreateMessage ?? toCreateMessage\n )<UI_MESSAGE>(message);\n\n if (!(message.startRun ?? message.role === \"user\")) {\n chatHelpers.setMessages((current) => [\n ...sliceMessagesUntil(current, message.parentId),\n toUIMessage<UI_MESSAGE>(createMessage, message.role),\n ]);\n return;\n }\n\n lastRunConfigRef.current = message.runConfig;\n chatHelpers.setMessages((current) =>\n sliceMessagesUntil(current, message.parentId),\n );\n await chatHelpers.sendMessage(createMessage, {\n metadata: message.runConfig,\n });\n },\n onDelete: async (messageId) => {\n const threadMessages = runtimeRef.current.thread.getState().messages;\n const messageIndex = threadMessages.findIndex(\n (message) => message.id === messageId,\n );\n if (messageIndex === -1) return;\n\n await deleteHistoryMessage(messageId);\n\n let removedToolArtifact = false;\n let removedToolInteractions = false;\n let removedToolApprovalResponse = false;\n let removedHostApprovalId = false;\n for (const part of threadMessages[messageIndex]!.content) {\n if (part.type === \"tool-call\") {\n removedToolArtifact =\n toolArtifactsRef.current.delete(part.toolCallId) ||\n removedToolArtifact;\n removedToolInteractions =\n toolInteractionsRef.current.delete(part.toolCallId) ||\n removedToolInteractions;\n if (part.approval) {\n ownedApprovals?.delete(part.approval.id);\n removedToolApprovalResponse =\n toolApprovalResponsesRef.current.delete(part.approval.id) ||\n removedToolApprovalResponse;\n removedHostApprovalId =\n hostApprovalIdsRef.current.delete(part.approval.id) ||\n removedHostApprovalId;\n }\n }\n }\n if (removedToolArtifact) markToolArtifactsChanged();\n if (removedToolInteractions) markToolInteractionsChanged();\n if (removedToolApprovalResponse || removedHostApprovalId) {\n if (approvalOwner) notifyHostApprovals(approvalOwner);\n setToolApprovalResponses(new Map(toolApprovalResponsesRef.current));\n }\n\n const deleteIds = new Set(\n getExternalStoreMessages<UI_MESSAGE>(threadMessages[messageIndex]!).map(\n (message) => message.id,\n ),\n );\n chatHelpers.setMessages((current) =>\n current.filter((message) => !deleteIds.has(message.id)),\n );\n },\n onReload: async (parentId: string | null, config) => {\n lastRunConfigRef.current = config.runConfig;\n const newMessages = sliceMessagesUntil(chatHelpers.messages, parentId);\n chatHelpers.setMessages(newMessages);\n\n await chatHelpers.regenerate({ metadata: config.runConfig });\n },\n onAddToolResult: ({\n messageId,\n toolCallId,\n toolName,\n result,\n isError,\n artifact,\n modelContent,\n }) => {\n if (artifact !== undefined) {\n toolArtifactsRef.current.set(toolCallId, artifact);\n markToolArtifactsChanged();\n }\n\n const targetIndex = findRawToolMessageIndex(\n chatHelpers.messages,\n messageId,\n toolCallId,\n joinStrategy,\n );\n\n const errorText =\n typeof result === \"string\" ? result : JSON.stringify(result);\n const output =\n !isError && modelContent !== undefined\n ? wrapModelContentEnvelope(result, modelContent)\n : result;\n\n if (targetIndex >= 0 && targetIndex !== chatHelpers.messages.length - 1) {\n const target = chatHelpers.messages[targetIndex]!;\n const targetPart = target.parts.find(\n (part) => isToolUIPart(part) && part.toolCallId === toolCallId,\n ) as { state?: string; preliminary?: boolean } | undefined;\n // An earlier message's settled output may already have reached the model, as the error a cancelling send writes does.\n if (\n targetPart?.state === \"output-error\" ||\n targetPart?.state === \"output-denied\" ||\n (targetPart?.state === \"output-available\" && !targetPart.preliminary)\n )\n return Promise.resolve();\n\n const targetMessageId = target.id;\n chatHelpers.setMessages((current) =>\n current.map((message) => {\n if (message.id !== targetMessageId) return message;\n\n return {\n ...message,\n parts: message.parts.map((part) => {\n if (!isToolUIPart(part) || part.toolCallId !== toolCallId)\n return part;\n\n const { preliminary: _preliminary, ...finalPart } =\n part as typeof part & { preliminary?: boolean };\n return {\n ...finalPart,\n state: isError\n ? (\"output-error\" as const)\n : (\"output-available\" as const),\n output: isError ? undefined : output,\n errorText: isError ? errorText : undefined,\n } as typeof part;\n }),\n };\n }),\n );\n return Promise.resolve();\n }\n\n const options = { metadata: lastRunConfigRef.current };\n if (isError) {\n return Promise.resolve(\n chatHelpers.addToolOutput({\n state: \"output-error\",\n tool: toolName ?? toolCallId,\n toolCallId,\n errorText,\n options,\n }),\n );\n }\n\n return Promise.resolve(\n chatHelpers.addToolOutput({\n tool: toolName,\n toolCallId,\n output,\n options,\n }),\n );\n },\n onRespondToToolApproval: (response) => {\n if (supersededApprovalProjection.approvalIds.has(response.approvalId))\n return Promise.reject(\n new Error(\n `Tool approval ${response.approvalId} is not waiting for a response.`,\n ),\n );\n return customOnRespondToToolApproval\n ? respondViaHost(customOnRespondToToolApproval, response)\n : respondViaAISDK(response);\n },\n unstable_onRecordToolInteraction: ({\n messageId,\n toolCallId,\n interaction,\n }) => {\n toolInteractionsRef.current.set(\n toolCallId,\n appendToolInteraction(\n toolInteractionsRef.current.get(toolCallId),\n interaction,\n ),\n );\n markToolInteractionsChanged();\n return persistToolInteractions(messageId);\n },\n ...pickExternalStoreSharedOptions(adapter),\n ...(adapter.unstable_messageRepositoryInstance && {\n unstable_messageRepositoryInstance:\n adapter.unstable_messageRepositoryInstance,\n }),\n ...(suggestionAdapter ? { suggestions: generatedSuggestions } : {}),\n ...(onResume && { onResume }),\n ...(onResumeToolCall && { onResumeToolCall }),\n ...(unstable_onBranchChange && { unstable_onBranchChange }),\n adapters: {\n attachments: vercelAttachmentAdapter,\n ...contextAdapters,\n ...adapters,\n },\n extras,\n isLoading,\n });\n\n const setMessagesRef = useRef(chatHelpers.setMessages);\n useInsertionEffect(() => {\n setMessagesRef.current = chatHelpers.setMessages;\n }, [chatHelpers.setMessages]);\n\n useEffect(() => {\n if (hasSeededRepositoryRef.current) return;\n if (!exportedMessageRepository) return;\n if (chatHelpers.messages.length > 0) {\n hasSeededRepositoryRef.current = true;\n return;\n }\n const tempRepo = new MessageRepository();\n tempRepo.import(exportedMessageRepository);\n setMessagesRef.current(\n tempRepo.getMessages().flatMap(getExternalStoreMessages<UI_MESSAGE>),\n );\n hasSeededRepositoryRef.current = true;\n }, [exportedMessageRepository, chatHelpers.messages.length]);\n return runtime;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgFA,MAAM0D,eACJC,eACAC,kBAEC;CACC,GAAGD;CACHE,IAAIF,cAAcE,MAAMhD,WAAW;CACnCiD,MAAMH,cAAcG,QAAQF;AAC9B;AAEF,MAAMG,8BACJP,aAEC;CACCK,IAAIL,QAAQK;CACZC,MAAMN,QAAQM;CACdE,OAAOR,QAAQS,QACZC,QAAQC,SAASA,KAAKC,SAAS,MAAM,CAAC,CACtCC,KAAKF,UAAU;EAAEC,MAAM;EAAQE,MAAMH,KAAKG;CAAK,EAAE;CACpDC,UAAU;EACR,GAAIf,QAAQe,SAASC,YAAY,EAAEA,UAAUhB,QAAQe,SAASC,SAAS;EACvE,GAAIC,OAAOC,KAAKlB,QAAQe,SAASI,MAAM,CAAC,CAACC,SAAS,KAAK,EACrDD,QAAQnB,QAAQe,SAASI,OAC3B;CACF;AACF;AAqFF,MAAMsB,oBAAiD,CAAA;AAEvD,MAAMC,2BAA0BC,mBAAA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AA4B;GAC5B,OAAOqC,wBAAwBzF,WAAS;EAC1C;EACA,GAAGjJ,+BAA+BmF,OAAO;EACzC,GAAIA,QAAQrC,sCAAsC,EAChDA,oCACEqC,QAAQrC,mCACZ;EACA,GAAIiB,oBAAoB,EAAEI,aAAaiK,qBAAqB,IAAI,CAAC;EACjE,GAAInL,YAAY,EAAEA,SAAS;EAC3B,GAAIC,oBAAoB,EAAEA,iBAAiB;EAC3C,GAAIU,2BAA2B,EAAEA,wBAAwB;EACzDlB,UAAU;GACRoS,aAAatU;GACb,GAAGyJ;GACH,GAAGvH;EACL;EACAqM;EACAR;CACF,CAAC;CAED,MAAMwG,iBAAiB7W,OAAO2L,YAAY+E,WAAW;CACrD5Q,yBAAyB;EACvB+W,eAAerQ,UAAUmF,YAAY+E;CACvC,GAAG,CAAC/E,YAAY+E,WAAW,CAAC;CAE5B7Q,gBAAgB;EACd,IAAI2S,uBAAuBhM,SAAS;EACpC,IAAI,CAACwJ,2BAA2B;EAChC,IAAIrE,YAAY7F,SAASxB,SAAS,GAAG;GACnCkO,uBAAuBhM,UAAU;GACjC;EACF;EACA,MAAMsQ,WAAW,IAAI7U,kBAAkB;EACvC6U,SAAS7C,OAAOjE,yBAAyB;EACzC6G,eAAerQ,QACbsQ,SAASC,YAAY,CAAC,CAAChF,QAAQlQ,wBAAoC,CACrE;EACA2Q,uBAAuBhM,UAAU;CACnC,GAAG,CAACwJ,2BAA2BrE,YAAY7F,SAASxB,MAAM,CAAC;CAC3D,OAAO8L;AACT;AAhkCgC,SAAApJ,MAAAoG,MAAA;CAAA,OAuBAA,KAAI9I,WAAY,IAAhB8I,OAAAzH;AAA4C"}
1
+ {"version":3,"file":"useAISDKRuntime.js","names":["c","_c","useCallback","useEffect","useInsertionEffect","useMemo","useRef","useState","UIMessage","useChat","CreateUIMessage","UseChatHelpers","isToolUIPart","generateId","getToolName","useExternalStoreRuntime","useRuntimeAdapters","JoinStrategy","useReplaySafeEffect","SuggestionAdapter","ThreadSuggestion","ToolExecutionStatus","ExternalStoreAdapter","ExternalStoreSharedOptions","ThreadHistoryAdapter","AssistantRuntime","ThreadMessage","MessageFormatAdapter","MessageFormatItem","MessageFormatRepository","AppendMessage","RunConfig","McpAppMetadata","RespondToToolApprovalOptions","Unstable_ToolInteractionLog","getExternalStoreMessages","pickExternalStoreSharedOptions","appendToolInteraction","consumeSuggestionResult","MessageRepository","ReadonlyJSONObject","AssistantError","sliceMessagesUntil","toCreateMessage","vercelAttachmentAdapter","getVercelAIMessages","AISDKMessageConverter","AISDKMessageConverterMetadata","wrapModelContentEnvelope","AISDKStorageFormat","aiSDKV6FormatAdapter","useExternalHistory","toExportedMessageRepository","useStreamingTiming","aiSDKExtras","CustomToCreateMessageFunction","message","UI_MESSAGE","toUIMessage","createMessage","fallbackRole","id","role","toVoiceTranscriptUIMessage","parts","content","filter","part","type","map","text","metadata","modality","Object","keys","custom","length","AISDKRuntimeAdapter","adapters","NonNullable","history","suggestion","unstable_messageRepositoryInstance","unstable_hostApprovalOwner","cancelPendingToolCallsOnSend","onResume","onResumeToolCall","onRespondToToolApproval","response","context","toolCallId","toolName","respondViaAISDK","Promise","joinStrategy","messageRepository","unstable_onBranchChange","EMPTY_SUGGESTIONS","useGeneratedSuggestions","suggestionAdapter","messages","isRunning","$","suggestions","setSuggestions","controllerRef","wasRunningRef","messagesRef","t0","t1","current","adapterRef","t2","t3","hasAdapter","t4","clearSuggestions","abort","_temp","adapter","currentMessages","last","at","status","controller","AbortController","signal","promiseOrGenerator","generate","onUpdate","t5","t6","t7","Symbol","for","NO_CANCELLED_MESSAGE_IDS","ReadonlySet","Set","NO_SUPERSEDED_APPROVAL_PROJECTION","freeze","approvalIds","statusMessageIds","NO_TOOL_APPROVAL_RESPONSES","ReadonlyMap","Map","OwnedApproval","hostToolApprovalsByChat","WeakMap","toApprovalResponses","owned","size","entry","hostApprovalListenersByChat","subscribeToHostApprovals","owner","listener","listeners","get","set","add","delete","notifyHostApprovals","getSupersededApprovalProjection","hostApprovalIds","lastIndex","lastAssistant","hasSupersededApproval","previousWasVoice","flush","hasOpenToolPart","some","state","approval","resolution","descriptor","undefined","index","isVoice","approvalId","has","findRawToolMessageIndex","messageId","containsToolCall","messageIndex","findIndex","start","end","toChatError","error","Error","code","name","useAISDKRuntime","chatHelpers","ReturnType","customToCreateMessage","customOnRespondToToolApproval","contextAdapters","toolStatuses","setToolStatuses","Record","cancelledMessages","setCancelledMessages","chatId","ids","approvalOwner","ownedApprovals","created","toolApprovalResponses","setToolApprovalResponses","toolArtifactEpoch","setToolArtifactEpoch","toolInteractionEpoch","setToolInteractionEpoch","toolApprovalResponsesRef","ownedApprovalIdsRef","hostApprovalIdsRef","sync","prev","next","unchanged","every","unsubscribe","lastApprovalOwnerRef","toolArgsKeyOrderCacheRef","toolLastInputCacheRef","toolArgsTextCacheRef","mcpAppMetadataCacheRef","toolArtifactsRef","toolInteractionsRef","lastRunConfigRef","markToolArtifactsChanged","epoch","markToolInteractionsChanged","hasExecutingTools","values","s","providerIsRunning","wasProviderRunningRef","messageTiming","lastMessage","optimisticMessageId","cancelledMessageIds","supportsRichToolApprovalResponses","supersededApprovalProjectionRef","supersededApprovalProjection","projection","previous","toThreadMessages","sourceMessages","toolArtifacts","toolInteractions","retractCancellation","resumedMessageId","wasProviderRunning","useThreadMessages","toolArgsKeyOrderCache","toolArgsTextCache","toolLastInputCache","mcpAppMetadataCache","cancelledToolApprovalIds","cancelledStatusMessageIds","exportedMessageRepository","converted","generatedSuggestions","runtimeRef","runtime","isLoading","deleteMessage","deleteHistoryMessage","persistToolInteractions","persistToolApprovalResponses","setMessages","chatMessages","chatStatus","extras","provide","chat","completePendingToolCalls","hasChanges","messageChanged","_approval","rest","const","errorText","approved","reason","resolve","addToolApprovalResponse","options","respondViaHost","onRespond","requested","flatMap","find","startedWith","startedOwner","startedResponses","isApplied","applyResponse","applied","remainsApplied","hasSeededRepositoryRef","shouldFeedRepository","unstable_persistsHistory","unstable_enableToolInvocations","Boolean","flat","onImport","onVoiceTranscript","onExportExternalState","exported","thread","export","expandedMessages","lastInnerIdMap","item","innerMessages","parentId","innerMessage","push","getId","result","headId","onLoadExternalState","repo","exportedRepo","import","onCancel","cancelledId","liveIds","m","kept","stop","onNew","startRun","runConfig","sendMessage","onEdit","onDelete","threadMessages","getState","removedToolArtifact","removedToolInteractions","removedToolApprovalResponse","removedHostApprovalId","deleteIds","onReload","config","newMessages","regenerate","onAddToolResult","isError","artifact","modelContent","targetIndex","JSON","stringify","output","target","targetPart","preliminary","targetMessageId","_preliminary","finalPart","addToolOutput","tool","reject","unstable_onRecordToolInteraction","interaction","attachments","setMessagesRef","tempRepo","getMessages","_c","useStreamingTiming"],"sources":["../../src/runtime/useAISDKRuntime.ts"],"sourcesContent":["\"use client\";\n\nimport {\n useCallback,\n useEffect,\n useInsertionEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type {\n UIMessage,\n useChat,\n CreateUIMessage,\n UseChatHelpers,\n} from \"@ai-sdk/react\";\nimport { isToolUIPart, generateId, getToolName } from \"ai\";\nimport {\n useExternalStoreRuntime,\n useRuntimeAdapters,\n type JoinStrategy,\n} from \"@assistant-ui/core/react\";\nimport { useReplaySafeEffect } from \"@assistant-ui/store/internal\";\nimport type {\n SuggestionAdapter,\n ThreadSuggestion,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type {\n ExternalStoreAdapter,\n ExternalStoreSharedOptions,\n ThreadHistoryAdapter,\n AssistantRuntime,\n ThreadMessage,\n MessageFormatAdapter,\n MessageFormatItem,\n MessageFormatRepository,\n AppendMessage,\n RunConfig,\n McpAppMetadata,\n RespondToToolApprovalOptions,\n Unstable_ToolInteractionLog,\n} from \"@assistant-ui/core\";\nimport {\n getExternalStoreMessages,\n pickExternalStoreSharedOptions,\n} from \"@assistant-ui/core\";\nimport {\n appendToolInteraction,\n consumeSuggestionResult,\n MessageRepository,\n} from \"@assistant-ui/core/internal\";\nimport type { ReadonlyJSONObject } from \"assistant-stream/utils\";\nimport type { AssistantError } from \"@assistant-ui/core\";\nimport { sliceMessagesUntil } from \"../utils/sliceMessagesUntil\";\nimport { toCreateMessage } from \"../converters/toCreateMessage\";\nimport { vercelAttachmentAdapter } from \"../adapters/vercelAttachmentAdapter\";\nimport { getVercelAIMessages } from \"../utils/getVercelAIMessages\";\nimport {\n AISDKMessageConverter,\n type AISDKMessageConverterMetadata,\n} from \"../converters/convertMessage\";\nimport { wrapModelContentEnvelope } from \"../converters/modelContentEnvelope\";\nimport {\n type AISDKStorageFormat,\n aiSDKV6FormatAdapter,\n} from \"../adapters/aiSDKFormatAdapter\";\nimport {\n useExternalHistory,\n toExportedMessageRepository,\n} from \"./useExternalHistory\";\nimport { useStreamingTiming } from \"./useStreamingTiming\";\nimport { aiSDKExtras } from \"../aiSDKExtras\";\n\nexport type CustomToCreateMessageFunction = <\n UI_MESSAGE extends UIMessage = UIMessage,\n>(\n message: AppendMessage,\n) => CreateUIMessage<UI_MESSAGE>;\n\nconst toUIMessage = <UI_MESSAGE extends UIMessage>(\n createMessage: CreateUIMessage<UI_MESSAGE>,\n fallbackRole: UI_MESSAGE[\"role\"],\n): UI_MESSAGE =>\n ({\n ...createMessage,\n id: createMessage.id ?? generateId(),\n role: createMessage.role ?? fallbackRole,\n }) as UI_MESSAGE;\n\nconst toVoiceTranscriptUIMessage = <UI_MESSAGE extends UIMessage>(\n message: ThreadMessage,\n): UI_MESSAGE =>\n ({\n id: message.id,\n role: message.role,\n parts: message.content\n .filter((part) => part.type === \"text\")\n .map((part) => ({ type: \"text\", text: part.text })),\n metadata: {\n ...(message.metadata.modality && { modality: message.metadata.modality }),\n ...(Object.keys(message.metadata.custom).length > 0 && {\n custom: message.metadata.custom,\n }),\n },\n }) as UI_MESSAGE;\n\nexport type AISDKRuntimeAdapter<UI_MESSAGE extends UIMessage = UIMessage> =\n ExternalStoreSharedOptions & {\n adapters?:\n | (NonNullable<ExternalStoreAdapter[\"adapters\"]> & {\n history?: ThreadHistoryAdapter | undefined;\n suggestion?: SuggestionAdapter | undefined;\n })\n | undefined;\n toCreateMessage?: CustomToCreateMessageFunction;\n unstable_messageRepositoryInstance?: MessageRepository | undefined;\n /**\n * The object a host answer belongs to, normally the `Chat` the runtime\n * renders. A host answer never reaches the `useChat` messages, so without\n * an owner it lives only as long as this runtime. With an owner, it\n * survives runtime remounts over the same chat.\n */\n unstable_hostApprovalOwner?: object | undefined;\n /**\n * Whether to automatically cancel pending interactive tool calls when the user sends a new message.\n *\n * When enabled (default), the pending tool calls will be marked as failed with an error message\n * indicating the user cancelled the tool call by sending a new message.\n *\n * @default true\n */\n cancelPendingToolCallsOnSend?: boolean | undefined;\n /**\n * Called when `runtime.thread.resumeRun(config)` is invoked.\n *\n * When omitted, `resumeRun` throws `\"Runtime does not support resuming runs.\"`.\n * Provide this to bridge resume invocations into a custom replay channel\n * (for example, an SSE reconnect endpoint keyed by turn id).\n */\n onResume?: ExternalStoreAdapter[\"onResume\"];\n /**\n * Called when `runtime.thread.resumeToolCall(options)` is invoked for a tool call the in-process tracker does not own.\n *\n * When omitted, `resumeToolCall` throws `\"Tool call ${toolCallId} is not waiting for resume.\"`.\n * Provide this to bridge resume-tool-call invocations into a custom handler.\n */\n onResumeToolCall?: ExternalStoreAdapter[\"onResumeToolCall\"];\n /**\n * Answers tool approval requests through a host-owned channel instead of the AI SDK's `addToolApprovalResponse`.\n *\n * Called for every approval request in the thread with the complete response, including option and free-form answers. Hand requests the host does not own to `respondViaAISDK`, which is what runs when this option is omitted. The answer applies to the approval when the handler starts and is removed if it throws. It is never written into the `useChat` messages, so `sendAutomaticallyWhen` cannot forward it. With a history adapter, the answer is stored with its message once the handler resolves and returns on reload. With `unstable_hostApprovalOwner`, in-memory answers survive runtime remounts over the same chat; without an owner or history adapter, they last only as long as the runtime. Bring the resumed run back into the chat, for example with `resumeStream`, and have the endpoint refuse a second resume.\n *\n * While a handler is set, an approval's `display`, `allowFreeform`, `dismissible` and `options` reach the renderer, because the handler can receive answers the AI SDK cannot carry. A stream declares them through the `approvalDescriptor` of its `tool-approval-request` chunk, the one approval field the AI SDK keeps opaque; the converter reads the request and answer fields from that descriptor when the approval itself lacks them.\n */\n onRespondToToolApproval?:\n | ((\n response: RespondToToolApprovalOptions,\n context: {\n toolCallId: string;\n toolName: string;\n /** Sends this response through the AI SDK's `addToolApprovalResponse`, which carries only `approved` and `reason`. */\n respondViaAISDK: () => Promise<void>;\n },\n ) => Promise<void> | void)\n | undefined;\n /**\n * How consecutive assistant messages are rendered.\n *\n * `\"concat-content\"` (the default) merges them into a single thread message.\n * `\"none\"` keeps each assistant message as its own thread message, which is\n * useful when a backend persists proactive or consecutive assistant messages\n * as separate entries.\n */\n joinStrategy?: JoinStrategy | undefined;\n /**\n * A branch-aware AI SDK message tree seeded once when `useChat` is empty.\n * After that seed, live updates come only from `useChat`. A later empty\n * chat or a new object identity does not reload the tree.\n */\n messageRepository?: MessageFormatRepository<UI_MESSAGE>;\n /**\n * Called after an explicit `switchToBranch` (for example a BranchPicker\n * click). Complements `setMessages` and does not enable switching by itself.\n *\n * @deprecated This API is still under active development and might change without notice.\n */\n unstable_onBranchChange?: ExternalStoreAdapter[\"unstable_onBranchChange\"];\n };\n\nconst EMPTY_SUGGESTIONS: readonly ThreadSuggestion[] = [];\n\nconst useGeneratedSuggestions = (\n suggestionAdapter: SuggestionAdapter | undefined,\n messages: readonly ThreadMessage[],\n isRunning: boolean,\n): readonly ThreadSuggestion[] => {\n const [suggestions, setSuggestions] =\n useState<readonly ThreadSuggestion[]>(EMPTY_SUGGESTIONS);\n const controllerRef = useRef<AbortController | null>(null);\n const wasRunningRef = useRef(false);\n const messagesRef = useRef(messages);\n useInsertionEffect(() => {\n messagesRef.current = messages;\n }, [messages]);\n const adapterRef = useRef(suggestionAdapter);\n useInsertionEffect(() => {\n adapterRef.current = suggestionAdapter;\n }, [suggestionAdapter]);\n const hasAdapter = suggestionAdapter != null;\n\n useEffect(() => {\n const clearSuggestions = () => {\n controllerRef.current?.abort();\n controllerRef.current = null;\n setSuggestions((prev) => (prev.length === 0 ? prev : EMPTY_SUGGESTIONS));\n };\n\n const adapter = adapterRef.current;\n if (!adapter) {\n clearSuggestions();\n wasRunningRef.current = isRunning;\n return;\n }\n\n if (isRunning) {\n if (!wasRunningRef.current) {\n clearSuggestions();\n }\n wasRunningRef.current = true;\n return;\n }\n\n if (!wasRunningRef.current) return;\n wasRunningRef.current = false;\n\n const currentMessages = messagesRef.current;\n const last = currentMessages.at(-1);\n if (last?.role !== \"assistant\") return;\n if (last.status?.type === \"requires-action\") return;\n\n const controller = new AbortController();\n controllerRef.current = controller;\n const { signal } = controller;\n\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: currentMessages,\n signal,\n });\n\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: setSuggestions,\n });\n } catch {}\n })();\n }, [hasAdapter, isRunning]);\n\n useReplaySafeEffect(() => {\n return () => {\n controllerRef.current?.abort();\n };\n }, []);\n\n return suggestions;\n};\n\nconst NO_CANCELLED_MESSAGE_IDS: ReadonlySet<string> = new Set();\n\nconst NO_SUPERSEDED_APPROVAL_PROJECTION = Object.freeze({\n approvalIds: Object.freeze(new Set<string>()),\n statusMessageIds: Object.freeze(new Set<string>()),\n});\n\nconst NO_TOOL_APPROVAL_RESPONSES: ReadonlyMap<\n string,\n RespondToToolApprovalOptions\n> = new Map();\n\n/**\n * A host answer is deliberately kept out of the `useChat` messages, so nothing\n * in the chat records it. Held in runtime state it would die with the runtime,\n * and a runtime mounted again over the same chat would show the request open\n * and take a second answer. Keyed on the chat instead, the answer lives as\n * long as the chat it belongs to, and is collected with it.\n */\ntype OwnedApproval = {\n response: RespondToToolApprovalOptions;\n};\n\nconst hostToolApprovalsByChat = new WeakMap<\n object,\n Map<string, OwnedApproval>\n>();\n\nconst toApprovalResponses = (\n owned: ReadonlyMap<string, OwnedApproval> | undefined,\n): ReadonlyMap<string, RespondToToolApprovalOptions> =>\n owned && owned.size > 0\n ? new Map([...owned].map(([id, entry]) => [id, entry.response]))\n : NO_TOOL_APPROVAL_RESPONSES;\n\n/**\n * The answers live on the owner, but each mounted runtime renders them from\n * its own state, so a write has to be announced: the runtime that performed it\n * may already be unmounted (a rollback resolving after a remount), and another\n * runtime may be mounted over the same owner.\n */\nconst hostApprovalListenersByChat = new WeakMap<object, Set<() => void>>();\n\nconst subscribeToHostApprovals = (owner: object, listener: () => void) => {\n const listeners = hostApprovalListenersByChat.get(owner) ?? new Set();\n hostApprovalListenersByChat.set(owner, listeners);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n};\n\nconst notifyHostApprovals = (owner: object) => {\n for (const listener of [...(hostApprovalListenersByChat.get(owner) ?? [])]) {\n listener();\n }\n};\n\nconst getSupersededApprovalProjection = <UI_MESSAGE extends UIMessage>(\n messages: readonly UI_MESSAGE[],\n hostApprovalIds: ReadonlySet<string>,\n joinStrategy: JoinStrategy | undefined,\n isRunning: boolean,\n) => {\n const approvalIds = new Set<string>();\n const statusMessageIds = new Set<string>();\n const lastIndex = messages.length - 1;\n let lastAssistant: UI_MESSAGE | undefined;\n let hasSupersededApproval = false;\n let previousWasVoice = false;\n\n const flush = () => {\n const hasOpenToolPart =\n lastAssistant === messages[lastIndex] &&\n lastAssistant?.parts?.some((part) => {\n if (\n !isToolUIPart(part) ||\n part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\"\n )\n return false;\n\n const approval = (\n part as {\n approval?: {\n resolution?: unknown;\n descriptor?: unknown;\n };\n }\n ).approval;\n const resolution =\n approval?.resolution ??\n (approval?.descriptor as { resolution?: unknown } | undefined)\n ?.resolution;\n return resolution !== \"cancelled\" && resolution !== \"expired\";\n });\n if (\n lastAssistant &&\n hasSupersededApproval &&\n !hasOpenToolPart &&\n !(isRunning && lastAssistant === messages[lastIndex])\n ) {\n statusMessageIds.add(lastAssistant.id);\n }\n lastAssistant = undefined;\n hasSupersededApproval = false;\n previousWasVoice = false;\n };\n\n for (let index = 0; index < messages.length; index++) {\n const message = messages[index]!;\n if (message.role !== \"assistant\") {\n flush();\n } else {\n const isVoice =\n (message.metadata as { modality?: unknown } | undefined)?.modality ===\n \"voice\";\n if (isVoice || previousWasVoice || joinStrategy === \"none\") flush();\n lastAssistant = message;\n previousWasVoice = isVoice;\n }\n\n for (const part of message.parts ?? []) {\n if (!isToolUIPart(part) || part.state !== \"approval-requested\") continue;\n\n const approval = part.approval;\n if (!approval) continue;\n\n const approvalId = approval.id;\n if (hostApprovalIds.has(approvalId)) continue;\n\n const resolution =\n (approval as { resolution?: unknown }).resolution ??\n (approval.descriptor as { resolution?: unknown } | null | undefined)\n ?.resolution;\n if (resolution === \"cancelled\" || resolution === \"expired\") continue;\n\n if (index !== lastIndex) {\n approvalIds.add(approvalId);\n if (message.role === \"assistant\") hasSupersededApproval = true;\n }\n }\n }\n flush();\n\n if (approvalIds.size === 0 && statusMessageIds.size === 0)\n return NO_SUPERSEDED_APPROVAL_PROJECTION;\n\n return { approvalIds, statusMessageIds };\n};\n\nconst findRawToolMessageIndex = <UI_MESSAGE extends UIMessage>(\n messages: readonly UI_MESSAGE[],\n messageId: string,\n toolCallId: string,\n joinStrategy: JoinStrategy | undefined,\n) => {\n const containsToolCall = (message: UI_MESSAGE) =>\n message.parts?.some(\n (part) => isToolUIPart(part) && part.toolCallId === toolCallId,\n ) === true;\n\n const messageIndex = messages.findIndex(\n (message) => message.id === messageId,\n );\n if (messageIndex === -1) return -1;\n if (containsToolCall(messages[messageIndex]!)) return messageIndex;\n if (joinStrategy === \"none\" || messages[messageIndex]?.role !== \"assistant\")\n return -1;\n\n let start = messageIndex;\n while (start > 0 && messages[start - 1]?.role === \"assistant\") start--;\n\n let end = messageIndex;\n while (end + 1 < messages.length && messages[end + 1]?.role === \"assistant\")\n end++;\n\n for (let index = start; index <= end; index++) {\n if (containsToolCall(messages[index]!)) return index;\n }\n return -1;\n};\n\nconst toChatError = (error: Error): AssistantError => {\n const code = (error as { code?: unknown }).code;\n return {\n code:\n typeof code === \"string\"\n ? code\n : error.name !== \"Error\"\n ? error.name\n : \"unknown\",\n message: error.message,\n };\n};\n\nexport const useAISDKRuntime = <UI_MESSAGE extends UIMessage = UIMessage>(\n chatHelpers: ReturnType<typeof useChat<UI_MESSAGE>>,\n adapter: AISDKRuntimeAdapter<UI_MESSAGE> = {},\n) => {\n const {\n adapters,\n toCreateMessage: customToCreateMessage,\n cancelPendingToolCallsOnSend = true,\n onResume,\n onResumeToolCall,\n onRespondToToolApproval: customOnRespondToToolApproval,\n joinStrategy,\n messageRepository,\n unstable_onBranchChange,\n } = adapter;\n const suggestionAdapter = adapters?.suggestion;\n const contextAdapters = useRuntimeAdapters();\n const [toolStatuses, setToolStatuses] = useState<\n Record<string, ToolExecutionStatus>\n >({});\n const [cancelledMessages, setCancelledMessages] = useState<{\n chatId: string;\n ids: ReadonlySet<string>;\n } | null>(null);\n // Set by hosts that own the chat across runtime lifetimes, so a host answer\n // outlives a remount over that same chat.\n const approvalOwner = adapter.unstable_hostApprovalOwner;\n const ownedApprovals = approvalOwner\n ? (hostToolApprovalsByChat.get(approvalOwner) ??\n (() => {\n const created = new Map<string, OwnedApproval>();\n hostToolApprovalsByChat.set(approvalOwner, created);\n return created;\n })())\n : undefined;\n const [toolApprovalResponses, setToolApprovalResponses] = useState<\n ReadonlyMap<string, RespondToToolApprovalOptions>\n >(() => toApprovalResponses(ownedApprovals));\n const [toolArtifactEpoch, setToolArtifactEpoch] = useState(0);\n const [toolInteractionEpoch, setToolInteractionEpoch] = useState(0);\n const toolApprovalResponsesRef = useRef(\n new Map(toApprovalResponses(ownedApprovals)),\n );\n const ownedApprovalIdsRef = useRef(new Set(ownedApprovals?.keys()));\n const hostApprovalIdsRef = useRef(new Set<string>(ownedApprovals?.keys()));\n\n // The owner's record is shared, so this runtime re-reads it whenever it is\n // written rather than only at mount: the write may come from a runtime that\n // has since unmounted, or from another runtime mounted over the same owner.\n useEffect(() => {\n if (!approvalOwner || !ownedApprovals) return undefined;\n const sync = () => {\n for (const id of ownedApprovalIdsRef.current)\n toolApprovalResponsesRef.current.delete(id);\n for (const [id, entry] of ownedApprovals)\n toolApprovalResponsesRef.current.set(id, entry.response);\n ownedApprovalIdsRef.current = new Set(ownedApprovals.keys());\n hostApprovalIdsRef.current = new Set(\n toolApprovalResponsesRef.current.keys(),\n );\n setToolApprovalResponses((prev) => {\n const next = new Map(toolApprovalResponsesRef.current);\n const unchanged =\n prev.size === next.size &&\n [...next].every(([id, response]) => prev.get(id) === response);\n return unchanged ? prev : next;\n });\n };\n const unsubscribe = subscribeToHostApprovals(approvalOwner, sync);\n // The state was seeded during render, so a write landing between then and\n // this subscription would otherwise never be seen.\n sync();\n return unsubscribe;\n }, [approvalOwner, ownedApprovals]);\n\n // A runtime kept mounted across a change of owner must not carry the\n // previous chat's answers: a reused approval id would render as already\n // answered and reject a genuine response.\n const lastApprovalOwnerRef = useRef(approvalOwner);\n if (lastApprovalOwnerRef.current !== approvalOwner) {\n lastApprovalOwnerRef.current = approvalOwner;\n hostApprovalIdsRef.current = new Set<string>(ownedApprovals?.keys());\n toolApprovalResponsesRef.current = new Map(\n toApprovalResponses(ownedApprovals),\n );\n ownedApprovalIdsRef.current = new Set(ownedApprovals?.keys());\n setToolApprovalResponses(new Map(toolApprovalResponsesRef.current));\n }\n const toolArgsKeyOrderCacheRef = useRef<Map<string, Map<string, string[]>>>(\n new Map(),\n );\n const toolLastInputCacheRef = useRef<Map<string, ReadonlyJSONObject>>(\n new Map(),\n );\n const toolArgsTextCacheRef = useRef<\n WeakMap<ReadonlyJSONObject, Map<string, string>>\n >(new WeakMap());\n const mcpAppMetadataCacheRef = useRef<Map<string, McpAppMetadata>>(new Map());\n const toolArtifactsRef = useRef<Map<string, unknown>>(new Map());\n const toolInteractionsRef = useRef<Map<string, Unstable_ToolInteractionLog>>(\n new Map(),\n );\n const lastRunConfigRef = useRef<RunConfig | undefined>(undefined);\n const markToolArtifactsChanged = useCallback(() => {\n setToolArtifactEpoch((epoch) => epoch + 1);\n }, []);\n const markToolInteractionsChanged = useCallback(() => {\n setToolInteractionEpoch((epoch) => epoch + 1);\n }, []);\n\n const hasExecutingTools = Object.values(toolStatuses).some(\n (s) => s?.type === \"executing\",\n );\n const providerIsRunning =\n chatHelpers.status === \"submitted\" || chatHelpers.status === \"streaming\";\n const isRunning = providerIsRunning || hasExecutingTools;\n const wasProviderRunningRef = useRef(providerIsRunning);\n\n const messageTiming = useStreamingTiming(chatHelpers.messages, isRunning);\n\n // Flag the streaming message optimistic: its id can be swapped for a server\n // id mid-run, and the repository then drops the orphaned pre-swap id (#4037).\n const lastMessage = chatHelpers.messages.at(-1);\n const optimisticMessageId =\n isRunning && lastMessage?.role === \"assistant\" ? lastMessage.id : undefined;\n\n const cancelledMessageIds =\n cancelledMessages?.chatId === chatHelpers.id\n ? cancelledMessages.ids\n : NO_CANCELLED_MESSAGE_IDS;\n const supportsRichToolApprovalResponses =\n customOnRespondToToolApproval != null;\n const supersededApprovalProjectionRef = useRef(\n NO_SUPERSEDED_APPROVAL_PROJECTION,\n );\n const supersededApprovalProjection = useMemo(\n () => {\n const projection = getSupersededApprovalProjection(\n chatHelpers.messages,\n hostApprovalIdsRef.current,\n joinStrategy,\n isRunning,\n );\n const previous = supersededApprovalProjectionRef.current;\n if (\n projection.approvalIds.size === previous.approvalIds.size &&\n projection.statusMessageIds.size === previous.statusMessageIds.size &&\n [...projection.approvalIds].every((id) =>\n previous.approvalIds.has(id),\n ) &&\n [...projection.statusMessageIds].every((id) =>\n previous.statusMessageIds.has(id),\n )\n )\n return previous;\n\n supersededApprovalProjectionRef.current = projection;\n return projection;\n },\n // oxlint-disable-next-line react/exhaustive-deps -- hostApprovalIdsRef changes alongside toolApprovalResponses, which invalidates the projection\n [chatHelpers.messages, joinStrategy, isRunning, toolApprovalResponses],\n );\n\n const toThreadMessages = useCallback(\n (sourceMessages: UI_MESSAGE[]) => {\n const metadata: AISDKMessageConverterMetadata = {\n supportsRichToolApprovalResponses,\n toolArtifacts: toolArtifactsRef.current,\n toolInteractions: toolInteractionsRef.current,\n toolApprovalResponses: toolApprovalResponsesRef.current,\n };\n return AISDKMessageConverter.toThreadMessages(\n sourceMessages,\n false,\n metadata,\n );\n },\n [supportsRichToolApprovalResponses],\n );\n\n const retractCancellation = useCallback(\n (chatId: string, messageId: string) => {\n setCancelledMessages((prev) => {\n if (prev?.chatId !== chatId || !prev.ids.has(messageId)) return prev;\n const ids = new Set(prev.ids);\n ids.delete(messageId);\n return { chatId, ids };\n });\n },\n [],\n );\n\n // A provider run that resumes the stopped response retracts its cancellation;\n // a run that starts a new response leaves the stopped one marked.\n const resumedMessageId =\n providerIsRunning && lastMessage?.role === \"assistant\"\n ? lastMessage.id\n : undefined;\n\n useEffect(() => {\n const wasProviderRunning = wasProviderRunningRef.current;\n wasProviderRunningRef.current = providerIsRunning;\n if (wasProviderRunning || !resumedMessageId) return;\n retractCancellation(chatHelpers.id, resumedMessageId);\n }, [\n providerIsRunning,\n resumedMessageId,\n chatHelpers.id,\n retractCancellation,\n ]);\n\n const messages = AISDKMessageConverter.useThreadMessages({\n isRunning,\n messages: chatHelpers.messages,\n joinStrategy,\n metadata: useMemo<AISDKMessageConverterMetadata>(\n () => ({\n toolStatuses,\n messageTiming,\n toolArgsKeyOrderCache: toolArgsKeyOrderCacheRef.current,\n toolArgsTextCache: toolArgsTextCacheRef.current,\n toolLastInputCache: toolLastInputCacheRef.current,\n mcpAppMetadataCache: mcpAppMetadataCacheRef.current,\n toolArtifacts: toolArtifactsRef.current,\n toolInteractions: toolInteractionsRef.current,\n supportsRichToolApprovalResponses,\n cancelledToolApprovalIds: supersededApprovalProjection.approvalIds,\n cancelledStatusMessageIds:\n supersededApprovalProjection.statusMessageIds,\n ...(optimisticMessageId && { optimisticMessageId }),\n ...(chatHelpers.error && {\n error: toChatError(chatHelpers.error),\n }),\n ...(cancelledMessageIds.size > 0 && { cancelledMessageIds }),\n ...(toolApprovalResponses.size > 0 && { toolApprovalResponses }),\n }),\n [\n toolStatuses,\n messageTiming,\n optimisticMessageId,\n chatHelpers.error,\n cancelledMessageIds,\n toolApprovalResponses,\n supportsRichToolApprovalResponses,\n supersededApprovalProjection,\n toolArtifactEpoch,\n toolInteractionEpoch,\n ],\n ),\n });\n\n const exportedMessageRepository = useMemo(() => {\n if (!messageRepository) return undefined;\n const converted = toExportedMessageRepository(\n toThreadMessages,\n messageRepository,\n );\n return converted.messages.length > 0 ? converted : undefined;\n }, [messageRepository, toThreadMessages]);\n\n const generatedSuggestions = useGeneratedSuggestions(\n suggestionAdapter,\n messages,\n isRunning,\n );\n\n const [runtimeRef] = useState(() => ({\n get current(): AssistantRuntime {\n return runtime;\n },\n }));\n\n const {\n isLoading,\n deleteMessage: deleteHistoryMessage,\n persistToolInteractions,\n persistToolApprovalResponses,\n } = useExternalHistory(\n runtimeRef,\n adapters?.history ?? contextAdapters?.history,\n toThreadMessages,\n aiSDKV6FormatAdapter as MessageFormatAdapter<\n UI_MESSAGE,\n AISDKStorageFormat\n >,\n (messages) => {\n chatHelpers.setMessages(messages);\n },\n toolArtifactsRef.current,\n markToolArtifactsChanged,\n toolInteractionsRef.current,\n markToolInteractionsChanged,\n toolApprovalResponsesRef.current,\n () => {\n for (const [id, entry] of ownedApprovals ?? []) {\n toolApprovalResponsesRef.current.set(id, entry.response);\n }\n hostApprovalIdsRef.current = new Set(\n toolApprovalResponsesRef.current.keys(),\n );\n setToolApprovalResponses(new Map(toolApprovalResponsesRef.current));\n },\n );\n\n const {\n id: chatId,\n messages: chatMessages,\n status: chatStatus,\n error,\n } = chatHelpers;\n const extras = useMemo(\n () =>\n aiSDKExtras.provide({\n chat: chatHelpers as unknown as UseChatHelpers<UIMessage>,\n error,\n }),\n // oxlint-disable-next-line react/exhaustive-deps -- keyed on the chat's identity and reactive snapshots; useChat re-mints the helpers object every render while its remaining fields are instance-bound methods, and a render-stable extras identity is what lets the external-store core dedupe adapter updates\n [chatId, chatMessages, chatStatus, error],\n );\n\n const completePendingToolCalls = async () => {\n if (!cancelPendingToolCallsOnSend) return;\n\n // The runtime auto-aborts in-flight tool invocations when a new run\n // is dispatched (append() / startRun()), so this only has to mark the\n // abandoned tools cancelled in the UI message list. Every non-terminal\n // tool call qualifies wherever it sits: the run that produced it is over,\n // and a staged `startRun: false` message can sit between it and the tail.\n // Uses setMessages to avoid triggering sendAutomaticallyWhen.\n chatHelpers.setMessages((messages) => {\n let hasChanges = false;\n\n const next = messages.map((message) => {\n if (message.role !== \"assistant\") return message;\n\n let messageChanged = false;\n const parts = message.parts?.map((part) => {\n if (!isToolUIPart(part)) return part;\n if (\n part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\"\n )\n return part;\n\n messageChanged = true;\n const { approval: _approval, ...rest } = part;\n return {\n ...rest,\n state: \"output-error\" as const,\n errorText: \"User cancelled tool call by sending a new message.\",\n };\n });\n\n if (!messageChanged) return message;\n hasChanges = true;\n return { ...message, parts };\n });\n\n if (!hasChanges) return messages;\n return next;\n });\n };\n\n const respondViaAISDK = ({\n approvalId,\n approved,\n reason,\n }: RespondToToolApprovalOptions) =>\n Promise.resolve(\n chatHelpers.addToolApprovalResponse({\n id: approvalId,\n approved,\n ...(reason != null && { reason }),\n options: { metadata: lastRunConfigRef.current },\n }),\n );\n\n const respondViaHost = async (\n onRespond: NonNullable<AISDKRuntimeAdapter[\"onRespondToToolApproval\"]>,\n response: RespondToToolApprovalOptions,\n ) => {\n const { approvalId } = response;\n const requested = chatHelpers.messages\n .flatMap((message) =>\n message.parts.flatMap((part) =>\n isToolUIPart(part) ? [{ messageId: message.id, part }] : [],\n ),\n )\n .find(\n ({ part }) =>\n part.state === \"approval-requested\" &&\n part.approval?.id === approvalId,\n );\n if (!requested || hostApprovalIdsRef.current.has(approvalId))\n throw new Error(\n `Tool approval ${approvalId} is not waiting for a response.`,\n );\n\n // A host answer stays out of the useChat messages, where sendAutomaticallyWhen would forward it to the chat route.\n // The owner can change while a response is in flight, and the id set is a\n // ref that is reseeded when it does. Both writes are therefore scoped to\n // the record this response started under, so a rollback never reaches a\n // different chat's state.\n const startedWith = ownedApprovals;\n const startedOwner = approvalOwner;\n const startedResponses = toolApprovalResponsesRef.current;\n // Whether this response is currently applied, tracked here rather than\n // read back from the id ref: that ref follows the chat on screen and is\n // reseeded when the owner changes, so it cannot answer for this response.\n let isApplied = false;\n const applyResponse = (applied: boolean) => {\n isApplied = applied;\n // The captured record is always corrected, so a rollback reaches the\n // chat the response belongs to even after the owner moved on.\n if (applied)\n startedWith?.set(approvalId, {\n response,\n });\n else startedWith?.delete(approvalId);\n\n if (startedOwner) {\n // Every runtime mounted over that owner re-reads the record, including\n // one mounted after this response started.\n notifyHostApprovals(startedOwner);\n return;\n }\n\n if (lastApprovalOwnerRef.current !== startedOwner) return;\n if (applied) hostApprovalIdsRef.current.add(approvalId);\n else hostApprovalIdsRef.current.delete(approvalId);\n if (applied) toolApprovalResponsesRef.current.set(approvalId, response);\n else toolApprovalResponsesRef.current.delete(approvalId);\n setToolApprovalResponses(new Map(toolApprovalResponsesRef.current));\n };\n\n applyResponse(true);\n try {\n await onRespond(response, {\n toolCallId: requested.part.toolCallId,\n toolName: getToolName(requested.part),\n respondViaAISDK: async () => {\n try {\n await respondViaAISDK(response);\n } finally {\n applyResponse(false);\n }\n },\n });\n } catch (error) {\n if (isApplied) applyResponse(false);\n throw error;\n }\n const remainsApplied =\n startedWith?.has(approvalId) ?? startedResponses.has(approvalId);\n if (isApplied && remainsApplied) {\n await persistToolApprovalResponses(requested.messageId);\n }\n };\n\n const hasSeededRepositoryRef = useRef(false);\n const shouldFeedRepository =\n exportedMessageRepository != null &&\n !hasSeededRepositoryRef.current &&\n messages.length === 0;\n\n const runtime = useExternalStoreRuntime({\n unstable_persistsHistory: true,\n isRunning: providerIsRunning,\n ...(shouldFeedRepository\n ? { messageRepository: exportedMessageRepository }\n : { messages }),\n unstable_enableToolInvocations: true,\n setToolStatuses,\n setMessages: (messages) =>\n chatHelpers.setMessages(\n messages\n .map(getVercelAIMessages<UI_MESSAGE>)\n .filter(Boolean)\n .flat(),\n ),\n onImport: (messages) =>\n chatHelpers.setMessages(\n messages\n .map(getVercelAIMessages<UI_MESSAGE>)\n .filter(Boolean)\n .flat(),\n ),\n onVoiceTranscript: (message: ThreadMessage) =>\n chatHelpers.setMessages((current) => [\n ...current,\n toVoiceTranscriptUIMessage<UI_MESSAGE>(message),\n ]),\n onExportExternalState: (): MessageFormatRepository<UI_MESSAGE> => {\n const exported = runtimeRef.current.thread.export();\n\n const expandedMessages: MessageFormatItem<UI_MESSAGE>[] = [];\n const lastInnerIdMap = new Map<string, string>();\n\n for (const item of exported.messages) {\n const innerMessages = getExternalStoreMessages<UI_MESSAGE>(\n item.message,\n );\n let parentId =\n item.parentId != null\n ? (lastInnerIdMap.get(item.parentId) ?? item.parentId)\n : null;\n for (const innerMessage of innerMessages) {\n expandedMessages.push({ parentId, message: innerMessage });\n parentId = aiSDKV6FormatAdapter.getId(innerMessage as UIMessage);\n }\n if (innerMessages.length > 0) {\n lastInnerIdMap.set(\n item.message.id,\n aiSDKV6FormatAdapter.getId(\n innerMessages[innerMessages.length - 1]! as UIMessage,\n ),\n );\n }\n }\n\n const result: MessageFormatRepository<UI_MESSAGE> = {\n messages: expandedMessages,\n };\n\n if (exported.headId != null) {\n result.headId = lastInnerIdMap.get(exported.headId) ?? exported.headId;\n }\n\n return result;\n },\n onLoadExternalState: (repo: MessageFormatRepository<UI_MESSAGE>) => {\n // Convert MessageFormatRepository to ExportedMessageRepository\n const exportedRepo = toExportedMessageRepository(toThreadMessages, repo);\n\n // Import into the thread's MessageRepository\n runtimeRef.current.thread.import(exportedRepo);\n },\n onCancel: async () => {\n const message = chatHelpers.messages.at(-1);\n const cancelledId =\n isRunning && message?.role === \"assistant\" ? message.id : undefined;\n if (cancelledId) {\n const liveIds = new Set(chatHelpers.messages.map((m) => m.id));\n setCancelledMessages((prev) => {\n const kept =\n prev?.chatId === chatHelpers.id\n ? [...prev.ids].filter((id) => liveIds.has(id))\n : [];\n return {\n chatId: chatHelpers.id,\n ids: new Set([...kept, cancelledId]),\n };\n });\n }\n try {\n await chatHelpers.stop();\n } catch (error) {\n if (!(error instanceof Error && error.name === \"AbortError\")) {\n if (cancelledId) retractCancellation(chatHelpers.id, cancelledId);\n throw error;\n }\n }\n },\n onNew: async (message) => {\n const createMessage = (\n customToCreateMessage ?? toCreateMessage\n )<UI_MESSAGE>(message);\n\n if (!(message.startRun ?? message.role === \"user\")) {\n chatHelpers.setMessages((current) => [\n ...current,\n toUIMessage<UI_MESSAGE>(createMessage, message.role),\n ]);\n return;\n }\n\n lastRunConfigRef.current = message.runConfig;\n await completePendingToolCalls();\n await chatHelpers.sendMessage(createMessage, {\n metadata: message.runConfig,\n });\n },\n onEdit: async (message) => {\n const createMessage = (\n customToCreateMessage ?? toCreateMessage\n )<UI_MESSAGE>(message);\n\n if (!(message.startRun ?? message.role === \"user\")) {\n chatHelpers.setMessages((current) => [\n ...sliceMessagesUntil(current, message.parentId),\n toUIMessage<UI_MESSAGE>(createMessage, message.role),\n ]);\n return;\n }\n\n lastRunConfigRef.current = message.runConfig;\n chatHelpers.setMessages((current) =>\n sliceMessagesUntil(current, message.parentId),\n );\n await chatHelpers.sendMessage(createMessage, {\n metadata: message.runConfig,\n });\n },\n onDelete: async (messageId) => {\n const threadMessages = runtimeRef.current.thread.getState().messages;\n const messageIndex = threadMessages.findIndex(\n (message) => message.id === messageId,\n );\n if (messageIndex === -1) return;\n\n await deleteHistoryMessage(messageId);\n\n let removedToolArtifact = false;\n let removedToolInteractions = false;\n let removedToolApprovalResponse = false;\n let removedHostApprovalId = false;\n for (const part of threadMessages[messageIndex]!.content) {\n if (part.type === \"tool-call\") {\n removedToolArtifact =\n toolArtifactsRef.current.delete(part.toolCallId) ||\n removedToolArtifact;\n removedToolInteractions =\n toolInteractionsRef.current.delete(part.toolCallId) ||\n removedToolInteractions;\n if (part.approval) {\n ownedApprovals?.delete(part.approval.id);\n removedToolApprovalResponse =\n toolApprovalResponsesRef.current.delete(part.approval.id) ||\n removedToolApprovalResponse;\n removedHostApprovalId =\n hostApprovalIdsRef.current.delete(part.approval.id) ||\n removedHostApprovalId;\n }\n }\n }\n if (removedToolArtifact) markToolArtifactsChanged();\n if (removedToolInteractions) markToolInteractionsChanged();\n if (removedToolApprovalResponse || removedHostApprovalId) {\n if (approvalOwner) notifyHostApprovals(approvalOwner);\n setToolApprovalResponses(new Map(toolApprovalResponsesRef.current));\n }\n\n const deleteIds = new Set(\n getExternalStoreMessages<UI_MESSAGE>(threadMessages[messageIndex]!).map(\n (message) => message.id,\n ),\n );\n chatHelpers.setMessages((current) =>\n current.filter((message) => !deleteIds.has(message.id)),\n );\n },\n onReload: async (parentId: string | null, config) => {\n lastRunConfigRef.current = config.runConfig;\n const newMessages = sliceMessagesUntil(chatHelpers.messages, parentId);\n chatHelpers.setMessages(newMessages);\n\n await chatHelpers.regenerate({ metadata: config.runConfig });\n },\n onAddToolResult: ({\n messageId,\n toolCallId,\n toolName,\n result,\n isError,\n artifact,\n modelContent,\n }) => {\n if (artifact !== undefined) {\n toolArtifactsRef.current.set(toolCallId, artifact);\n markToolArtifactsChanged();\n }\n\n const targetIndex = findRawToolMessageIndex(\n chatHelpers.messages,\n messageId,\n toolCallId,\n joinStrategy,\n );\n\n const errorText =\n typeof result === \"string\" ? result : JSON.stringify(result);\n const output =\n !isError && modelContent !== undefined\n ? wrapModelContentEnvelope(result, modelContent)\n : result;\n\n if (targetIndex >= 0 && targetIndex !== chatHelpers.messages.length - 1) {\n const target = chatHelpers.messages[targetIndex]!;\n const targetPart = target.parts.find(\n (part) => isToolUIPart(part) && part.toolCallId === toolCallId,\n ) as { state?: string; preliminary?: boolean } | undefined;\n // An earlier message's settled output may already have reached the model, as the error a cancelling send writes does.\n if (\n targetPart?.state === \"output-error\" ||\n targetPart?.state === \"output-denied\" ||\n (targetPart?.state === \"output-available\" && !targetPart.preliminary)\n )\n return Promise.resolve();\n\n const targetMessageId = target.id;\n chatHelpers.setMessages((current) =>\n current.map((message) => {\n if (message.id !== targetMessageId) return message;\n\n return {\n ...message,\n parts: message.parts.map((part) => {\n if (!isToolUIPart(part) || part.toolCallId !== toolCallId)\n return part;\n\n const { preliminary: _preliminary, ...finalPart } =\n part as typeof part & { preliminary?: boolean };\n return {\n ...finalPart,\n state: isError\n ? (\"output-error\" as const)\n : (\"output-available\" as const),\n output: isError ? undefined : output,\n errorText: isError ? errorText : undefined,\n } as typeof part;\n }),\n };\n }),\n );\n return Promise.resolve();\n }\n\n const options = { metadata: lastRunConfigRef.current };\n if (isError) {\n return Promise.resolve(\n chatHelpers.addToolOutput({\n state: \"output-error\",\n tool: toolName ?? toolCallId,\n toolCallId,\n errorText,\n options,\n }),\n );\n }\n\n return Promise.resolve(\n chatHelpers.addToolOutput({\n tool: toolName,\n toolCallId,\n output,\n options,\n }),\n );\n },\n onRespondToToolApproval: (response) => {\n if (supersededApprovalProjection.approvalIds.has(response.approvalId))\n return Promise.reject(\n new Error(\n `Tool approval ${response.approvalId} is not waiting for a response.`,\n ),\n );\n return customOnRespondToToolApproval\n ? respondViaHost(customOnRespondToToolApproval, response)\n : respondViaAISDK(response);\n },\n unstable_onRecordToolInteraction: ({\n messageId,\n toolCallId,\n interaction,\n }) => {\n toolInteractionsRef.current.set(\n toolCallId,\n appendToolInteraction(\n toolInteractionsRef.current.get(toolCallId),\n interaction,\n ),\n );\n markToolInteractionsChanged();\n return persistToolInteractions(messageId);\n },\n ...pickExternalStoreSharedOptions(adapter),\n ...(adapter.unstable_messageRepositoryInstance && {\n unstable_messageRepositoryInstance:\n adapter.unstable_messageRepositoryInstance,\n }),\n ...(suggestionAdapter ? { suggestions: generatedSuggestions } : {}),\n ...(onResume && { onResume }),\n ...(onResumeToolCall && { onResumeToolCall }),\n ...(unstable_onBranchChange && { unstable_onBranchChange }),\n adapters: {\n attachments: vercelAttachmentAdapter,\n ...contextAdapters,\n ...adapters,\n },\n extras,\n isLoading,\n });\n\n const setMessagesRef = useRef(chatHelpers.setMessages);\n useInsertionEffect(() => {\n setMessagesRef.current = chatHelpers.setMessages;\n }, [chatHelpers.setMessages]);\n\n useEffect(() => {\n if (hasSeededRepositoryRef.current) return;\n if (!exportedMessageRepository) return;\n if (chatHelpers.messages.length > 0) {\n hasSeededRepositoryRef.current = true;\n return;\n }\n const tempRepo = new MessageRepository();\n tempRepo.import(exportedMessageRepository);\n setMessagesRef.current(\n tempRepo.getMessages().flatMap(getExternalStoreMessages<UI_MESSAGE>),\n );\n hasSeededRepositoryRef.current = true;\n }, [exportedMessageRepository, chatHelpers.messages.length]);\n return runtime;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgFA,MAAM0D,eACJC,eACAC,kBAEC;CACC,GAAGD;CACHE,IAAIF,cAAcE,MAAMhD,WAAW;CACnCiD,MAAMH,cAAcG,QAAQF;AAC9B;AAEF,MAAMG,8BACJP,aAEC;CACCK,IAAIL,QAAQK;CACZC,MAAMN,QAAQM;CACdE,OAAOR,QAAQS,QACZC,QAAQC,SAASA,KAAKC,SAAS,MAAM,CAAC,CACtCC,KAAKF,UAAU;EAAEC,MAAM;EAAQE,MAAMH,KAAKG;CAAK,EAAE;CACpDC,UAAU;EACR,GAAIf,QAAQe,SAASC,YAAY,EAAEA,UAAUhB,QAAQe,SAASC,SAAS;EACvE,GAAIC,OAAOC,KAAKlB,QAAQe,SAASI,MAAM,CAAC,CAACC,SAAS,KAAK,EACrDD,QAAQnB,QAAQe,SAASI,OAC3B;CACF;AACF;AAqFF,MAAMsB,oBAAiD,CAAA;AAEvD,MAAMC,2BAA0BC,mBAAAC,UAAAC,cAAA;CAAA,MAAAC,IAAArG,EAAA,EAAA;CAK9B,MAAA,CAAAsG,aAAAC,kBACEjG,SAAsC0F,iBAAiB;CACzD,MAAAQ,gBAAsBnG,OAA+B,IAAI;CACzD,MAAAoG,gBAAsBpG,OAAO,KAAK;CAClC,MAAAqG,cAAoBrG,OAAO8F,QAAQ;CAAE,IAAAQ;CAAA,IAAAC;CAAA,IAA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A,iBAAiB;EAC3C,GAAIU,2BAA2B,EAAEA,wBAAwB;EACzDlB,UAAU;GACRoS,aAAatU;GACb,GAAGyJ;GACH,GAAGvH;EACL;EACAqM;EACAR;CACF,CAAC;CAED,MAAMwG,iBAAiB7W,OAAO2L,YAAY+E,WAAW;CACrD5Q,yBAAyB;EACvB+W,eAAerQ,UAAUmF,YAAY+E;CACvC,GAAG,CAAC/E,YAAY+E,WAAW,CAAC;CAE5B7Q,gBAAgB;EACd,IAAI2S,uBAAuBhM,SAAS;EACpC,IAAI,CAACwJ,2BAA2B;EAChC,IAAIrE,YAAY7F,SAASxB,SAAS,GAAG;GACnCkO,uBAAuBhM,UAAU;GACjC;EACF;EACA,MAAMsQ,WAAW,IAAI7U,kBAAkB;EACvC6U,SAAS7C,OAAOjE,yBAAyB;EACzC6G,eAAerQ,QACbsQ,SAASC,YAAY,CAAC,CAAChF,QAAQlQ,wBAAoC,CACrE;EACA2Q,uBAAuBhM,UAAU;CACnC,GAAG,CAACwJ,2BAA2BrE,YAAY7F,SAASxB,MAAM,CAAC;CAC3D,OAAO8L;AACT;AAhkCgC,SAAApJ,MAAAoG,MAAA;CAAA,OAuBAA,KAAI9I,WAAY,IAAhB8I,OAAAzH;AAA4C"}
@@ -1 +1 @@
1
- {"version":3,"file":"useChatRuntime.js","names":["c","_c","UIMessage","AssistantCloud","AssistantRuntime","useCloudThreadListAdapter","useRemoteThreadListRuntime","useAui","useAuiState","useHostDestroySignal","useChatThread","ChatThreadOptions","AI_SDK_SDK","UseChatRuntimeOptions","UI_MESSAGE","cloud","onThreadIdChange","threadId","useChatThreadRuntime","options","hostDestroySignal","$","id","_temp","isMainThread","_temp2","aui","t0","threadListItem","source","undefined","t1","getThreadListItem","stopOnClientDestroy","useChatRuntime","cloudAdapter","sdk","runtimeHook","RuntimeHook","adapter","allowNesting","s","s_0","threads","mainThreadId"],"sources":["../../src/runtime/useChatRuntime.ts"],"sourcesContent":["\"use client\";\n\nimport type { UIMessage } from \"@ai-sdk/react\";\nimport type { AssistantCloud } from \"assistant-cloud\";\nimport type { AssistantRuntime } from \"@assistant-ui/core\";\nimport {\n useCloudThreadListAdapter,\n useRemoteThreadListRuntime,\n} from \"@assistant-ui/core/react\";\nimport { useAui, useAuiState } from \"@assistant-ui/store\";\nimport { useHostDestroySignal } from \"@assistant-ui/store/internal\";\nimport { useChatThread, type ChatThreadOptions } from \"./useChatThread\";\nimport { AI_SDK_SDK } from \"./sdkIdentity\";\n\nexport type UseChatRuntimeOptions<UI_MESSAGE extends UIMessage = UIMessage> =\n ChatThreadOptions<UI_MESSAGE> & {\n cloud?: AssistantCloud | undefined;\n onThreadIdChange?: ((threadId: string | undefined) => void) | undefined;\n };\n\nconst useChatThreadRuntime = <UI_MESSAGE extends UIMessage = UIMessage>(\n options: ChatThreadOptions<UI_MESSAGE> | undefined,\n hostDestroySignal: AbortSignal,\n): AssistantRuntime => {\n const id = useAuiState((s) => s.threadListItem.id);\n const isMainThread = useAuiState(\n (s) => s.threads.mainThreadId === s.threadListItem.id,\n );\n const aui = useAui();\n return useChatThread(options, {\n id,\n isMainThread,\n getThreadListItem: () =>\n aui.threadListItem.source ? aui.threadListItem : undefined,\n stopOnClientDestroy: true,\n hostDestroySignal,\n });\n};\n\nexport const useChatRuntime = <UI_MESSAGE extends UIMessage = UIMessage>({\n cloud,\n onThreadIdChange,\n ...options\n}: UseChatRuntimeOptions<UI_MESSAGE> = {}): AssistantRuntime => {\n const hostDestroySignal = useHostDestroySignal();\n const cloudAdapter = useCloudThreadListAdapter({ cloud, sdk: AI_SDK_SDK });\n return useRemoteThreadListRuntime({\n runtimeHook: function RuntimeHook() {\n return useChatThreadRuntime(options, hostDestroySignal);\n },\n adapter: cloudAdapter,\n allowNesting: true,\n onThreadIdChange,\n });\n};\n"],"mappings":";;;;;;;;AAoBA,MAAMkB,wBAAuBC,SAAAC,sBAAA;CAAA,MAAAC,IAAApB,EAAA,CAAA;CAI3B,MAAAqB,KAAWd,YAAYe,KAA0B;CACjD,MAAAC,eAAqBhB,YACnBiB,MACF;CACA,MAAAC,MAAYnB,OAAO;CAAE,IAAAoB;CAAA,IAAAN,EAAA,OAAAK,KAAA;EAIAC,WACjBD,IAAGE,eAAeC,SAAUH,IAAGE,iBAA/BE,KAAAA;EAA0DT,EAAA,KAAAK;EAAAL,EAAA,KAAAM;CAAA,OAAAA,KAAAN,EAAA;CAAA,IAAAU;CAAA,IAAAV,EAAA,OAAAD,qBAAAC,EAAA,OAAAC,MAAAD,EAAA,OAAAG,gBAAAH,EAAA,OAAAM,IAAA;EAJhCI,KAAA;GAAAT;GAAAE;GAAAQ,mBAGTL;GACyCM,qBACvC;GAAIb;EAE3B;EAACC,EAAA,KAAAD;EAAAC,EAAA,KAAAC;EAAAD,EAAA,KAAAG;EAAAH,EAAA,KAAAM;EAAAN,EAAA,KAAAU;CAAA,OAAAA,KAAAV,EAAA;CAAA,OAPMX,cAAcS,SAASY,EAO7B;AAAC;AAGJ,MAAaG,kBAA4D,EACvEnB,OACAC,kBACA,GAAGG,YACkC,CAAC,MAAwB;CAC9D,MAAMC,oBAAoBX,qBAAqB;CAC/C,MAAM0B,eAAe9B,0BAA0B;EAAEU;EAAOqB,KAAKxB;CAAW,CAAC;CACzE,OAAON,2BAA2B;EAChC+B,aAAa,SAASC,cAAc;GAClC,OAAOpB,qBAAqBC,SAASC,iBAAiB;EACxD;EACAmB,SAASJ;EACTK,cAAc;EACdxB;CACF,CAAC;AACH;AAlC6B,SAAAO,MAAAkB,GAAA;CAAA,OAIGA,EAACb,eAAeN;AAAG;AAJtB,SAAAG,OAAAiB,KAAA;CAAA,OAMlBD,IAACE,QAAQC,iBAAkBH,IAACb,eAAeN;AAAG"}
1
+ {"version":3,"file":"useChatRuntime.js","names":["c","_c","UIMessage","AssistantCloud","AssistantRuntime","useCloudThreadListAdapter","useRemoteThreadListRuntime","useAui","useAuiState","useHostDestroySignal","useChatThread","ChatThreadOptions","AI_SDK_SDK","UseChatRuntimeOptions","UI_MESSAGE","cloud","onThreadIdChange","threadId","useChatThreadRuntime","options","hostDestroySignal","$","id","_temp","isMainThread","_temp2","aui","t0","threadListItem","source","undefined","t1","getThreadListItem","stopOnClientDestroy","useChatRuntime","cloudAdapter","sdk","runtimeHook","RuntimeHook","adapter","allowNesting","s","s_0","threads","mainThreadId","_c"],"sources":["../../src/runtime/useChatRuntime.ts"],"sourcesContent":["\"use client\";\n\nimport type { UIMessage } from \"@ai-sdk/react\";\nimport type { AssistantCloud } from \"assistant-cloud\";\nimport type { AssistantRuntime } from \"@assistant-ui/core\";\nimport {\n useCloudThreadListAdapter,\n useRemoteThreadListRuntime,\n} from \"@assistant-ui/core/react\";\nimport { useAui, useAuiState } from \"@assistant-ui/store\";\nimport { useHostDestroySignal } from \"@assistant-ui/store/internal\";\nimport { useChatThread, type ChatThreadOptions } from \"./useChatThread\";\nimport { AI_SDK_SDK } from \"./sdkIdentity\";\n\nexport type UseChatRuntimeOptions<UI_MESSAGE extends UIMessage = UIMessage> =\n ChatThreadOptions<UI_MESSAGE> & {\n cloud?: AssistantCloud | undefined;\n onThreadIdChange?: ((threadId: string | undefined) => void) | undefined;\n };\n\nconst useChatThreadRuntime = <UI_MESSAGE extends UIMessage = UIMessage>(\n options: ChatThreadOptions<UI_MESSAGE> | undefined,\n hostDestroySignal: AbortSignal,\n): AssistantRuntime => {\n const id = useAuiState((s) => s.threadListItem.id);\n const isMainThread = useAuiState(\n (s) => s.threads.mainThreadId === s.threadListItem.id,\n );\n const aui = useAui();\n return useChatThread(options, {\n id,\n isMainThread,\n getThreadListItem: () =>\n aui.threadListItem.source ? aui.threadListItem : undefined,\n stopOnClientDestroy: true,\n hostDestroySignal,\n });\n};\n\nexport const useChatRuntime = <UI_MESSAGE extends UIMessage = UIMessage>({\n cloud,\n onThreadIdChange,\n ...options\n}: UseChatRuntimeOptions<UI_MESSAGE> = {}): AssistantRuntime => {\n const hostDestroySignal = useHostDestroySignal();\n const cloudAdapter = useCloudThreadListAdapter({ cloud, sdk: AI_SDK_SDK });\n return useRemoteThreadListRuntime({\n runtimeHook: function RuntimeHook() {\n return useChatThreadRuntime(options, hostDestroySignal);\n },\n adapter: cloudAdapter,\n allowNesting: true,\n onThreadIdChange,\n });\n};\n"],"mappings":";;;;;;;;AAoBA,MAAMkB,wBAAuBC,SAAAC,sBAAA;CAAA,MAAAC,IAAApB,EAAA,CAAA;CAI3B,MAAAqB,KAAWd,YAAYe,KAA0B;CACjD,MAAAC,eAAqBhB,YACnBiB,MACF;CACA,MAAAC,MAAYnB,OAAO;CAAE,IAAAoB;CAAA,IAAAN,EAAA,OAAAK,KAAA;EAIAC,WACjBD,IAAGE,eAAeC,SAAUH,IAAGE,iBAA/BE,KAAAA;EAA0DT,EAAA,KAAAK;EAAAL,EAAA,KAAAM;CAAA,OAAAA,KAAAN,EAAA;CAAA,IAAAU;CAAA,IAAAV,EAAA,OAAAD,qBAAAC,EAAA,OAAAC,MAAAD,EAAA,OAAAG,gBAAAH,EAAA,OAAAM,IAAA;EAJhCI,KAAA;GAAAT;GAAAE;GAAAQ,mBAGTL;GACyCM,qBACvC;GAAIb;EAE3B;EAACC,EAAA,KAAAD;EAAAC,EAAA,KAAAC;EAAAD,EAAA,KAAAG;EAAAH,EAAA,KAAAM;EAAAN,EAAA,KAAAU;CAAA,OAAAA,KAAAV,EAAA;CAAA,OAPMX,cAAcS,SAASY,EAO7B;AAAC;AAGJ,MAAaG,kBAA4D,EACvEnB,OACAC,kBACA,GAAGG,YACkC,CAAC,MAAwB;CAC9D,MAAMC,oBAAoBX,qBAAqB;CAC/C,MAAM0B,eAAe9B,0BAA0B;EAAEU;EAAOqB,KAAKxB;CAAW,CAAC;CACzE,OAAON,2BAA2B;EAChC+B,aAAa,SAASC,cAAc;GAClC,OAAOpB,qBAAqBC,SAASC,iBAAiB;EACxD;EACAmB,SAASJ;EACTK,cAAc;EACdxB;CACF,CAAC;AACH;AAlC6B,SAAAO,MAAAkB,GAAA;CAAA,OAIGA,EAACb,eAAeN;AAAG;AAJtB,SAAAG,OAAAiB,KAAA;CAAA,OAMlBD,IAACE,QAAQC,iBAAkBH,IAACb,eAAeN;AAAG"}
@@ -1 +1 @@
1
- {"version":3,"file":"useExternalHistory.d.ts","sourceRoot":"","sources":["../../src/runtime/useExternalHistory.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,gBAAgB,EAChB,oBAAoB,EACpB,aAAa,EACb,oBAAoB,EAEpB,uBAAuB,EACvB,yBAAyB,EACzB,4BAA4B,EAC5B,2BAA2B,EAC5B,MAAM,oBAAoB,CAAC;AAO5B,OAAO,EAIL,KAAK,SAAS,EAGf,MAAM,OAAO,CAAC;AAEf,eAAO,MAAM,2BAA2B,GAAI,QAAQ,EAClD,kBAAkB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE,EAC3D,UAAU,uBAAuB,CAAC,QAAQ,CAAC,KAC1C,yBAoBF,CAAC;AAmOF,eAAO,MAAM,kBAAkB,GAAI,QAAQ,EACzC,YAAY,SAAS,CAAC,gBAAgB,CAAC,EACvC,gBAAgB,oBAAoB,GAAG,SAAS,EAChD,kBAAkB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE,EAC3D,sBAAsB,oBAAoB,CAAC,QAAQ,EAAE,GAAG,CAAC,EACzD,eAAe,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,IAAI,EAC7C,gBAAgB,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,EACpC,0BAA0B,MAAM,IAAI,EACpC,mBAAmB,GAAG,CAAC,MAAM,EAAE,2BAA2B,CAAC,EAC3D,6BAA6B,MAAM,IAAI,EACvC,wBAAwB,GAAG,CAAC,MAAM,EAAE,4BAA4B,CAAC,EACjE,kCAAkC,MAAM,IAAI;;+BA+dxB,MAAM;yCA3UZ,MAAM;8CAAN,MAAM;CAyXrB,CAAC"}
1
+ {"version":3,"file":"useExternalHistory.d.ts","sourceRoot":"","sources":["../../src/runtime/useExternalHistory.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,gBAAgB,EAChB,oBAAoB,EACpB,aAAa,EACb,oBAAoB,EAEpB,uBAAuB,EACvB,yBAAyB,EACzB,4BAA4B,EAC5B,2BAA2B,EAC5B,MAAM,oBAAoB,CAAC;AAO5B,OAAO,EAIL,KAAK,SAAS,EAGf,MAAM,OAAO,CAAC;AAGf,eAAO,MAAM,2BAA2B,GAAI,QAAQ,EAClD,kBAAkB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE,EAC3D,UAAU,uBAAuB,CAAC,QAAQ,CAAC,KAC1C,yBAoBF,CAAC;AAsOF,eAAO,MAAM,kBAAkB,GAAI,QAAQ,EACzC,YAAY,SAAS,CAAC,gBAAgB,CAAC,EACvC,gBAAgB,oBAAoB,GAAG,SAAS,EAChD,kBAAkB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE,EAC3D,sBAAsB,oBAAoB,CAAC,QAAQ,EAAE,GAAG,CAAC,EACzD,eAAe,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,IAAI,EAC7C,gBAAgB,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,EACpC,0BAA0B,MAAM,IAAI,EACpC,mBAAmB,GAAG,CAAC,MAAM,EAAE,2BAA2B,CAAC,EAC3D,6BAA6B,MAAM,IAAI,EACvC,wBAAwB,GAAG,CAAC,MAAM,EAAE,4BAA4B,CAAC,EACjE,kCAAkC,MAAM,IAAI;;+BA+dxB,MAAM;yCA3UZ,MAAM;8CAAN,MAAM;CAyXrB,CAAC"}
@@ -1,4 +1,5 @@
1
1
  "use client";
2
+ import { normalizeToolApprovalAnswers } from "../converters/toolApprovalAnswers.js";
2
3
  import { MessageRepository, readToolInteractionLog } from "@assistant-ui/core/internal";
3
4
  import { getExternalStoreMessages } from "@assistant-ui/core";
4
5
  import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
@@ -59,6 +60,7 @@ const collectToolApprovalResponses = (message, toolApprovalResponses) => {
59
60
  approved: response.approved,
60
61
  ...response.optionId != null && { optionId: response.optionId },
61
62
  ...response.text != null && { text: response.text },
63
+ ...response.answers != null && { answers: response.answers },
62
64
  ...response.reason != null && { reason: response.reason }
63
65
  }]];
64
66
  });
@@ -110,11 +112,13 @@ const restoreToolData = (message, toolArtifacts, toolInteractions, toolApprovalR
110
112
  const approvalResponses = metadata[TOOL_APPROVAL_RESPONSES_METADATA_KEY];
111
113
  if (toolApprovalResponses && isRecord(approvalResponses)) for (const [approvalId, value] of Object.entries(approvalResponses)) {
112
114
  if (!isRecord(value) || typeof value.approved !== "boolean") continue;
115
+ const answers = normalizeToolApprovalAnswers(value.answers);
113
116
  toolApprovalResponses.set(approvalId, {
114
117
  approvalId,
115
118
  approved: value.approved,
116
119
  ...typeof value.optionId === "string" && { optionId: value.optionId },
117
120
  ...typeof value.text === "string" && { text: value.text },
121
+ ...answers && Object.keys(answers).length > 0 && { answers },
118
122
  ...typeof value.reason === "string" && { reason: value.reason }
119
123
  });
120
124
  }