@copilotkit/react-core 2.0.0-rc.30 → 2.0.0-rc.32

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 (34) hide show
  1. package/README.md +1 -1
  2. package/dist/MarkdownRendererContext-CPfNVyde.d.mts +241 -0
  3. package/dist/MarkdownRendererContext-CPfNVyde.d.mts.map +1 -0
  4. package/dist/MarkdownRendererContext-iOl2pj9l.d.cts +241 -0
  5. package/dist/MarkdownRendererContext-iOl2pj9l.d.cts.map +1 -0
  6. package/dist/MarkdownSurfaces-BFoO6wSB.cjs +1650 -0
  7. package/dist/MarkdownSurfaces-BFoO6wSB.cjs.map +1 -0
  8. package/dist/MarkdownSurfaces-BQ1HGCzB.mjs +1442 -0
  9. package/dist/MarkdownSurfaces-BQ1HGCzB.mjs.map +1 -0
  10. package/dist/generative-ui.cjs +687 -2964
  11. package/dist/generative-ui.cjs.map +1 -1
  12. package/dist/generative-ui.d.cts +2478 -2683
  13. package/dist/generative-ui.d.cts.map +1 -1
  14. package/dist/generative-ui.d.mts +2477 -2682
  15. package/dist/generative-ui.d.mts.map +1 -1
  16. package/dist/generative-ui.mjs +299 -2585
  17. package/dist/generative-ui.mjs.map +1 -1
  18. package/dist/index.cjs +26 -1367
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +1 -1
  21. package/dist/index.d.mts +1 -1
  22. package/dist/index.mjs +11 -1352
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/index.umd.js +124 -3358
  25. package/dist/index.umd.js.map +1 -1
  26. package/package.json +9 -9
  27. package/dist/MarkdownRendererContext-BX26QLwl.d.cts +0 -937
  28. package/dist/MarkdownRendererContext-BX26QLwl.d.cts.map +0 -1
  29. package/dist/MarkdownRendererContext-DAOMewji.d.mts +0 -937
  30. package/dist/MarkdownRendererContext-DAOMewji.d.mts.map +0 -1
  31. package/dist/MarkdownSurfaces-BbrHcSHN.cjs +0 -3903
  32. package/dist/MarkdownSurfaces-BbrHcSHN.cjs.map +0 -1
  33. package/dist/MarkdownSurfaces-DQbRS91-.mjs +0 -3587
  34. package/dist/MarkdownSurfaces-DQbRS91-.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
 
3
- import { A as ExpressionError, B as renderSlot, C as issueKey, D as getMarkdownSurfaceSource, E as containsDynamicValue, F as toJsonSchema, G as CopilotIcon, H as CopilotChatConfigurationProvider, I as defineToolCallRenderer, J as StreamingMarkdownDefaultRenderer, L as MarkdownRendererProvider, M as catalogIdsOf, N as componentCatalogIds, R as useMarkdownRenderer, S as isAsyncIssue, T as withoutRejectedNulls, U as useCopilotChatConfiguration, V as ControlledModalOpenScope, W as useShallowStableRef, a as GenerativeUIToolCallRenderer, i as GenerativeUIChatSlotContext, j as GenerativeUIError, k as BASIC_FUNCTIONS, o as createGenerativeUIActivityRenderer, q as cn, s as createGenerativeUIFunctionCallActivityRenderer, t as MarkdownSurfaces, v as GenerativeUIRuntimeContext, w as validateSchemaSync, x as formatIssues, y as useGenerativeUIRuntime, z as isReactComponentType } from "./MarkdownSurfaces-DQbRS91-.mjs";
3
+ import { A as useShallowStableRef, C as MarkdownRendererProvider, D as ControlledModalOpenScope, E as renderSlot, N as cn, O as CopilotChatConfigurationProvider, P as StreamingMarkdownDefaultRenderer, S as defineToolCallRenderer, T as isReactComponentType, _ as GenerativeUIRuntimeContext, a as GenerativeUIToolCallRenderer, b as catalogIdsOf, i as GenerativeUIChatSlotContext, j as CopilotIcon, k as useCopilotChatConfiguration, o as createGenerativeUIActivityRenderer, s as createGenerativeUIFunctionCallActivityRenderer, t as MarkdownSurfaces, v as useGenerativeUIRuntime, w as useMarkdownRenderer } from "./MarkdownSurfaces-BQ1HGCzB.mjs";
4
4
  import { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotChatDefaultLabels, CopilotChatDefaultLabels as CopilotChatDefaultLabels$1, CopilotKitCore, CopilotKitCore as CopilotKitCore$1, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, CopilotKitCoreRuntimeConnectionStatus as CopilotKitCoreRuntimeConnectionStatus$1, CopilotKitHeaderResolutionError, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL, GENERATE_SANDBOXED_UI_TOOL_NAME, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, INTERRUPT_EVENT_NAME, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, OPEN_GENERATIVE_UI_ACTIVITY_TYPE, OPEN_GENERATIVE_UI_ACTIVITY_TYPE as OPEN_GENERATIVE_UI_ACTIVITY_TYPE$1, ProxiedCopilotRuntimeAgent, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, ToolCallStatus as ToolCallStatus$1, TranscriptionError, TranscriptionErrorCode, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵA2UIActivityController, ɵA2UIActivityController as ɵA2UIActivityController$1, ɵA2UI_DEFAULT_SURFACE_ID, ɵA2UI_LIFECYCLE_TEXT, ɵA2UI_LIFECYCLE_TEXT as ɵA2UI_LIFECYCLE_TEXT$1, ɵA2UI_OPERATIONS_KEY, ɵA2UI_PAINT_FALLBACK_MS, ɵA2UI_RECOVERY_DEFAULTS, ɵA2UI_ROOT_COMPONENT_ID, ɵA2UI_SKELETON_ROWS, ɵA2UI_SKELETON_ROWS as ɵA2UI_SKELETON_ROWS$1, ɵA2UI_SURFACE_ACTIVITY_TYPE, ɵA2UI_SURFACE_ACTIVITY_TYPE as ɵA2UI_SURFACE_ACTIVITY_TYPE$1, ɵA2UI_SURFACE_CONTENT_SCHEMA, ɵA2UI_SURFACE_CONTENT_SCHEMA as ɵA2UI_SURFACE_CONTENT_SCHEMA$1, ɵALL_AGENT_UPDATES, ɵAgentResolver, ɵAttachmentQueue, ɵAttachmentQueue as ɵAttachmentQueue$1, ɵAudioRecorder, ɵAudioRecorder as ɵAudioRecorder$1, ɵAudioRecorderError, ɵAudioRecorderError as AudioRecorderError, ɵCOMPOSER_DEFAULT_MAX_ROWS, ɵCOPILOTKIT_FEATURES, ɵCOPILOT_CLOUD_PUBLIC_API_KEY_HEADER, ɵCOPILOT_CLOUD_RUNTIME_URL, ɵCOPY_FEEDBACK_RESET_MS, ɵChatConfigurationStore, ɵChatConnection, ɵChatConnection as ɵChatConnection$1, ɵChatSubmitter, ɵComposerAutosize, ɵComposerController, ɵComposerController as ɵComposerController$1, ɵCopyFeedback, ɵCopyFeedback as ɵCopyFeedback$1, ɵDockedSidebar, ɵDockedSidebarRegistry, ɵExitPresence, ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS, ɵFeedbackCommentController, ɵFeedbackCommentController as ɵFeedbackCommentController$1, ɵFreshThreadId, ɵFreshThreadId as ɵFreshThreadId$1, ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA, ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA as ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA$1, ɵHITL_ABORTED_MESSAGE, ɵHOVER_MENU_CLOSE_DELAY_MS, ɵHoverMenuController, ɵHoverMenuController as ɵHoverMenuController$1, ɵHumanInTheLoopRegistry, ɵINLINE_FEATURE_WARNING_STYLE, ɵINLINE_FEATURE_WARNING_STYLE as ɵINLINE_FEATURE_WARNING_STYLE$1, ɵInspectorThreadOverride, ɵInspectorThreadOverride as ɵInspectorThreadOverride$1, ɵInterruptController, ɵInterruptController as ɵInterruptController$1, ɵInterruptExpiredError, ɵInterruptState, ɵKEYBOARD_OPEN_THRESHOLD_PX, ɵLICENSE_BANNER_OFFSET, ɵLICENSE_BANNER_STYLE, ɵLICENSE_BANNER_STYLE as ɵLICENSE_BANNER_STYLE$1, ɵLearningAutoStarter, ɵLearningAutoStarter as ɵLearningAutoStarter$1, ɵMAX_SOCKET_RETRIES, ɵMESSAGE_FEEDBACK_EVENT_NAME, ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH, ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH as ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH$1, ɵMOBILE_MAX_WIDTH_QUERY, ɵMessageViewModel, ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA, ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA as ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA$1, ɵOPEN_GENERATIVE_UI_DESIGN_CONTEXT_DESCRIPTION, ɵOPEN_GENERATIVE_UI_SANDBOX_FUNCTIONS_CONTEXT_DESCRIPTION, ɵOpenGenerativeUIController, ɵOpenGenerativeUIController as ɵOpenGenerativeUIController$1, ɵPLACEHOLDER_CYCLE_MS, ɵPOPUP_ANIMATION_MS, ɵPOPUP_DEFAULT_HEIGHT, ɵPOPUP_DEFAULT_HEIGHT as ɵPOPUP_DEFAULT_HEIGHT$1, ɵPOPUP_DEFAULT_WIDTH, ɵPOPUP_DEFAULT_WIDTH as ɵPOPUP_DEFAULT_WIDTH$1, ɵPlaceholderCycler, ɵPlaceholderCycler as ɵPlaceholderCycler$1, ɵRENDER_A2UI_TOOL_NAME, ɵRENDER_A2UI_TOOL_NAME as ɵRENDER_A2UI_TOOL_NAME$1, ɵRESIZE_SETTLE_MS, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵReasoningDisclosure, ɵReasoningDisclosure as ɵReasoningDisclosure$1, ɵRendererRegistry, ɵRendererRegistry as ɵRendererRegistry$1, ɵRuntimeInfoStore, ɵSCROLL_BOTTOM_THRESHOLD_PX, ɵSIDEBAR_DEFAULT_WIDTH, ɵSIDEBAR_DEFAULT_WIDTH as ɵSIDEBAR_DEFAULT_WIDTH$1, ɵSIDEBAR_TRANSITION_MS, ɵSIDEBAR_TRANSITION_MS as ɵSIDEBAR_TRANSITION_MS$1, ɵSTABLE_ARRAY_WARNINGS, ɵStickToBottom, ɵTAB_STOP_SELECTOR, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵTOOL_CALL_STATUS_ICONS, ɵTOOL_CALL_STATUS_ICONS as ɵTOOL_CALL_STATUS_ICONS$1, ɵTOOL_CALL_STATUS_LABEL_KEYS, ɵTOOL_CALL_STATUS_LABEL_KEYS as ɵTOOL_CALL_STATUS_LABEL_KEYS$1, ɵTRANSCRIPTION_ERROR_TIMEOUT_MS, ɵThreadSelection, ɵThreadSwitchCoordinator, ɵThreadsController, ɵThreadsController as ɵThreadsController$1, ɵadaptDefaultToolCallRenderProps, ɵadaptDefaultToolCallRenderProps as ɵadaptDefaultToolCallRenderProps$1, ɵaddOpenGenerativeUIContexts, ɵaddOpenGenerativeUIContexts as ɵaddOpenGenerativeUIContexts$1, ɵagentUpdateHandlers, ɵappendTranscript, ɵassembleActivityRenderers, ɵassembleActivityRenderers as ɵassembleActivityRenderers$1, ɵassembleHumanInTheLoop, ɵassembleHumanInTheLoop as ɵassembleHumanInTheLoop$1, ɵassembleProviderRegistry, ɵassembleProviderToolRenderers, ɵassembleProviderToolRenderers as ɵassembleProviderToolRenderers$1, ɵassembleProviderTools, ɵassembleProviderTools as ɵassembleProviderTools$1, ɵbindDialogFocus, ɵbindDialogFocus as ɵbindDialogFocus$1, ɵbindPopupDismiss, ɵbindPopupDismiss as ɵbindPopupDismiss$1, ɵbindSuggestionsConfig, ɵbindSuggestionsConfig as ɵbindSuggestionsConfig$1, ɵbuildHumanInTheLoopTool, ɵbuildHumanInTheLoopTool as ɵbuildHumanInTheLoopTool$1, ɵbuildLearnFromUserActionPayload, ɵbuildLearnFromUserActionPayload as ɵbuildLearnFromUserActionPayload$1, ɵbuildOpenGenerativeUIContexts, ɵbuildToolCallRenderProps, ɵbuildToolCallRenderProps as ɵbuildToolCallRenderProps$1, ɵbuildUserMessage, ɵbuildUserMessageContent, ɵcanPreviewDocument, ɵcanPreviewDocument as ɵcanPreviewDocument$1, ɵclampSlashIndex, ɵclearAgentInterruptState, ɵclearAgentThreadCursors, ɵcn, ɵcomponentToolDescription, ɵcomponentToolDescription as ɵcomponentToolDescription$1, ɵcomposerButtonState, ɵcomposerButtonState as ɵcomposerButtonState$1, ɵcopilotIconSvgAttributes, ɵcopilotIcons, ɵcountFailedToolCalls, ɵcountFailedToolCalls as ɵcountFailedToolCalls$1, ɵcreateChatSubmitter, ɵcreateChatSubmitter as ɵcreateChatSubmitter$1, ɵcreateComposerAutosize, ɵcreateComposerAutosize as ɵcreateComposerAutosize$1, ɵcreateDockedSidebar, ɵcreateDockedSidebar as ɵcreateDockedSidebar$1, ɵcreateExitPresence, ɵcreateExitPresence as ɵcreateExitPresence$1, ɵcreateLastUserMessageTracker, ɵcreateLastUserMessageTracker as ɵcreateLastUserMessageTracker$1, ɵcreateMemoryStore, ɵcreateMessageViewModel, ɵcreateMessageViewModel as ɵcreateMessageViewModel$1, ɵcreateObjectUrlFromSource, ɵcreateObjectUrlFromSource as ɵcreateObjectUrlFromSource$1, ɵcreateOpenGenerativeUITool, ɵcreateOpenGenerativeUITool as ɵcreateOpenGenerativeUITool$1, ɵcreateStickToBottom, ɵcreateThreadSelectors, ɵcreateThreadStore, ɵcreateThreadStore as ɵcreateThreadStore$1, ɵcreateThreadsDrawerActions, ɵcreateThreadsDrawerActions as ɵcreateThreadsDrawerActions$1, ɵcreateWaveformRenderer, ɵcreateWaveformRenderer as ɵcreateWaveformRenderer$1, ɵdecodeTextSource, ɵdecodeTextSource as ɵdecodeTextSource$1, ɵdeduplicateMessages, ɵdeduplicateMessages as ɵdeduplicateMessages$1, ɵdescribeActivityRendererFailure, ɵdescribeActivityRendererFailure as ɵdescribeActivityRendererFailure$1, ɵdescribeUnrenderedToolCalls, ɵdescribeUnrenderedToolCalls as ɵdescribeUnrenderedToolCalls$1, ɵdiagnoseMissingSurface, ɵdiagnoseUnpaintedSurface, ɵdiagnoseUnresolvedRoot, ɵdimensionToCss, ɵdimensionToCss as ɵdimensionToCss$1, ɵdockedSidebarRegistryFor, ɵduplicateMessagesWarning, ɵduplicateMessagesWarning as ɵduplicateMessagesWarning$1, ɵextractCompleteStyles, ɵfilterCommands, ɵfindActivityRenderer, ɵfindActivityRenderer as ɵfindActivityRenderer$1, ɵfindChatInput, ɵfindToolMessage, ɵfitTextareaHeight, ɵflattenCommandItems, ɵflattenToolsMenuForDisplay, ɵflattenUserMessageContent, ɵflattenUserMessageContent as ɵflattenUserMessageContent$1, ɵformatA2UIDebugPayload, ɵformatA2UIRetryLabel, ɵformatCountLabel, ɵformatCountLabel as ɵformatCountLabel$1, ɵformatLabel, ɵformatLabel as ɵformatLabel$1, ɵformatReasoningDuration, ɵformatReasoningDurationLabel, ɵformatToolNames, ɵformatToolNames as ɵformatToolNames$1, ɵformatWorkDuration, ɵgetA2UIOperationSurfaceId, ɵgetA2UIOperations, ɵgetA2UIProgressPhase, ɵgetAgentCapabilities, ɵgetAgentCapabilities as ɵgetAgentCapabilities$1, ɵgetAgentInterruptState, ɵgetAgentResolver, ɵgetAgentResolver as ɵgetAgentResolver$1, ɵgetArgumentPreview, ɵgetArgumentPreview as ɵgetArgumentPreview$1, ɵgetBranchNavState, ɵgetBranchNavState as ɵgetBranchNavState$1, ɵgetChatViewState, ɵgetChatViewState as ɵgetChatViewState$1, ɵgetCustomMessageRenderProps, ɵgetCustomMessageRenderProps as ɵgetCustomMessageRenderProps$1, ɵgetInlineFeatureWarningSpec, ɵgetInlineFeatureWarningSpec as ɵgetInlineFeatureWarningSpec$1, ɵgetLastUserMessageId, ɵgetLatestTurnKey, ɵgetLicenseBannerSpec, ɵgetLicenseBannerSpec as ɵgetLicenseBannerSpec$1, ɵgetMessageFeedback, ɵgetMessageFeedback as ɵgetMessageFeedback$1, ɵgetMessageFeedbackControls, ɵgetMessageFeedbackControls as ɵgetMessageFeedbackControls$1, ɵgetMessageRunStateSnapshot, ɵgetMessageRunStateSnapshot as ɵgetMessageRunStateSnapshot$1, ɵgetReasoningHeaderLabel, ɵgetReasoningHeaderLabel as ɵgetReasoningHeaderLabel$1, ɵgetThreadsDrawerElementProps, ɵgetThreadsDrawerElementProps as ɵgetThreadsDrawerElementProps$1, ɵgetToolCallBadge, ɵgetToolCallBadge as ɵgetToolCallBadge$1, ɵgetToolCallGroupState, ɵgetToolCallGroupState as ɵgetToolCallGroupState$1, ɵgetToolCallLayouts, ɵgetToolCallLayouts as ɵgetToolCallLayouts$1, ɵgetToolCallPreview, ɵgetToolCallRendererNames, ɵgetToolCallRendererNames as ɵgetToolCallRendererNames$1, ɵgetToolCallRowStatus, ɵgetToolCallStatus, ɵgetToolResults, ɵgetTurnWork, ɵgetUserMessageMediaFilename, ɵgetUserMessageMediaFilename as ɵgetUserMessageMediaFilename$1, ɵgetUserMessageMediaParts, ɵgetUserMessageMediaParts as ɵgetUserMessageMediaParts$1, ɵgetWorkOpenState, ɵgetWorkSummaryText, ɵgetWorkSummaryText as ɵgetWorkSummaryText$1, ɵgroupA2UIOperationsBySurface, ɵgroupA2UIOperationsBySurface as ɵgroupA2UIOperationsBySurface$1, ɵhasAssistantMessageText, ɵhasAssistantMessageText as ɵhasAssistantMessageText$1, ɵhitlRenderProps, ɵhitlRenderProps as ɵhitlRenderProps$1, ɵimplementsConnect, ɵinitialKeyboardState, ɵinitialKeyboardState as ɵinitialKeyboardState$1, ɵinspectorKiteFill, ɵinspectorKiteFill as ɵinspectorKiteFill$1, ɵinspectorKiteIcon, ɵinspectorKiteIcon as ɵinspectorKiteIcon$1, ɵinspectorShortcuts, ɵinspectorShortcuts as ɵinspectorShortcuts$1, ɵisContentPart, ɵisContentScrolledToBottom, ɵisContentScrolledToBottom as ɵisContentScrolledToBottom$1, ɵisCopilotKitFeature, ɵisFocusVisible, ɵisHttpAgent, ɵisLearningFeedbackEnabled, ɵisLearningFeedbackEnabled as ɵisLearningFeedbackEnabled$1, ɵisMobileViewport, ɵisOpenGenerativeUIActive, ɵisOpenGenerativeUIActive as ɵisOpenGenerativeUIActive$1, ɵisOwnFeedbackThumb, ɵisOwnFeedbackThumb as ɵisOwnFeedbackThumb$1, ɵisRetryableMemoryStatus, ɵisScrolledToBottom, ɵisScrolledToBottom as ɵisScrolledToBottom$1, ɵisTurnWorkOpen, ɵisTurnWorking, ɵjoinPhoenixChannel$, ɵloadWebsandbox, ɵmapMemoryMetadataEvent, ɵmatchActivityRenderer, ɵmatchActivityRenderer as ɵmatchActivityRenderer$1, ɵmeasureTextarea, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵmessagesFingerprint as ɵmessagesFingerprint$1, ɵmorphViewTransition, ɵmorphViewTransition as ɵmorphViewTransition$1, ɵnextSlashIndex, ɵnextTabStop, ɵnormalizeAutoScroll, ɵnormalizeAutoScroll as ɵnormalizeAutoScroll$1, ɵnormalizeToolCallStatus, ɵnormalizeToolCallStatus as ɵnormalizeToolCallStatus$1, ɵnormalizeToolsMenu, ɵnormalizeToolsMenu as ɵnormalizeToolsMenu$1, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵparseSlashQuery, ɵparseToolCallArguments, ɵphoenixChannel$, ɵphoenixSocket$, ɵpinMessageToTop, ɵpinMessageToTop as ɵpinMessageToTop$1, ɵpluralize, ɵprocessPartialHtml, ɵprojectThread, ɵpublicKeyHeaderDefaults, ɵpublicKeyHeaderDefaults as ɵpublicKeyHeaderDefaults$1, ɵreadA2UILifecycle, ɵreadKeyboardState, ɵrecordAnnotation, ɵrecordAnnotation as ɵrecordAnnotation$1, ɵrecordWorkTime, ɵregisterFrontendTools, ɵregisterFrontendTools as ɵregisterFrontendTools$1, ɵreportProviderConfigDiagnostics, ɵreportProviderConfigDiagnostics as ɵreportProviderConfigDiagnostics$1, ɵreserveLicenseBannerOffset, ɵreserveLicenseBannerOffset as ɵreserveLicenseBannerOffset$1, ɵresetAgentThreadBaseline, ɵresetMessageFeedbackCache, ɵresolveA2UIActivation, ɵresolveA2UIActivation as ɵresolveA2UIActivation$1, ɵresolveA2UIDebugExposure, ɵresolveActivityRenderer, ɵresolveAgentId, ɵresolveAgentId as ɵresolveAgentId$1, ɵresolveAgentThreadId, ɵresolveAgentThreadId as ɵresolveAgentThreadId$1, ɵresolveChatNotice, ɵresolveChatNotice as ɵresolveChatNotice$1, ɵresolveComposerKey, ɵresolveCustomMessageRenderContext, ɵresolveCustomMessageRenderContext as ɵresolveCustomMessageRenderContext$1, ɵresolveCustomMessageRenderers, ɵresolveLicenseState, ɵresolveLicenseState as ɵresolveLicenseState$1, ɵresolveProviderConfig, ɵresolveProviderConfig as ɵresolveProviderConfig$1, ɵresolveSlashKey, ɵresolveThreadsLicense, ɵresolveThreadsLicense as ɵresolveThreadsLicense$1, ɵresolveToolCallAgentId, ɵresolveToolCallAgentId as ɵresolveToolCallAgentId$1, ɵresolveToolCallRenderer, ɵresolveToolCallRenderer as ɵresolveToolCallRenderer$1, ɵrmsAmplitude, ɵrunA2UIAction, ɵrunA2UIAction as ɵrunA2UIAction$1, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemories as ɵselectMemories$1, ɵselectMemoriesAvailable, ɵselectMemoriesAvailable as ɵselectMemoriesAvailable$1, ɵselectMemoriesError, ɵselectMemoriesError as ɵselectMemoriesError$1, ɵselectMemoriesIsLoading, ɵselectMemoriesIsLoading as ɵselectMemoriesIsLoading$1, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectMemoriesRealtimeStatus as ɵselectMemoriesRealtimeStatus$1, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵserializeContextValue, ɵserializeContextValue as ɵserializeContextValue$1, ɵsetMessageFeedback, ɵshallowEqualRecord, ɵshouldShowAssistantToolbar, ɵshouldShowAssistantToolbar as ɵshouldShowAssistantToolbar$1, ɵshouldShowMessageCursor, ɵshowsComposerDisclaimer, ɵshowsComposerDisclaimer as ɵshowsComposerDisclaimer$1, ɵsnapshotAgentState, ɵstableArrayPropWarning, ɵstableArrayPropWarning as ɵstableArrayPropWarning$1, ɵstopAgentWithFallback, ɵstringifyToolCallAttr, ɵstringifyToolCallAttr as ɵstringifyToolCallAttr$1, ɵstringifyToolCallPayload, ɵstringifyToolCallPayload as ɵstringifyToolCallPayload$1, ɵsubscribeToAgentErrors, ɵsubscribeToAgentErrors as ɵsubscribeToAgentErrors$1, ɵsubscribeToAgentSuggestions, ɵsubscribeToAgentSuggestions as ɵsubscribeToAgentSuggestions$1, ɵsubscribeToAgentUpdates, ɵsubscribeToAgentUpdates as ɵsubscribeToAgentUpdates$1, ɵsubscribeToLearningFeedbackEnabled, ɵsubscribeToLearningFeedbackEnabled as ɵsubscribeToLearningFeedbackEnabled$1, ɵsubscribeToMessageFeedback, ɵsubscribeToMessageFeedback as ɵsubscribeToMessageFeedback$1, ɵsurfaceHasRenderableContent, ɵsyncRecorderToMode, ɵsyncRecorderToMode as ɵsyncRecorderToMode$1, ɵthreadAdapterEvents, ɵtoA2UIClientEvent, ɵtoA2UIClientEvent as ɵtoA2UIClientEvent$1, ɵtoDefaultToolCallStatus, ɵtoDrawerThread, ɵtoDrawerThread as ɵtoDrawerThread$1, ɵtoLearningConfig, ɵtoLearningConfig as ɵtoLearningConfig$1, ɵtoolCallAppearance, ɵtoolCallAppearance as ɵtoolCallAppearance$1, ɵtoolRendererShapeChanged, ɵtranscribeAudio, ɵtranscriptionErrorMessageKey, ɵtranscriptionErrorNotice, ɵvalidateAgentBinding, ɵvalidateAgentBinding as ɵvalidateAgentBinding$1, ɵwaitForActiveRun, ɵwatchElementHeight, ɵwatchElementHeight as ɵwatchElementHeight$1, ɵwatchElementWidth, ɵwatchElementWidth as ɵwatchElementWidth$1, ɵwatchKeyboardState, ɵwatchKeyboardState as ɵwatchKeyboardState$1, ɵwatchMobileViewport, ɵwatchMobileViewport as ɵwatchMobileViewport$1, ɵwithHeaderDefaults, ɵwithHeaderDefaults as ɵwithHeaderDefaults$1 } from "@copilotkit/core";
5
5
  import { ACTIVITY_HISTORY_METADATA, AGUIConnectNotImplementedError, AGUIEnforcementLimitError, AGUIError, AGUI_METADATA_KEY, AbstractAgent, BackwardCompatibility_0_0_39, BackwardCompatibility_0_0_45, BackwardCompatibility_0_0_57, CompatibilityBoundary, DEFAULT_MAX_ENFORCED_ENTRIES, DebugLogger, EventType, FilterToolCallsMiddleware, FunctionMiddleware, HttpAgent, Middleware, PROTOCOL_VERSION, aggregateTokenUsage, authoritativeActivityTypes, buildResumeArray, compactEvents, contentHasMedia, contentToText, convertToLegacyEvents, createDebugLogger, defaultApplyEvents, enforceEvents, enforceOutgoingInput, getRunOutcome, isInterruptExpired, isRecognizedEvent, mergeMetadata, omitOptionalNulls, parseProtoStream, parseSSEStream, randomUUID, resolveAgentDebugConfig, resolveDebugLogger, runHttpRequest, structuredClone_, tokenUsageFromAiSdkUsage, tokenUsageFromLangChainMetadata, transformChunks, transformHttpEventStream, verifyEvents, withAuthoritativeActivityTypes } from "@ag-ui/client";
6
6
  import { ActivityDeltaEventSchema, ActivityMessageSchema, ActivitySnapshotEventSchema, AddOperationSchema, AgentCapabilitiesSchema, AssistantMessageSchema, AttributableSchema, AudioInputContentSchema, AudioInputPartSchema, AudioPartSchema, BaseEventSchema, BaseMessageSchema, ContentPartSchema, ContextSchema, CopyOperationSchema, CustomEventSchema, DataSourceSchema, DeveloperMessageSchema, DocumentInputContentSchema, DocumentInputPartSchema, DocumentPartSchema, EventSchema, EventSchemas, EventTypeSchema, ExecutionCapabilitiesSchema, FileSourceSchema, FunctionCallSchema, HumanInTheLoopCapabilitiesSchema, IdentityCapabilitiesSchema, ImageInputContentSchema, ImageInputPartSchema, ImagePartSchema, InputContentDataSourceSchema, InputContentSchema, InputContentSourceSchema, InputContentUrlSourceSchema, InterruptSchema, JsonPatchOperationSchema, JsonPatchSchema, JsonPointerSchema, MessageSchema, MessagesSnapshotEventSchema, MetadataSchema, MoveOperationSchema, MultiAgentCapabilitiesSchema, MultimodalCapabilitiesSchema, MultimodalInputCapabilitiesSchema, MultimodalOutputCapabilitiesSchema, OptionalMetadataSchema, OutputCapabilitiesSchema, PartSourceSchema, RawEventSchema, ReasoningCapabilitiesSchema, ReasoningEncryptedValueEventSchema, ReasoningEncryptedValueSubtypeSchema, ReasoningEndEventSchema, ReasoningMessageChunkEventSchema, ReasoningMessageContentEventSchema, ReasoningMessageEndEventSchema, ReasoningMessageSchema, ReasoningMessageStartEventSchema, ReasoningStartEventSchema, RemoveOperationSchema, ReplaceOperationSchema, ResumeEntrySchema, RoleSchema, RunAgentInputSchema, RunErrorEventSchema, RunFinishedCancelledOutcomeSchema, RunFinishedEventSchema, RunFinishedInterruptOutcomeSchema, RunFinishedOutcomeSchema, RunFinishedSuccessOutcomeSchema, RunStartedEventSchema, StateCapabilitiesSchema, StateDeltaEventSchema, StateSchema, StateSnapshotEventSchema, StepFinishedEventSchema, StepStartedEventSchema, SubagentErrorEventSchema, SubagentFinishedEventSchema, SubagentFinishedOutcomeSchema, SubagentFinishedSuccessOutcomeSchema, SubagentFinishedSuspendedOutcomeSchema, SubagentInfoSchema, SubagentRunIdSchema, SubagentStartedEventSchema, SystemMessageSchema, TestOperationSchema, TextInputContentSchema, TextMessageChunkEventSchema, TextMessageContentEventSchema, TextMessageEndEventSchema, TextMessageRoleSchema, TextMessageStartEventSchema, TextPartSchema, TokenUsageSchema, ToolCallArgsEventSchema, ToolCallChunkEventSchema, ToolCallEndEventSchema, ToolCallResultEventSchema, ToolCallSchema, ToolCallStartEventSchema, ToolMessageSchema, ToolSchema, ToolsCapabilitiesSchema, TransportCapabilitiesSchema, UrlSourceSchema, UserMessageSchema, VideoInputContentSchema, VideoInputPartSchema, VideoPartSchema } from "@ag-ui/core/schemas";
@@ -10,13 +10,14 @@ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
10
10
  import { CopilotKitAgentIdContext, CopilotKitContext, LicenseContext, useCopilotKit, useCopilotKit as useCopilotKit$1, useDefaultAgentId, useLicenseContext, useLicenseContext as useLicenseContext$1 } from "@copilotkit/react-core/context";
11
11
  import * as TooltipPrimitive from "@radix-ui/react-tooltip";
12
12
  import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
13
- import { A2UI_COMPONENT_ENVELOPE_KEYS, A2UI_VERSION, COPILOTKIT_FORWARDED_PROPS_KEY, COPILOTKIT_UI_ENVELOPE_FORMAT, DEFAULT_AGENT_ID, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_AGENT_FUNCTION_CALLS, GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON, GENERATIVE_UI_CHAT_TARGET, GENERATIVE_UI_FUNCTIONS, GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE, GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION, GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION, GENERATIVE_UI_MAX_REJECTION_LENGTH, GENERATIVE_UI_MAX_SUMMARY_REJECTIONS, applyDescriptionOverrides, buildGenerativeUIMarkdownGuidelines, buildGenerativeUIPrompt, callerProblem, commitRowKeyStore, copyToClipboard, createRowKeyStore, defaultGenerativeUIPromptSpec, envelopeToManifest, formatFileSize, functionCallers, generativeUIGuideFeatures, getDocumentIcon, getOperationKind, getOperationSurfaceId, getSourceUrl, randomUUID as randomUUID$1, renderGenerativeUISchema, resolveRowRenderKeysById, shouldEnableInspector, toA2UIActionMessage, validateOperation } from "@copilotkit/shared";
13
+ import { COPILOTKIT_FORWARDED_PROPS_KEY, DEFAULT_AGENT_ID, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION, GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION, buildGenerativeUIMarkdownGuidelines, commitRowKeyStore, copyToClipboard, createRowKeyStore, defaultGenerativeUIPromptSpec, formatFileSize, generativeUIGuideFeatures, getDocumentIcon, getSourceUrl, randomUUID as randomUUID$1, renderGenerativeUISchema, resolveRowRenderKeysById, shouldEnableInspector, toA2UIActionMessage } from "@copilotkit/shared";
14
14
  import { ɵmountInspector } from "@copilotkit/web-inspector/mount";
15
15
  import { MCPAppsActivityContentSchema, MCPAppsActivityType, ɵMcpAppHost, ɵrunMcpFollowUp } from "@copilotkit/mcp-apps-renderer/activity";
16
16
  import { A2UIProvider, A2UIRenderer, Catalog, basicCatalog, defaultTheme as a2uiDefaultTheme, filterCatalog, initializeDefaultCatalog, injectStyles, useA2UIActions, useA2UIError, viewerTheme } from "@copilotkit/a2ui-renderer";
17
17
  import { A2UISurfaceDiagnostics } from "@copilotkit/a2ui-renderer/engine-core";
18
18
  import * as z from "zod";
19
- import { Catalog as Catalog$1, ComponentModel, DataModel, SurfaceModel } from "@a2ui/web_core/v0_9";
19
+ import { GenerativeUISurfaceManager, activityFunctionCalls, buildActionMessageText, buildGenerativeUIEnvelope, buildGenerativeUIManifest, createFunctionCallRunner, createGenerativeUIDebugSource, createGenerativeUIDispatcher, describeGenerativeUIRun, envelopeOptionsFor, getMarkdownSurfaceSource, markdownFunctionCalls, surfaceLabelResolver } from "@copilotkit/core/generative-ui";
20
+ import { GenerativeUIError } from "@copilotkit/shared/generative-ui";
20
21
  import { A2UICatalogController } from "@copilotkit/a2ui-renderer/catalog-schema";
21
22
  import { stylesheet } from "@copilotkit/core/styles";
22
23
  import * as PopoverPrimitive from "@radix-ui/react-popover";
@@ -818,7 +819,7 @@ function ɵuseOwnedCore(ref, create) {
818
819
 
819
820
  //#endregion
820
821
  //#region package.json
821
- var version$1 = "2.0.0-rc.30";
822
+ var version$1 = "2.0.0-rc.32";
822
823
 
823
824
  //#endregion
824
825
  //#region src/components/CopilotKitInspector.tsx
@@ -1465,550 +1466,6 @@ function A2UIBuiltInToolCallRenderer() {
1465
1466
  return null;
1466
1467
  }
1467
1468
 
1468
- //#endregion
1469
- //#region src/generative-ui/action-message.ts
1470
- /** Context keys that supply the message's first line, in priority order. */
1471
- const TEXT_KEYS = ["message", "label"];
1472
- function isNonEmptyString(value) {
1473
- return typeof value === "string" && value.trim().length > 0;
1474
- }
1475
- /** `choose_plan`, `choose-plan` and `choosePlan` all become "Choose plan". */
1476
- function humanize(name) {
1477
- const spaced = name.replace(/[_-]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").trim();
1478
- return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();
1479
- }
1480
- function formatContextValue(value) {
1481
- return typeof value === "object" ? JSON.stringify(value) : String(value);
1482
- }
1483
- /**
1484
- * Turns a user event that no function handles into the text of a visible
1485
- * user message.
1486
- *
1487
- * The first line is, in order: `userMessage`, `context.message`,
1488
- * `context.label`, the label of the source component (from `resolveLabel`),
1489
- * or the event name made readable (`choose_plan` becomes "Choose plan").
1490
- * Each other context field follows as one `key: value` line. Objects are
1491
- * written as JSON. `null` and `undefined` fields are skipped.
1492
- *
1493
- * @param event - The user event, as sent by a surface.
1494
- * @param resolveLabel - Finds the visible label of a component by id. Build
1495
- * one with {@link createComponentLabelResolver}.
1496
- *
1497
- * @example
1498
- * ```ts
1499
- * buildActionMessageText({
1500
- * name: "choose_plan",
1501
- * surfaceId: "plans",
1502
- * componentId: "team-button",
1503
- * userMessage: "I pick the Team plan",
1504
- * context: { seats: 12 },
1505
- * });
1506
- * // "I pick the Team plan\n\nseats: 12"
1507
- * ```
1508
- */
1509
- function buildActionMessageText(event, resolveLabel) {
1510
- const { context, userMessage } = event;
1511
- const explicit = [userMessage, ...TEXT_KEYS.map((key) => context[key])].find(isNonEmptyString);
1512
- const resolved = explicit ? void 0 : resolveLabel?.(event.componentId);
1513
- const head = explicit ?? (isNonEmptyString(resolved) ? resolved.trim() : humanize(event.name));
1514
- const lines = Object.entries(context).filter(([key, value]) => !TEXT_KEYS.includes(key) && value !== void 0 && value !== null).map(([key, value]) => `${key}: ${formatContextValue(value)}`);
1515
- return lines.length > 0 ? `${head}\n\n${lines.join("\n")}` : head;
1516
- }
1517
- function ownText(component) {
1518
- if (!component) return void 0;
1519
- if (isNonEmptyString(component.label)) return component.label;
1520
- if (isNonEmptyString(component.text)) return component.text;
1521
- }
1522
- function childIds(component) {
1523
- const { child, children } = component;
1524
- const single = typeof child === "string" ? [child] : [];
1525
- const multiple = Array.isArray(children) ? children.filter((id) => typeof id === "string") : [];
1526
- return [...single, ...multiple];
1527
- }
1528
- /** The components that an operation adds, inline or in an update. */
1529
- function componentsOf(operation) {
1530
- if ("createSurface" in operation) return operation.createSurface.components ?? [];
1531
- if ("updateComponents" in operation) return operation.updateComponents.components;
1532
- return [];
1533
- }
1534
- /**
1535
- * Builds a function that finds the visible label of a component on a surface.
1536
- *
1537
- * The label is the component's own string `label`, else its string `text`,
1538
- * else the first `child` or `children` component that has a string `label`
1539
- * or `text`. When a component id is defined more than once, the last
1540
- * definition wins, as in the renderer.
1541
- *
1542
- * @param operations - The committed operations of the surface.
1543
- *
1544
- * @example
1545
- * ```ts
1546
- * const resolveLabel = createComponentLabelResolver(surface.operations);
1547
- * buildActionMessageText(event, resolveLabel);
1548
- * ```
1549
- */
1550
- function createComponentLabelResolver(operations) {
1551
- const byId = /* @__PURE__ */ new Map();
1552
- for (const operation of operations) {
1553
- const components = componentsOf(operation);
1554
- for (const component of components) byId.set(component.id, component);
1555
- }
1556
- return (componentId) => {
1557
- const component = byId.get(componentId);
1558
- if (!component) return void 0;
1559
- const own = ownText(component);
1560
- if (own) return own;
1561
- const ids = childIds(component);
1562
- for (const id of ids) {
1563
- const text = ownText(byId.get(id));
1564
- if (text) return text;
1565
- }
1566
- };
1567
- }
1568
-
1569
- //#endregion
1570
- //#region src/generative-ui/manifest.ts
1571
- /**
1572
- * The built-in functions (the A2UI basic catalog plus calc and series) as
1573
- * manifest entries. Their args are described by the short signature, not
1574
- * by a full JSON Schema: the renderer checks them when they run. An app
1575
- * function of the same name replaces the entry.
1576
- */
1577
- function builtInFunctionManifests() {
1578
- return Object.fromEntries(Object.entries(GENERATIVE_UI_FUNCTIONS).map(([name, fn]) => [name, {
1579
- description: fn.description,
1580
- parameters: {
1581
- type: "object",
1582
- description: fn.parameters
1583
- },
1584
- returnType: fn.returnType,
1585
- allowedCallers: fn.allowedCallers,
1586
- ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
1587
- }]));
1588
- }
1589
- /**
1590
- * The manifest of a catalog, with no React runtime: the components of `ui`,
1591
- * the built-in functions (minus the names the app declares) and
1592
- * `options.functions`, the chat target and `options.targets`, and
1593
- * `options.surfaces`. `buildGenerativeUIManifest` builds the per-run
1594
- * manifest with it; tools that run outside React use it directly.
1595
- *
1596
- * @example
1597
- * ```ts
1598
- * const manifest = buildCatalogManifest(standardUI);
1599
- * manifest.targets; // [{ id: "chat", kind: "chat" }]
1600
- * ```
1601
- */
1602
- function buildCatalogManifest(ui, options = {}) {
1603
- return {
1604
- catalogId: ui.id,
1605
- catalogIds: catalogIdsOf(ui),
1606
- components: applyDescriptionOverrides({ components: ui.manifestComponents }, defaultGenerativeUIPromptSpec().descriptions).manifest.components,
1607
- functions: {
1608
- ...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
1609
- ...options.functions
1610
- },
1611
- targets: [{
1612
- id: GENERATIVE_UI_CHAT_TARGET,
1613
- kind: "chat"
1614
- }, ...options.targets ?? []],
1615
- surfaces: options.surfaces ?? {}
1616
- };
1617
- }
1618
- /**
1619
- * Builds the per-run manifest. Never contains handlers or renderers.
1620
- *
1621
- * - `functions`: the built-in functions, then the declared functions with
1622
- * exactly one mounted handler.
1623
- * - `targets`: the chat first, then each mounted `<GenerativeUISurface>`,
1624
- * with its `description` and its `components` when it has them.
1625
- */
1626
- function buildGenerativeUIManifest(runtime, threadId) {
1627
- const { ui, manager, dispatcher } = runtime;
1628
- const inlineTargets = manager.getMountedTargets().filter((target) => target.id !== GENERATIVE_UI_CHAT_TARGET).map(({ id, ...rest }) => ({
1629
- id,
1630
- kind: "inline",
1631
- ...rest
1632
- }));
1633
- return buildCatalogManifest(ui, {
1634
- functions: dispatcher.listExposed(),
1635
- targets: inlineTargets,
1636
- surfaces: threadId ? manager.describeSurfaces(threadId) : {}
1637
- });
1638
- }
1639
- /**
1640
- * Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
1641
- * from the per-run manifest. It has the A2UI v1.0 renderer capabilities
1642
- * shape: one inline catalog with the id of the UI, and the CopilotKit data
1643
- * in `metadata.extensions`.
1644
- *
1645
- * The inline catalog has no `components` only for the markdown transport
1646
- * with `includeCatalog: false`. It has `instructions` for the markdown
1647
- * transport, or when given.
1648
- *
1649
- * @param runtime - The generative UI runtime of the provider.
1650
- * @param threadId - The thread of the run. Its surfaces go in `copilotkit_surfaces`.
1651
- * @param options - The transport and what to send.
1652
- *
1653
- * @example
1654
- * ```ts
1655
- * const envelope = buildGenerativeUIEnvelope(runtime, agent.threadId, {
1656
- * transport: "tool",
1657
- * includeCatalog: true,
1658
- * contextSent: false,
1659
- * });
1660
- * envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
1661
- * ```
1662
- */
1663
- function buildGenerativeUIEnvelope(runtime, threadId, options) {
1664
- const { transport, includeCatalog, contextSent, action } = options;
1665
- const manifest = buildGenerativeUIManifest(runtime, threadId);
1666
- const instructions = options.instructions ?? (transport === "markdown" ? buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest)) : void 0);
1667
- const omitComponents = transport === "markdown" && !includeCatalog;
1668
- return {
1669
- "1.0": {
1670
- supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
1671
- inlineCatalogs: [{
1672
- catalogId: manifest.catalogId,
1673
- protocolVersion: "1.0",
1674
- ...omitComponents ? {} : { components: manifest.components },
1675
- functions: manifest.functions,
1676
- ...instructions === void 0 ? {} : { instructions }
1677
- }]
1678
- },
1679
- metadata: { extensions: {
1680
- copilotkit_format: COPILOTKIT_UI_ENVELOPE_FORMAT,
1681
- copilotkit_transport: transport,
1682
- copilotkit_targets: manifest.targets,
1683
- copilotkit_surfaces: manifest.surfaces,
1684
- copilotkit_contextSent: contextSent,
1685
- ...action === void 0 ? {} : { copilotkit_action: action }
1686
- } }
1687
- };
1688
- }
1689
-
1690
- //#endregion
1691
- //#region src/generative-ui/debug-source.ts
1692
- /**
1693
- * What a run of `threadId` sends: its envelope, and the text that goes into
1694
- * the prompt of the model because of it.
1695
- *
1696
- * - Tool transport: the runtime adds the `render_ui` guide. It builds it
1697
- * from the envelope with `buildGenerativeUIPrompt`, as done here.
1698
- * - Markdown transport: the provider sends the guideline and the compact
1699
- * schema as context entries. With `sendContext: false`, the backend builds
1700
- * its own prompt, usually from the `instructions` of the envelope.
1701
- */
1702
- function describeGenerativeUIRun(runtime, threadId, options) {
1703
- const envelope = buildGenerativeUIEnvelope(runtime, threadId, options);
1704
- if (options.transport === "tool") return {
1705
- envelope,
1706
- prompt: [{
1707
- title: "render_ui guide",
1708
- source: "runtime",
1709
- text: buildGenerativeUIPrompt(envelopeToManifest(envelope))
1710
- }]
1711
- };
1712
- const manifest = buildGenerativeUIManifest(runtime, threadId);
1713
- if (!options.contextSent) return {
1714
- envelope,
1715
- prompt: [{
1716
- title: "Envelope instructions",
1717
- source: "backend",
1718
- text: envelopeToManifest(envelope).instructions ?? ""
1719
- }]
1720
- };
1721
- const guideline = buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest));
1722
- const schema = renderGenerativeUISchema(manifest, defaultGenerativeUIPromptSpec().schema.markdown);
1723
- return {
1724
- envelope,
1725
- prompt: [{
1726
- title: "Markdown guideline",
1727
- source: "context",
1728
- text: guideline
1729
- }, {
1730
- title: "Component schema",
1731
- source: "context",
1732
- text: schema
1733
- }]
1734
- };
1735
- }
1736
- /** The declared functions, with the JSON Schema of their parameters. */
1737
- function debugFunctions(runtime) {
1738
- const functions = {};
1739
- for (const [name, declared] of runtime.ui.functions) {
1740
- let parameters = {};
1741
- try {
1742
- parameters = toJsonSchema(declared.parameters);
1743
- } catch {}
1744
- functions[name] = {
1745
- ...declared.description ? { description: declared.description } : {},
1746
- parameters,
1747
- handlers: runtime.dispatcher.handlerCount(name)
1748
- };
1749
- }
1750
- return functions;
1751
- }
1752
- /**
1753
- * The debug source that the provider gives core for the inspector. It builds
1754
- * a snapshot only when the inspector reads one.
1755
- *
1756
- * @param runtime - The generative UI parts of the provider.
1757
- * @param getOptions - The envelope options and agent ids of the current config.
1758
- * @returns The source, and `recordRun` for each run start.
1759
- */
1760
- function createGenerativeUIDebugSource(runtime, getOptions) {
1761
- const listeners = /* @__PURE__ */ new Set();
1762
- let lastRun;
1763
- const notify = () => {
1764
- for (const listener of [...listeners]) listener();
1765
- };
1766
- return {
1767
- source: {
1768
- getSnapshot() {
1769
- const { options, agentIds } = getOptions();
1770
- const threadId = runtime.manager.getActiveThread();
1771
- const manifest = buildGenerativeUIManifest(runtime, threadId);
1772
- return {
1773
- catalogId: runtime.ui.id,
1774
- transport: options.transport,
1775
- ...agentIds ? { agentIds } : {},
1776
- components: runtime.ui.manifestComponents,
1777
- componentCatalogs: Object.fromEntries(componentCatalogIds(runtime.ui)),
1778
- functions: debugFunctions(runtime),
1779
- state: { ...runtime.manager.getState() },
1780
- targets: manifest.targets,
1781
- activeThreadId: threadId,
1782
- surfaces: runtime.manager.debugSurfaces(),
1783
- lastRun,
1784
- nextRun: {
1785
- agentId: void 0,
1786
- threadId,
1787
- ...describeGenerativeUIRun(runtime, threadId, options)
1788
- }
1789
- };
1790
- },
1791
- subscribe(listener) {
1792
- listeners.add(listener);
1793
- const unsubscribe = runtime.manager.subscribe(listener);
1794
- return () => {
1795
- listeners.delete(listener);
1796
- unsubscribe();
1797
- };
1798
- }
1799
- },
1800
- recordRun(run) {
1801
- lastRun = run;
1802
- notify();
1803
- }
1804
- };
1805
- }
1806
-
1807
- //#endregion
1808
- //#region src/generative-ui/dispatcher.ts
1809
- const messageOf = (error) => error instanceof Error ? error.message : String(error);
1810
- /**
1811
- * Creates the registry of functions that generated UI may call.
1812
- *
1813
- * A function is callable when it is declared in `getDeclared()` and exactly
1814
- * one handler is mounted for it with `register`. Names are resolved at call
1815
- * time and fail closed. Nothing is sent to the agent.
1816
- * Neither `invoke` nor `listExposed` throws.
1817
- *
1818
- * @param options.getDeclared - Returns the declared functions.
1819
- * @param options.onError - Gets each failed call.
1820
- *
1821
- * @example
1822
- * ```ts
1823
- * const dispatcher = createGenerativeUIDispatcher({
1824
- * getDeclared: () => new Map(Object.entries(ui.functions)),
1825
- * });
1826
- * const unregister = dispatcher.register("addToCart", handlerRef);
1827
- * await dispatcher.invoke("addToCart", { productId: "p1" }, origin);
1828
- * unregister();
1829
- * ```
1830
- */
1831
- /**
1832
- * True while the browser counts the current task as user-activated (a
1833
- * click, a key press). Where the API is missing (older browsers, test
1834
- * environments), the gesture is assumed.
1835
- */
1836
- function hasUserActivation() {
1837
- if (typeof navigator === "undefined") return true;
1838
- const activation = navigator.userActivation;
1839
- return activation === void 0 || activation.isActive;
1840
- }
1841
- /**
1842
- * The permissions of a declared function as the manifest states them: the
1843
- * callers always written out, so a reader needs no default.
1844
- */
1845
- function permissionsOf(fn) {
1846
- const callers = functionCallers(fn);
1847
- return {
1848
- allowedCallers: callers.renderer && callers.agent ? "rendererOrAgent" : callers.agent ? "agentOnly" : "rendererOnly",
1849
- ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
1850
- };
1851
- }
1852
- function createGenerativeUIDispatcher(options) {
1853
- const handlers = /* @__PURE__ */ new Map();
1854
- const resolveUnchecked = (name) => {
1855
- const declared = options.getDeclared().get(name);
1856
- if (!declared) return {
1857
- ok: false,
1858
- error: new GenerativeUIError("function_not_found", `No generative UI function named "${name}" is declared in createGenerativeUI({ functions })`)
1859
- };
1860
- const mounted = [...handlers.get(name) ?? []];
1861
- const [ref] = mounted;
1862
- if (!ref) return {
1863
- ok: false,
1864
- error: new GenerativeUIError("function_not_found", `"${name}" is declared, but no useGenerativeUIFunction handler is mounted for it`)
1865
- };
1866
- if (mounted.length > 1) return {
1867
- ok: false,
1868
- error: new GenerativeUIError("function_conflict", `"${name}" has ${mounted.length} useGenerativeUIFunction handlers mounted. Mount exactly one.`)
1869
- };
1870
- return {
1871
- ok: true,
1872
- declared,
1873
- ref
1874
- };
1875
- };
1876
- const isDeclared = (name) => {
1877
- try {
1878
- return options.getDeclared().has(name);
1879
- } catch {
1880
- return false;
1881
- }
1882
- };
1883
- const resolve = (name) => {
1884
- try {
1885
- return resolveUnchecked(name);
1886
- } catch (error) {
1887
- return {
1888
- ok: false,
1889
- error: new GenerativeUIError("handler_failed", `"${name}" could not be resolved: ${messageOf(error)}`)
1890
- };
1891
- }
1892
- };
1893
- const validateArgs = async (name, schema, args) => {
1894
- try {
1895
- const validation = await schema["~standard"].validate(args);
1896
- if (!validation.issues) return {
1897
- ok: true,
1898
- value: validation.value
1899
- };
1900
- return {
1901
- ok: false,
1902
- error: new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${validation.issues.map((i) => `${(i.path ?? []).map((p) => typeof p === "object" ? p.key : p).join(".") || "args"}: ${i.message}`).join("; ")}`)
1903
- };
1904
- } catch (error) {
1905
- return {
1906
- ok: false,
1907
- error: new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${messageOf(error)}`)
1908
- };
1909
- }
1910
- };
1911
- const failWith = (name, origin, error) => {
1912
- try {
1913
- options.onError?.({
1914
- name,
1915
- origin,
1916
- error
1917
- });
1918
- } catch {}
1919
- return {
1920
- ok: false,
1921
- error
1922
- };
1923
- };
1924
- /**
1925
- * Why `origin` may not call a function with these permissions now, as an
1926
- * error, or `undefined` when it may. The agent is refused what is for the
1927
- * renderer; a component is refused what is for the agent, and a gesture
1928
- * function when the browser counts no user activation.
1929
- */
1930
- const callerError = (name, fn, origin) => {
1931
- const isComponent = "componentId" in origin;
1932
- if (!isComponent && !GENERATIVE_UI_AGENT_FUNCTION_CALLS) return new GenerativeUIError("invalid_function_call", GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
1933
- const problem = callerProblem(name, fn, isComponent ? "renderer" : "agent");
1934
- if (problem !== void 0) return new GenerativeUIError("invalid_function_call", problem);
1935
- if (isComponent && fn.requiresUserActivation && !hasUserActivation()) return new GenerativeUIError("invalid_function_call", `function "${name}" runs only from a user gesture; this event was not one`);
1936
- };
1937
- /**
1938
- * Runs a basic function of the A2UI catalog. They are value functions of
1939
- * the renderer: the agent cannot call them, and one that needs a user
1940
- * gesture runs only from an event binding.
1941
- */
1942
- const invokeBasic = (name, args, origin) => {
1943
- const info = GENERATIVE_UI_FUNCTIONS[name];
1944
- const run = BASIC_FUNCTIONS[name];
1945
- if (info === void 0 || run === void 0) throw new Error(`"${name}" is not a basic function`);
1946
- const refused = callerError(name, info, origin);
1947
- if (refused) return failWith(name, origin, refused);
1948
- if (args !== void 0 && !(typeof args === "object" && args !== null && !Array.isArray(args))) return failWith(name, origin, new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": args must be an object`));
1949
- try {
1950
- return {
1951
- ok: true,
1952
- result: run(args ?? {})
1953
- };
1954
- } catch (error) {
1955
- return failWith(name, origin, new GenerativeUIError(error instanceof ExpressionError ? "invalid_arguments" : "handler_failed", `"${name}" failed: ${messageOf(error)}`));
1956
- }
1957
- };
1958
- return {
1959
- async invoke(name, args, origin) {
1960
- const resolved = resolve(name);
1961
- if (!resolved.ok && resolved.error.code === "function_not_found" && !isDeclared(name) && Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name)) return invokeBasic(name, args, origin);
1962
- if (!resolved.ok) return failWith(name, origin, resolved.error);
1963
- const refused = callerError(name, resolved.declared, origin);
1964
- if (refused) return failWith(name, origin, refused);
1965
- const validated = await validateArgs(name, resolved.declared.parameters, args ?? {});
1966
- if (!validated.ok) return failWith(name, origin, validated.error);
1967
- try {
1968
- return {
1969
- ok: true,
1970
- result: await resolved.ref.current(validated.value)
1971
- };
1972
- } catch (error) {
1973
- return failWith(name, origin, new GenerativeUIError("handler_failed", `"${name}" failed: ${messageOf(error)}`));
1974
- }
1975
- },
1976
- listExposed() {
1977
- let names;
1978
- try {
1979
- names = [...options.getDeclared().keys()];
1980
- } catch {
1981
- return {};
1982
- }
1983
- const listed = {};
1984
- for (const name of names) {
1985
- const resolved = resolve(name);
1986
- if (!resolved.ok) continue;
1987
- if (!functionCallers(resolved.declared).renderer && !GENERATIVE_UI_AGENT_FUNCTION_CALLS) continue;
1988
- const { description, parameters, returnType } = resolved.declared;
1989
- try {
1990
- listed[name] = {
1991
- ...description ? { description } : {},
1992
- parameters: toJsonSchema(parameters),
1993
- ...returnType ? { returnType } : {},
1994
- ...permissionsOf(resolved.declared)
1995
- };
1996
- } catch {}
1997
- }
1998
- return listed;
1999
- },
2000
- register(name, ref) {
2001
- const mounted = handlers.get(name) ?? /* @__PURE__ */ new Set();
2002
- mounted.add(ref);
2003
- handlers.set(name, mounted);
2004
- return () => {
2005
- mounted.delete(ref);
2006
- };
2007
- },
2008
- handlerCount: (name) => handlers.get(name)?.size ?? 0
2009
- };
2010
- }
2011
-
2012
1469
  //#endregion
2013
1470
  //#region src/generative-ui/markdown/context.ts
2014
1471
  /**
@@ -2087,815 +1544,13 @@ function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
2087
1544
  ]);
2088
1545
  }
2089
1546
 
2090
- //#endregion
2091
- //#region src/generative-ui/surface-manager.ts
2092
- function surfaceKey(threadId, surfaceId) {
2093
- return `${threadId}::${surfaceId}`;
2094
- }
2095
- let creationCounter = 0;
2096
- const FORBIDDEN_SEGMENTS = new Set([
2097
- "__proto__",
2098
- "constructor",
2099
- "prototype"
2100
- ]);
2101
- /** "/a/b/" to "/a/b". The root stays "/". */
2102
- function normalizePath(path) {
2103
- return (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path) || "/";
2104
- }
2105
- /** True when `path` is `ancestor` or below it. */
2106
- function isAtOrBelow(path, ancestor) {
2107
- if (ancestor === "/") return true;
2108
- return path === ancestor || path.startsWith(`${ancestor}/`);
2109
- }
2110
- /**
2111
- * Rejections as `"operation <index>: <reason>"` lines, cut to the size that
2112
- * the envelope reader accepts.
2113
- */
2114
- function summarizeRejections(rejections) {
2115
- return rejections.slice(0, GENERATIVE_UI_MAX_SUMMARY_REJECTIONS).map(({ index, reason }) => `operation ${index}: ${reason}`.slice(0, GENERATIVE_UI_MAX_REJECTION_LENGTH));
2116
- }
2117
- /**
2118
- * Framework-agnostic store of generated surfaces. One web_core SurfaceModel per
2119
- * (threadId, surfaceId), shared by every mount. Applies only newly committed
2120
- * operations, validates each before applying it, and owns app state and the
2121
- * data model paths that the user wrote, so agent updates cannot overwrite
2122
- * them. App state never goes into a surface's data model. Selectors read it
2123
- * with `getState()`.
2124
- */
2125
- var GenerativeUISurfaceManager = class {
2126
- surfaces = /* @__PURE__ */ new Map();
2127
- bookkeeping = /* @__PURE__ */ new Map();
2128
- listeners = /* @__PURE__ */ new Set();
2129
- /** Mounts of each target id, in mount order. */
2130
- targets = /* @__PURE__ */ new Map();
2131
- state = {};
2132
- /**
2133
- * User-owned data model values, by surface key, then by path. Kept when a
2134
- * surface is rebuilt. Cleared when the surface is deleted.
2135
- */
2136
- owned = /* @__PURE__ */ new Map();
2137
- /**
2138
- * Keys of the surfaces that a `deleteSurface` removed. A surface id is
2139
- * unique for the life of the page, so a key stays here when its surface is
2140
- * built again.
2141
- */
2142
- deletedKeys = /* @__PURE__ */ new Set();
2143
- /**
2144
- * Surfaces that share their data model, by surface key: the parts of a
2145
- * chat surface that the prose lift split. A user write to one part goes
2146
- * to every part, so an input in one part drives a binding in another.
2147
- */
2148
- linked = /* @__PURE__ */ new Map();
2149
- webCoreCatalog;
2150
- activeThreadId;
2151
- version = 0;
2152
- constructor(ui, options = {}) {
2153
- this.ui = ui;
2154
- this.options = options;
2155
- this.webCoreCatalog = new Catalog$1(ui.id, [...ui.components.keys()].map((name) => ({
2156
- name,
2157
- schema: z.any()
2158
- })), []);
2159
- }
2160
- subscribe = (listener) => {
2161
- this.listeners.add(listener);
2162
- return () => {
2163
- this.listeners.delete(listener);
2164
- };
2165
- };
2166
- getVersion = () => this.version;
2167
- notify() {
2168
- this.version++;
2169
- for (const listener of [...this.listeners]) listener();
2170
- }
2171
- setActiveThread(threadId) {
2172
- if (threadId === this.activeThreadId) return;
2173
- this.activeThreadId = threadId;
2174
- this.notify();
2175
- }
2176
- getActiveThread() {
2177
- return this.activeThreadId;
2178
- }
2179
- ingest(threadId, agentId, content) {
2180
- const key = surfaceKey(threadId, content.surfaceId);
2181
- const operations = content.operations ?? [];
2182
- let surface = this.surfaces.get(key);
2183
- let book = this.bookkeeping.get(key);
2184
- let changed = false;
2185
- if (surface && book && !this.extendsApplied(book, operations)) {
2186
- this.disposeSurface(key);
2187
- surface = void 0;
2188
- book = void 0;
2189
- }
2190
- if (!surface || !book) {
2191
- surface = this.createSurface(key, threadId, agentId, content);
2192
- this.restoreOwnedValues(surface);
2193
- book = {
2194
- appliedCount: 0,
2195
- lastFingerprint: void 0
2196
- };
2197
- this.surfaces.set(key, surface);
2198
- this.bookkeeping.set(key, book);
2199
- changed = true;
2200
- }
2201
- const serverRejected = content.rejected ?? [];
2202
- if (surface.clientRejected.length > 0 && (surface.status !== "streaming" && content.status === "streaming" || serverRejected.length < surface.serverRejected.length)) {
2203
- surface.clientRejected = [];
2204
- changed = true;
2205
- }
2206
- if (operations.length > 0) {
2207
- const lastFingerprint = JSON.stringify(operations[operations.length - 1]);
2208
- const isReplay = operations.some((op) => getOperationKind(op) === "deleteSurface");
2209
- for (let index = book.appliedCount; index < operations.length; index++) {
2210
- this.applyOperation(surface, operations[index], {
2211
- index,
2212
- isReplay
2213
- });
2214
- changed = true;
2215
- }
2216
- book.appliedCount = operations.length;
2217
- surface.operations = operations;
2218
- book.lastFingerprint = lastFingerprint;
2219
- }
2220
- if (surface.status !== content.status || surface.target !== content.target || surface.serverRejected.length !== serverRejected.length) {
2221
- surface.status = content.status;
2222
- surface.target = content.target;
2223
- surface.serverRejected = serverRejected;
2224
- changed = true;
2225
- }
2226
- if (changed) this.notify();
2227
- }
2228
- /** The surface of a `key` (see `surfaceKey`), unless it is deleted. */
2229
- getSurfaceByKey(key) {
2230
- const surface = this.surfaces.get(key);
2231
- return surface && !surface.deleted ? surface : void 0;
2232
- }
2233
- getSurface(threadId, surfaceId) {
2234
- const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
2235
- return surface && !surface.deleted ? surface : void 0;
2236
- }
2237
- getSurfaceForTarget(target, threadId = this.activeThreadId) {
2238
- if (!threadId) return void 0;
2239
- let latest;
2240
- for (const surface of this.surfaces.values()) {
2241
- if (surface.threadId !== threadId || surface.target !== target || surface.deleted) continue;
2242
- if (!latest || surface.createdAt > latest.createdAt) latest = surface;
2243
- }
2244
- return latest;
2245
- }
2246
- /**
2247
- * A surface whose first createSurface was rejected, so the chat can show
2248
- * the error where the surface would be. `undefined` for any other surface.
2249
- */
2250
- getFailedSurface(threadId, surfaceId) {
2251
- const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
2252
- return surface?.failed ? surface : void 0;
2253
- }
2254
- /**
2255
- * The surfaces of a thread, for the model. A surface with user-owned
2256
- * values lists them in `dataModel`, so the model can read what the user
2257
- * entered. A surface with dropped operations lists them in `rejected`, so
2258
- * the model can fix them on the next run. A deleted surface, or one that
2259
- * was never created, has a `status`, so the model knows that the id is
2260
- * not a live surface.
2261
- */
2262
- describeSurfaces(threadId) {
2263
- const described = {};
2264
- for (const surface of this.surfaces.values()) {
2265
- if (surface.threadId !== threadId) continue;
2266
- const owned = this.owned.get(surface.key);
2267
- const rejections = [...surface.serverRejected, ...surface.clientRejected];
2268
- const status = this.deletedKeys.has(surface.key) ? "deleted" : surface.failed ? "failed" : void 0;
2269
- described[surface.surfaceId] = {
2270
- target: surface.target,
2271
- ...owned && owned.size > 0 ? { dataModel: Object.fromEntries(owned) } : {},
2272
- ...rejections.length > 0 && status !== "deleted" ? { rejected: summarizeRejections(rejections) } : {},
2273
- ...status ? { status } : {}
2274
- };
2275
- }
2276
- return described;
2277
- }
2278
- /** Every surface that is not deleted, oldest first, for the inspector. */
2279
- debugSurfaces() {
2280
- return [...this.surfaces.values()].filter((surface) => !surface.deleted).sort((a, b) => a.createdAt - b.createdAt).map((surface) => ({
2281
- surfaceId: surface.surfaceId,
2282
- threadId: surface.threadId,
2283
- agentId: surface.agentId,
2284
- target: surface.target,
2285
- status: surface.status,
2286
- operations: surface.operations,
2287
- dataModel: surface.model.dataModel.get("/"),
2288
- userValues: Object.fromEntries(this.owned.get(surface.key) ?? []),
2289
- rejected: [...surface.serverRejected.map((r) => ({
2290
- ...r,
2291
- source: "runtime"
2292
- })), ...surface.clientRejected.map((r) => ({
2293
- ...r,
2294
- source: "browser"
2295
- }))]
2296
- }));
2297
- }
2298
- /**
2299
- * Marks a target as mounted. Returns the function that unmounts it. Calling
2300
- * that function more than once has no effect.
2301
- *
2302
- * @param id - The target id.
2303
- * @param options - The description and the allowed components of this mount.
2304
- */
2305
- registerTarget(id, options = {}) {
2306
- const registration = { ...options };
2307
- const registrations = this.targets.get(id) ?? /* @__PURE__ */ new Set();
2308
- registrations.add(registration);
2309
- this.targets.set(id, registrations);
2310
- this.notify();
2311
- let released = false;
2312
- return () => {
2313
- if (released) return;
2314
- released = true;
2315
- registrations.delete(registration);
2316
- if (registrations.size === 0) this.targets.delete(id);
2317
- this.notify();
2318
- };
2319
- }
2320
- /**
2321
- * The mounted targets. Each has the description and the component list of
2322
- * its earliest mount that has one.
2323
- */
2324
- getMountedTargets() {
2325
- const mounted = [];
2326
- for (const [id, registrations] of this.targets) {
2327
- const description = [...registrations].find((registration) => registration.description !== void 0)?.description;
2328
- const components = this.targetComponents(id);
2329
- mounted.push({
2330
- id,
2331
- ...description === void 0 ? {} : { description },
2332
- ...components === void 0 ? {} : { components: [...components] }
2333
- });
2334
- }
2335
- return mounted;
2336
- }
2337
- /**
2338
- * The component list of the earliest mount of `id` that has one.
2339
- * `undefined` when no mount of `id` limits its components.
2340
- */
2341
- targetComponents(id) {
2342
- return [...this.targets.get(id) ?? /* @__PURE__ */ new Set()].find((registration) => registration.components !== void 0)?.components;
2343
- }
2344
- /** The components that `validateOperation` allows on a surface. */
2345
- allowedComponentsFor(surface) {
2346
- const components = this.targetComponents(surface.target);
2347
- return components === void 0 ? void 0 : {
2348
- target: surface.target,
2349
- names: new Set(components)
2350
- };
2351
- }
2352
- /**
2353
- * The app state object. It is the same object until a key changes, so it
2354
- * can be a `useSyncExternalStore` snapshot.
2355
- */
2356
- getState = () => this.state;
2357
- /** Sets one state key. Notifies only when the value changed. */
2358
- setState(key, value) {
2359
- if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
2360
- this.state = {
2361
- ...this.state,
2362
- [key]: value
2363
- };
2364
- this.notify();
2365
- }
2366
- /** Removes one state key. Notifies only when the key was set. */
2367
- removeState(key) {
2368
- if (!Object.hasOwn(this.state, key)) return;
2369
- const { [key]: _removed, ...rest } = this.state;
2370
- this.state = rest;
2371
- this.notify();
2372
- }
2373
- /**
2374
- * Makes the surfaces of `surfaceIds` share their data model: a user write
2375
- * to one of them goes to all of them (see `setOwnedValue`). The markdown
2376
- * transport links the parts of a chat surface that the prose lift split.
2377
- * A later call for one of the surfaces replaces its group.
2378
- *
2379
- * @param threadId - The thread of the surfaces.
2380
- * @param surfaceIds - The surface ids of the group. One id clears a link.
2381
- */
2382
- linkSurfaces(threadId, surfaceIds) {
2383
- const keys = new Set(surfaceIds.map((id) => surfaceKey(threadId, id)));
2384
- for (const key of keys) if (keys.size > 1) this.linked.set(key, keys);
2385
- else this.linked.delete(key);
2386
- }
2387
- /**
2388
- * Writes a user value into the data model of a surface, and marks `path`
2389
- * as user-owned. Then agent writes to that path, or below it, are ignored.
2390
- * An agent write above it keeps the user value. Ownership ends when the
2391
- * surface is deleted. Does nothing for an unknown or deleted surface. The
2392
- * surfaces linked to it (see `linkSurfaces`) get the same write.
2393
- *
2394
- * @param key - The `key` of the surface.
2395
- * @param path - An absolute JSON pointer, for example "/form/email".
2396
- * @param value - The new value. It is copied.
2397
- * @throws Error when a path segment is "__proto__", "constructor" or
2398
- * "prototype", or when the path does not fit the data (for example, a
2399
- * segment above it holds a string).
2400
- */
2401
- setOwnedValue(key, path, value) {
2402
- const normalized = normalizePath(path);
2403
- const forbidden = normalized.split("/").find((segment) => FORBIDDEN_SEGMENTS.has(segment));
2404
- if (forbidden !== void 0) throw new Error(`[generativeUI] path segment "${forbidden}" is not allowed in "${path}".`);
2405
- for (const target of this.linked.get(key) ?? [key]) this.writeOwnedValue(target, normalized, value);
2406
- }
2407
- writeOwnedValue(key, path, value) {
2408
- const surface = this.surfaces.get(key);
2409
- if (!surface || surface.deleted) return;
2410
- surface.model.dataModel.set(path, structuredClone(value));
2411
- const owned = this.owned.get(key) ?? /* @__PURE__ */ new Map();
2412
- owned.set(path, structuredClone(value));
2413
- this.owned.set(key, owned);
2414
- }
2415
- /**
2416
- * Writes the user-owned values into the new, empty data model of a rebuilt
2417
- * surface. The agent operations are applied after it.
2418
- */
2419
- restoreOwnedValues(surface) {
2420
- const owned = this.owned.get(surface.key) ?? /* @__PURE__ */ new Map();
2421
- for (const [path, value] of owned) surface.model.dataModel.set(path, structuredClone(value));
2422
- }
2423
- /**
2424
- * The value that an agent write puts at `path`, with the user-owned values
2425
- * below `path` written back into it. `undefined` when `path` is user-owned
2426
- * or below a user-owned path, so the agent cannot write it. Throws when a
2427
- * user value does not fit the new value.
2428
- */
2429
- mergeOwnedValues(key, path, value) {
2430
- const merged = { value: structuredClone(value) };
2431
- const owned = this.owned.get(key);
2432
- if (!owned) return merged;
2433
- const ownedPaths = [...owned.keys()];
2434
- if (ownedPaths.some((ownedPath) => isAtOrBelow(path, ownedPath))) return void 0;
2435
- const below = ownedPaths.filter((ownedPath) => isAtOrBelow(ownedPath, path));
2436
- if (below.length === 0) return merged;
2437
- const scratch = new DataModel({ value: merged.value });
2438
- const prefix = path === "/" ? "" : path;
2439
- for (const ownedPath of below) {
2440
- const relative = ownedPath.slice(prefix.length);
2441
- scratch.set(`/value${relative}`, structuredClone(owned.get(ownedPath)));
2442
- }
2443
- return { value: scratch.get("/value") };
2444
- }
2445
- extendsApplied(book, operations) {
2446
- if (operations.length < book.appliedCount) return false;
2447
- if (book.appliedCount === 0) return true;
2448
- return JSON.stringify(operations[book.appliedCount - 1]) === book.lastFingerprint;
2449
- }
2450
- createSurface(key, threadId, agentId, content) {
2451
- return {
2452
- key,
2453
- threadId,
2454
- surfaceId: content.surfaceId,
2455
- agentId,
2456
- model: new SurfaceModel(content.surfaceId, this.webCoreCatalog),
2457
- createdAt: ++creationCounter,
2458
- target: content.target,
2459
- status: content.status,
2460
- deleted: false,
2461
- failed: false,
2462
- serverRejected: content.rejected ?? [],
2463
- clientRejected: [],
2464
- operations: []
2465
- };
2466
- }
2467
- disposeSurface(key) {
2468
- this.surfaces.get(key)?.model.dispose();
2469
- this.surfaces.delete(key);
2470
- this.bookkeeping.delete(key);
2471
- }
2472
- /**
2473
- * Marks a surface deleted and frees its components and data. The record
2474
- * stays, so the model is still told about the id and the bookkeeping does
2475
- * not rebuild the surface for content that was already applied.
2476
- */
2477
- closeSurface(surface) {
2478
- surface.deleted = true;
2479
- surface.model.dispose();
2480
- surface.model = new SurfaceModel(surface.surfaceId, this.webCoreCatalog);
2481
- this.owned.delete(surface.key);
2482
- this.linked.delete(surface.key);
2483
- }
2484
- /** The surfaces of a thread that a part of `surfaceId` reads, for tests. */
2485
- getLinkedSurfaceIds(threadId, surfaceId) {
2486
- const keys = this.linked.get(surfaceKey(threadId, surfaceId));
2487
- if (!keys) return [surfaceId];
2488
- const prefix = `${threadId}::`;
2489
- return [...keys].map((key) => key.slice(prefix.length));
2490
- }
2491
- /**
2492
- * Drops the node keys that the app sets: bound props and matched events.
2493
- * The model does not see them, so a model value for one is ignored, not
2494
- * rejected. This runs before validation, because validation rejects keys
2495
- * that are not in the manifest. It never changes the given operation.
2496
- */
2497
- dropAppSetKeys(op) {
2498
- const kind = getOperationKind(op);
2499
- if (kind !== "updateComponents" && kind !== "createSurface") return op;
2500
- const record = op;
2501
- const payload = record[kind];
2502
- const nodes = payload?.components;
2503
- if (!Array.isArray(nodes)) return op;
2504
- return {
2505
- ...record,
2506
- [kind]: {
2507
- ...payload,
2508
- components: nodes.map((node) => this.dropAppSetNodeKeys(node))
2509
- }
2510
- };
2511
- }
2512
- dropAppSetNodeKeys(node) {
2513
- if (typeof node !== "object" || node === null || !("component" in node)) return node;
2514
- const { component } = node;
2515
- if (typeof component !== "string") return node;
2516
- const definition = this.ui.components.get(component);
2517
- if (!definition) return node;
2518
- return Object.fromEntries(Object.entries(node).filter(([key]) => !Object.hasOwn(definition.selectors, key) && !Object.hasOwn(definition.eventFunctions, key)));
2519
- }
2520
- /**
2521
- * The surfaces that `validateOperation` gets for one operation of the
2522
- * content of `surface`.
2523
- *
2524
- * - `knownSurfaces`: the surface, when it exists before the operation. It
2525
- * does not exist before its first createSurface, or after a delete.
2526
- * - `createdSurfaces`: the surface, when a createSurface at this position
2527
- * uses its id again. That is the case after the first operation, and for
2528
- * a surface that was deleted before, unless the content replays that
2529
- * delete.
2530
- */
2531
- surfacesFor(surface, kind, position) {
2532
- const isFirstCreate = kind === "createSurface" && position.index === 0;
2533
- const exists = !surface.deleted && !isFirstCreate;
2534
- const isRecreate = this.deletedKeys.has(surface.key) && !position.isReplay;
2535
- const isUsedAgain = position.index > 0 || isRecreate;
2536
- return {
2537
- knownSurfaces: new Set(exists ? [surface.surfaceId] : []),
2538
- createdSurfaces: new Set(isUsedAgain ? [surface.surfaceId] : [])
2539
- };
2540
- }
2541
- applyOperation(surface, received, position) {
2542
- const { index } = position;
2543
- const kind = getOperationKind(received);
2544
- if (kind === "callRendererFunction") return;
2545
- const reject = (reason) => {
2546
- if (kind === "createSurface" && index === 0) {
2547
- this.closeSurface(surface);
2548
- surface.failed = true;
2549
- }
2550
- surface.clientRejected.push({
2551
- index,
2552
- reason
2553
- });
2554
- this.options.onOperationRejected?.({
2555
- surfaceId: surface.surfaceId,
2556
- index,
2557
- reason
2558
- });
2559
- };
2560
- const targetId = getOperationSurfaceId(received);
2561
- if (targetId !== void 0 && targetId !== surface.surfaceId) return reject(`operation is for surface "${targetId}", not "${surface.surfaceId}"`);
2562
- const op = this.dropAppSetKeys(received);
2563
- const validation = validateOperation(op, {
2564
- manifest: {
2565
- catalogId: this.ui.id,
2566
- catalogIds: catalogIdsOf(this.ui),
2567
- components: this.ui.manifestComponents
2568
- },
2569
- ...this.surfacesFor(surface, kind, position),
2570
- allowedComponents: this.allowedComponentsFor(surface)
2571
- });
2572
- if (!validation.ok) return reject(validation.reason);
2573
- const typed = op;
2574
- if ("createSurface" in typed) {
2575
- const { dataModel, components = [] } = typed.createSurface;
2576
- const problem = this.nodesProblem(components);
2577
- if (problem) return reject(problem);
2578
- if (dataModel) {
2579
- const failure = this.writeAgentData(surface, "/", dataModel);
2580
- if (failure) return reject(failure);
2581
- }
2582
- for (const node of components) this.upsertNode(surface.model, node);
2583
- return;
2584
- }
2585
- if ("updateComponents" in typed) {
2586
- const nodes = typed.updateComponents.components;
2587
- const problem = this.nodesProblem(nodes);
2588
- if (problem) return reject(problem);
2589
- for (const node of nodes) this.upsertNode(surface.model, node);
2590
- return;
2591
- }
2592
- if ("updateDataModel" in typed) {
2593
- const { path = "/", value } = typed.updateDataModel;
2594
- const written = value === null ? void 0 : value;
2595
- const failure = this.writeAgentData(surface, normalizePath(path), written);
2596
- if (failure) return reject(failure);
2597
- return;
2598
- }
2599
- if ("deleteSurface" in typed) {
2600
- this.closeSurface(surface);
2601
- this.deletedKeys.add(surface.key);
2602
- }
2603
- }
2604
- /** The first node with props of the wrong type, as a reason. */
2605
- nodesProblem(nodes) {
2606
- for (const node of nodes) {
2607
- const problem = this.checkNodeProps(node);
2608
- if (problem) return `component "${node.id}": ${problem}`;
2609
- }
2610
- }
2611
- /**
2612
- * Writes an agent value at `path` and keeps the user-owned values. A write
2613
- * to a user-owned path is ignored, not rejected. Gives the reason when the
2614
- * value does not fit the data, else `undefined`.
2615
- */
2616
- writeAgentData(surface, path, value) {
2617
- try {
2618
- const merged = this.mergeOwnedValues(surface.key, path, value);
2619
- if (merged) surface.model.dataModel.set(path, merged.value);
2620
- return;
2621
- } catch (error) {
2622
- return error instanceof Error ? error.message : String(error);
2623
- }
2624
- }
2625
- checkNodeProps(node) {
2626
- const definition = this.ui.components.get(node.component);
2627
- if (!definition) return `unknown component "${node.component}"`;
2628
- const { id: _id, component: _component, ...rest } = node;
2629
- const dataProps = Object.fromEntries(Object.entries(rest).filter(([key]) => !definition.events?.[key] && !definition.slots?.[key] && !A2UI_COMPONENT_ENVELOPE_KEYS.has(key)));
2630
- if (!definition.props) return void 0;
2631
- const unknownNow = new Set(Object.keys(definition.selectors));
2632
- const literals = {};
2633
- for (const [key, value] of Object.entries(dataProps)) if (containsDynamicValue(value)) unknownNow.add(key);
2634
- else literals[key] = value;
2635
- let result = validateSchemaSync(definition.props, literals);
2636
- if (!result.success) {
2637
- const unset = withoutRejectedNulls(literals, result.issues);
2638
- if (unset) result = validateSchemaSync(definition.props, unset);
2639
- }
2640
- if (result.success) return void 0;
2641
- const issues = result.issues.filter((issue) => {
2642
- const key = issueKey(issue);
2643
- return key === void 0 ? isAsyncIssue(issue) : !unknownNow.has(key);
2644
- });
2645
- return issues.length > 0 ? formatIssues(issues) : void 0;
2646
- }
2647
- upsertNode(model, node) {
2648
- const { id, component, ...rest } = node;
2649
- const properties = structuredClone(rest);
2650
- const existing = model.componentsModel.get(id);
2651
- if (existing && existing.type === component) {
2652
- existing.properties = properties;
2653
- return;
2654
- }
2655
- if (existing) model.componentsModel.removeComponent(id);
2656
- model.componentsModel.addComponent(new ComponentModel(id, component, properties));
2657
- }
2658
- };
2659
-
2660
1547
  //#endregion
2661
1548
  //#region src/generative-ui/use-generative-ui-root.ts
2662
1549
  const isDevelopment = () => process.env.NODE_ENV !== "production";
2663
- /** At most this many function follow-up runs for each user turn. */
2664
- const MAX_FUNCTION_FOLLOW_UPS = 5;
2665
1550
  function ingestMessages(manager, agent, messages) {
2666
1551
  if (!agent.threadId) return;
2667
1552
  for (const message of messages) if (message.role === "activity" && message.activityType === GENERATIVE_UI_ACTIVITY_TYPE) manager.ingest(agent.threadId, agent.agentId, message.content);
2668
1553
  }
2669
- /** What the envelope of a run says, from the provider config. */
2670
- function envelopeOptionsFor(config) {
2671
- if (config.transport === "markdown") return {
2672
- transport: "markdown",
2673
- includeCatalog: config.includeCatalog !== false,
2674
- contextSent: config.sendContext !== false
2675
- };
2676
- return {
2677
- transport: "tool",
2678
- includeCatalog: true,
2679
- contextSent: false
2680
- };
2681
- }
2682
- /**
2683
- * The components of a surface as one `updateComponents` operation, so that
2684
- * the label of the component that sent an event can be found.
2685
- */
2686
- function surfaceComponents(surface) {
2687
- const components = [...surface.model.componentsModel.entries].map(([id, model]) => ({
2688
- ...model.properties,
2689
- id,
2690
- component: model.type
2691
- }));
2692
- return [{
2693
- version: A2UI_VERSION,
2694
- updateComponents: {
2695
- surfaceId: surface.surfaceId,
2696
- components
2697
- }
2698
- }];
2699
- }
2700
- /** True when `value` names a `functionCallId`. */
2701
- function hasFunctionCallId(value) {
2702
- return typeof value === "object" && value !== null && "functionCallId" in value && typeof value.functionCallId === "string" && value.functionCallId !== "";
2703
- }
2704
- /** The `functionCallId` that a developer message answers, if any. */
2705
- function answeredCallId(content) {
2706
- if (!content.includes("rendererFunctionResponse")) return void 0;
2707
- try {
2708
- const parsed = JSON.parse(content);
2709
- const response = typeof parsed === "object" && parsed !== null && "rendererFunctionResponse" in parsed ? parsed.rendererFunctionResponse : void 0;
2710
- return hasFunctionCallId(response) ? response.functionCallId : void 0;
2711
- } catch {
2712
- return;
2713
- }
2714
- }
2715
- /** The function calls that a developer message in `messages` answers. */
2716
- function answeredCallIds(messages) {
2717
- const ids = /* @__PURE__ */ new Set();
2718
- for (const message of messages) {
2719
- if (message.role !== "developer") continue;
2720
- const id = answeredCallId(message.content);
2721
- if (id !== void 0) ids.add(id);
2722
- }
2723
- return ids;
2724
- }
2725
- /** The id of the last user message. A user turn starts with it. */
2726
- function lastUserMessageId(messages) {
2727
- for (let index = messages.length - 1; index >= 0; index--) {
2728
- const message = messages[index];
2729
- if (message?.role === "user") return message.id;
2730
- }
2731
- }
2732
- /** The function calls of the tool transport: its function-call activities. */
2733
- function activityFunctionCalls(messages) {
2734
- const requests = [];
2735
- for (const message of messages) {
2736
- if (!(message.role === "activity" && message.activityType === GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE) || !hasFunctionCallId(message.content)) continue;
2737
- requests.push({
2738
- functionCallId: message.content.functionCallId,
2739
- operation: {
2740
- version: A2UI_VERSION,
2741
- callRendererFunction: message.content
2742
- }
2743
- });
2744
- }
2745
- return requests;
2746
- }
2747
- /** The function calls of the markdown transport: its fence lines. */
2748
- function markdownFunctionCalls(calls) {
2749
- const requests = [];
2750
- for (const { operation } of calls) {
2751
- const payload = operation.callRendererFunction;
2752
- if (!hasFunctionCallId(payload)) continue;
2753
- requests.push({
2754
- functionCallId: payload.functionCallId,
2755
- operation
2756
- });
2757
- }
2758
- return requests;
2759
- }
2760
- /** The text of a `rendererFunctionResponse` developer message. */
2761
- function responseContent(response) {
2762
- return JSON.stringify({
2763
- version: A2UI_VERSION,
2764
- rendererFunctionResponse: response
2765
- });
2766
- }
2767
- function errorAnswer(functionCallId, code, message) {
2768
- return {
2769
- content: responseContent({
2770
- functionCallId,
2771
- error: {
2772
- code,
2773
- message
2774
- }
2775
- }),
2776
- followUp: true
2777
- };
2778
- }
2779
- const overCapAnswer = (functionCallId) => ({
2780
- content: responseContent({
2781
- functionCallId,
2782
- error: {
2783
- code: "follow_up_limit",
2784
- message: `The function did not run. A user turn can have at most ${MAX_FUNCTION_FOLLOW_UPS} function follow-up runs. Wait for the next user message.`
2785
- }
2786
- }),
2787
- followUp: false
2788
- });
2789
- /**
2790
- * Runs the functions that the agent calls with `callRendererFunction`, for
2791
- * both transports, and answers each call.
2792
- *
2793
- * - Each `functionCallId` runs once for each thread. A replay, a sync of
2794
- * the same messages again, or a call that already has an answer message
2795
- * does not run it again.
2796
- * - The answer is a hidden developer message with a `rendererFunctionResponse`.
2797
- * The answers go to the agent only when it is not running. Then one
2798
- * follow-up run starts for all of them.
2799
- * - A user turn has at most {@link MAX_FUNCTION_FOLLOW_UPS} follow-up runs.
2800
- * A call after that does not run. It gets a `follow_up_limit` error and
2801
- * starts no follow-up run.
2802
- */
2803
- function createFunctionCallRunner(options) {
2804
- const { copilotkit, dispatcher, manifest } = options;
2805
- const threads = /* @__PURE__ */ new Map();
2806
- const threadState = (threadId) => {
2807
- let state = threads.get(threadId);
2808
- if (!state) {
2809
- state = {
2810
- done: /* @__PURE__ */ new Set(),
2811
- pending: [],
2812
- turn: void 0,
2813
- followUps: 0,
2814
- flushing: false
2815
- };
2816
- threads.set(threadId, state);
2817
- }
2818
- return state;
2819
- };
2820
- const answer = async (request) => {
2821
- const { functionCallId } = request;
2822
- const validation = validateOperation(request.operation, {
2823
- manifest,
2824
- knownSurfaces: /* @__PURE__ */ new Set()
2825
- });
2826
- if (!validation.ok) return errorAnswer(functionCallId, "invalid_arguments", validation.reason);
2827
- const operation = request.operation;
2828
- if (!("callRendererFunction" in operation)) return errorAnswer(functionCallId, "invalid_arguments", "the operation is not a callRendererFunction");
2829
- const { callFunction } = operation.callRendererFunction;
2830
- const name = callFunction["@call"];
2831
- const result = await dispatcher.invoke(name, callFunction.args ?? {}, { functionCallId });
2832
- if (!result.ok) return errorAnswer(functionCallId, result.error.code, result.error.message);
2833
- try {
2834
- return {
2835
- content: responseContent({
2836
- functionCallId,
2837
- value: result.result ?? null
2838
- }),
2839
- followUp: true
2840
- };
2841
- } catch (cause) {
2842
- return errorAnswer(functionCallId, "handler_failed", `The result of "${name}" is not JSON: ${cause instanceof Error ? cause.message : String(cause)}`);
2843
- }
2844
- };
2845
- /**
2846
- * Adds the pending answers of a thread to the agent, then starts one
2847
- * follow-up run. It waits while the agent runs: the next read of the
2848
- * thread, at the end of the run, flushes again.
2849
- */
2850
- const flush = async (agent, threadId, state) => {
2851
- if (state.flushing) return;
2852
- state.flushing = true;
2853
- try {
2854
- while (state.pending.length > 0) {
2855
- const batch = [...state.pending];
2856
- const answers = await Promise.all(batch);
2857
- await copilotkit.waitForPendingFrameworkUpdates();
2858
- if (agent.isRunning || agent.threadId !== threadId) return;
2859
- if (state.pending.length > batch.length) continue;
2860
- state.pending = [];
2861
- for (const { content } of answers) agent.addMessage({
2862
- id: randomUUID$1(),
2863
- role: "developer",
2864
- content
2865
- });
2866
- if (!answers.some((item) => item.followUp)) continue;
2867
- state.followUps++;
2868
- await copilotkit.runAgent({ agent });
2869
- }
2870
- } catch (error) {
2871
- if (isDevelopment()) console.warn("[generativeUI] function follow-up run failed:", error);
2872
- } finally {
2873
- state.flushing = false;
2874
- }
2875
- };
2876
- return { run(agent, requests, messages, running) {
2877
- const { threadId } = agent;
2878
- if (!threadId) return;
2879
- const state = threadState(threadId);
2880
- const turn = lastUserMessageId(messages);
2881
- if (turn !== state.turn) {
2882
- state.turn = turn;
2883
- state.followUps = 0;
2884
- }
2885
- const isNew = (request) => !state.done.has(request.functionCallId);
2886
- const fresh = requests.filter(isNew);
2887
- const answered = fresh.length > 0 ? answeredCallIds(messages) : /* @__PURE__ */ new Set();
2888
- for (const request of fresh) {
2889
- const { functionCallId } = request;
2890
- if (state.done.has(functionCallId)) continue;
2891
- state.done.add(functionCallId);
2892
- if (answered.has(functionCallId)) continue;
2893
- const isOverCap = state.followUps >= MAX_FUNCTION_FOLLOW_UPS;
2894
- state.pending.push(isOverCap ? Promise.resolve(overCapAnswer(functionCallId)) : answer(request));
2895
- }
2896
- if (!running) flush(agent, threadId, state);
2897
- } };
2898
- }
2899
1554
  /** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */
2900
1555
  function useGenerativeUIRoot(copilotkit, config) {
2901
1556
  const configRef = useRef(config);
@@ -2933,12 +1588,16 @@ function useGenerativeUIRoot(copilotkit, config) {
2933
1588
  }
2934
1589
  });
2935
1590
  const functionCalls = createFunctionCallRunner({
2936
- copilotkit,
1591
+ core: copilotkit,
2937
1592
  dispatcher,
2938
1593
  manifest: {
2939
1594
  catalogId: ui.id,
2940
1595
  catalogIds: catalogIdsOf(ui),
2941
1596
  components: ui.manifestComponents
1597
+ },
1598
+ settle: () => copilotkit.waitForPendingFrameworkUpdates(),
1599
+ warn: (message, error) => {
1600
+ if (isDevelopment()) console.warn(message, error);
2942
1601
  }
2943
1602
  });
2944
1603
  const forwardingAgents = /* @__PURE__ */ new Set();
@@ -3018,7 +1677,7 @@ function useGenerativeUIRoot(copilotkit, config) {
3018
1677
  forwardingAgents.add(agent);
3019
1678
  try {
3020
1679
  const surface = agent.threadId ? manager.getSurface(agent.threadId, event.surfaceId) : void 0;
3021
- const resolveLabel = surface ? createComponentLabelResolver(surfaceComponents(surface)) : void 0;
1680
+ const resolveLabel = surface ? surfaceLabelResolver(surface) : void 0;
3022
1681
  agent.addMessage({
3023
1682
  id: randomUUID$1(),
3024
1683
  role: "user",