@copilotkit/react-core 2.0.0-rc.2 → 2.0.0-rc.20

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 (47) hide show
  1. package/dist/{MarkdownRendererContext-B4Us6mwL.d.cts → MarkdownRendererContext-Bsl28Gmn.d.mts} +17 -33
  2. package/dist/MarkdownRendererContext-Bsl28Gmn.d.mts.map +1 -0
  3. package/dist/{MarkdownRendererContext-CRKFzsEB.d.mts → MarkdownRendererContext-CBppkb5j.d.cts} +17 -33
  4. package/dist/MarkdownRendererContext-CBppkb5j.d.cts.map +1 -0
  5. package/dist/{MarkdownSurfaces-Bd--93O1.mjs → MarkdownSurfaces-Bt7TD_U1.mjs} +177 -136
  6. package/dist/MarkdownSurfaces-Bt7TD_U1.mjs.map +1 -0
  7. package/dist/{MarkdownSurfaces-S4wfUl3J.cjs → MarkdownSurfaces-CoUoPhR9.cjs} +198 -156
  8. package/dist/MarkdownSurfaces-CoUoPhR9.cjs.map +1 -0
  9. package/dist/context.cjs +28 -26
  10. package/dist/context.cjs.map +1 -1
  11. package/dist/context.d.cts +38 -98
  12. package/dist/context.d.cts.map +1 -1
  13. package/dist/context.d.mts +38 -98
  14. package/dist/context.d.mts.map +1 -1
  15. package/dist/context.mjs +28 -26
  16. package/dist/context.mjs.map +1 -1
  17. package/dist/generative-ui.cjs +570 -567
  18. package/dist/generative-ui.cjs.map +1 -1
  19. package/dist/generative-ui.d.cts +2137 -4178
  20. package/dist/generative-ui.d.cts.map +1 -1
  21. package/dist/generative-ui.d.mts +2137 -4178
  22. package/dist/generative-ui.d.mts.map +1 -1
  23. package/dist/generative-ui.mjs +75 -73
  24. package/dist/generative-ui.mjs.map +1 -1
  25. package/dist/headless.cjs +55 -84
  26. package/dist/headless.cjs.map +1 -1
  27. package/dist/headless.d.cts +78 -253
  28. package/dist/headless.d.cts.map +1 -1
  29. package/dist/headless.d.mts +56 -202
  30. package/dist/headless.d.mts.map +1 -1
  31. package/dist/headless.mjs +48 -82
  32. package/dist/headless.mjs.map +1 -1
  33. package/dist/index.cjs +1628 -2398
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.cts +203 -540
  36. package/dist/index.d.cts.map +1 -1
  37. package/dist/index.d.mts +202 -539
  38. package/dist/index.d.mts.map +1 -1
  39. package/dist/index.mjs +965 -2248
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/index.umd.js +1776 -2466
  42. package/dist/index.umd.js.map +1 -1
  43. package/package.json +17 -18
  44. package/dist/MarkdownRendererContext-B4Us6mwL.d.cts.map +0 -1
  45. package/dist/MarkdownRendererContext-CRKFzsEB.d.mts.map +0 -1
  46. package/dist/MarkdownSurfaces-Bd--93O1.mjs.map +0 -1
  47. package/dist/MarkdownSurfaces-S4wfUl3J.cjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,136 +1,28 @@
1
1
  "use client";
2
2
 
3
- import { A as GenerativeUIError, B as renderSlot, C as issueKey, D as getMarkdownSurfaceSource, E as containsDynamicValue, F as toJsonSchema, G as useCopilotChatConfiguration, H as ControlledModalOpenScope, I as defineToolCallRenderer, K as useShallowStableRef, L as MarkdownRendererProvider, M as catalogIdsOf, N as componentCatalogIds, O as BASIC_FUNCTIONS, R as useMarkdownRenderer, S as isAsyncIssue, T as withoutRejectedNulls, U as CopilotChatConfigurationProvider, V as cn, W as CopilotChatDefaultLabels, a as GenerativeUIToolCallRenderer, i as GenerativeUIChatSlotContext, j as isRecord, k as ExpressionError, o as createGenerativeUIActivityRenderer, q as StreamingMarkdownDefaultRenderer, s as createGenerativeUIFunctionCallActivityRenderer, t as MarkdownSurfaces, v as GenerativeUIRuntimeContext, w as validateSchemaSync, x as formatIssues, y as useGenerativeUIRuntime, z as isReactComponentType } from "./MarkdownSurfaces-Bd--93O1.mjs";
4
- import { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotKitCore, CopilotKitCore as CopilotKitCore$1, CopilotKitCoreErrorCode, CopilotKitCoreErrorCode as CopilotKitCoreErrorCode$1, CopilotKitCoreRuntimeConnectionStatus, CopilotKitCoreRuntimeConnectionStatus as CopilotKitCoreRuntimeConnectionStatus$1, CopilotKitHeaderResolutionError, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, IntelligenceAgent, MEMORY_ERROR_REGISTRY, MemoryError, ProxiedCopilotRuntimeAgent, ProxiedCopilotRuntimeAgent as ProxiedCopilotRuntimeAgent$1, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, ToolCallStatus as ToolCallStatus$1, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorActiveThread as emitInspectorActiveThread$1, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, emitInspectorViewThreadResult as emitInspectorViewThreadResult$1, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isInspectorThreadBridgeEnabled as isInspectorThreadBridgeEnabled$1, isRunCompletionAware, isRunCompletionAware as isRunCompletionAware$1, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorStopViewing as onInspectorStopViewing$1, onInspectorViewThread, onInspectorViewThread as onInspectorViewThread$1, onInspectorViewThreadResult, parseMarkdown, parseMarkdown as parseMarkdown$1, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵInterruptState as ɵInterruptState$1, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, ɵclearAgentInterruptState as ɵclearAgentInterruptState$1, ɵcreateMemoryStore, ɵcreateThreadSelectors, ɵcreateThreadStore, ɵcreateThreadStore as ɵcreateThreadStore$1, ɵgetAgentInterruptState, ɵgetAgentInterruptState as ɵgetAgentInterruptState$1, ɵisCopilotKitFeature, ɵisHttpAgent, ɵisHttpAgent as ɵisHttpAgent$1, ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectFetchMoreError as ɵselectFetchMoreError$1, ɵselectHasNextPage, ɵselectHasNextPage as ɵselectHasNextPage$1, ɵselectIsFetchingNextPage, ɵselectIsFetchingNextPage as ɵselectIsFetchingNextPage$1, ɵselectIsMutating, ɵselectIsMutating as ɵselectIsMutating$1, ɵ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, ɵselectThreads as ɵselectThreads$1, ɵselectThreadsError, ɵselectThreadsError as ɵselectThreadsError$1, ɵselectThreadsIsLoading, ɵselectThreadsIsLoading as ɵselectThreadsIsLoading$1, ɵthreadAdapterEvents, ɵwithHeaderDefaults, ɵwithHeaderDefaults as ɵwithHeaderDefaults$1 } from "@copilotkit/core";
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-Bt7TD_U1.mjs";
4
+ import { A2UI_FENCE_LANGUAGE, AgentRegistry, AgentThreadLockedError, ContextStore, CopilotChatDefaultLabels, CopilotChatDefaultLabels as CopilotChatDefaultLabels$1, CopilotKitCore, CopilotKitCore as CopilotKitCore$1, CopilotKitCoreErrorCode, CopilotKitCoreErrorCode as CopilotKitCoreErrorCode$1, CopilotKitCoreRuntimeConnectionStatus, CopilotKitCoreRuntimeConnectionStatus as CopilotKitCoreRuntimeConnectionStatus$1, CopilotKitHeaderResolutionError, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL as DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL$1, GENERATE_SANDBOXED_UI_TOOL_NAME, GENERATE_SANDBOXED_UI_TOOL_NAME as GENERATE_SANDBOXED_UI_TOOL_NAME$1, 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, ProxiedCopilotRuntimeAgent as ProxiedCopilotRuntimeAgent$1, RunHandler, StateManager, SuggestionEngine, ToolCallStatus, ToolCallStatus as ToolCallStatus$1, TranscriptionError, TranscriptionError as TranscriptionError$1, TranscriptionErrorCode, WebMCPRegistry, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorActiveThread as emitInspectorActiveThread$1, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, emitInspectorViewThreadResult as emitInspectorViewThreadResult$1, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isInspectorThreadBridgeEnabled as isInspectorThreadBridgeEnabled$1, isRunCompletionAware, isRunCompletionAware as isRunCompletionAware$1, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorStopViewing as onInspectorStopViewing$1, onInspectorViewThread, onInspectorViewThread as onInspectorViewThread$1, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵCOPY_FEEDBACK_RESET_MS, ɵCopyFeedback, ɵCopyFeedback as ɵCopyFeedback$1, ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS, ɵFeedbackCommentController, ɵFeedbackCommentController as ɵFeedbackCommentController$1, ɵHOVER_MENU_CLOSE_DELAY_MS, ɵHoverMenuController, ɵHoverMenuController as ɵHoverMenuController$1, ɵINLINE_FEATURE_WARNING_STYLE, ɵINLINE_FEATURE_WARNING_STYLE as ɵINLINE_FEATURE_WARNING_STYLE$1, ɵInterruptState, ɵInterruptState as ɵInterruptState$1, ɵKEYBOARD_OPEN_THRESHOLD_PX, ɵLICENSE_BANNER_OFFSET, ɵLICENSE_BANNER_STYLE, ɵLICENSE_BANNER_STYLE as ɵLICENSE_BANNER_STYLE$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, ɵOpenGenerativeUIController, ɵOpenGenerativeUIController as ɵOpenGenerativeUIController$1, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, ɵclearAgentInterruptState as ɵclearAgentInterruptState$1, ɵcn, ɵcomposerButtonState, ɵcomposerButtonState as ɵcomposerButtonState$1, ɵcopilotIconSvgAttributes, ɵcopilotIcons, ɵcountFailedToolCalls, ɵcountFailedToolCalls as ɵcountFailedToolCalls$1, ɵcreateMemoryStore, ɵcreateThreadSelectors, ɵcreateThreadStore, ɵcreateThreadStore as ɵcreateThreadStore$1, ɵdeduplicateMessages, ɵdeduplicateMessages as ɵdeduplicateMessages$1, ɵextractCompleteStyles, ɵflattenUserMessageContent, ɵflattenUserMessageContent as ɵflattenUserMessageContent$1, ɵformatCountLabel, ɵformatCountLabel as ɵformatCountLabel$1, ɵformatLabel, ɵformatLabel as ɵformatLabel$1, ɵformatReasoningDuration, ɵformatReasoningDurationLabel, ɵformatReasoningDurationLabel as ɵformatReasoningDurationLabel$1, ɵformatToolNames, ɵformatToolNames as ɵformatToolNames$1, ɵformatWorkDuration, ɵgetAgentInterruptState, ɵgetAgentInterruptState as ɵgetAgentInterruptState$1, ɵgetArgumentPreview, ɵgetArgumentPreview as ɵgetArgumentPreview$1, ɵgetBranchNavState, ɵgetBranchNavState as ɵgetBranchNavState$1, ɵgetInlineFeatureWarningSpec, ɵgetInlineFeatureWarningSpec as ɵgetInlineFeatureWarningSpec$1, ɵgetLatestTurnKey, ɵgetLatestTurnKey as ɵgetLatestTurnKey$1, ɵgetLicenseBannerSpec, ɵgetLicenseBannerSpec as ɵgetLicenseBannerSpec$1, ɵgetMessageFeedback, ɵgetMessageFeedback as ɵgetMessageFeedback$1, ɵgetMessageFeedbackControls, ɵgetMessageFeedbackControls as ɵgetMessageFeedbackControls$1, ɵgetToolCallLayouts, ɵgetToolCallLayouts as ɵgetToolCallLayouts$1, ɵgetToolCallPreview, ɵgetToolCallPreview as ɵgetToolCallPreview$1, ɵgetToolCallRendererNames, ɵgetToolCallRendererNames as ɵgetToolCallRendererNames$1, ɵgetToolCallRowStatus, ɵgetToolCallRowStatus as ɵgetToolCallRowStatus$1, ɵgetToolResults, ɵgetTurnWork, ɵgetTurnWork as ɵgetTurnWork$1, ɵgetUserMessageMediaFilename, ɵgetUserMessageMediaFilename as ɵgetUserMessageMediaFilename$1, ɵgetUserMessageMediaParts, ɵgetUserMessageMediaParts as ɵgetUserMessageMediaParts$1, ɵgetWorkOpenState, ɵgetWorkOpenState as ɵgetWorkOpenState$1, ɵgetWorkSummaryText, ɵgetWorkSummaryText as ɵgetWorkSummaryText$1, ɵhasAssistantMessageText, ɵhasAssistantMessageText as ɵhasAssistantMessageText$1, ɵinitialKeyboardState, ɵinitialKeyboardState as ɵinitialKeyboardState$1, ɵinspectorKiteFill, ɵinspectorKiteFill as ɵinspectorKiteFill$1, ɵinspectorKiteIcon, ɵinspectorKiteIcon as ɵinspectorKiteIcon$1, ɵinspectorShortcuts, ɵinspectorShortcuts as ɵinspectorShortcuts$1, ɵisCopilotKitFeature, ɵisHttpAgent, ɵisHttpAgent as ɵisHttpAgent$1, ɵisLearningFeedbackEnabled, ɵisLearningFeedbackEnabled as ɵisLearningFeedbackEnabled$1, ɵisMobileViewport, ɵisRetryableMemoryStatus, ɵisTurnWorkOpen, ɵisTurnWorkOpen as ɵisTurnWorkOpen$1, ɵisTurnWorking, ɵisTurnWorking as ɵisTurnWorking$1, ɵjoinPhoenixChannel$, ɵloadWebsandbox, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵmessagesFingerprint as ɵmessagesFingerprint$1, ɵnormalizeAutoScroll, ɵnormalizeAutoScroll as normalizeAutoScroll, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵpinMessageToTop, ɵpinMessageToTop as ɵpinMessageToTop$1, ɵpluralize, ɵprocessPartialHtml, ɵreadKeyboardState, ɵrecordWorkTime, ɵrecordWorkTime as ɵrecordWorkTime$1, ɵreserveLicenseBannerOffset, ɵreserveLicenseBannerOffset as ɵreserveLicenseBannerOffset$1, ɵresetMessageFeedbackCache, ɵresolveActivityRenderer, ɵresolveActivityRenderer as ɵresolveActivityRenderer$1, ɵresolveComposerKey, ɵresolveComposerKey as ɵresolveComposerKey$1, ɵresolveCustomMessageRenderers, ɵresolveCustomMessageRenderers as ɵresolveCustomMessageRenderers$1, ɵresolveLicenseState, ɵresolveLicenseState as ɵresolveLicenseState$1, ɵresolveThreadsLicense, ɵresolveToolCallRenderer, ɵresolveToolCallRenderer as ɵresolveToolCallRenderer$1, ɵselectFetchMoreError, ɵselectFetchMoreError as ɵselectFetchMoreError$1, ɵselectHasNextPage, ɵselectHasNextPage as ɵselectHasNextPage$1, ɵselectIsFetchingNextPage, ɵselectIsFetchingNextPage as ɵselectIsFetchingNextPage$1, ɵselectIsMutating, ɵselectIsMutating as ɵselectIsMutating$1, ɵ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, ɵselectThreads as ɵselectThreads$1, ɵselectThreadsError, ɵselectThreadsError as ɵselectThreadsError$1, ɵselectThreadsIsLoading, ɵselectThreadsIsLoading as ɵselectThreadsIsLoading$1, ɵsetMessageFeedback, ɵshallowEqualRecord, ɵshouldShowAssistantToolbar, ɵshouldShowAssistantToolbar as ɵshouldShowAssistantToolbar$1, ɵstringifyToolCallPayload, ɵstringifyToolCallPayload as ɵstringifyToolCallPayload$1, ɵsubscribeToLearningFeedbackEnabled, ɵsubscribeToLearningFeedbackEnabled as ɵsubscribeToLearningFeedbackEnabled$1, ɵsubscribeToMessageFeedback, ɵsubscribeToMessageFeedback as ɵsubscribeToMessageFeedback$1, ɵthreadAdapterEvents, ɵtranscribeAudio, ɵtranscribeAudio as ɵtranscribeAudio$1, ɵtranscriptionErrorMessageKey, ɵtranscriptionErrorMessageKey as ɵtranscriptionErrorMessageKey$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, AGUIError, AGUI_METADATA_KEY, AbstractAgent, BackwardCompatibility_0_0_39, BackwardCompatibility_0_0_45, BackwardCompatibility_0_0_57, CompatibilityBoundary, 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, randomUUID as randomUUID$1, 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";
7
7
  import * as React$1 from "react";
8
8
  import React, { Fragment, createContext, createElement, forwardRef, memo, useCallback, useContext, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, version } from "react";
9
9
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
10
- import { ArrowUp, Check, ChevronDown, ChevronLeft, ChevronRight, ChevronRightIcon, Circle, Copy, Edit, EyeOff, Loader2, MessageCircle, Mic, PanelLeftOpen, Play, Plus, RefreshCw, Square, ThumbsDown, ThumbsUp, Upload, Volume2, Wrench, X } from "lucide-react";
11
- import { A2UI_COMPONENT_ENVELOPE_KEYS, A2UI_DEFAULT_DESIGN_GUIDELINES, A2UI_DEFAULT_GENERATION_GUIDELINES, A2UI_VERSION, COPILOTKIT_FORWARDED_PROPS_KEY, COPILOTKIT_UI_ENVELOPE_FORMAT, DEFAULT_AGENT_ID, GENERATE_SANDBOXED_UI_DESCRIPTION, 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, TranscriptionErrorCode, TranscriptionErrorCode as TranscriptionErrorCode$1, buildGenerativeUIMarkdownGuidelines, buildGenerativeUIPrompt, callerProblem, childRefKind, commitRowKeyStore, copyToClipboard, createAttachmentContent, createLicenseContextValue, createRowKeyStore, envelopeToManifest, exceedsMaxSize, formatFileSize, functionCallers, generateVideoThumbnail, generativeUIGuideFeatures, getDocumentIcon, getModalityFromMimeType, getOperationKind, getOperationSurfaceId, getSourceUrl, matchesAcceptFilter, partialJSONParse, randomUUID as randomUUID$2, readFileAsBase64, resolveRowRenderKeysById, schemaToJsonSchema, shouldEnableInspector, toA2UIActionMessage, validateOperation } from "@copilotkit/shared";
10
+ import { A2UI_COMPONENT_ENVELOPE_KEYS, A2UI_DEFAULT_DESIGN_GUIDELINES, A2UI_DEFAULT_GENERATION_GUIDELINES, A2UI_VERSION, COPILOTKIT_FORWARDED_PROPS_KEY, COPILOTKIT_UI_ENVELOPE_FORMAT, DEFAULT_AGENT_ID, GENERATE_SANDBOXED_UI_DESCRIPTION, 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, createAttachmentContent, createRowKeyStore, defaultGenerativeUIPromptSpec, envelopeToManifest, exceedsMaxSize, formatFileSize, functionCallers, generateVideoThumbnail, generativeUIGuideFeatures, getDocumentIcon, getModalityFromMimeType, getOperationKind, getOperationSurfaceId, getSourceUrl, matchesAcceptFilter, partialJSONParse, randomUUID as randomUUID$2, readFileAsBase64, renderGenerativeUISchema, resolveRowRenderKeysById, schemaToJsonSchema, shouldEnableInspector, toA2UIActionMessage, validateOperation, ɵanySchema } from "@copilotkit/shared";
12
11
  import { CopilotKitAgentIdContext, CopilotKitContext, LicenseContext, useCopilotKit, useCopilotKit as useCopilotKit$1, useDefaultAgentId, useLicenseContext, useLicenseContext as useLicenseContext$1 } from "@copilotkit/react-core/context";
13
- import { Slot } from "@radix-ui/react-slot";
14
12
  import * as TooltipPrimitive from "@radix-ui/react-tooltip";
15
13
  import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
16
14
  import { contentToText as contentToText$1 } from "@ag-ui/core";
17
- import { z } from "zod";
18
15
  import { MCPAppsActivityContentSchema, MCPAppsActivityType, ɵrunMcpFollowUp } from "@copilotkit/mcp-apps-renderer/activity";
16
+ import * as z from "zod";
19
17
  import { A2UIProvider, A2UIRenderer, A2UI_SCHEMA_CONTEXT_DESCRIPTION, Catalog, DEFAULT_SURFACE_ID, ROOT_COMPONENT_ID, buildCatalogContextValue, defaultTheme as a2uiDefaultTheme, extractCatalogComponentSchemas, filterCatalog, initializeDefaultCatalog, injectStyles, useA2UIActions, useA2UIError, viewerTheme } from "@copilotkit/a2ui-renderer";
20
- import { zodToJsonSchema } from "zod-to-json-schema";
21
18
  import { Catalog as Catalog$1, ComponentModel, DataModel, SurfaceModel } from "@a2ui/web_core/v0_9";
22
19
  import { stylesheet } from "@copilotkit/core/styles";
23
20
  import * as PopoverPrimitive from "@radix-ui/react-popover";
24
21
  import { createPortal, flushSync } from "react-dom";
25
- import { useVirtualizer } from "@tanstack/react-virtual";
22
+ import { observeElementRect, useVirtualizer } from "@tanstack/react-virtual";
26
23
  import { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";
27
24
  import { COPILOTKIT_THREADS_DRAWER_TAG, defineCopilotKitThreadsDrawer } from "@copilotkit/web-components/threads-drawer";
28
25
 
29
- //#region src/components/chat/BasicMarkdownRenderer.tsx
30
- const SAFE_HREF = /^(https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i;
31
- const SAFE_IMG_SRC = /^(https?:|data:image\/(?!svg)|\/|\.\/|\.\.\/)/i;
32
- function sanitizeHref(href) {
33
- if (!href) return void 0;
34
- return SAFE_HREF.test(href.trim()) ? href : void 0;
35
- }
36
- function sanitizeImgSrc(src) {
37
- if (!src) return void 0;
38
- return SAFE_IMG_SRC.test(src.trim()) ? src : void 0;
39
- }
40
- /**
41
- * Dependency-light built-in markdown renderer (basic GFM). Walks the
42
- * framework-agnostic token tree from `@copilotkit/core` into React elements.
43
- * No syntax highlighting, no math, no table/image action buttons — plug in a
44
- * custom renderer via `CopilotKitProvider markdownRenderer={...}` for those.
45
- */
46
- function BasicMarkdownRenderer({ content, className }) {
47
- const tokens = React.useMemo(() => parseMarkdown$1(content ?? ""), [content]);
48
- if (!tokens.length) return null;
49
- return /* @__PURE__ */ jsx("div", {
50
- className,
51
- children: tokens.map((t, i) => /* @__PURE__ */ jsx(BlockToken, { token: t }, i))
52
- });
53
- }
54
- function renderInline(tokens) {
55
- if (!tokens) return null;
56
- return tokens.map((token, i) => {
57
- switch (token.type) {
58
- case "text": return "tokens" in token && token.tokens ? renderInline(token.tokens) : token.text;
59
- case "strong": return /* @__PURE__ */ jsx("strong", { children: renderInline(token.tokens) }, i);
60
- case "em": return /* @__PURE__ */ jsx("em", { children: renderInline(token.tokens) }, i);
61
- case "del": return /* @__PURE__ */ jsx("del", { children: renderInline(token.tokens) }, i);
62
- case "codespan": return /* @__PURE__ */ jsx("code", {
63
- className: "cpk-markdown-inline-code",
64
- children: token.text
65
- }, i);
66
- case "br": return /* @__PURE__ */ jsx("br", {}, i);
67
- case "link": {
68
- const l = token;
69
- return /* @__PURE__ */ jsx("a", {
70
- href: sanitizeHref(l.href),
71
- target: "_blank",
72
- rel: "noopener noreferrer",
73
- children: l.tokens ? renderInline(l.tokens) : l.text
74
- }, i);
75
- }
76
- case "image": {
77
- const img = token;
78
- return /* @__PURE__ */ jsx("img", {
79
- src: sanitizeImgSrc(img.href),
80
- alt: img.text,
81
- className: "cpk-markdown-image"
82
- }, i);
83
- }
84
- case "escape": return token.text;
85
- default: return "text" in token ? token.text : null;
86
- }
87
- });
88
- }
89
- function BlockToken({ token }) {
90
- switch (token.type) {
91
- case "space": return null;
92
- case "heading": {
93
- const h = token;
94
- return /* @__PURE__ */ jsx(`h${Math.min(Math.max(h.depth, 1), 6)}`, { children: renderInline(h.tokens) });
95
- }
96
- case "paragraph": return /* @__PURE__ */ jsx("p", { children: renderInline(token.tokens ?? []) });
97
- case "blockquote": return /* @__PURE__ */ jsx("blockquote", { children: (token.tokens ?? []).map((t, i) => /* @__PURE__ */ jsx(BlockToken, { token: t }, i)) });
98
- case "code": {
99
- const c = token;
100
- return /* @__PURE__ */ jsx("pre", {
101
- className: "cpk-markdown-code-block",
102
- children: /* @__PURE__ */ jsx("code", {
103
- "data-language": c.lang || void 0,
104
- children: c.text
105
- })
106
- });
107
- }
108
- case "hr": return /* @__PURE__ */ jsx("hr", {});
109
- case "list": {
110
- const list = token;
111
- const items = list.items.map((item, i) => /* @__PURE__ */ jsx("li", { children: (item.tokens ?? []).map((t, j) => /* @__PURE__ */ jsx(BlockToken, { token: t }, j)) }, i));
112
- return list.ordered ? /* @__PURE__ */ jsx("ol", {
113
- start: typeof list.start === "number" ? list.start : void 0,
114
- children: items
115
- }) : /* @__PURE__ */ jsx("ul", { children: items });
116
- }
117
- case "table": {
118
- const tbl = token;
119
- return /* @__PURE__ */ jsx("div", {
120
- className: "cpk-markdown-table-container",
121
- children: /* @__PURE__ */ jsxs("table", { children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: tbl.header.map((cell, i) => /* @__PURE__ */ jsx("th", { children: renderInline(cell.tokens) }, i)) }) }), /* @__PURE__ */ jsx("tbody", { children: tbl.rows.map((row, i) => /* @__PURE__ */ jsx("tr", { children: row.map((cell, j) => /* @__PURE__ */ jsx("td", { children: renderInline(cell.tokens) }, j)) }, i)) })] })
122
- });
123
- }
124
- case "text": {
125
- const t = token;
126
- return /* @__PURE__ */ jsx("p", { children: t.tokens ? renderInline(t.tokens) : t.text });
127
- }
128
- default: return "text" in token ? /* @__PURE__ */ jsx("span", { children: token.text }) : null;
129
- }
130
- }
131
- BasicMarkdownRenderer.displayName = "BasicMarkdownRenderer";
132
-
133
- //#endregion
134
26
  //#region src/components/ui/button.tsx
135
27
  const variantClasses = {
136
28
  default: "cpk-button-default",
@@ -158,8 +50,8 @@ const sizeClasses = {
158
50
  function buttonVariants({ variant, size, className, class: classProp } = {}) {
159
51
  return cn("cpk-button", variant !== null && variantClasses[variant ?? "default"], size !== null && sizeClasses[size ?? "default"], classProp, className);
160
52
  }
161
- const Button = React$1.forwardRef(function Button({ className, variant, size, asChild = false, ...props }, ref) {
162
- return /* @__PURE__ */ jsx(asChild ? Slot : "button", {
53
+ const Button = React$1.forwardRef(function Button({ className, variant, size, ...props }, ref) {
54
+ return /* @__PURE__ */ jsx("button", {
163
55
  ref,
164
56
  "data-slot": "button",
165
57
  className: buttonVariants({
@@ -264,7 +156,10 @@ function DropdownMenuSubTrigger({ className, inset, children, ...props }) {
264
156
  "data-inset": inset,
265
157
  className: cn("cpk-dropdown-menu-sub-trigger", className),
266
158
  ...props,
267
- children: [children, /* @__PURE__ */ jsx(ChevronRightIcon, { className: "cpk-dropdown-menu-sub-trigger-icon" })]
159
+ children: [children, /* @__PURE__ */ jsx(CopilotIcon, {
160
+ name: "ChevronRight",
161
+ className: "cpk-dropdown-menu-sub-trigger-icon"
162
+ })]
268
163
  });
269
164
  }
270
165
  function DropdownMenuSubContent({ className, ...props }) {
@@ -504,7 +399,7 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
504
399
  const audioRecorderRef = useRef(null);
505
400
  const slashMenuRef = useRef(null);
506
401
  const config = useCopilotChatConfiguration();
507
- const labels = config?.labels ?? CopilotChatDefaultLabels;
402
+ const labels = config?.labels ?? CopilotChatDefaultLabels$1;
508
403
  const previousModalStateRef = useRef(void 0);
509
404
  const measurementCanvasRef = useRef(null);
510
405
  const measurementsRef = useRef({
@@ -625,6 +520,14 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
625
520
  inputRef.current?.focus();
626
521
  });
627
522
  }, [clearInputValue]);
523
+ const composerInput = {
524
+ mode,
525
+ isRunning,
526
+ value: resolvedValue,
527
+ canSubmit: !!onSubmitMessage,
528
+ canStop: !!onStop
529
+ };
530
+ const { isProcessing, action: buttonAction, disabled: buttonDisabled } = ɵcomposerButtonState$1(composerInput);
628
531
  const handleKeyDown = (e) => {
629
532
  if (e.nativeEvent.isComposing || e.keyCode === 229) return;
630
533
  if (commandQuery !== null && mode === "input") {
@@ -663,11 +566,15 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
663
566
  return;
664
567
  }
665
568
  }
666
- if (e.key === "Enter" && !e.shiftKey) {
667
- e.preventDefault();
668
- if (isProcessing && !canSend) onStop?.();
669
- else send();
670
- }
569
+ if (e.key === "Enter" && !e.shiftKey) e.preventDefault();
570
+ const action = ɵresolveComposerKey$1({
571
+ key: e.key,
572
+ shiftKey: e.shiftKey,
573
+ isComposing: e.nativeEvent.isComposing,
574
+ keyCode: e.keyCode
575
+ }, composerInput);
576
+ if (action === "stop") onStop?.();
577
+ else if (action === "send") send();
671
578
  };
672
579
  const send = () => {
673
580
  if (!onSubmitMessage) return;
@@ -692,9 +599,6 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
692
599
  autoFocus,
693
600
  className: isExpanded ? "cpk-chat-input-textarea-expanded" : "cpk-chat-input-textarea-compact"
694
601
  });
695
- const isProcessing = mode !== "transcribe" && isRunning;
696
- const canSend = resolvedValue.trim().length > 0 && !!onSubmitMessage;
697
- const canStop = !!onStop;
698
602
  const handleSendButtonClick = () => {
699
603
  if (isProcessing) {
700
604
  onStop?.();
@@ -703,12 +607,15 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
703
607
  send();
704
608
  };
705
609
  const BoundAudioRecorder = renderSlot(audioRecorder, CopilotChatAudioRecorder, { ref: audioRecorderRef });
706
- const showsStop = isProcessing && canStop;
610
+ const showsStop = buttonAction === "stop";
707
611
  const BoundSendButton = renderSlot(sendButton, CopilotChatInput.SendButton, {
708
612
  onClick: handleSendButtonClick,
709
- disabled: isProcessing ? !canStop : !canSend,
613
+ disabled: buttonDisabled,
710
614
  "aria-label": showsStop ? labels.chatInputToolbarStopButtonLabel : labels.chatInputToolbarSendButtonLabel,
711
- children: showsStop ? /* @__PURE__ */ jsx(Square, { className: "cpk-chat-input-stop-icon" }) : void 0
615
+ children: showsStop ? /* @__PURE__ */ jsx(CopilotIcon, {
616
+ name: "Square",
617
+ className: "cpk-chat-input-stop-icon"
618
+ }) : void 0
712
619
  });
713
620
  const BoundStartTranscribeButton = renderSlot(startTranscribeButton, CopilotChatInput.StartTranscribeButton, { onClick: onStartTranscribe });
714
621
  const BoundCancelTranscribeButton = renderSlot(cancelTranscribeButton, CopilotChatInput.CancelTranscribeButton, { onClick: onCancelTranscribe });
@@ -965,7 +872,10 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
965
872
  className: "cpk-chat-input-field",
966
873
  children: mode === "transcribe" ? BoundAudioRecorder : mode === "processing" ? /* @__PURE__ */ jsx("div", {
967
874
  className: "cpk-chat-input-processing",
968
- children: /* @__PURE__ */ jsx(Loader2, { className: "cpk-chat-input-processing-spinner" })
875
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
876
+ name: "Loader2",
877
+ className: "cpk-chat-input-processing-spinner"
878
+ })
969
879
  }) : /* @__PURE__ */ jsxs(Fragment$1, { children: [BoundTextArea, slashMenu] })
970
880
  }),
971
881
  /* @__PURE__ */ jsx("div", {
@@ -1025,7 +935,7 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
1025
935
  }
1026
936
  (function(_CopilotChatInput) {
1027
937
  _CopilotChatInput.SendButton = ({ className, children, ...props }) => {
1028
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
938
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
1029
939
  return /* @__PURE__ */ jsx("div", {
1030
940
  className: "cpk-chat-input-send",
1031
941
  children: /* @__PURE__ */ jsx(Button, {
@@ -1036,12 +946,15 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
1036
946
  className: cn("cpk-chat-input-send-button", className),
1037
947
  "aria-label": labels.chatInputToolbarSendButtonLabel,
1038
948
  ...props,
1039
- children: children ?? /* @__PURE__ */ jsx(ArrowUp, { className: "cpk-chat-input-send-icon" })
949
+ children: children ?? /* @__PURE__ */ jsx(CopilotIcon, {
950
+ name: "ArrowUp",
951
+ className: "cpk-chat-input-send-icon"
952
+ })
1040
953
  })
1041
954
  });
1042
955
  };
1043
956
  const ToolbarButton = _CopilotChatInput.ToolbarButton = ({ icon, labelKey, defaultClassName, className, ...props }) => {
1044
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
957
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
1045
958
  return /* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsx(TooltipTrigger, {
1046
959
  asChild: true,
1047
960
  children: /* @__PURE__ */ jsx(Button, {
@@ -1060,27 +973,36 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
1060
973
  };
1061
974
  _CopilotChatInput.StartTranscribeButton = (props) => /* @__PURE__ */ jsx(ToolbarButton, {
1062
975
  "data-testid": "copilot-start-transcribe-button",
1063
- icon: /* @__PURE__ */ jsx(Mic, { className: "cpk-chat-input-toolbar-icon" }),
976
+ icon: /* @__PURE__ */ jsx(CopilotIcon, {
977
+ name: "Mic",
978
+ className: "cpk-chat-input-toolbar-icon"
979
+ }),
1064
980
  labelKey: "chatInputToolbarStartTranscribeButtonLabel",
1065
981
  defaultClassName: "cpk-chat-input-start-transcribe-button",
1066
982
  ...props
1067
983
  });
1068
984
  _CopilotChatInput.CancelTranscribeButton = (props) => /* @__PURE__ */ jsx(ToolbarButton, {
1069
985
  "data-testid": "copilot-cancel-transcribe-button",
1070
- icon: /* @__PURE__ */ jsx(X, { className: "cpk-chat-input-toolbar-icon" }),
986
+ icon: /* @__PURE__ */ jsx(CopilotIcon, {
987
+ name: "X",
988
+ className: "cpk-chat-input-toolbar-icon"
989
+ }),
1071
990
  labelKey: "chatInputToolbarCancelTranscribeButtonLabel",
1072
991
  defaultClassName: "cpk-chat-input-cancel-transcribe-button",
1073
992
  ...props
1074
993
  });
1075
994
  _CopilotChatInput.FinishTranscribeButton = (props) => /* @__PURE__ */ jsx(ToolbarButton, {
1076
995
  "data-testid": "copilot-finish-transcribe-button",
1077
- icon: /* @__PURE__ */ jsx(Check, { className: "cpk-chat-input-toolbar-icon" }),
996
+ icon: /* @__PURE__ */ jsx(CopilotIcon, {
997
+ name: "Check",
998
+ className: "cpk-chat-input-toolbar-icon"
999
+ }),
1078
1000
  labelKey: "chatInputToolbarFinishTranscribeButtonLabel",
1079
1001
  defaultClassName: "cpk-chat-input-finish-transcribe-button",
1080
1002
  ...props
1081
1003
  });
1082
1004
  _CopilotChatInput.AddMenuButton = ({ className, toolsMenu, onAddFile, disabled, ...props }) => {
1083
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
1005
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
1084
1006
  const [mounted, setMounted] = useState(false);
1085
1007
  useEffect(() => setMounted(true), []);
1086
1008
  const menuItems = useMemo(() => {
@@ -1122,7 +1044,10 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
1122
1044
  disabled: isDisabled,
1123
1045
  "aria-label": labels.chatInputToolbarAddButtonLabel,
1124
1046
  ...props,
1125
- children: /* @__PURE__ */ jsx(Plus, { className: "cpk-chat-input-add-menu-icon" })
1047
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
1048
+ name: "Plus",
1049
+ className: "cpk-chat-input-add-menu-icon"
1050
+ })
1126
1051
  });
1127
1052
  if (!mounted) return button;
1128
1053
  return /* @__PURE__ */ jsxs(DropdownMenu, { children: [/* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsx(TooltipTrigger, {
@@ -1148,7 +1073,7 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
1148
1073
  };
1149
1074
  _CopilotChatInput.TextArea = forwardRef(function TextArea({ style, className, autoFocus, placeholder, ...props }, ref) {
1150
1075
  const internalTextareaRef = useRef(null);
1151
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
1076
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
1152
1077
  useImperativeHandle(ref, () => internalTextareaRef.current);
1153
1078
  useEffect(() => {
1154
1079
  if (autoFocus) internalTextareaRef.current?.focus({ preventScroll: true });
@@ -1169,7 +1094,7 @@ function CopilotChatInput({ mode = "input", onSubmitMessage, onStop, isRunning =
1169
1094
  });
1170
1095
  _CopilotChatInput.AudioRecorder = CopilotChatAudioRecorder;
1171
1096
  _CopilotChatInput.Disclaimer = ({ className, ...props }) => {
1172
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
1097
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
1173
1098
  return /* @__PURE__ */ jsx("div", {
1174
1099
  className: cn("cpk-chat-input-disclaimer", className),
1175
1100
  ...props,
@@ -1265,16 +1190,7 @@ function useToolCallRenderers() {
1265
1190
  */
1266
1191
  function useToolCallRendererNames() {
1267
1192
  const renderers = useToolCallRenderers();
1268
- return useMemo(() => {
1269
- const named = renderers.filter((rc) => rc.name !== "*");
1270
- const wildcards = renderers.filter((rc) => rc.name === "*");
1271
- return {
1272
- named: new Set(named.map((rc) => rc.name)),
1273
- groupedNames: new Set(named.filter((rc) => rc.group).map((rc) => rc.name)),
1274
- wildcard: wildcards.length > 0,
1275
- wildcardGroups: wildcards.some((rc) => rc.group)
1276
- };
1277
- }, [renderers]);
1193
+ return useMemo(() => ɵgetToolCallRendererNames$1(renderers), [renderers]);
1278
1194
  }
1279
1195
  /**
1280
1196
  * Hook that returns a function to render tool calls based on the render functions
@@ -1289,18 +1205,17 @@ function useRenderToolCall() {
1289
1205
  const warnedToolNames = useRef(/* @__PURE__ */ new Set());
1290
1206
  const renderToolCalls = useToolCallRenderers();
1291
1207
  const renderToolCall = useCallback(({ toolCall, toolMessage }) => {
1292
- const exactMatches = renderToolCalls.filter((rc) => rc.name === toolCall.function.name);
1293
- const renderConfig = exactMatches.find((rc) => rc.agentId === agentId) || exactMatches.find((rc) => !rc.agentId) || exactMatches[0] || renderToolCalls.find((rc) => rc.name === "*");
1208
+ const renderConfig = ɵresolveToolCallRenderer$1(renderToolCalls, toolCall.function.name, agentId);
1294
1209
  if (!renderConfig) {
1295
1210
  if (IS_DEVELOPMENT$1) unrenderedToolNames.current.add(toolCall.function.name);
1296
1211
  return null;
1297
1212
  }
1298
- const RenderComponent = renderConfig.render;
1213
+ const isExecuting = executingToolCallIds.has(toolCall.id);
1299
1214
  return /* @__PURE__ */ jsx(ToolCallRenderer, {
1300
1215
  toolCall,
1301
1216
  toolMessage,
1302
- RenderComponent,
1303
- isExecuting: executingToolCallIds.has(toolCall.id)
1217
+ RenderComponent: renderConfig.render,
1218
+ isExecuting
1304
1219
  }, toolCall.id);
1305
1220
  }, [
1306
1221
  renderToolCalls,
@@ -1322,7 +1237,7 @@ function useRenderToolCall() {
1322
1237
 
1323
1238
  //#endregion
1324
1239
  //#region package.json
1325
- var version$1 = "2.0.0-rc.2";
1240
+ var version$1 = "2.0.0-rc.20";
1326
1241
 
1327
1242
  //#endregion
1328
1243
  //#region src/components/CopilotKitInspector.tsx
@@ -1393,157 +1308,51 @@ function useCopilotKitInspector() {
1393
1308
 
1394
1309
  //#endregion
1395
1310
  //#region src/components/license-warning-banner.tsx
1396
- const LICENSE_BANNER_OFFSET_PX = 52;
1397
- const LICENSE_BANNER_OFFSET_VAR = "--copilotkit-license-banner-offset";
1398
- const BANNER_STYLES = {
1399
- base: {
1400
- position: "fixed",
1401
- bottom: "8px",
1402
- left: "50%",
1403
- transform: "translateX(-50%)",
1404
- zIndex: 99999,
1405
- display: "inline-flex",
1406
- alignItems: "center",
1407
- gap: "12px",
1408
- whiteSpace: "nowrap",
1409
- padding: "8px 16px",
1410
- fontSize: "13px",
1411
- fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif",
1412
- borderRadius: "6px",
1413
- boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)"
1414
- },
1415
- info: {
1416
- backgroundColor: "#eff6ff",
1417
- border: "1px solid #93c5fd",
1418
- color: "#1e40af"
1419
- },
1420
- warning: {
1421
- backgroundColor: "#fffbeb",
1422
- border: "1px solid #fbbf24",
1423
- color: "#92400e"
1424
- },
1425
- critical: {
1426
- backgroundColor: "#fef2f2",
1427
- border: "1px solid #fca5a5",
1428
- color: "#991b1b"
1429
- }
1430
- };
1431
- function getSeverityStyle(severity) {
1432
- switch (severity) {
1433
- case "warning": return BANNER_STYLES.warning;
1434
- case "critical": return BANNER_STYLES.critical;
1435
- default: return BANNER_STYLES.info;
1436
- }
1311
+ /** The chat labels in effect, or the default ones outside a chat. */
1312
+ function useLabels$2() {
1313
+ return useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
1437
1314
  }
1438
- function BannerShell({ severity, message, actionLabel, actionUrl, onDismiss }) {
1439
- useEffect(() => {
1440
- if (typeof document === "undefined") return;
1441
- const root = document.documentElement;
1442
- root.style.setProperty(LICENSE_BANNER_OFFSET_VAR, `${LICENSE_BANNER_OFFSET_PX}px`);
1443
- return () => {
1444
- root.style.removeProperty(LICENSE_BANNER_OFFSET_VAR);
1445
- };
1446
- }, []);
1315
+ /**
1316
+ * The fixed license banner. Core's `ɵgetLicenseBannerSpec` picks its text,
1317
+ * link, and severity; this component renders them.
1318
+ */
1319
+ function LicenseWarningBanner({ type, onDismiss, ...details }) {
1320
+ const spec = ɵgetLicenseBannerSpec$1(type, useLabels$2(), details);
1321
+ useEffect(() => ɵreserveLicenseBannerOffset$1(), []);
1447
1322
  return /* @__PURE__ */ jsxs("div", {
1448
1323
  style: {
1449
- ...BANNER_STYLES.base,
1450
- ...getSeverityStyle(severity)
1324
+ ...ɵLICENSE_BANNER_STYLE$1.base,
1325
+ ...ɵLICENSE_BANNER_STYLE$1.severity[spec.severity]
1451
1326
  },
1452
- children: [/* @__PURE__ */ jsx("span", { children: message }), /* @__PURE__ */ jsxs("div", {
1453
- style: {
1454
- display: "flex",
1455
- gap: "8px",
1456
- alignItems: "center"
1457
- },
1327
+ children: [/* @__PURE__ */ jsx("span", { children: spec.message }), /* @__PURE__ */ jsxs("div", {
1328
+ style: ɵLICENSE_BANNER_STYLE$1.actions,
1458
1329
  children: [/* @__PURE__ */ jsx("a", {
1459
- href: actionUrl,
1330
+ href: spec.actionUrl,
1460
1331
  target: "_blank",
1461
1332
  rel: "noopener noreferrer",
1462
- style: {
1463
- fontWeight: 600,
1464
- textDecoration: "underline",
1465
- color: "inherit"
1466
- },
1467
- children: actionLabel
1333
+ style: ɵLICENSE_BANNER_STYLE$1.link,
1334
+ children: spec.actionLabel
1468
1335
  }), onDismiss && /* @__PURE__ */ jsx("button", {
1469
1336
  onClick: onDismiss,
1470
- style: {
1471
- background: "none",
1472
- border: "none",
1473
- cursor: "pointer",
1474
- color: "inherit",
1475
- fontSize: "16px"
1476
- },
1337
+ style: ɵLICENSE_BANNER_STYLE$1.dismiss,
1477
1338
  children: "×"
1478
1339
  })]
1479
1340
  })]
1480
1341
  });
1481
1342
  }
1482
- function LicenseWarningBanner({ type, featureName, expiryDate, graceRemaining, onDismiss }) {
1483
- switch (type) {
1484
- case "no_license": return /* @__PURE__ */ jsx(BannerShell, {
1485
- severity: "info",
1486
- message: "Powered by CopilotKit",
1487
- actionLabel: "Get a license",
1488
- actionUrl: "https://copilotkit.ai/pricing",
1489
- onDismiss
1490
- });
1491
- case "feature_unlicensed": return /* @__PURE__ */ jsx(BannerShell, {
1492
- severity: "warning",
1493
- message: `⚠ The "${featureName}" feature requires a CopilotKit license.`,
1494
- actionLabel: "Get a license",
1495
- actionUrl: "https://copilotkit.ai/pricing",
1496
- onDismiss
1497
- });
1498
- case "expiring": return /* @__PURE__ */ jsx(BannerShell, {
1499
- severity: "warning",
1500
- message: `Your CopilotKit license expires in ${graceRemaining} day${graceRemaining !== 1 ? "s" : ""}. Please renew.`,
1501
- actionLabel: "Renew",
1502
- actionUrl: "https://dashboard.operations.copilotkit.ai",
1503
- onDismiss
1504
- });
1505
- case "expired": return /* @__PURE__ */ jsx(BannerShell, {
1506
- severity: "critical",
1507
- message: `Your CopilotKit license expired${expiryDate ? ` on ${expiryDate}` : ""}. Please renew at copilotkit.ai/pricing`,
1508
- actionLabel: "Renew now",
1509
- actionUrl: "https://copilotkit.ai/pricing",
1510
- onDismiss
1511
- });
1512
- case "invalid": return /* @__PURE__ */ jsx(BannerShell, {
1513
- severity: "critical",
1514
- message: "Invalid CopilotKit license token. Please check your configuration.",
1515
- actionLabel: "Get a license",
1516
- actionUrl: "https://copilotkit.ai/pricing",
1517
- onDismiss
1518
- });
1519
- default: return null;
1520
- }
1521
- }
1522
1343
  function InlineFeatureWarning({ featureName }) {
1344
+ const spec = ɵgetInlineFeatureWarningSpec$1(featureName, useLabels$2());
1523
1345
  return /* @__PURE__ */ jsxs("div", {
1524
- style: {
1525
- padding: "8px 12px",
1526
- backgroundColor: "#fffbeb",
1527
- border: "1px solid #fbbf24",
1528
- borderRadius: "6px",
1529
- fontSize: "13px",
1530
- color: "#92400e",
1531
- fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif"
1532
- },
1346
+ style: ɵINLINE_FEATURE_WARNING_STYLE$1.container,
1533
1347
  children: [
1534
- "⚠ The \"",
1535
- featureName,
1536
- "\" feature requires a CopilotKit license.",
1348
+ spec.message,
1537
1349
  " ",
1538
1350
  /* @__PURE__ */ jsx("a", {
1539
- href: "https://copilotkit.ai/pricing",
1351
+ href: spec.actionUrl,
1540
1352
  target: "_blank",
1541
1353
  rel: "noopener noreferrer",
1542
- style: {
1543
- color: "#b45309",
1544
- textDecoration: "underline"
1545
- },
1546
- children: "Get one at copilotkit.ai/pricing"
1354
+ style: ɵINLINE_FEATURE_WARNING_STYLE$1.link,
1355
+ children: spec.actionLabel
1547
1356
  })
1548
1357
  ]
1549
1358
  });
@@ -1705,44 +1514,9 @@ function useSandboxFunctions() {
1705
1514
  return useContext(SandboxFunctionsContext);
1706
1515
  }
1707
1516
 
1708
- //#endregion
1709
- //#region src/lib/processPartialHtml.ts
1710
- /**
1711
- * Extracts all complete `<style>` blocks from the raw HTML.
1712
- * Returns the concatenated style tags, suitable for injection into `<head>`.
1713
- */
1714
- function extractCompleteStyles(html) {
1715
- const matches = html.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi);
1716
- return matches ? matches.join("") : "";
1717
- }
1718
- /**
1719
- * Processes raw accumulated HTML for safe preview via innerHTML injection.
1720
- * Pure function, no DOM dependencies.
1721
- *
1722
- * Pipeline (order matters):
1723
- * 1. Strip incomplete tag at end
1724
- * 2. Strip complete <style>, <script>, and <head> blocks
1725
- * 3. Strip incomplete <style>/<script>/<head> blocks
1726
- * 4. Strip incomplete HTML entities
1727
- * 5. Extract body content (or use full string if no <body>)
1728
- */
1729
- function processPartialHtml(html) {
1730
- let result = html;
1731
- result = result.replace(/<[^>]*$/, "");
1732
- result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*?<\/\1>/gi, "");
1733
- result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*$/gi, "");
1734
- result = result.replace(/&[a-zA-Z0-9#]*$/, "");
1735
- const bodyMatch = result.match(/<body[^>]*>([\s\S]*)/i);
1736
- if (bodyMatch) {
1737
- result = bodyMatch[1];
1738
- result = result.replace(/<\/body>[\s\S]*/i, "");
1739
- }
1740
- return result;
1741
- }
1742
-
1743
1517
  //#endregion
1744
1518
  //#region src/components/OpenGenerativeUIRenderer.tsx
1745
- const OpenGenerativeUIActivityType = "open-generative-ui";
1519
+ const OpenGenerativeUIActivityType = OPEN_GENERATIVE_UI_ACTIVITY_TYPE$1;
1746
1520
  const OpenGenerativeUIContentSchema = z.object({
1747
1521
  initialHeight: z.number().optional(),
1748
1522
  generating: z.boolean().optional(),
@@ -1767,262 +1541,36 @@ const GenerateSandboxedUiArgsSchema = z.object({
1767
1541
  jsFunctions: z.string().optional(),
1768
1542
  jsExpressions: z.array(z.string()).optional()
1769
1543
  });
1770
- const THROTTLE_MS = 1e3;
1771
1544
  /**
1772
- * Returns true when the inner component should re-render immediately
1773
- * (no throttle delay).
1774
- */
1775
- function shouldFlushImmediately(prev, next) {
1776
- if (next.cssComplete && (!prev || !prev.cssComplete)) return true;
1777
- if (next.htmlComplete) return true;
1778
- if (next.generating === false) return true;
1779
- if (next.jsFunctions && (!prev || !prev.jsFunctions)) return true;
1780
- if ((next.jsExpressions?.length ?? 0) > (prev?.jsExpressions?.length ?? 0)) return true;
1781
- if (next.html?.length && (!prev || !prev.html?.length)) return true;
1782
- return false;
1783
- }
1784
- /**
1785
- * Outer wrapper — absorbs every parent re-render but only forwards
1786
- * throttled content snapshots to the memoized inner component.
1545
+ * Renders an Open Generative UI activity. The core controller throttles the
1546
+ * content and runs the websandbox iframes inside the container div.
1787
1547
  */
1788
1548
  const OpenGenerativeUIActivityRenderer = function OpenGenerativeUIActivityRenderer({ content }) {
1789
- const latestContentRef = useRef(content);
1790
- latestContentRef.current = content;
1791
- const [throttledContent, setThrottledContent] = useState(content);
1792
- const throttledContentRef = useRef(throttledContent);
1793
- const timerRef = useRef(null);
1794
- if (throttledContentRef.current !== content) {
1795
- if (shouldFlushImmediately(throttledContentRef.current, content)) {
1796
- if (timerRef.current !== null) {
1797
- clearTimeout(timerRef.current);
1798
- timerRef.current = null;
1799
- }
1800
- throttledContentRef.current = content;
1801
- setThrottledContent(content);
1802
- }
1803
- }
1804
- const flush = useCallback(() => {
1805
- timerRef.current = null;
1806
- const latest = latestContentRef.current;
1807
- throttledContentRef.current = latest;
1808
- setThrottledContent(latest);
1809
- }, []);
1810
- useEffect(() => {
1811
- if (throttledContentRef.current === content) return;
1812
- if (timerRef.current === null) timerRef.current = setTimeout(flush, THROTTLE_MS);
1813
- }, [content, flush]);
1814
- useEffect(() => {
1815
- return () => {
1816
- if (timerRef.current !== null) clearTimeout(timerRef.current);
1817
- };
1818
- }, []);
1819
- return /* @__PURE__ */ jsx(OpenGenerativeUIActivityRendererInner, { content: throttledContent });
1820
- };
1821
- function ensureHead(html) {
1822
- if (/<head[\s>]/i.test(html)) return html;
1823
- return `<head></head>${html}`;
1824
- }
1825
- function injectCssIntoHtml(html, css) {
1826
- const headCloseIdx = html.indexOf("</head>");
1827
- if (headCloseIdx !== -1) return html.slice(0, headCloseIdx) + `<style>${css}</style>` + html.slice(headCloseIdx);
1828
- return `<head><style>${css}</style></head>${html}`;
1829
- }
1830
- const OpenGenerativeUIActivityRendererInner = React.memo(function OpenGenerativeUIActivityRendererInner({ content }) {
1831
- const initialHeight = content.initialHeight ?? 200;
1832
- const [autoHeight, setAutoHeight] = useState(null);
1549
+ const [controller] = useState(() => {
1550
+ const created = new ɵOpenGenerativeUIController$1();
1551
+ created.setContent(content);
1552
+ return created;
1553
+ });
1833
1554
  const sandboxFunctions = useSandboxFunctions();
1834
- const localApi = useMemo(() => {
1835
- const api = {};
1836
- for (const fn of sandboxFunctions) api[fn.name] = fn.handler;
1837
- return api;
1838
- }, [sandboxFunctions]);
1839
- const fullHtml = content.htmlComplete && content.html?.length ? content.html.join("") : void 0;
1840
- const css = content.cssComplete ? content.css : void 0;
1841
- const cssReady = !!content.cssComplete;
1842
- const partialHtml = !content.htmlComplete && content.html?.length ? content.html.join("") : void 0;
1843
- const previewBody = partialHtml ? processPartialHtml(partialHtml) : void 0;
1844
- const previewStyles = partialHtml ? extractCompleteStyles(partialHtml) : "";
1845
- const hasPreview = cssReady && !!previewBody?.trim();
1846
- const hasVisibleSandbox = !!fullHtml || hasPreview;
1847
1555
  const containerRef = useRef(null);
1848
- const sandboxRef = useRef(null);
1849
- const previewSandboxRef = useRef(null);
1850
- const previewReadyRef = useRef(false);
1851
- const sandboxReadyRef = useRef(false);
1852
- const executedIndexRef = useRef(0);
1853
- const pendingQueueRef = useRef([]);
1854
- const jsFunctionsInjectedRef = useRef(false);
1556
+ const state = useSyncExternalStore(controller.subscribe, controller.getState, controller.getState);
1855
1557
  useEffect(() => {
1856
- const container = containerRef.current;
1857
- if (!container || fullHtml || !hasPreview || previewSandboxRef.current) return;
1858
- let cancelled = false;
1859
- import("@jetbrains/websandbox").then((mod) => {
1860
- if (cancelled) return;
1861
- const sandbox = (mod.default?.default ?? mod.default).create({}, {
1862
- frameContainer: container,
1863
- frameContent: "<head></head><body></body>",
1864
- allowAdditionalAttributes: ""
1865
- });
1866
- previewSandboxRef.current = sandbox;
1867
- sandbox.iframe.style.width = "100%";
1868
- sandbox.iframe.style.height = "100%";
1869
- sandbox.iframe.style.border = "none";
1870
- sandbox.iframe.style.backgroundColor = "transparent";
1871
- sandbox.promise.then(() => {
1872
- if (cancelled) return;
1873
- previewReadyRef.current = true;
1874
- sandbox.run(`
1875
- var s = document.createElement('style');
1876
- s.textContent = 'html, body { overflow: hidden !important; }';
1877
- document.head.appendChild(s);
1878
- `);
1879
- const headParts = [];
1880
- if (css) headParts.push(`<style>${css}</style>`);
1881
- if (previewStyles) headParts.push(previewStyles);
1882
- if (headParts.length) sandbox.run(`document.head.innerHTML = ${JSON.stringify(headParts.join(""))}`);
1883
- if (previewBody) sandbox.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
1884
- });
1885
- }).catch((err) => {
1886
- console.error("[OpenGenerativeUI] Failed to load sandbox module:", err);
1887
- });
1888
- return () => {
1889
- cancelled = true;
1890
- };
1891
- }, [hasPreview, fullHtml]);
1558
+ controller.setSandboxFunctions(sandboxFunctions);
1559
+ }, [controller, sandboxFunctions]);
1892
1560
  useEffect(() => {
1893
- if (!previewSandboxRef.current || !previewReadyRef.current) return;
1894
- const headParts = [];
1895
- if (css) headParts.push(`<style>${css}</style>`);
1896
- if (previewStyles) headParts.push(previewStyles);
1897
- if (headParts.length) previewSandboxRef.current.run(`document.head.innerHTML = ${JSON.stringify(headParts.join(""))}`);
1898
- if (!previewBody) return;
1899
- previewSandboxRef.current.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
1900
- }, [
1901
- previewBody,
1902
- previewStyles,
1903
- css
1904
- ]);
1561
+ controller.setContent(content);
1562
+ }, [controller, content]);
1905
1563
  useEffect(() => {
1906
- const container = containerRef.current;
1907
- if (!container || !fullHtml) return;
1908
- if (previewSandboxRef.current) {
1909
- previewSandboxRef.current.destroy();
1910
- previewSandboxRef.current = null;
1911
- previewReadyRef.current = false;
1912
- }
1913
- let cancelled = false;
1914
- executedIndexRef.current = 0;
1915
- jsFunctionsInjectedRef.current = false;
1916
- sandboxReadyRef.current = false;
1917
- pendingQueueRef.current = [];
1918
- const htmlContent = css ? injectCssIntoHtml(fullHtml, css) : fullHtml;
1919
- import("@jetbrains/websandbox").then((mod) => {
1920
- if (cancelled) return;
1921
- const sandbox = (mod.default?.default ?? mod.default).create(localApi, {
1922
- frameContainer: container,
1923
- frameContent: ensureHead(htmlContent),
1924
- allowAdditionalAttributes: ""
1925
- });
1926
- sandboxRef.current = sandbox;
1927
- sandbox.iframe.style.width = "100%";
1928
- sandbox.iframe.style.height = "100%";
1929
- sandbox.iframe.style.border = "none";
1930
- sandbox.iframe.style.backgroundColor = "transparent";
1931
- sandbox.promise.then(() => {
1932
- if (cancelled) return;
1933
- sandboxReadyRef.current = true;
1934
- sandbox.run(`
1935
- var s = document.createElement('style');
1936
- s.textContent = 'html, body { overflow: hidden !important; }';
1937
- document.head.appendChild(s);
1938
- `);
1939
- const queue = pendingQueueRef.current;
1940
- pendingQueueRef.current = [];
1941
- for (const code of queue) sandbox.run(code);
1942
- });
1943
- }).catch((err) => {
1944
- console.error("[OpenGenerativeUI] Failed to load sandbox module:", err);
1945
- });
1946
- return () => {
1947
- cancelled = true;
1948
- if (previewSandboxRef.current) {
1949
- previewSandboxRef.current.destroy();
1950
- previewSandboxRef.current = null;
1951
- previewReadyRef.current = false;
1952
- }
1953
- if (sandboxRef.current) {
1954
- sandboxRef.current.destroy();
1955
- sandboxRef.current = null;
1956
- }
1957
- sandboxReadyRef.current = false;
1958
- setAutoHeight(null);
1959
- };
1960
- }, [
1961
- fullHtml,
1962
- css,
1963
- localApi
1964
- ]);
1965
- useEffect(() => {
1966
- if (!content.jsFunctions || jsFunctionsInjectedRef.current) return;
1967
- jsFunctionsInjectedRef.current = true;
1968
- const sandbox = sandboxRef.current;
1969
- if (sandboxReadyRef.current && sandbox) sandbox.run(content.jsFunctions);
1970
- else pendingQueueRef.current.push(content.jsFunctions);
1971
- }, [content.jsFunctions]);
1972
- useEffect(() => {
1973
- const expressions = content.jsExpressions;
1974
- if (!expressions || expressions.length === 0) return;
1975
- const startIndex = executedIndexRef.current;
1976
- if (startIndex >= expressions.length) return;
1977
- const newExprs = expressions.slice(startIndex);
1978
- executedIndexRef.current = expressions.length;
1979
- const sandbox = sandboxRef.current;
1980
- if (sandboxReadyRef.current && sandbox) (async () => {
1981
- for (const expr of newExprs) await sandbox.run(expr);
1982
- })();
1983
- else pendingQueueRef.current.push(...newExprs);
1984
- }, [content.jsExpressions?.length]);
1985
- const generationDone = content.generating === false;
1986
- useEffect(() => {
1987
- const sandbox = sandboxRef.current;
1988
- if (!generationDone || !sandbox) return;
1989
- let handled = false;
1990
- const onMessage = (e) => {
1991
- if (handled) return;
1992
- if (e.source === sandbox.iframe.contentWindow && e.data?.type === "__ck_resize") {
1993
- handled = true;
1994
- setAutoHeight(e.data.height);
1995
- window.removeEventListener("message", onMessage);
1996
- }
1997
- };
1998
- window.addEventListener("message", onMessage);
1999
- const measureOnce = `
2000
- (function() {
2001
- var s = document.createElement('style');
2002
- s.textContent = 'body { height: auto !important; min-height: 0 !important; }';
2003
- document.head.appendChild(s);
2004
- var h = document.body.scrollHeight;
2005
- var cs = getComputedStyle(document.body);
2006
- h += parseFloat(cs.marginTop) || 0;
2007
- h += parseFloat(cs.marginBottom) || 0;
2008
- s.remove();
2009
- parent.postMessage({ type: "__ck_resize", height: Math.ceil(h) }, "*");
2010
- })();
2011
- `;
2012
- if (sandboxReadyRef.current) sandbox.run(measureOnce);
2013
- else pendingQueueRef.current.push(measureOnce);
2014
- return () => {
2015
- window.removeEventListener("message", onMessage);
2016
- };
2017
- }, [generationDone]);
2018
- const height = autoHeight ?? initialHeight;
2019
- const isGenerating = content.generating !== false;
1564
+ controller.setHost(containerRef.current);
1565
+ return () => controller.destroy();
1566
+ }, [controller]);
1567
+ const hasVisibleSandbox = state.phase !== "placeholder";
2020
1568
  return /* @__PURE__ */ jsx("div", {
2021
1569
  ref: containerRef,
2022
1570
  style: {
2023
1571
  position: "relative",
2024
1572
  width: "100%",
2025
- height: `${height}px`,
1573
+ height: `${state.height}px`,
2026
1574
  borderRadius: "8px",
2027
1575
  backgroundColor: hasVisibleSandbox ? "transparent" : "#f5f5f5",
2028
1576
  border: hasVisibleSandbox ? "none" : "1px solid #e0e0e0",
@@ -2031,7 +1579,7 @@ const OpenGenerativeUIActivityRendererInner = React.memo(function OpenGenerative
2031
1579
  justifyContent: hasVisibleSandbox ? void 0 : "center",
2032
1580
  overflow: "hidden"
2033
1581
  },
2034
- children: isGenerating && /* @__PURE__ */ jsxs("div", {
1582
+ children: state.generating && /* @__PURE__ */ jsxs("div", {
2035
1583
  style: {
2036
1584
  position: "absolute",
2037
1585
  inset: 0,
@@ -2063,7 +1611,7 @@ const OpenGenerativeUIActivityRendererInner = React.memo(function OpenGenerative
2063
1611
  }), /* @__PURE__ */ jsx("style", { children: `@keyframes ck-spin { to { transform: rotate(360deg) } }` })]
2064
1612
  })
2065
1613
  });
2066
- }, (prev, next) => prev.content === next.content);
1614
+ };
2067
1615
  /**
2068
1616
  * Frontend tool renderer for generateSandboxedUi.
2069
1617
  * Displays placeholder messages while the UI is being generated.
@@ -2100,7 +1648,7 @@ const OpenGenerativeUIToolRenderer = function OpenGenerativeUIToolRenderer(props
2100
1648
  //#region src/a2ui/A2UIRecoveryStates.tsx
2101
1649
  /**
2102
1650
  * The pre-paint lifecycle fields the middleware stamps onto the `a2ui-surface`
2103
- * activity content (alongside `a2ui_operations` on paint). `.passthrough()` keeps
1651
+ * activity content (alongside `a2ui_operations` on paint). `.loose()` keeps
2104
1652
  * `a2ui_operations` and any future fields intact.
2105
1653
  */
2106
1654
  const A2UILifecycleFields = {
@@ -2506,12 +2054,12 @@ function ensureInitialized() {
2506
2054
  * stable messageId (OSS-162): pre-paint `status` ("building" | "retrying" |
2507
2055
  * "failed") with recovery detail, then `a2ui_operations` on paint. The states
2508
2056
  * swap in place, so the painted surface replaces the skeleton with no extra
2509
- * coordination. `.passthrough()` preserves operations + any future fields.
2057
+ * coordination. `.loose()` preserves operations + any future fields.
2510
2058
  */
2511
2059
  const A2UISurfaceContentSchema = z.object({
2512
2060
  a2ui_operations: z.array(z.any()).optional(),
2513
2061
  ...A2UILifecycleFields
2514
- }).passthrough();
2062
+ }).loose();
2515
2063
  const IS_DEVELOPMENT = process.env.NODE_ENV !== "production";
2516
2064
  /**
2517
2065
  * How long to wait for a surface to report its first paint before giving up on
@@ -3071,6 +2619,35 @@ function builtInFunctionManifests() {
3071
2619
  }]));
3072
2620
  }
3073
2621
  /**
2622
+ * The manifest of a catalog, with no React runtime: the components of `ui`,
2623
+ * the built-in functions (minus the names the app declares) and
2624
+ * `options.functions`, the chat target and `options.targets`, and
2625
+ * `options.surfaces`. `buildGenerativeUIManifest` builds the per-run
2626
+ * manifest with it; tools that run outside React use it directly.
2627
+ *
2628
+ * @example
2629
+ * ```ts
2630
+ * const manifest = buildCatalogManifest(standardUI);
2631
+ * manifest.targets; // [{ id: "chat", kind: "chat" }]
2632
+ * ```
2633
+ */
2634
+ function buildCatalogManifest(ui, options = {}) {
2635
+ return {
2636
+ catalogId: ui.id,
2637
+ catalogIds: catalogIdsOf(ui),
2638
+ components: applyDescriptionOverrides({ components: ui.manifestComponents }, defaultGenerativeUIPromptSpec().descriptions).manifest.components,
2639
+ functions: {
2640
+ ...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
2641
+ ...options.functions
2642
+ },
2643
+ targets: [{
2644
+ id: GENERATIVE_UI_CHAT_TARGET,
2645
+ kind: "chat"
2646
+ }, ...options.targets ?? []],
2647
+ surfaces: options.surfaces ?? {}
2648
+ };
2649
+ }
2650
+ /**
3074
2651
  * Builds the per-run manifest. Never contains handlers or renderers.
3075
2652
  *
3076
2653
  * - `functions`: the built-in functions, then the declared functions with
@@ -3085,20 +2662,11 @@ function buildGenerativeUIManifest(runtime, threadId) {
3085
2662
  kind: "inline",
3086
2663
  ...rest
3087
2664
  }));
3088
- return {
3089
- catalogId: ui.id,
3090
- catalogIds: catalogIdsOf(ui),
3091
- components: ui.manifestComponents,
3092
- functions: {
3093
- ...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
3094
- ...dispatcher.listExposed()
3095
- },
3096
- targets: [{
3097
- id: GENERATIVE_UI_CHAT_TARGET,
3098
- kind: "chat"
3099
- }, ...inlineTargets],
2665
+ return buildCatalogManifest(ui, {
2666
+ functions: dispatcher.listExposed(),
2667
+ targets: inlineTargets,
3100
2668
  surfaces: threadId ? manager.describeSurfaces(threadId) : {}
3101
- };
2669
+ });
3102
2670
  }
3103
2671
  /**
3104
2672
  * Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
@@ -3121,7 +2689,7 @@ function buildGenerativeUIManifest(runtime, threadId) {
3121
2689
  * includeCatalog: true,
3122
2690
  * contextSent: false,
3123
2691
  * });
3124
- * envelope["v1.0"].supportedCatalogIds; // [runtime.ui.id]
2692
+ * envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
3125
2693
  * ```
3126
2694
  */
3127
2695
  function buildGenerativeUIEnvelope(runtime, threadId, options) {
@@ -3130,7 +2698,7 @@ function buildGenerativeUIEnvelope(runtime, threadId, options) {
3130
2698
  const instructions = options.instructions ?? (transport === "markdown" ? buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest)) : void 0);
3131
2699
  const omitComponents = transport === "markdown" && !includeCatalog;
3132
2700
  return {
3133
- "v1.0": {
2701
+ "1.0": {
3134
2702
  supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
3135
2703
  inlineCatalogs: [{
3136
2704
  catalogId: manifest.catalogId,
@@ -3151,251 +2719,6 @@ function buildGenerativeUIEnvelope(runtime, threadId, options) {
3151
2719
  };
3152
2720
  }
3153
2721
 
3154
- //#endregion
3155
- //#region src/generative-ui/markdown/context.ts
3156
- /** Objects nested deeper than this show as `object`. */
3157
- const MAX_OBJECT_DEPTH = 2;
3158
- /** A prop must appear verbatim in at least this many components to be hoisted. */
3159
- const COMMON_PROP_MIN_COMPONENTS = 8;
3160
- /** A JSON Schema of a list of schemas (`anyOf`, `oneOf`), else an empty list. */
3161
- function schemaList(value) {
3162
- return Array.isArray(value) ? value.filter(isRecord) : [];
3163
- }
3164
- /**
3165
- * Puts a top-level union in parentheses, so that `[]` applies to all of
3166
- * it. A union inside braces needs none.
3167
- */
3168
- function asArrayItem(type) {
3169
- let outside = type;
3170
- for (let inner = outside.replace(/\{[^{}]*\}/g, ""); inner !== outside;) {
3171
- outside = inner;
3172
- inner = outside.replace(/\{[^{}]*\}/g, "");
3173
- }
3174
- return outside.includes(" | ") ? `(${type})[]` : `${type}[]`;
3175
- }
3176
- /**
3177
- * A JSON Schema as a short TypeScript-like type, for example
3178
- * `{ label: string; size?: "sm" | "md" }`.
3179
- */
3180
- function compactType(schema, depth) {
3181
- const ref = childRefKind(schema);
3182
- if (ref === "single") return "componentId";
3183
- if (ref === "multiple") return "componentId[] | { componentId: string; path: string }";
3184
- if ("const" in schema) return JSON.stringify(schema.const);
3185
- if (Array.isArray(schema.enum)) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
3186
- const variants = [...schemaList(schema.anyOf), ...schemaList(schema.oneOf)];
3187
- if (variants.length > 0) return variants.map((variant) => compactType(variant, depth)).join(" | ");
3188
- return (Array.isArray(schema.type) ? schema.type : [schema.type]).map((type) => {
3189
- switch (type) {
3190
- case "string":
3191
- case "boolean":
3192
- case "null": return type;
3193
- case "number":
3194
- case "integer": return "number";
3195
- case "array": return isRecord(schema.items) ? asArrayItem(compactType(schema.items, depth)) : "unknown[]";
3196
- case "object": return compactObject(schema, depth);
3197
- default: return "unknown";
3198
- }
3199
- }).join(" | ");
3200
- }
3201
- /** An object schema as `{ key: type; other?: type }`. */
3202
- function compactObject(schema, depth) {
3203
- const properties = isRecord(schema.properties) ? schema.properties : {};
3204
- const entries = Object.entries(properties);
3205
- if (entries.length === 0) return isRecord(schema.additionalProperties) ? `Record<string, ${compactType(schema.additionalProperties, depth + 1)}>` : "object";
3206
- if (depth >= MAX_OBJECT_DEPTH) return "object";
3207
- const required = Array.isArray(schema.required) ? schema.required : [];
3208
- return `{ ${entries.map(([key, value]) => {
3209
- const type = isRecord(value) ? compactType(value, depth + 1) : "unknown";
3210
- return `${key}${required.includes(key) ? "" : "?"}: ${type}`;
3211
- }).join("; ")} }`;
3212
- }
3213
- /** A schema as its type, with its description after `//`. */
3214
- function describedType(schema, depth) {
3215
- const type = compactType(schema, depth);
3216
- return typeof schema.description === "string" ? `${type} // ${schema.description}` : type;
3217
- }
3218
- /** The props of a component: `{ "label": "string", "size?": "..." }`. */
3219
- function compactProps(schema) {
3220
- const properties = isRecord(schema.properties) ? schema.properties : {};
3221
- const required = Array.isArray(schema.required) ? schema.required : [];
3222
- const props = {};
3223
- for (const [key, value] of Object.entries(properties)) {
3224
- if (!isRecord(value)) continue;
3225
- const name = required.includes(key) ? key : `${key}?`;
3226
- props[name] = describedType(value, 1);
3227
- }
3228
- return props;
3229
- }
3230
- /**
3231
- * The prop set worth listing once. Candidates are (key, type) pairs that at
3232
- * least {@link COMMON_PROP_MIN_COMPONENTS} components carry verbatim. The
3233
- * candidate subset of each component is a possible common set, scored by
3234
- * the characters it saves (set size times the components that contain all
3235
- * of it). `undefined` when no set is shared by enough components.
3236
- */
3237
- function findCommonProps(propsList) {
3238
- const pairKey = (key, type) => `${key}\u0000${type}`;
3239
- const counts = /* @__PURE__ */ new Map();
3240
- for (const props of propsList) for (const [key, type] of Object.entries(props)) {
3241
- const id = pairKey(key, type);
3242
- counts.set(id, (counts.get(id) ?? 0) + 1);
3243
- }
3244
- let best;
3245
- let bestScore = 0;
3246
- const seen = /* @__PURE__ */ new Set();
3247
- for (const props of propsList) {
3248
- const subset = Object.entries(props).filter(([key, type]) => (counts.get(pairKey(key, type)) ?? 0) >= COMMON_PROP_MIN_COMPONENTS);
3249
- if (subset.length < 2) continue;
3250
- const signature = subset.map(([key, type]) => pairKey(key, type)).join("\n");
3251
- if (seen.has(signature)) continue;
3252
- seen.add(signature);
3253
- const members = propsList.filter((other) => subset.every(([key, type]) => other[key] === type)).length;
3254
- if (members < COMMON_PROP_MIN_COMPONENTS) continue;
3255
- const score = subset.reduce((total, [key, type]) => total + key.length + type.length, 0) * (members - 1);
3256
- if (score > bestScore) {
3257
- bestScore = score;
3258
- best = Object.fromEntries(subset);
3259
- }
3260
- }
3261
- return best;
3262
- }
3263
- /**
3264
- * The component schema of the markdown transport, from the per-run
3265
- * manifest. It is smaller than the manifest: each prop is one short type,
3266
- * and the props that many components share verbatim (the layout props of
3267
- * the containers) are listed once in `commonProps`; a component that takes
3268
- * them is flagged `includesCommonProps`.
3269
- * It has the catalog id, the targets with their descriptions and their
3270
- * component lists, the functions with their parameters, the components
3271
- * with their props, events and slots, and the surfaces of the thread. A surface lists the
3272
- * values that the user set and the operations that the client dropped.
3273
- *
3274
- * @param manifest - The manifest from `buildGenerativeUIManifest`.
3275
- * @returns A JSON-ready object.
3276
- *
3277
- * @example
3278
- * ```ts
3279
- * const value = JSON.stringify(
3280
- * buildCompactGenerativeUISchema(buildGenerativeUIManifest(runtime, threadId)),
3281
- * );
3282
- * ```
3283
- */
3284
- function buildCompactGenerativeUISchema(manifest) {
3285
- const components = {};
3286
- for (const [name, component] of Object.entries(manifest.components)) {
3287
- const events = Object.entries(component.events ?? {}).map(([event, definition]) => [event, definition.description ?? compactType(definition.parameters, 0)]);
3288
- components[name] = {
3289
- ...component.description ? { description: component.description } : {},
3290
- props: compactProps(component.props),
3291
- ...events.length > 0 ? { events: Object.fromEntries(events) } : {},
3292
- ...component.slots ? { slots: component.slots } : {}
3293
- };
3294
- }
3295
- const common = findCommonProps(Object.values(components).map((component) => component.props));
3296
- if (common) {
3297
- const commonKeys = Object.keys(common);
3298
- for (const component of Object.values(components)) {
3299
- if (!commonKeys.every((key) => component.props[key] === common[key])) continue;
3300
- component.includesCommonProps = true;
3301
- component.props = Object.fromEntries(Object.entries(component.props).filter(([key]) => !(key in common)));
3302
- }
3303
- }
3304
- const functions = Object.fromEntries(Object.entries(manifest.functions).map(([name, fn]) => {
3305
- const signature = fn.parameters.description;
3306
- const hasSignature = typeof signature === "string" && signature.startsWith("{") && Object.keys(fn.parameters).length === 2;
3307
- const callers = functionCallers(fn);
3308
- return [name, {
3309
- ...fn.description ? { description: fn.description } : {},
3310
- parameters: hasSignature ? signature : compactType(fn.parameters, 0),
3311
- ...callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS ? { callers: callers.renderer ? "UI or agent" : "agent only" } : {}
3312
- }];
3313
- }));
3314
- return {
3315
- catalogId: manifest.catalogId,
3316
- targets: manifest.targets,
3317
- functions,
3318
- ...common ? { commonProps: common } : {},
3319
- components,
3320
- surfaces: manifest.surfaces
3321
- };
3322
- }
3323
- /**
3324
- * Registers the two context entries of the markdown transport: the compact
3325
- * component schema and the fence guideline. Both go only to `agentIds`.
3326
- *
3327
- * The schema is built again at each run start and when a
3328
- * `<GenerativeUISurface>` mounts, unmounts, or changes its description or
3329
- * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
3330
- *
3331
- * @param copilotkit - The CopilotKit core of the provider.
3332
- * @param runtime - The generative UI runtime parts, or null without one.
3333
- * @param options - `enabled` and `agentIds`.
3334
- *
3335
- * @example
3336
- * ```ts
3337
- * useGenerativeUIMarkdownContext(copilotkit, core, {
3338
- * enabled: config?.transport === "markdown" && config.sendContext !== false,
3339
- * agentIds: config?.agentIds,
3340
- * });
3341
- * ```
3342
- */
3343
- function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
3344
- const { enabled, agentIds } = options;
3345
- const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
3346
- useEffect(() => {
3347
- if (!runtime || !enabled) return;
3348
- const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
3349
- const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
3350
- let guidelineId;
3351
- let guidelineValue;
3352
- let schemaId;
3353
- let schemaValue;
3354
- const refreshSchema = (threadId) => {
3355
- const manifest = buildGenerativeUIManifest(runtime, threadId);
3356
- const guideline = buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest));
3357
- if (guideline !== guidelineValue) {
3358
- if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
3359
- guidelineValue = guideline;
3360
- guidelineId = copilotkit.addContext({
3361
- description: GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
3362
- value: guideline,
3363
- ...scope
3364
- });
3365
- }
3366
- const value = JSON.stringify(buildCompactGenerativeUISchema(manifest));
3367
- if (value === schemaValue) return;
3368
- if (schemaId !== void 0) copilotkit.removeContext(schemaId);
3369
- schemaValue = value;
3370
- schemaId = copilotkit.addContext({
3371
- description: GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
3372
- value,
3373
- ...scope
3374
- });
3375
- };
3376
- refreshSchema(runtime.manager.getActiveThread());
3377
- let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
3378
- const unsubscribeManager = runtime.manager.subscribe(() => {
3379
- const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
3380
- if (nextKey === targetsKey) return;
3381
- targetsKey = nextKey;
3382
- refreshSchema(runtime.manager.getActiveThread());
3383
- });
3384
- const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
3385
- return () => {
3386
- subscription.unsubscribe();
3387
- unsubscribeManager();
3388
- if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
3389
- if (schemaId !== void 0) copilotkit.removeContext(schemaId);
3390
- };
3391
- }, [
3392
- copilotkit,
3393
- runtime,
3394
- enabled,
3395
- agentIdsKey
3396
- ]);
3397
- }
3398
-
3399
2722
  //#endregion
3400
2723
  //#region src/generative-ui/debug-source.ts
3401
2724
  /**
@@ -3428,7 +2751,7 @@ function describeGenerativeUIRun(runtime, threadId, options) {
3428
2751
  }]
3429
2752
  };
3430
2753
  const guideline = buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest));
3431
- const schema = JSON.stringify(buildCompactGenerativeUISchema(manifest));
2754
+ const schema = renderGenerativeUISchema(manifest, defaultGenerativeUIPromptSpec().schema.markdown);
3432
2755
  return {
3433
2756
  envelope,
3434
2757
  prompt: [{
@@ -3649,13 +2972,16 @@ function createGenerativeUIDispatcher(options) {
3649
2972
  * gesture runs only from an event binding.
3650
2973
  */
3651
2974
  const invokeBasic = (name, args, origin) => {
3652
- const refused = callerError(name, GENERATIVE_UI_FUNCTIONS[name], origin);
2975
+ const info = GENERATIVE_UI_FUNCTIONS[name];
2976
+ const run = BASIC_FUNCTIONS[name];
2977
+ if (info === void 0 || run === void 0) throw new Error(`"${name}" is not a basic function`);
2978
+ const refused = callerError(name, info, origin);
3653
2979
  if (refused) return failWith(name, origin, refused);
3654
2980
  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`));
3655
2981
  try {
3656
2982
  return {
3657
2983
  ok: true,
3658
- result: BASIC_FUNCTIONS[name](args ?? {})
2984
+ result: run(args ?? {})
3659
2985
  };
3660
2986
  } catch (error) {
3661
2987
  return failWith(name, origin, new GenerativeUIError(error instanceof ExpressionError ? "invalid_arguments" : "handler_failed", `"${name}" failed: ${messageOf(error)}`));
@@ -3701,18 +3027,96 @@ function createGenerativeUIDispatcher(options) {
3701
3027
  };
3702
3028
  } catch {}
3703
3029
  }
3704
- return listed;
3705
- },
3706
- register(name, ref) {
3707
- const mounted = handlers.get(name) ?? /* @__PURE__ */ new Set();
3708
- mounted.add(ref);
3709
- handlers.set(name, mounted);
3710
- return () => {
3711
- mounted.delete(ref);
3712
- };
3713
- },
3714
- handlerCount: (name) => handlers.get(name)?.size ?? 0
3715
- };
3030
+ return listed;
3031
+ },
3032
+ register(name, ref) {
3033
+ const mounted = handlers.get(name) ?? /* @__PURE__ */ new Set();
3034
+ mounted.add(ref);
3035
+ handlers.set(name, mounted);
3036
+ return () => {
3037
+ mounted.delete(ref);
3038
+ };
3039
+ },
3040
+ handlerCount: (name) => handlers.get(name)?.size ?? 0
3041
+ };
3042
+ }
3043
+
3044
+ //#endregion
3045
+ //#region src/generative-ui/markdown/context.ts
3046
+ /**
3047
+ * Registers the two context entries of the markdown transport: the compact
3048
+ * component schema and the fence guideline. Both go only to `agentIds`.
3049
+ *
3050
+ * The schema is built again at each run start and when a
3051
+ * `<GenerativeUISurface>` mounts, unmounts, or changes its description or
3052
+ * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
3053
+ *
3054
+ * @param copilotkit - The CopilotKit core of the provider.
3055
+ * @param runtime - The generative UI runtime parts, or null without one.
3056
+ * @param options - `enabled` and `agentIds`.
3057
+ *
3058
+ * @example
3059
+ * ```ts
3060
+ * useGenerativeUIMarkdownContext(copilotkit, core, {
3061
+ * enabled: config?.transport === "markdown" && config.sendContext !== false,
3062
+ * agentIds: config?.agentIds,
3063
+ * });
3064
+ * ```
3065
+ */
3066
+ function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
3067
+ const { enabled, agentIds } = options;
3068
+ const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
3069
+ useEffect(() => {
3070
+ if (!runtime || !enabled) return;
3071
+ const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
3072
+ const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
3073
+ let guidelineId;
3074
+ let guidelineValue;
3075
+ let schemaId;
3076
+ let schemaValue;
3077
+ const refreshSchema = (threadId) => {
3078
+ const manifest = buildGenerativeUIManifest(runtime, threadId);
3079
+ const guideline = buildGenerativeUIMarkdownGuidelines(generativeUIGuideFeatures(manifest));
3080
+ if (guideline !== guidelineValue) {
3081
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
3082
+ guidelineValue = guideline;
3083
+ guidelineId = copilotkit.addContext({
3084
+ description: GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
3085
+ value: guideline,
3086
+ ...scope
3087
+ });
3088
+ }
3089
+ const value = renderGenerativeUISchema(manifest, defaultGenerativeUIPromptSpec().schema.markdown);
3090
+ if (value === schemaValue) return;
3091
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
3092
+ schemaValue = value;
3093
+ schemaId = copilotkit.addContext({
3094
+ description: GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
3095
+ value,
3096
+ ...scope
3097
+ });
3098
+ };
3099
+ refreshSchema(runtime.manager.getActiveThread());
3100
+ let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
3101
+ const unsubscribeManager = runtime.manager.subscribe(() => {
3102
+ const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
3103
+ if (nextKey === targetsKey) return;
3104
+ targetsKey = nextKey;
3105
+ refreshSchema(runtime.manager.getActiveThread());
3106
+ });
3107
+ const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
3108
+ return () => {
3109
+ subscription.unsubscribe();
3110
+ unsubscribeManager();
3111
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
3112
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
3113
+ };
3114
+ }, [
3115
+ copilotkit,
3116
+ runtime,
3117
+ enabled,
3118
+ agentIdsKey
3119
+ ]);
3716
3120
  }
3717
3121
 
3718
3122
  //#endregion
@@ -3751,31 +3155,47 @@ function summarizeRejections(rejections) {
3751
3155
  * with `getState()`.
3752
3156
  */
3753
3157
  var GenerativeUISurfaceManager = class {
3158
+ surfaces = /* @__PURE__ */ new Map();
3159
+ bookkeeping = /* @__PURE__ */ new Map();
3160
+ listeners = /* @__PURE__ */ new Set();
3161
+ /** Mounts of each target id, in mount order. */
3162
+ targets = /* @__PURE__ */ new Map();
3163
+ state = {};
3164
+ /**
3165
+ * User-owned data model values, by surface key, then by path. Kept when a
3166
+ * surface is rebuilt. Cleared when the surface is deleted.
3167
+ */
3168
+ owned = /* @__PURE__ */ new Map();
3169
+ /**
3170
+ * Keys of the surfaces that a `deleteSurface` removed. A surface id is
3171
+ * unique for the life of the page, so a key stays here when its surface is
3172
+ * built again.
3173
+ */
3174
+ deletedKeys = /* @__PURE__ */ new Set();
3175
+ /**
3176
+ * Surfaces that share their data model, by surface key: the parts of a
3177
+ * chat surface that the prose lift split. A user write to one part goes
3178
+ * to every part, so an input in one part drives a binding in another.
3179
+ */
3180
+ linked = /* @__PURE__ */ new Map();
3181
+ webCoreCatalog;
3182
+ activeThreadId;
3183
+ version = 0;
3754
3184
  constructor(ui, options = {}) {
3755
3185
  this.ui = ui;
3756
3186
  this.options = options;
3757
- this.surfaces = /* @__PURE__ */ new Map();
3758
- this.bookkeeping = /* @__PURE__ */ new Map();
3759
- this.listeners = /* @__PURE__ */ new Set();
3760
- this.targets = /* @__PURE__ */ new Map();
3761
- this.state = {};
3762
- this.owned = /* @__PURE__ */ new Map();
3763
- this.deletedKeys = /* @__PURE__ */ new Set();
3764
- this.linked = /* @__PURE__ */ new Map();
3765
- this.version = 0;
3766
- this.subscribe = (listener) => {
3767
- this.listeners.add(listener);
3768
- return () => {
3769
- this.listeners.delete(listener);
3770
- };
3771
- };
3772
- this.getVersion = () => this.version;
3773
- this.getState = () => this.state;
3774
3187
  this.webCoreCatalog = new Catalog$1(ui.id, [...ui.components.keys()].map((name) => ({
3775
3188
  name,
3776
3189
  schema: z.any()
3777
3190
  })), []);
3778
3191
  }
3192
+ subscribe = (listener) => {
3193
+ this.listeners.add(listener);
3194
+ return () => {
3195
+ this.listeners.delete(listener);
3196
+ };
3197
+ };
3198
+ getVersion = () => this.version;
3779
3199
  notify() {
3780
3200
  this.version++;
3781
3201
  for (const listener of [...this.listeners]) listener();
@@ -3961,6 +3381,11 @@ var GenerativeUISurfaceManager = class {
3961
3381
  names: new Set(components)
3962
3382
  };
3963
3383
  }
3384
+ /**
3385
+ * The app state object. It is the same object until a key changes, so it
3386
+ * can be a `useSyncExternalStore` snapshot.
3387
+ */
3388
+ getState = () => this.state;
3964
3389
  /** Sets one state key. Notifies only when the value changed. */
3965
3390
  setState(key, value) {
3966
3391
  if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
@@ -4764,15 +4189,34 @@ function useGenerativeUIRoot(copilotkit, config) {
4764
4189
 
4765
4190
  //#endregion
4766
4191
  //#region src/lib/react-core.ts
4192
+ /**
4193
+ * Wait for pending React state updates before the follow-up agent run.
4194
+ *
4195
+ * When a frontend tool handler calls setState(), React 18 batches the update
4196
+ * and schedules a commit via its internal scheduler (MessageChannel). The
4197
+ * useAgentContext hook registers context via useLayoutEffect, which runs
4198
+ * synchronously after React commits that batch.
4199
+ *
4200
+ * Awaiting a zero-delay timeout yields to the macrotask queue. React's
4201
+ * MessageChannel task runs first, committing the pending state and running
4202
+ * useLayoutEffect (which updates the context store). The follow-up runAgent
4203
+ * call then reads fresh context.
4204
+ */
4205
+ function waitForReactCommit() {
4206
+ return new Promise((resolve) => setTimeout(resolve, 0));
4207
+ }
4767
4208
  var CopilotKitCoreReact = class extends CopilotKitCore$1 {
4209
+ _renderToolCalls = [];
4210
+ _hookRenderToolCalls = /* @__PURE__ */ new Map();
4211
+ _cachedMergedRenderToolCalls = null;
4212
+ _renderCustomMessages = [];
4213
+ _renderActivityMessages = [];
4214
+ _interruptElement = null;
4768
4215
  constructor(config) {
4769
- super(config);
4770
- this._renderToolCalls = [];
4771
- this._hookRenderToolCalls = /* @__PURE__ */ new Map();
4772
- this._cachedMergedRenderToolCalls = null;
4773
- this._renderCustomMessages = [];
4774
- this._renderActivityMessages = [];
4775
- this._interruptElement = null;
4216
+ super({
4217
+ ...config,
4218
+ ɵwaitForFrameworkUpdates: waitForReactCommit
4219
+ });
4776
4220
  this._renderToolCalls = config.renderToolCalls ?? [];
4777
4221
  this._renderCustomMessages = config.renderCustomMessages ?? [];
4778
4222
  this._renderActivityMessages = config.renderActivityMessages ?? [];
@@ -4818,8 +4262,7 @@ var CopilotKitCoreReact = class extends CopilotKitCore$1 {
4818
4262
  }
4819
4263
  _notifyRenderToolCallsChanged() {
4820
4264
  this.notifySubscribers((subscriber) => {
4821
- const reactSubscriber = subscriber;
4822
- if (reactSubscriber.onRenderToolCallsChanged) reactSubscriber.onRenderToolCallsChanged({
4265
+ return subscriber.onRenderToolCallsChanged?.({
4823
4266
  copilotkit: this,
4824
4267
  renderToolCalls: this.renderToolCalls
4825
4268
  });
@@ -4831,7 +4274,7 @@ var CopilotKitCoreReact = class extends CopilotKitCore$1 {
4831
4274
  setInterruptElement(element) {
4832
4275
  this._interruptElement = element;
4833
4276
  this.notifySubscribers((subscriber) => {
4834
- subscriber.onInterruptElementChanged?.({
4277
+ return subscriber.onInterruptElementChanged?.({
4835
4278
  copilotkit: this,
4836
4279
  interruptElement: this._interruptElement
4837
4280
  });
@@ -4840,22 +4283,6 @@ var CopilotKitCoreReact = class extends CopilotKitCore$1 {
4840
4283
  subscribe(subscriber) {
4841
4284
  return super.subscribe(subscriber);
4842
4285
  }
4843
- /**
4844
- * Wait for pending React state updates before the follow-up agent run.
4845
- *
4846
- * When a frontend tool handler calls setState(), React 18 batches the update
4847
- * and schedules a commit via its internal scheduler (MessageChannel). The
4848
- * useAgentContext hook registers context via useLayoutEffect, which runs
4849
- * synchronously after React commits that batch.
4850
- *
4851
- * Awaiting a zero-delay timeout yields to the macrotask queue. React's
4852
- * MessageChannel task runs first, committing the pending state and running
4853
- * useLayoutEffect (which updates the context store). The follow-up runAgent
4854
- * call then reads fresh context.
4855
- */
4856
- async waitForPendingFrameworkUpdates() {
4857
- await new Promise((resolve) => setTimeout(resolve, 0));
4858
- }
4859
4286
  };
4860
4287
 
4861
4288
  //#endregion
@@ -4897,10 +4324,6 @@ function CopilotKitStyles() {
4897
4324
 
4898
4325
  //#endregion
4899
4326
  //#region src/providers/CopilotKitProvider.tsx
4900
- const zodToJsonSchemaAdapter = (schema, options) => {
4901
- const refStrategy = options?.$refStrategy;
4902
- return zodToJsonSchema(schema, refStrategy === "root" || refStrategy === "relative" || refStrategy === "none" || refStrategy === "seen" ? { $refStrategy: refStrategy } : {});
4903
- };
4904
4327
  const HEADER_NAME = "X-CopilotCloud-Public-Api-Key";
4905
4328
  const COPILOT_CLOUD_CHAT_URL = "https://api.cloud.copilotkit.ai/copilotkit/v1";
4906
4329
  const EMPTY_HEADERS = Object.freeze({});
@@ -4909,16 +4332,6 @@ const EMPTY_AGENTS = Object.freeze({});
4909
4332
  /** Registration name of a catch-all tool: handles any otherwise-unhandled call. */
4910
4333
  const WILDCARD_TOOL_NAME$1 = "*";
4911
4334
  const HUMAN_IN_THE_LOOP_ABORTED_MESSAGE = "Human-in-the-loop interaction aborted";
4912
- const DEFAULT_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:
4913
-
4914
- - Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.
4915
- - Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.
4916
- - Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.
4917
- - Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.
4918
- - Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).
4919
- - Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
4920
- - Minimal transitions (150ms) for hover/focus states only. No decorative animations.
4921
- - Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
4922
4335
  /** The MCP Apps renderer with `mcpApps.allowSameOriginFallback` applied. */
4923
4336
  const SameOriginMCPAppsActivityRenderer = (props) => /* @__PURE__ */ jsx(MCPAppsActivityRenderer, {
4924
4337
  ...props,
@@ -5129,7 +4542,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
5129
4542
  const builtInFrontendTools = useMemo(() => {
5130
4543
  if (!openGenUIActive) return [];
5131
4544
  return [{
5132
- name: "generateSandboxedUi",
4545
+ name: GENERATE_SANDBOXED_UI_TOOL_NAME$1,
5133
4546
  description: GENERATE_SANDBOXED_UI_DESCRIPTION,
5134
4547
  parameters: GenerateSandboxedUiArgsSchema,
5135
4548
  handler: async () => "UI generated",
@@ -5153,7 +4566,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
5153
4566
  const combined = [...renderToolCallsList];
5154
4567
  [...frontendToolsList, ...builtInFrontendTools].forEach((tool) => {
5155
4568
  if (tool.render) {
5156
- const args = tool.parameters || (tool.name === "*" ? z.any() : void 0);
4569
+ const args = tool.parameters || (tool.name === "*" ? ɵanySchema : void 0);
5157
4570
  if (args) combined.push({
5158
4571
  name: tool.name,
5159
4572
  args,
@@ -5354,7 +4767,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
5354
4767
  useEffect(() => {
5355
4768
  copilotkit.setDefaultThrottleMs(defaultThrottleMs);
5356
4769
  }, [copilotkit, defaultThrottleMs]);
5357
- const designSkill = openGenerativeUI?.designSkill ?? DEFAULT_DESIGN_SKILL;
4770
+ const designSkill = openGenerativeUI?.designSkill ?? DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL$1;
5358
4771
  useLayoutEffect(() => {
5359
4772
  if (!copilotkit || !openGenUIActive) return;
5360
4773
  const id = copilotkit.addContext({
@@ -5374,7 +4787,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
5374
4787
  return JSON.stringify(sandboxFunctionsList.map((fn) => ({
5375
4788
  name: fn.name,
5376
4789
  description: fn.description,
5377
- parameters: schemaToJsonSchema(fn.parameters, { zodToJsonSchema: zodToJsonSchemaAdapter })
4790
+ parameters: schemaToJsonSchema(fn.parameters)
5378
4791
  })));
5379
4792
  }, [sandboxFunctionsList]);
5380
4793
  useLayoutEffect(() => {
@@ -5400,26 +4813,17 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
5400
4813
  executingToolCallIds,
5401
4814
  showIntelligenceIndicator
5402
4815
  ]);
5403
- const retryableRuntimeEntitlementFailure = runtimeEntitlements?.status !== "ready" && runtimeEntitlements?.error.retryable === true;
5404
- const hasNonReadyRuntimeEntitlement = runtimeEntitlements !== void 0 && runtimeEntitlements.status !== "ready";
5405
- const hasLegacyRuntimeEntitlementFallback = runtimeLicenseStatus === "valid" || runtimeLicenseStatus === "expiring";
5406
- const runtimeEntitlementRetryInProgress = retryableRuntimeEntitlementFailure && runtimeEntitlementRetryPending && !hasLegacyRuntimeEntitlementFallback;
5407
- const terminalRuntimeEntitlementFailure = hasNonReadyRuntimeEntitlement && !retryableRuntimeEntitlementFailure && !hasLegacyRuntimeEntitlementFallback;
5408
- const licenseContextValue = useMemo(() => {
5409
- const runtimeLicenseContext = createLicenseContextValue(runtimeEntitlementRetryInProgress ? void 0 : runtimeLicenseStatus, runtimeEntitlements);
5410
- if (!terminalRuntimeEntitlementFailure) return runtimeLicenseContext;
5411
- return {
5412
- ...runtimeLicenseContext,
5413
- checkFeature: () => false,
5414
- getLimit: () => null
5415
- };
5416
- }, [
5417
- terminalRuntimeEntitlementFailure,
5418
- runtimeEntitlementRetryInProgress,
4816
+ const licenseState = useMemo(() => ɵresolveLicenseState$1({
4817
+ status: runtimeLicenseStatus,
4818
+ entitlements: runtimeEntitlements,
4819
+ retryPending: runtimeEntitlementRetryPending,
4820
+ publicKey: resolvedPublicKey
4821
+ }), [
4822
+ runtimeLicenseStatus,
5419
4823
  runtimeEntitlements,
5420
- runtimeLicenseStatus
4824
+ runtimeEntitlementRetryPending,
4825
+ resolvedPublicKey
5421
4826
  ]);
5422
- const runtimeLicenseWarningStatus = runtimeEntitlementRetryInProgress ? void 0 : licenseContextValue.status ?? void 0;
5423
4827
  return /* @__PURE__ */ jsx(CopilotStyleOptionsProvider, {
5424
4828
  value: useMemo(() => ({
5425
4829
  nonce,
@@ -5430,7 +4834,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
5430
4834
  children: /* @__PURE__ */ jsx(CopilotKitContext.Provider, {
5431
4835
  value: contextValue,
5432
4836
  children: /* @__PURE__ */ jsxs(LicenseContext.Provider, {
5433
- value: licenseContextValue,
4837
+ value: licenseState.context,
5434
4838
  children: [
5435
4839
  a2uiActive && /* @__PURE__ */ jsx(A2UIBuiltInToolCallRenderer, {}),
5436
4840
  generativeUIActive && /* @__PURE__ */ jsx(GenerativeUIToolCallRenderer, {}),
@@ -5455,10 +4859,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
5455
4859
  }) : null]
5456
4860
  })
5457
4861
  }),
5458
- runtimeLicenseWarningStatus === "none" && !resolvedPublicKey && /* @__PURE__ */ jsx(LicenseWarningBanner, { type: "no_license" }),
5459
- runtimeLicenseWarningStatus === "expired" && /* @__PURE__ */ jsx(LicenseWarningBanner, { type: "expired" }),
5460
- runtimeLicenseWarningStatus === "invalid" && /* @__PURE__ */ jsx(LicenseWarningBanner, { type: "invalid" }),
5461
- runtimeLicenseWarningStatus === "expiring" && /* @__PURE__ */ jsx(LicenseWarningBanner, { type: "expiring" })
4862
+ licenseState.bannerType && /* @__PURE__ */ jsx(LicenseWarningBanner, { type: licenseState.bannerType })
5462
4863
  ]
5463
4864
  })
5464
4865
  })
@@ -5473,11 +4874,7 @@ function useRenderCustomMessages() {
5473
4874
  const config = useCopilotChatConfiguration();
5474
4875
  if (!config) return null;
5475
4876
  const { agentId, threadId } = config;
5476
- const customMessageRenderers = copilotkit.renderCustomMessages.filter((renderer) => renderer.agentId === void 0 || renderer.agentId === agentId).sort((a, b) => {
5477
- const aHasAgent = a.agentId !== void 0;
5478
- if (aHasAgent === (b.agentId !== void 0)) return 0;
5479
- return aHasAgent ? -1 : 1;
5480
- });
4877
+ const customMessageRenderers = ɵresolveCustomMessageRenderers$1(copilotkit.renderCustomMessages, agentId);
5481
4878
  if (!customMessageRenderers.length) return null;
5482
4879
  return function(params) {
5483
4880
  const { message, position } = params;
@@ -5513,6 +4910,18 @@ function useRenderCustomMessages() {
5513
4910
 
5514
4911
  //#endregion
5515
4912
  //#region src/hooks/use-render-activity-message.tsx
4913
+ /**
4914
+ * Explain why an activity message that has a renderer drew nothing: its
4915
+ * content validates asynchronously, or it fails the renderer's schema.
4916
+ */
4917
+ function warnAboutRejectedContent(renderer, message) {
4918
+ const result = renderer.content["~standard"].validate(message.content);
4919
+ if (result instanceof Promise) {
4920
+ console.warn(`Async content validation is not supported for activity message '${message.activityType}'`);
4921
+ return;
4922
+ }
4923
+ if (result.issues) console.warn(`Failed to parse content for activity message '${message.activityType}':`, result.issues);
4924
+ }
5516
4925
  function useRenderActivityMessage() {
5517
4926
  const { copilotkit } = useCopilotKit();
5518
4927
  const agentId = useCopilotChatConfiguration()?.agentId ?? DEFAULT_AGENT_ID;
@@ -5523,29 +4932,29 @@ function useRenderActivityMessage() {
5523
4932
  return matches.find((candidate) => candidate.agentId === agentId) ?? matches.find((candidate) => candidate.agentId === void 0) ?? renderers.find((candidate) => candidate.activityType === "*") ?? null;
5524
4933
  }, [agentId, renderers]);
5525
4934
  const renderActivityMessage = useCallback((message) => {
5526
- const renderer = findRenderer(message.activityType);
5527
- if (!renderer) return null;
5528
- const parseResult = renderer.content["~standard"].validate(message.content);
5529
- if (parseResult instanceof Promise) {
5530
- console.warn(`Async content validation is not supported for activity message '${message.activityType}'`);
5531
- return null;
5532
- }
5533
- if (parseResult.issues) {
5534
- console.warn(`Failed to parse content for activity message '${message.activityType}':`, parseResult.issues);
4935
+ const match = ɵresolveActivityRenderer$1(renderers, {
4936
+ activityType: message.activityType,
4937
+ agentId,
4938
+ content: message.content
4939
+ });
4940
+ if (!match) {
4941
+ const renderer = findRenderer(message.activityType);
4942
+ if (renderer) warnAboutRejectedContent(renderer, message);
5535
4943
  return null;
5536
4944
  }
5537
- const Component = renderer.render;
4945
+ const Component = match.renderer.render;
5538
4946
  const agent = copilotkit.getAgent(agentId);
5539
4947
  return /* @__PURE__ */ jsx(Component, {
5540
4948
  activityType: message.activityType,
5541
- content: parseResult.value,
4949
+ content: match.content,
5542
4950
  message,
5543
4951
  agent
5544
4952
  }, message.id);
5545
4953
  }, [
5546
4954
  agentId,
5547
4955
  copilotkit,
5548
- findRenderer
4956
+ findRenderer,
4957
+ renderers
5549
4958
  ]);
5550
4959
  return useMemo(() => ({
5551
4960
  renderActivityMessage,
@@ -5630,6 +5039,30 @@ function useDepsVersion(deps) {
5630
5039
 
5631
5040
  //#endregion
5632
5041
  //#region src/hooks/use-frontend-tool.tsx
5042
+ /**
5043
+ * Register a frontend tool while the component is mounted. The agent can
5044
+ * call it, and its `render` component draws the call in the chat.
5045
+ *
5046
+ * A tool with the same name and agentId as a tool that is already registered
5047
+ * (for example one from the provider's `tools`) overrides it while this
5048
+ * component is mounted. When the component unmounts, the overridden tool is
5049
+ * active again. The renderer stays registered after unmount, so past tool
5050
+ * calls still render in the chat history.
5051
+ *
5052
+ * @param tool - The tool to register.
5053
+ * @param deps - Extra values that re-register the tool when they change. Use
5054
+ * it when the handler closes over a value that is not part of the tool.
5055
+ *
5056
+ * @example
5057
+ * ```tsx
5058
+ * useFrontendTool({
5059
+ * name: "showWeather",
5060
+ * description: "Show the weather for a city",
5061
+ * parameters: z.object({ city: z.string() }),
5062
+ * handler: async ({ city }) => `Sunny in ${city}`,
5063
+ * });
5064
+ * ```
5065
+ */
5633
5066
  function useFrontendTool(tool, deps) {
5634
5067
  const { copilotkit } = useCopilotKit$1();
5635
5068
  const depsVersion = useDepsVersion(deps);
@@ -5638,11 +5071,8 @@ function useFrontendTool(tool, deps) {
5638
5071
  if (copilotkit.getTool({
5639
5072
  toolName: name,
5640
5073
  agentId: tool.agentId
5641
- })) {
5642
- console.warn(`Tool '${name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
5643
- copilotkit.removeTool(name, tool.agentId);
5644
- }
5645
- copilotkit.addTool(tool);
5074
+ })) console.warn(`Tool '${name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
5075
+ const unregister = copilotkit.addTool(tool);
5646
5076
  if (tool.render) copilotkit.addHookRenderToolCall({
5647
5077
  name,
5648
5078
  args: tool.parameters,
@@ -5650,7 +5080,7 @@ function useFrontendTool(tool, deps) {
5650
5080
  render: tool.render
5651
5081
  });
5652
5082
  return () => {
5653
- copilotkit.removeTool(name, tool.agentId);
5083
+ unregister();
5654
5084
  };
5655
5085
  }, [
5656
5086
  tool.name,
@@ -5675,8 +5105,10 @@ const EMPTY_TOOLS = [];
5675
5105
  *
5676
5106
  * Tools are keyed by `name` plus `agentId`, the same as `useFrontendTool`. A
5677
5107
  * tool that disappears from the array is unregistered on the next render, and
5678
- * every tool is unregistered on unmount. Renderers stay registered after
5679
- * unmount so past tool calls still render in the chat history.
5108
+ * every tool is unregistered on unmount. A listed tool hides a tool with the
5109
+ * same name and agentId (for example one from the provider's `tools`) until it
5110
+ * is unregistered, and then the hidden tool is active again. Renderers stay
5111
+ * registered after unmount so past tool calls still render in the chat history.
5680
5112
  *
5681
5113
  * @param tools - The tools to register. May be empty and may change length.
5682
5114
  * @param deps - Extra dependencies that force re-registration, compared by
@@ -5726,15 +5158,13 @@ function useFrontendTools(tools, deps) {
5726
5158
  deduped.set(key, tool);
5727
5159
  }
5728
5160
  const registered = [...deduped.values()];
5161
+ const unregisters = [];
5729
5162
  for (const tool of registered) {
5730
5163
  if (copilotkit.getTool({
5731
5164
  toolName: tool.name,
5732
5165
  agentId: tool.agentId
5733
- })) {
5734
- console.warn(`Tool '${tool.name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
5735
- copilotkit.removeTool(tool.name, tool.agentId);
5736
- }
5737
- copilotkit.addTool(tool);
5166
+ })) console.warn(`Tool '${tool.name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`);
5167
+ unregisters.push(copilotkit.addTool(tool));
5738
5168
  if (tool.render) copilotkit.addHookRenderToolCall({
5739
5169
  name: tool.name,
5740
5170
  args: tool.parameters,
@@ -5743,7 +5173,7 @@ function useFrontendTools(tools, deps) {
5743
5173
  });
5744
5174
  }
5745
5175
  return () => {
5746
- for (const tool of registered) copilotkit.removeTool(tool.name, tool.agentId);
5176
+ for (const unregister of unregisters) unregister();
5747
5177
  };
5748
5178
  }, [
5749
5179
  JSON.stringify(toolList.map((tool) => [
@@ -5918,34 +5348,24 @@ function useRenderTool(config, deps) {
5918
5348
  * @internal
5919
5349
  */
5920
5350
  const ToolCallGroupContext = createContext(null);
5921
- /**
5922
- * A call without a result is running only while the group is active: once
5923
- * the run has moved on or ended, its result is never coming.
5924
- */
5925
- const entryStatus = ({ toolMessage }, active) => toolMessage ? toolMessage.error ? "failed" : "done" : active ? "running" : "stopped";
5926
- /** @internal */
5927
- const statusLabels = {
5928
- running: "Running",
5929
- done: "Done",
5930
- failed: "Failed",
5931
- stopped: "Stopped"
5351
+ /** The label key for each call status. */
5352
+ const STATUS_LABEL_KEYS = {
5353
+ running: "toolCallStatusRunningLabel",
5354
+ done: "toolCallStatusDoneLabel",
5355
+ failed: "toolCallStatusFailedLabel",
5356
+ stopped: "toolCallStatusStoppedLabel"
5932
5357
  };
5933
- /** The first non-empty string argument: usually a command, path or query. */
5934
- function argumentPreview(parameters) {
5935
- if (!parameters || typeof parameters !== "object") return void 0;
5936
- return Object.values(parameters).find((v) => typeof v === "string" && v.trim().length > 0)?.replace(/\s+/g, " ");
5937
- }
5938
- const entryPreview = (entry) => argumentPreview(partialJSONParse(entry.toolCall.function.arguments));
5939
- /** "run_command ×2, read_file" */
5940
- function toolNames(calls) {
5941
- const counts = /* @__PURE__ */ new Map();
5942
- for (const { toolCall } of calls) {
5943
- const name = toolCall.function.name;
5944
- counts.set(name, (counts.get(name) ?? 0) + 1);
5945
- }
5946
- return [...counts].map(([name, count]) => count > 1 ? `${name} ×${count}` : name).join(", ");
5358
+ /** The icon for each call status. */
5359
+ const STATUS_ICONS = {
5360
+ running: "Loader2",
5361
+ done: "Check",
5362
+ failed: "X",
5363
+ stopped: "Circle"
5364
+ };
5365
+ /** The chat labels from the nearest chat configuration, or the defaults. */
5366
+ function useLabels$1() {
5367
+ return useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
5947
5368
  }
5948
- const pluralize = (count, noun) => `${count} ${noun}${count === 1 ? "" : "s"}`;
5949
5369
  /**
5950
5370
  * Height transition between closed and its content's height. Closed content
5951
5371
  * stays mounted (so its state survives) but is inert.
@@ -5968,55 +5388,35 @@ function Collapsible({ open, id, className, children }) {
5968
5388
  });
5969
5389
  }
5970
5390
  function StatusIcon({ status, className }) {
5971
- const Icon = {
5972
- running: Loader2,
5973
- done: Check,
5974
- failed: X,
5975
- stopped: Circle
5976
- }[status];
5977
- return /* @__PURE__ */ jsx(Icon, {
5391
+ return /* @__PURE__ */ jsx(CopilotIcon, {
5392
+ name: STATUS_ICONS[status],
5978
5393
  "aria-hidden": "true",
5979
5394
  className: cn("cpk-tool-call-status-icon", status === "running" && "cpk-tool-call-status-icon-running", status === "failed" && "cpk-tool-call-status-icon-failed", className)
5980
5395
  });
5981
5396
  }
5982
5397
  function Chevron({ open, className }) {
5983
- return /* @__PURE__ */ jsx(ChevronRight, {
5398
+ return /* @__PURE__ */ jsx(CopilotIcon, {
5399
+ name: "ChevronRight",
5984
5400
  "aria-hidden": "true",
5985
5401
  className: cn("cpk-tool-call-chevron", open && "cpk-tool-call-chevron-open", className)
5986
5402
  });
5987
5403
  }
5988
5404
  function FailedCount({ calls }) {
5989
- const failed = calls.filter((call) => call.toolMessage?.error).length;
5405
+ const labels = useLabels$1();
5406
+ const failed = ɵcountFailedToolCalls$1(calls);
5990
5407
  if (!failed) return null;
5991
- return /* @__PURE__ */ jsxs("span", {
5408
+ return /* @__PURE__ */ jsx("span", {
5992
5409
  className: "cpk-tool-call-failed-count",
5993
- children: [failed, " failed"]
5410
+ children: ɵformatLabel$1(labels.toolCallFailedCountLabel, { count: failed })
5994
5411
  });
5995
5412
  }
5996
- /**
5997
- * Guarded JSON.stringify for the payload blocks. A circular reference would
5998
- * otherwise crash the entire React tree on render.
5999
- */
6000
- function stringifyPayload(value) {
6001
- if (typeof value === "string") return value;
6002
- try {
6003
- return JSON.stringify(value, null, 2);
6004
- } catch (err) {
6005
- console.warn("[CopilotKit] Failed to JSON.stringify tool-call payload; falling back to String():", err);
6006
- try {
6007
- return String(value);
6008
- } catch {
6009
- return "[unserializable]";
6010
- }
6011
- }
6012
- }
6013
5413
  function Payload({ label, value }) {
6014
5414
  return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("div", {
6015
5415
  className: "cpk-tool-call-payload-label",
6016
5416
  children: label
6017
5417
  }), /* @__PURE__ */ jsx("pre", {
6018
5418
  className: "cpk-tool-call-payload-code",
6019
- children: stringifyPayload(value)
5419
+ children: ɵstringifyToolCallPayload$1(value)
6020
5420
  })] });
6021
5421
  }
6022
5422
  /**
@@ -6024,13 +5424,14 @@ function Payload({ label, value }) {
6024
5424
  * @internal
6025
5425
  */
6026
5426
  function ToolCallPayloads({ parameters, result, className }) {
5427
+ const labels = useLabels$1();
6027
5428
  return /* @__PURE__ */ jsxs("div", {
6028
5429
  className: cn("cpk-tool-call-payloads", className),
6029
5430
  children: [/* @__PURE__ */ jsx(Payload, {
6030
- label: "Arguments",
5431
+ label: labels.toolCallArgumentsLabel,
6031
5432
  value: parameters ?? {}
6032
5433
  }), result !== void 0 && /* @__PURE__ */ jsx(Payload, {
6033
- label: "Result",
5434
+ label: labels.toolCallResultLabel,
6034
5435
  value: result
6035
5436
  })]
6036
5437
  });
@@ -6041,9 +5442,10 @@ function ToolCallPayloads({ parameters, result, className }) {
6041
5442
  * @internal
6042
5443
  */
6043
5444
  function ToolCallRow({ name, parameters, result, status, appearance, className, ...props }) {
5445
+ const labels = useLabels$1();
6044
5446
  const [open, setOpen] = useState(false);
6045
5447
  const detailsId = useId();
6046
- const preview = argumentPreview(parameters);
5448
+ const preview = ɵgetArgumentPreview$1(parameters);
6047
5449
  return /* @__PURE__ */ jsxs("div", {
6048
5450
  "data-copilotkit": true,
6049
5451
  className: cn("cpk-tool-call-row", `cpk-tool-call-row-${appearance}`, className),
@@ -6068,7 +5470,7 @@ function ToolCallRow({ name, parameters, result, status, appearance, className,
6068
5470
  /* @__PURE__ */ jsx("span", {
6069
5471
  "data-testid": "copilot-tool-render-status",
6070
5472
  className: "cpk-tool-call-row-status",
6071
- children: statusLabels[status]
5473
+ children: labels[STATUS_LABEL_KEYS[status]]
6072
5474
  }),
6073
5475
  /* @__PURE__ */ jsx(Chevron, {
6074
5476
  open,
@@ -6097,14 +5499,15 @@ function ToolCallRow({ name, parameters, result, status, appearance, className,
6097
5499
  * draws.
6098
5500
  */
6099
5501
  function CopilotChatToolCallGroup({ calls, renderCall, appearance = "card", isActive = false, className, ...props }) {
5502
+ const labels = useLabels$1();
6100
5503
  const [open, setOpen] = useState(false);
6101
5504
  const bodyId = useId();
6102
5505
  const latest = calls[calls.length - 1];
6103
5506
  if (!latest) return null;
6104
5507
  const current = isActive ? calls.find((call) => !call.toolMessage) ?? latest : void 0;
6105
- const preview = current ? entryPreview(current) : void 0;
5508
+ const preview = current ? ɵgetToolCallPreview$1(current) : void 0;
6106
5509
  const done = calls.filter((call) => call.toolMessage).length;
6107
- const statuses = calls.map((call) => entryStatus(call, isActive));
5510
+ const statuses = calls.map((call) => ɵgetToolCallRowStatus$1(call, isActive));
6108
5511
  const failedIds = new Set(calls.filter((_, index) => statuses[index] === "failed").map((call) => call.toolCall.id));
6109
5512
  const status = current ? "running" : failedIds.size > 0 ? "failed" : statuses.includes("stopped") ? "stopped" : "done";
6110
5513
  const rows = (rowAppearance) => /* @__PURE__ */ jsx(ToolCallGroupContext.Provider, {
@@ -6122,9 +5525,9 @@ function CopilotChatToolCallGroup({ calls, renderCall, appearance = "card", isAc
6122
5525
  "data-state": status,
6123
5526
  ...props
6124
5527
  };
6125
- const runningLabel = current && /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs("span", {
5528
+ const runningLabel = current && /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("span", {
6126
5529
  className: "cpk-tool-call-group-running cpk-shimmer",
6127
- children: ["Running ", current.toolCall.function.name]
5530
+ children: ɵformatLabel$1(labels.toolCallRunningLabel, { name: current.toolCall.function.name })
6128
5531
  }), preview && /* @__PURE__ */ jsx("span", {
6129
5532
  className: "cpk-tool-call-group-preview",
6130
5533
  children: preview
@@ -6152,13 +5555,16 @@ function CopilotChatToolCallGroup({ calls, renderCall, appearance = "card", isAc
6152
5555
  onClick: () => setOpen((value) => !value),
6153
5556
  className: "cpk-tool-call-group-line-toggle",
6154
5557
  children: [runningLabel || /* @__PURE__ */ jsxs(Fragment$1, { children: [
6155
- /* @__PURE__ */ jsxs("span", {
5558
+ /* @__PURE__ */ jsx("span", {
6156
5559
  className: "cpk-tool-call-group-line-summary",
6157
- children: ["Used ", pluralize(calls.length, "tool")]
5560
+ children: ɵformatCountLabel$1(calls.length, {
5561
+ one: labels.toolCallUsedToolsOne,
5562
+ other: labels.toolCallUsedToolsOther
5563
+ })
6158
5564
  }),
6159
5565
  /* @__PURE__ */ jsx("span", {
6160
5566
  className: "cpk-tool-call-group-line-names",
6161
- children: toolNames(calls)
5567
+ children: ɵformatToolNames$1(calls)
6162
5568
  }),
6163
5569
  /* @__PURE__ */ jsx(FailedCount, { calls })
6164
5570
  ] }), /* @__PURE__ */ jsx(Chevron, { open })]
@@ -6175,8 +5581,8 @@ function CopilotChatToolCallGroup({ calls, renderCall, appearance = "card", isAc
6175
5581
  if (appearance === "stack") {
6176
5582
  const behind = open ? 0 : Math.min(calls.length - 1, 2);
6177
5583
  const layer = "cpk-tool-call-group-stack-layer";
6178
- const latestStatus = entryStatus(latest, isActive);
6179
- const latestPreview = entryPreview(latest);
5584
+ const latestStatus = ɵgetToolCallRowStatus$1(latest, isActive);
5585
+ const latestPreview = ɵgetToolCallPreview$1(latest);
6180
5586
  return /* @__PURE__ */ jsxs("div", {
6181
5587
  ...groupProps,
6182
5588
  className: cn("cpk-tool-call-group cpk-tool-call-group-stack", className),
@@ -6203,11 +5609,14 @@ function CopilotChatToolCallGroup({ calls, renderCall, appearance = "card", isAc
6203
5609
  onClick: () => setOpen((value) => !value),
6204
5610
  className: cn("cpk-tool-call-group-stack-toggle", open ? "cpk-tool-call-group-stack-toggle-open" : [layer, "cpk-tool-call-group-stack-toggle-closed"]),
6205
5611
  children: open ? /* @__PURE__ */ jsxs(Fragment$1, { children: [
6206
- pluralize(calls.length, "tool call"),
5612
+ ɵformatCountLabel$1(calls.length, {
5613
+ one: labels.toolCallToolCallCountOne,
5614
+ other: labels.toolCallToolCallCountOther
5615
+ }),
6207
5616
  /* @__PURE__ */ jsx(FailedCount, { calls }),
6208
5617
  /* @__PURE__ */ jsxs("span", {
6209
5618
  className: "cpk-tool-call-group-stack-collapse",
6210
- children: ["Collapse", /* @__PURE__ */ jsx(Chevron, {
5619
+ children: [labels.toolCallCollapseLabel, /* @__PURE__ */ jsx(Chevron, {
6211
5620
  open: true,
6212
5621
  className: "cpk-tool-call-group-stack-collapse-icon"
6213
5622
  })]
@@ -6226,7 +5635,7 @@ function CopilotChatToolCallGroup({ calls, renderCall, appearance = "card", isAc
6226
5635
  }),
6227
5636
  /* @__PURE__ */ jsx("span", {
6228
5637
  className: "cpk-tool-call-group-stack-status",
6229
- children: statusLabels[latestStatus]
5638
+ children: labels[STATUS_LABEL_KEYS[latestStatus]]
6230
5639
  })
6231
5640
  ]
6232
5641
  }, latest.toolCall.id), /* @__PURE__ */ jsxs("span", {
@@ -6235,7 +5644,10 @@ function CopilotChatToolCallGroup({ calls, renderCall, appearance = "card", isAc
6235
5644
  /* @__PURE__ */ jsx(FailedCount, { calls }),
6236
5645
  /* @__PURE__ */ jsx("span", {
6237
5646
  className: "cpk-tool-call-group-stack-count",
6238
- children: pluralize(calls.length, "call")
5647
+ children: ɵformatCountLabel$1(calls.length, {
5648
+ one: labels.toolCallCallCountOne,
5649
+ other: labels.toolCallCallCountOther
5650
+ })
6239
5651
  }),
6240
5652
  /* @__PURE__ */ jsx(Chevron, {
6241
5653
  open: false,
@@ -6247,7 +5659,7 @@ function CopilotChatToolCallGroup({ calls, renderCall, appearance = "card", isAc
6247
5659
  /* @__PURE__ */ jsx("span", {
6248
5660
  "aria-live": "polite",
6249
5661
  className: "cpk-tool-call-group-stack-live",
6250
- children: open ? "" : `${latest.toolCall.function.name}: ${statusLabels[latestStatus]}`
5662
+ children: open ? "" : `${latest.toolCall.function.name}: ${labels[STATUS_LABEL_KEYS[latestStatus]]}`
6251
5663
  })
6252
5664
  ]
6253
5665
  }), open && /* @__PURE__ */ jsx("div", {
@@ -6279,18 +5691,21 @@ function CopilotChatToolCallGroup({ calls, renderCall, appearance = "card", isAc
6279
5691
  className: "cpk-tool-call-group-card-toggle",
6280
5692
  children: [
6281
5693
  /* @__PURE__ */ jsx(StatusIcon, { status }),
6282
- runningLabel || /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs("span", {
5694
+ runningLabel || /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("span", {
6283
5695
  className: "cpk-tool-call-group-card-summary",
6284
- children: ["Used ", pluralize(calls.length, "tool")]
5696
+ children: ɵformatCountLabel$1(calls.length, {
5697
+ one: labels.toolCallUsedToolsOne,
5698
+ other: labels.toolCallUsedToolsOther
5699
+ })
6285
5700
  }), /* @__PURE__ */ jsx("span", {
6286
5701
  className: "cpk-tool-call-group-card-names",
6287
- children: toolNames(calls)
5702
+ children: ɵformatToolNames$1(calls)
6288
5703
  })] }),
6289
5704
  /* @__PURE__ */ jsxs("span", {
6290
5705
  className: "cpk-tool-call-group-card-meta",
6291
5706
  children: [status === "failed" ? /* @__PURE__ */ jsx(FailedCount, { calls }) : /* @__PURE__ */ jsx("span", {
6292
5707
  className: "cpk-tool-call-group-card-status",
6293
- children: status !== "running" ? statusLabels[status] : done > 0 && `${done} done`
5708
+ children: status !== "running" ? labels[STATUS_LABEL_KEYS[status]] : done > 0 && ɵformatLabel$1(labels.toolCallDoneCountLabel, { count: done })
6294
5709
  }), /* @__PURE__ */ jsx(Chevron, { open })]
6295
5710
  })
6296
5711
  ]
@@ -7057,11 +6472,6 @@ function normalizeStaticSuggestions(suggestions) {
7057
6472
  }));
7058
6473
  }
7059
6474
 
7060
- //#endregion
7061
- //#region src/types/interrupt.ts
7062
- /** Name of the legacy custom event agents emit to signal an interrupt. */
7063
- const INTERRUPT_EVENT_NAME = "on_interrupt";
7064
-
7065
6475
  //#endregion
7066
6476
  //#region src/hooks/use-interrupt.tsx
7067
6477
  /** Recognize thenables returned by interrupt preprocessing handlers. */
@@ -7290,7 +6700,7 @@ function useInterrupt(config) {
7290
6700
  try {
7291
6701
  maybePromise = handler({
7292
6702
  event: legacyEvent,
7293
- interrupt: pending.kind === "standard" ? pending.interrupts[0] : null,
6703
+ interrupt: pending.kind === "standard" ? pending.interrupts[0] ?? null : null,
7294
6704
  interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
7295
6705
  resolve: resolveRef.current,
7296
6706
  cancel: cancelRef.current
@@ -7319,7 +6729,7 @@ function useInterrupt(config) {
7319
6729
  if (!isEnabled(legacyEvent)) return null;
7320
6730
  return renderRef.current({
7321
6731
  event: legacyEvent,
7322
- interrupt: pending.kind === "standard" ? pending.interrupts[0] : null,
6732
+ interrupt: pending.kind === "standard" ? pending.interrupts[0] ?? null : null,
7323
6733
  interrupts: pending.kind === "standard" ? [...pending.interrupts] : [],
7324
6734
  result: handlerResult,
7325
6735
  resolve,
@@ -7951,8 +7361,11 @@ function useAttachments({ config }) {
7951
7361
  console.error("[CopilotKit] Paste error:", error);
7952
7362
  }
7953
7363
  };
7954
- document.addEventListener("paste", handlePaste);
7955
- return () => document.removeEventListener("paste", handlePaste);
7364
+ const onPaste = (e) => {
7365
+ handlePaste(e);
7366
+ };
7367
+ document.addEventListener("paste", onPaste);
7368
+ return () => document.removeEventListener("paste", onPaste);
7956
7369
  }, [enabled, processFiles]);
7957
7370
  return {
7958
7371
  attachments,
@@ -7978,297 +7391,11 @@ function useAttachments({ config }) {
7978
7391
  };
7979
7392
  }
7980
7393
 
7981
- //#endregion
7982
- //#region src/hooks/use-learning-containers.tsx
7983
- /** The default learning containers value. Matches the backend default. */
7984
- const DEFAULT_CONTAINERS = ["project"];
7985
- /**
7986
- * Legacy compatibility hook that keeps a thread's plural learning-container
7987
- * annotation in sync by emitting
7988
- * `set_learning_containers` annotations via the CopilotKit runtime annotate
7989
- * endpoint (`POST ${runtimeUrl}/annotate`).
7990
- *
7991
- * **Emit rules:**
7992
- * - On mount with `["project"]` (the backend default) → does NOT emit.
7993
- * Absence of an annotation equals the default, so the round-trip is skipped.
7994
- * - On mount with any other value → emits immediately.
7995
- * - On any subsequent content change (including a switch back to
7996
- * `["project"]`) → emits (a deliberate switch is always recorded).
7997
- * - On unmount or threadId change → emits a reset to `["project"]`
7998
- * so the backend is left in a clean state for the next consumer.
7999
- * Changing `learningContainers` within the same thread does NOT reset the
8000
- * thread; only the new value is emitted.
8001
- *
8002
- * Content-equality is evaluated via `JSON.stringify` so a fresh array literal
8003
- * with the same items does NOT trigger a redundant emit.
8004
- *
8005
- * If `runtimeUrl` is absent, all emits are silently skipped.
8006
- *
8007
- * @example
8008
- * ```tsx
8009
- * function ThreadPane({ threadId, userScope }: Props) {
8010
- * useLearningContainers({
8011
- * threadId,
8012
- * learningContainers: [userScope],
8013
- * });
8014
- * // ...
8015
- * }
8016
- * ```
8017
- *
8018
- * @deprecated This hook supports only the legacy plural-container annotation.
8019
- * Configure `getLearningContainerId` on `CopilotKitIntelligence` for new
8020
- * Intelligence runtimes.
8021
- */
8022
- function useLearningContainers({ threadId, learningContainers }) {
8023
- const { copilotkit } = useCopilotKit$1();
8024
- /**
8025
- * Tracks the last-synced container list so content-identical rerenders
8026
- * (fresh array, same values) do not fire a redundant emit.
8027
- * `null` = nothing synced yet (initial state or after a threadId reset).
8028
- */
8029
- const lastSyncedRef = useRef(null);
8030
- /** Guards the missing-runtimeUrl warning so it fires at most once per hook instance. */
8031
- const warnedMissingUrlRef = useRef(false);
8032
- const runtimeUrlRef = useRef(copilotkit.runtimeUrl);
8033
- const runtimeFetchRef = useRef(copilotkit.ɵruntimeFetch);
8034
- runtimeUrlRef.current = copilotkit.runtimeUrl;
8035
- runtimeFetchRef.current = copilotkit.ɵruntimeFetch;
8036
- const key = JSON.stringify(learningContainers);
8037
- const defaultKey = JSON.stringify(DEFAULT_CONTAINERS);
8038
- useEffect(() => {
8039
- const runtimeUrl = copilotkit.runtimeUrl;
8040
- /**
8041
- * Fire-and-forget emit; errors must not surface in render.
8042
- * Failures are logged as warnings so they are diagnosable without
8043
- * propagating into the React render cycle.
8044
- */
8045
- const emit = (containers) => {
8046
- if (!runtimeUrl) {
8047
- if (!warnedMissingUrlRef.current) {
8048
- warnedMissingUrlRef.current = true;
8049
- console.warn("useLearningContainers: runtimeUrl not configured; learning-container sync disabled");
8050
- }
8051
- return;
8052
- }
8053
- recordAnnotation({
8054
- fetch: copilotkit.ɵruntimeFetch,
8055
- runtimeUrl,
8056
- headers: {},
8057
- type: "set_learning_containers",
8058
- payload: { containers },
8059
- threadId
8060
- }).catch((err) => {
8061
- console.warn("useLearningContainers: failed to record set_learning_containers", err);
8062
- });
8063
- };
8064
- if (lastSyncedRef.current === null) {
8065
- if (key === defaultKey) {
8066
- lastSyncedRef.current = learningContainers;
8067
- return;
8068
- }
8069
- emit(learningContainers);
8070
- lastSyncedRef.current = learningContainers;
8071
- } else if (key !== JSON.stringify(lastSyncedRef.current)) {
8072
- emit(learningContainers);
8073
- lastSyncedRef.current = learningContainers;
8074
- }
8075
- }, [threadId, key]);
8076
- useEffect(() => {
8077
- const capturedThreadId = threadId;
8078
- return () => {
8079
- const capturedRuntimeUrl = runtimeUrlRef.current;
8080
- if (capturedRuntimeUrl) recordAnnotation({
8081
- fetch: runtimeFetchRef.current,
8082
- runtimeUrl: capturedRuntimeUrl,
8083
- headers: {},
8084
- type: "set_learning_containers",
8085
- payload: { containers: DEFAULT_CONTAINERS },
8086
- threadId: capturedThreadId
8087
- }).catch((err) => {
8088
- console.warn("useLearningContainers: failed to record set_learning_containers", err);
8089
- });
8090
- lastSyncedRef.current = null;
8091
- };
8092
- }, [threadId]);
8093
- }
8094
-
8095
- //#endregion
8096
- //#region src/hooks/use-learning-containers-in-current-thread.tsx
8097
- /**
8098
- * Legacy compatibility hook that keeps the **current chat thread's** plural
8099
- * learning-container annotation in sync. The `threadId` is sourced from the surrounding
8100
- * `<CopilotChatConfigurationProvider>` (the same provider `<CopilotChat>`,
8101
- * `<CopilotSidebar>`, and friends set up), so callers in a chat-aware
8102
- * subtree don't need to thread an id through manually.
8103
- *
8104
- * **Throws on render** when there is no chat-config provider in scope or
8105
- * when the provider does not yet have an active `threadId`. Mount the hook
8106
- * inside a subtree that is guaranteed to have a thread context.
8107
- *
8108
- * If you need to manage an explicit thread, use {@link useLearningContainers}
8109
- * directly — two hooks, two crisp contracts, no mode confusion.
8110
- *
8111
- * @throws When no `CopilotChatConfigurationProvider` is in scope or when the
8112
- * active `threadId` is absent/empty.
8113
- *
8114
- * @example
8115
- * ```tsx
8116
- * function ThreadPanel({ scope }: Props) {
8117
- * useLearningContainersInCurrentThread({
8118
- * learningContainers: [scope],
8119
- * });
8120
- * // ...
8121
- * }
8122
- * ```
8123
- *
8124
- * @deprecated This hook supports only the legacy plural-container annotation.
8125
- * Configure `getLearningContainerId` on `CopilotKitIntelligence` for new
8126
- * Intelligence runtimes.
8127
- */
8128
- function useLearningContainersInCurrentThread({ learningContainers }) {
8129
- const threadId = useCopilotChatConfiguration()?.threadId;
8130
- if (!threadId) throw new Error("useLearningContainersInCurrentThread must be used within a thread context (no active threadId). Wrap the component in <CopilotChat>, <CopilotSidebar>, or <CopilotChatConfigurationProvider>, or use `useLearningContainers()` and pass `threadId` explicitly.");
8131
- useLearningContainers({
8132
- threadId,
8133
- learningContainers
8134
- });
8135
- }
8136
-
8137
7394
  //#endregion
8138
7395
  //#region src/components/chat/tool-call-display-context.ts
8139
7396
  /** @internal */
8140
7397
  const ToolCallDisplayContext = createContext(null);
8141
7398
 
8142
- //#endregion
8143
- //#region src/components/chat/tool-call-layout.ts
8144
- function contentLength(content) {
8145
- return typeof content === "string" ? content.length : JSON.stringify(content ?? "").length;
8146
- }
8147
- const entrySignature = ({ toolCall, toolMessage }) => [
8148
- toolCall.id,
8149
- toolCall.function.name,
8150
- toolCall.function.arguments.length,
8151
- toolMessage ? `${contentLength(toolMessage.content)}${toolMessage.error ? "!" : ""}` : "-"
8152
- ].join(":");
8153
- function signatureOf(segments) {
8154
- return segments.map((segment) => segment.kind === "call" ? `c(${entrySignature(segment.call)})` : `g${segment.trailing ? "*" : ""}(${segment.calls.map(entrySignature).join(",")})`).join("|");
8155
- }
8156
- /** Index of tool results by the call they answer. */
8157
- function getToolResults(messages) {
8158
- const results = /* @__PURE__ */ new Map();
8159
- for (const message of messages) if (message.role === "tool") results.set(message.toolCallId, message);
8160
- return results;
8161
- }
8162
- /**
8163
- * Lays out the tool calls of every assistant message in `rendered`.
8164
- *
8165
- * Calls drawn by a renderer that opted into grouping join the group that's
8166
- * open; anything else that shows between them closes it: assistant text, a
8167
- * user, reasoning or activity message, or a call drawn by any other renderer. A group belongs to
8168
- * the message where it starts, so later messages whose calls joined it render
8169
- * no tool calls themselves.
8170
- *
8171
- * @param rendered - The messages as the chat renders them, in order.
8172
- * @param all - Every message, for finding tool results (a transform may hide them).
8173
- * @param renderers - The registered renderers.
8174
- */
8175
- function getToolCallLayouts(rendered, all, renderers) {
8176
- const results = getToolResults(all);
8177
- const layouts = /* @__PURE__ */ new Map();
8178
- let open;
8179
- for (const message of rendered) {
8180
- if (message.role === "tool") continue;
8181
- if (message.role !== "assistant") {
8182
- open = void 0;
8183
- continue;
8184
- }
8185
- if (typeof message.content === "string" && message.content.trim()) open = void 0;
8186
- const segments = [];
8187
- layouts.set(message.id, segments);
8188
- const toolCalls = /* @__PURE__ */ new Map();
8189
- for (const toolCall of message.toolCalls ?? []) toolCalls.set(toolCall.id, toolCall);
8190
- for (const toolCall of toolCalls.values()) {
8191
- const entry = {
8192
- toolCall,
8193
- toolMessage: results.get(toolCall.id)
8194
- };
8195
- const name = toolCall.function.name;
8196
- const named = renderers.named.has(name);
8197
- const rendered = named || renderers.wildcard;
8198
- const groups = named ? renderers.groupedNames.has(name) : renderers.wildcardGroups;
8199
- if (!rendered || !groups) {
8200
- if (rendered) open = void 0;
8201
- segments.push({
8202
- kind: "call",
8203
- id: toolCall.id,
8204
- call: entry,
8205
- rendered
8206
- });
8207
- } else if (open) open.calls.push(entry);
8208
- else {
8209
- open = {
8210
- kind: "group",
8211
- id: toolCall.id,
8212
- calls: [entry],
8213
- trailing: false
8214
- };
8215
- segments.push(open);
8216
- }
8217
- }
8218
- }
8219
- if (open) open.trailing = true;
8220
- const layout = /* @__PURE__ */ new Map();
8221
- for (const [id, segments] of layouts) layout.set(id, {
8222
- segments,
8223
- signature: signatureOf(segments)
8224
- });
8225
- return layout;
8226
- }
8227
- /**
8228
- * Finds the working phase of every reply in `rendered`: its messages up to the
8229
- * last one that calls a tool. Text in there was narration; what follows is the
8230
- * reply itself. Replies that called no tools are omitted, except the latest,
8231
- * which may be about to.
8232
- */
8233
- function getTurnWork(rendered, layouts) {
8234
- const turns = /* @__PURE__ */ new Map();
8235
- let start = 0;
8236
- while (start < rendered.length) {
8237
- let end = start;
8238
- while (end < rendered.length && rendered[end].role !== "user") end++;
8239
- const key = start > 0 ? rendered[start - 1].id : "start";
8240
- const visible = rendered.slice(start, end).filter((message) => message.role !== "tool");
8241
- const isLatest = end === rendered.length;
8242
- const calls = [];
8243
- for (const message of visible) for (const segment of layouts.get(message.id)?.segments ?? []) if (segment.kind === "group") calls.push(...segment.calls);
8244
- else if (segment.rendered) calls.push(segment.call);
8245
- const shown = new Set(calls.map((entry) => entry.toolCall.id));
8246
- let lastWork = -1;
8247
- visible.forEach((message, index) => {
8248
- if (message.role === "assistant" && message.toolCalls?.some((call) => shown.has(call.id))) lastWork = index;
8249
- });
8250
- const first = visible[0];
8251
- if (first && (calls.length > 0 || isLatest)) {
8252
- let lastAssistant = -1;
8253
- visible.forEach((message, index) => {
8254
- if (message.role === "assistant") lastAssistant = index;
8255
- });
8256
- const replyText = visible[lastAssistant]?.content;
8257
- const endsWithWork = lastAssistant >= 0 && lastAssistant <= lastWork && typeof replyText === "string" && replyText.trim().length > 0;
8258
- turns.set(key, {
8259
- key,
8260
- firstMessageId: first.id,
8261
- workMessageIds: new Set(visible.slice(0, lastWork + 1).map((message) => message.id)),
8262
- replyTextMessageId: endsWithWork ? visible[lastAssistant].id : void 0,
8263
- calls,
8264
- isLatest
8265
- });
8266
- }
8267
- start = end + 1;
8268
- }
8269
- return turns;
8270
- }
8271
-
8272
7399
  //#endregion
8273
7400
  //#region src/components/chat/CopilotChatToolCallsView.tsx
8274
7401
  const appearances = {
@@ -8288,7 +7415,7 @@ function CopilotChatToolCallsView({ message, messages = [], display: displayProp
8288
7415
  const viewLayout = context?.layouts.get(message.id);
8289
7416
  const layout = useMemo(() => {
8290
7417
  if (display === "separate") return void 0;
8291
- return viewLayout ?? getToolCallLayouts([message], messages, rendererNames).get(message.id);
7418
+ return viewLayout ?? ɵgetToolCallLayouts$1([message], messages, rendererNames).get(message.id);
8292
7419
  }, [
8293
7420
  display,
8294
7421
  viewLayout,
@@ -8337,172 +7464,65 @@ function CopilotChatToolCallsView({ message, messages = [], display: displayProp
8337
7464
  })
8338
7465
  })
8339
7466
  }, segment.id);
8340
- }
8341
- return /* @__PURE__ */ jsx(React.Fragment, { children: renderSlot(group, CopilotChatToolCallGroup, {
8342
- calls: segment.calls,
8343
- renderCall,
8344
- appearance: appearances[display] ?? "card",
8345
- isActive: groupActive(segment.trailing)
8346
- }) }, segment.id);
8347
- }) });
8348
- }
8349
-
8350
- //#endregion
8351
- //#region src/components/chat/CopilotChatInspectorButton.tsx
8352
- let shortcutsHidden = false;
8353
- const listeners$1 = /* @__PURE__ */ new Set();
8354
- const subscribe = (listener) => {
8355
- listeners$1.add(listener);
8356
- return () => {
8357
- listeners$1.delete(listener);
8358
- };
8359
- };
8360
- const getSnapshot = () => shortcutsHidden;
8361
- const getServerSnapshot = () => false;
8362
- function useInspectorShortcutsHidden() {
8363
- return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
8364
- }
8365
- function hideShortcuts() {
8366
- shortcutsHidden = true;
8367
- listeners$1.forEach((listener) => listener());
8368
- }
8369
- function InspectorKiteIcon({ className, ...props }) {
8370
- const id = useId();
8371
- return /* @__PURE__ */ jsxs("svg", {
8372
- ...props,
8373
- "aria-hidden": "true",
8374
- className: cn("cpk-inspector-button-kite-icon", className),
8375
- viewBox: "4.57 3.36 17.8 17.8",
8376
- fill: "none",
8377
- children: [
8378
- /* @__PURE__ */ jsx("path", {
8379
- d: "M6.36084 10.9855C8.34277 8.393 9.98843 5.82939 10.6204 3.75914C10.6382 3.70281 10.7043 3.67888 10.7534 3.7114C12.9536 5.16894 16.9635 6.12833 20.5086 6.15085C20.5703 6.15124 20.6124 6.2114 20.5895 6.26829C19.4109 9.25938 17.9705 14.6189 17.9148 20.7392C17.9148 20.8301 17.7873 20.8627 17.7419 20.7837C15.7236 17.2522 9.26021 12.2898 6.39414 11.1186C6.34112 11.0968 6.32556 11.0313 6.36084 10.9855Z",
8380
- fill: `url(#${id}-paint0_linear)`
8381
- }),
8382
- /* @__PURE__ */ jsx("path", {
8383
- d: "M13.0475 9.39974C9.95016 10.3806 7.11935 10.9259 6.44331 11.0498C6.40027 11.0577 6.39115 11.1172 6.43152 11.134C9.3203 12.3347 15.7516 17.2826 17.7511 20.7998C17.7551 20.8075 17.7647 20.8103 17.7728 20.8068C17.7809 20.803 17.7853 20.793 17.7819 20.7844L13.0475 9.39974Z",
8384
- fill: `url(#${id}-paint1_linear)`
8385
- }),
8386
- /* @__PURE__ */ jsx("path", {
8387
- d: "M10.762 3.705C13.4137 5.15161 16.4787 5.80132 20.545 6.14367C20.5703 6.14585 20.5787 6.18008 20.5557 6.19197C20.0359 6.45923 17.0574 7.97512 14.8455 8.78701C14.2524 9.00453 13.6564 9.20632 13.0692 9.39249C13.0562 9.39656 13.0419 9.39015 13.0369 9.37774L10.7005 3.75979C10.6849 3.72196 10.7257 3.68538 10.762 3.705Z",
8388
- fill: `url(#${id}-paint2_linear)`
8389
- }),
8390
- /* @__PURE__ */ jsx("path", {
8391
- d: "M10.7145 3.79041L17.8305 20.7659",
8392
- stroke: "#513C9F",
8393
- strokeWidth: "0.17284",
8394
- strokeLinecap: "round"
8395
- }),
8396
- /* @__PURE__ */ jsx("path", {
8397
- d: "M6.44531 11.0476C6.44531 11.0476 10.375 10.3422 14.0686 9.06804C17.7623 7.7939 20.5122 6.23373 20.5122 6.23373",
8398
- stroke: "#513C9F",
8399
- strokeWidth: "0.17284",
8400
- strokeLinecap: "round"
8401
- }),
8402
- /* @__PURE__ */ jsx("path", {
8403
- d: "M11.6914 5.93518L9.05534 14.7068M9.05534 14.7068H15.3203M9.05534 14.7068L0.15625 26.3646",
8404
- stroke: "#ABABAB",
8405
- strokeWidth: "0.302474",
8406
- strokeLinecap: "round"
8407
- }),
8408
- /* @__PURE__ */ jsx("path", {
8409
- d: "M6.02539 23.9646L4.85806 24.1287C5.46272 25.7287 6.70381 26.4276 8.18528 26.4276C11.8147 26.4276 10.707 22.3227 12.8103 22.3227C14.3358 22.3227 13.7155 25.6498 16.9992 25.6498C19.0029 25.6498 19.2028 23.631 18.8607 22.7625C18.8589 22.7572 18.8568 22.7524 18.8538 22.7476L18.3166 21.9253C18.2817 21.8706 18.1968 21.8912 18.1907 21.9562L18.0908 22.9529C18.0838 23.0222 18.0857 23.0913 18.0936 23.1605C18.1764 23.8491 18.2291 25.5202 16.9992 25.5202C15.7015 25.5202 15.3895 22.2362 12.8103 22.2362C9.78393 22.2362 10.1726 26.298 8.31487 26.298C7.08938 26.298 6.15447 24.9153 6.02539 23.9646Z",
8410
- fill: `url(#${id}-paint3_linear)`
8411
- }),
8412
- /* @__PURE__ */ jsxs("defs", { children: [
8413
- /* @__PURE__ */ jsxs("linearGradient", {
8414
- id: `${id}-paint0_linear`,
8415
- x1: "15.5372",
8416
- y1: "5.0278",
8417
- x2: "12.0802",
8418
- y2: "14.534",
8419
- gradientUnits: "userSpaceOnUse",
8420
- children: [/* @__PURE__ */ jsx("stop", { stopColor: "#6430AB" }), /* @__PURE__ */ jsx("stop", {
8421
- offset: "1",
8422
- stopColor: "#AA89D8"
8423
- })]
8424
- }),
8425
- /* @__PURE__ */ jsxs("linearGradient", {
8426
- id: `${id}-paint1_linear`,
8427
- x1: "12.8583",
8428
- y1: "10.3858",
8429
- x2: "8.40764",
8430
- y2: "18.9846",
8431
- gradientUnits: "userSpaceOnUse",
8432
- children: [/* @__PURE__ */ jsx("stop", { stopColor: "#005DBB" }), /* @__PURE__ */ jsx("stop", {
8433
- offset: "1",
8434
- stopColor: "#3D92E8"
8435
- })]
8436
- }),
8437
- /* @__PURE__ */ jsxs("linearGradient", {
8438
- id: `${id}-paint2_linear`,
8439
- x1: "14.8452",
8440
- y1: "5.02774",
8441
- x2: "13.5047",
8442
- y2: "9.21911",
8443
- gradientUnits: "userSpaceOnUse",
8444
- children: [/* @__PURE__ */ jsx("stop", { stopColor: "#1B70C4" }), /* @__PURE__ */ jsx("stop", {
8445
- offset: "1",
8446
- stopColor: "#54A4F2"
8447
- })]
8448
- }),
8449
- /* @__PURE__ */ jsxs("linearGradient", {
8450
- id: `${id}-paint3_linear`,
8451
- x1: "4.85806",
8452
- y1: "24.2455",
8453
- x2: "18.9963",
8454
- y2: "24.2455",
8455
- gradientUnits: "userSpaceOnUse",
8456
- children: [
8457
- /* @__PURE__ */ jsx("stop", { stopColor: "#4497EA" }),
8458
- /* @__PURE__ */ jsx("stop", {
8459
- offset: "0.254755",
8460
- stopColor: "#1463B2"
8461
- }),
8462
- /* @__PURE__ */ jsx("stop", {
8463
- offset: "0.498725",
8464
- stopColor: "#0A437D"
8465
- }),
8466
- /* @__PURE__ */ jsx("stop", {
8467
- offset: "0.666667",
8468
- stopColor: "#2476C8"
8469
- }),
8470
- /* @__PURE__ */ jsx("stop", {
8471
- offset: "0.972542",
8472
- stopColor: "#0C549A"
8473
- })
8474
- ]
8475
- })
8476
- ] })
8477
- ]
7467
+ }
7468
+ return /* @__PURE__ */ jsx(React.Fragment, { children: renderSlot(group, CopilotChatToolCallGroup, {
7469
+ calls: segment.calls,
7470
+ renderCall,
7471
+ appearance: appearances[display] ?? "card",
7472
+ isActive: groupActive(segment.trailing)
7473
+ }) }, segment.id);
7474
+ }) });
7475
+ }
7476
+
7477
+ //#endregion
7478
+ //#region src/components/chat/CopilotChatInspectorButton.tsx
7479
+ const subscribeToShortcuts = (listener) => ɵinspectorShortcuts$1.subscribe(listener);
7480
+ const getShortcutsHidden = () => ɵinspectorShortcuts$1.hidden;
7481
+ const getServerShortcutsHidden = () => false;
7482
+ /** Whether the user hid the Inspector shortcuts until the page reloads. */
7483
+ function useInspectorShortcutsHidden() {
7484
+ return useSyncExternalStore(subscribeToShortcuts, getShortcutsHidden, getServerShortcutsHidden);
7485
+ }
7486
+ const hideShortcuts = () => ɵinspectorShortcuts$1.hide();
7487
+ function InspectorKiteIcon({ className, ...props }) {
7488
+ const id = useId();
7489
+ return /* @__PURE__ */ jsxs("svg", {
7490
+ ...props,
7491
+ "aria-hidden": "true",
7492
+ className: cn("cpk-inspector-button-kite-icon", className),
7493
+ viewBox: ɵinspectorKiteIcon$1.viewBox,
7494
+ fill: "none",
7495
+ children: [ɵinspectorKiteIcon$1.paths.map((path) => /* @__PURE__ */ jsx("path", {
7496
+ d: path.d,
7497
+ fill: ɵinspectorKiteFill$1(id, path),
7498
+ stroke: path.stroke,
7499
+ strokeWidth: path.strokeWidth,
7500
+ strokeLinecap: path.strokeLinecap
7501
+ }, path.d)), /* @__PURE__ */ jsx("defs", { children: ɵinspectorKiteIcon$1.gradients.map((gradient) => /* @__PURE__ */ jsx("linearGradient", {
7502
+ id: `${id}-${gradient.id}`,
7503
+ x1: gradient.x1,
7504
+ y1: gradient.y1,
7505
+ x2: gradient.x2,
7506
+ y2: gradient.y2,
7507
+ gradientUnits: "userSpaceOnUse",
7508
+ children: gradient.stops.map((stop) => /* @__PURE__ */ jsx("stop", {
7509
+ offset: stop.offset,
7510
+ stopColor: stop.color
7511
+ }, `${stop.offset ?? "0"}-${stop.color}`))
7512
+ }, gradient.id)) })]
8478
7513
  });
8479
7514
  }
8480
7515
  function CopilotChatInspectorButton({ title, className, onClick, onPointerDown, onPointerEnter, onPointerLeave, onKeyDown, disabled, ...props }) {
8481
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
7516
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
8482
7517
  const { isInspectorEnabled } = useCopilotKitInspector();
8483
7518
  const hidden = useInspectorShortcutsHidden();
8484
- const [open, setOpen] = useState(false);
8485
- const [dark, setDark] = useState(false);
7519
+ const [menu] = useState(() => new ɵHoverMenuController$1());
7520
+ const { open, dark } = useSyncExternalStore(menu.subscribe, menu.getSnapshot, menu.getSnapshot);
8486
7521
  const trigger = useRef(null);
8487
- const closeTimer = useRef(null);
8488
- const openedByHover = useRef(false);
8489
7522
  const primaryLabel = title || labels.assistantMessageToolbarInspectorLabel;
8490
- const cancelClose = () => {
8491
- if (closeTimer.current !== null) clearTimeout(closeTimer.current);
8492
- closeTimer.current = null;
8493
- };
8494
- useEffect(() => cancelClose, []);
8495
- const changeOpen = (next) => {
8496
- cancelClose();
8497
- if (next) setDark(!!trigger.current?.closest(".dark"));
8498
- setOpen(next);
8499
- };
8500
- const scheduleClose = () => {
8501
- cancelClose();
8502
- closeTimer.current = setTimeout(() => {
8503
- if (openedByHover.current) setOpen(false);
8504
- }, 180);
8505
- };
7523
+ useEffect(() => menu.dispose, [menu]);
7524
+ const { cancelClose, scheduleClose } = menu;
7525
+ const changeOpen = (next) => menu.setOpen(next, trigger.current);
8506
7526
  if (!isInspectorEnabled || hidden) return null;
8507
7527
  return /* @__PURE__ */ jsxs(DropdownMenu, {
8508
7528
  open,
@@ -8522,10 +7542,11 @@ function CopilotChatInspectorButton({ title, className, onClick, onPointerDown,
8522
7542
  className: cn("cpk-inspector-button", className),
8523
7543
  onPointerEnter: (event) => {
8524
7544
  onPointerEnter?.(event);
8525
- if (!disabled && event.pointerType !== "touch") {
8526
- openedByHover.current = true;
8527
- changeOpen(true);
8528
- }
7545
+ menu.pointerEnter({
7546
+ pointerType: event.pointerType,
7547
+ disabled,
7548
+ trigger: trigger.current
7549
+ });
8529
7550
  },
8530
7551
  onPointerLeave: (event) => {
8531
7552
  onPointerLeave?.(event);
@@ -8540,14 +7561,15 @@ function CopilotChatInspectorButton({ title, className, onClick, onPointerDown,
8540
7561
  onClick?.(event);
8541
7562
  },
8542
7563
  onKeyDown: (event) => {
8543
- openedByHover.current = false;
7564
+ menu.keyboardUsed();
8544
7565
  onKeyDown?.(event);
8545
7566
  if (!event.defaultPrevented && (event.key === "Enter" || event.key === " ")) {
8546
7567
  event.preventDefault();
8547
7568
  event.currentTarget.click();
8548
7569
  }
8549
7570
  },
8550
- children: /* @__PURE__ */ jsx(Wrench, {
7571
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
7572
+ name: "Wrench",
8551
7573
  "aria-hidden": "true",
8552
7574
  className: "cpk-inspector-button-icon",
8553
7575
  "data-testid": "copilot-inspector-icon"
@@ -8560,14 +7582,12 @@ function CopilotChatInspectorButton({ title, className, onClick, onPointerDown,
8560
7582
  className: cn("cpk-inspector-button-menu", dark && "dark"),
8561
7583
  onPointerEnter: cancelClose,
8562
7584
  onPointerLeave: scheduleClose,
8563
- onKeyDown: () => {
8564
- openedByHover.current = false;
8565
- },
7585
+ onKeyDown: menu.keyboardUsed,
8566
7586
  onOpenAutoFocus: (event) => {
8567
- if (openedByHover.current) event.preventDefault();
7587
+ if (menu.openedByHover) event.preventDefault();
8568
7588
  },
8569
7589
  onCloseAutoFocus: (event) => {
8570
- if (openedByHover.current) event.preventDefault();
7590
+ if (menu.openedByHover) event.preventDefault();
8571
7591
  },
8572
7592
  onFocusOutside: () => changeOpen(false),
8573
7593
  children: [
@@ -8614,7 +7634,8 @@ function CopilotChatInspectorButton({ title, className, onClick, onPointerDown,
8614
7634
  /* @__PURE__ */ jsxs(DropdownMenuItem, {
8615
7635
  onSelect: hideShortcuts,
8616
7636
  className: "cpk-inspector-button-menu-item cpk-inspector-button-hide-item",
8617
- children: [/* @__PURE__ */ jsx(EyeOff, {
7637
+ children: [/* @__PURE__ */ jsx(CopilotIcon, {
7638
+ name: "EyeOff",
8618
7639
  "aria-hidden": "true",
8619
7640
  className: "cpk-inspector-button-menu-item-icon"
8620
7641
  }), /* @__PURE__ */ jsxs("span", { children: [/* @__PURE__ */ jsx("span", {
@@ -8660,82 +7681,6 @@ const PopoverContent = React$1.forwardRef(({ className, align = "start", sideOff
8660
7681
  }) }));
8661
7682
  PopoverContent.displayName = "PopoverContent";
8662
7683
 
8663
- //#endregion
8664
- //#region src/lib/message-feedback.ts
8665
- /** Trajectory event name for a rating of one assistant message. */
8666
- const MESSAGE_FEEDBACK_EVENT_NAME = "message.feedback";
8667
- /** Longest comment kept, in characters; the rest is cut so the event stays small. */
8668
- const MESSAGE_FEEDBACK_MAX_COMMENT_LENGTH = 1e3;
8669
- /** Longest excerpt of the rated response sent with the rating, in characters. */
8670
- const RESPONSE_EXCERPT_LENGTH = 500;
8671
- const ratings = /* @__PURE__ */ new Map();
8672
- const listeners = /* @__PURE__ */ new Map();
8673
- const threadKey = (agentId, threadId) => JSON.stringify([agentId, threadId]);
8674
- const messageKey = (agentId, threadId, messageId) => JSON.stringify([
8675
- agentId,
8676
- threadId,
8677
- messageId
8678
- ]);
8679
- /** Cuts `text` to `max` characters without splitting a surrogate pair. */
8680
- const clip = (text, max) => {
8681
- const characters = Array.from(text);
8682
- return characters.length > max ? characters.slice(0, max).join("") : text;
8683
- };
8684
- /** The comment as kept and sent: trimmed and capped, or none. */
8685
- const normalizeComment = (comment) => {
8686
- if (typeof comment !== "string") return void 0;
8687
- const text = clip(comment.trim(), MESSAGE_FEEDBACK_MAX_COMMENT_LENGTH);
8688
- return text === "" ? void 0 : text;
8689
- };
8690
- /** The rating this page gave one message, if any. */
8691
- function getMessageFeedback(agentId, threadId, messageId) {
8692
- return ratings.get(messageKey(agentId, threadId, messageId));
8693
- }
8694
- /** Calls `listener` whenever a rating in this Thread changes. */
8695
- function subscribeToMessageFeedback(agentId, threadId, listener) {
8696
- const key = threadKey(agentId, threadId);
8697
- let set = listeners.get(key);
8698
- if (set === void 0) {
8699
- set = /* @__PURE__ */ new Set();
8700
- listeners.set(key, set);
8701
- }
8702
- set.add(listener);
8703
- return () => {
8704
- set.delete(listener);
8705
- if (set.size === 0) listeners.delete(key);
8706
- };
8707
- }
8708
- /**
8709
- * Sets (or, with `null`, clears) this page's rating of one message and sends
8710
- * it to the active Trajectory. Every change is a new event; the newest event
8711
- * for a `feedbackId` is the current one. Like any Trajectory event, a change
8712
- * made while no Trajectory captures, for example during a reconnect, is not
8713
- * sent; the page still shows it.
8714
- */
8715
- function setMessageFeedback(params) {
8716
- const { copilotkit, agentId, threadId, message } = params;
8717
- const comment = normalizeComment(params.feedback?.comment);
8718
- const feedback = params.feedback && {
8719
- rating: params.feedback.rating,
8720
- ...comment ? { comment } : {}
8721
- };
8722
- const key = messageKey(agentId, threadId, message.id);
8723
- if (feedback) ratings.set(key, feedback);
8724
- else ratings.delete(key);
8725
- for (const listener of listeners.get(threadKey(agentId, threadId)) ?? []) listener();
8726
- const runId = copilotkit.getRunIdForMessage(agentId, threadId, message.id);
8727
- copilotkit.emitTrajectoryEvent(MESSAGE_FEEDBACK_EVENT_NAME, {
8728
- feedbackId: `${threadId}:${message.id}`,
8729
- threadId,
8730
- messageId: message.id,
8731
- agentId,
8732
- ...runId ? { runId } : {},
8733
- rating: feedback?.rating ?? null,
8734
- ...feedback?.comment ? { comment: feedback.comment } : {},
8735
- ...copilotkit.ɵlearningCapturesAgentText ? { response: clip(message.content ?? "", RESPONSE_EXCERPT_LENGTH) } : {}
8736
- });
8737
- }
8738
-
8739
7684
  //#endregion
8740
7685
  //#region src/components/chat/message-feedback.tsx
8741
7686
  /**
@@ -8744,180 +7689,61 @@ function setMessageFeedback(params) {
8744
7689
  * or thumb slots.
8745
7690
  */
8746
7691
  const MessageFeedbackScopeContext = createContext(null);
8747
- const capturedCores = /* @__PURE__ */ new WeakSet();
8748
- const rememberCapture = (copilotkit) => {
8749
- if (capturedCores.has(copilotkit)) return;
8750
- capturedCores.add(copilotkit);
8751
- const unsubscribe = copilotkit.ɵsubscribeToLearningConfigured(() => {
8752
- if (copilotkit.ɵlearningConfigured) return;
8753
- capturedCores.delete(copilotkit);
8754
- unsubscribe();
8755
- });
8756
- };
8757
7692
  /**
8758
- * Whether the thumbs record feedback for Learning. True once a Trajectory of
8759
- * this Core has started and as long as Learning stays configured, also while
8760
- * capture reconnects or is stopped, so the buttons do not flicker. Ratings
8761
- * given meanwhile still show but, like any Trajectory event, are not
8762
- * sent. A capture that never starts (for example without a license) leaves it
8763
- * false.
7693
+ * Whether the thumbs record feedback for Learning. See core's
7694
+ * `ɵisLearningFeedbackEnabled` for the rules.
8764
7695
  */
8765
7696
  function useLearningFeedbackEnabled(copilotkit) {
8766
- const configured = useSyncExternalStore(useCallback((onChange) => copilotkit.ɵsubscribeToLearningConfigured(onChange), [copilotkit]), () => copilotkit.ɵlearningConfigured, () => false);
8767
- const capturing = useSyncExternalStore(useCallback((onChange) => copilotkit.subscribe({ onTrajectoryChanged: onChange }).unsubscribe, [copilotkit]), () => copilotkit.trajectoryId !== null, () => false);
8768
- useEffect(() => {
8769
- if (capturing) rememberCapture(copilotkit);
8770
- }, [capturing, copilotkit]);
8771
- return configured && (capturing || capturedCores.has(copilotkit));
7697
+ return useSyncExternalStore(useCallback((onChange) => ɵsubscribeToLearningFeedbackEnabled$1(copilotkit, onChange), [copilotkit]), () => ɵisLearningFeedbackEnabled$1(copilotkit), () => false);
8772
7698
  }
8773
7699
  const noSubscription = () => () => {};
8774
7700
  /** Feedback controls for `message`, or `null` when this chat collects none. */
8775
7701
  function useMessageFeedback(message) {
8776
7702
  const scope = useContext(MessageFeedbackScopeContext);
8777
- const subscribe = useCallback((onChange) => scope ? subscribeToMessageFeedback(scope.agentId, scope.threadId, onChange) : noSubscription(), [scope]);
8778
- const getSnapshot = () => scope ? getMessageFeedback(scope.agentId, scope.threadId, message.id) : void 0;
8779
- const feedback = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
8780
- if (!scope) return null;
8781
- const save = (next) => setMessageFeedback({
8782
- ...scope,
8783
- message,
8784
- feedback: next
8785
- });
8786
- return {
8787
- feedback,
8788
- rate: (rating) => {
8789
- if (feedback?.rating !== rating) save({ rating });
8790
- },
8791
- clear: () => {
8792
- if (feedback) save(null);
8793
- },
8794
- comment: (comment) => {
8795
- if (feedback) save({
8796
- rating: feedback.rating,
8797
- comment
8798
- });
8799
- }
8800
- };
7703
+ const subscribe = useCallback((onChange) => scope ? ɵsubscribeToMessageFeedback$1(scope.agentId, scope.threadId, onChange) : noSubscription(), [scope]);
7704
+ const getSnapshot = () => scope ? ɵgetMessageFeedback$1(scope.agentId, scope.threadId, message.id) : void 0;
7705
+ useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
7706
+ return scope ? ɵgetMessageFeedbackControls$1(scope, message) : null;
8801
7707
  }
8802
7708
  /**
8803
- * How long the pointer may be away from the rating and its comment before the
8804
- * comment closes: enough to cross the gap between them, short enough that
8805
- * passing over a rating does not leave it open.
8806
- */
8807
- const FEEDBACK_COMMENT_CLOSE_DELAY_MS = 150;
8808
- /**
8809
- * Drives the comment popover of a rated message.
8810
- *
8811
- * It opens when a rating is given and whenever the pointer or keyboard focus
8812
- * reaches the chosen thumb, with the saved comment in the field. It closes by
8813
- * itself shortly after the pointer leaves the thumb and the popover, unless
8814
- * focus is in the field: then it stays until focus moves away, Enter, or
8815
- * Escape. Closing saves a changed comment; Escape, a click on a thumb, and
8816
- * removing the rating discard it.
7709
+ * Drives the comment popover of a rated message with core's
7710
+ * `ɵFeedbackCommentController`, which holds the open and close rules.
8817
7711
  */
8818
7712
  function useFeedbackComment(controls) {
8819
- const [open, setOpen] = useState(false);
8820
- const [draft, setDraft] = useState("");
8821
- const [focusRequest, setFocusRequest] = useState(0);
7713
+ const latestControls = useRef(controls);
7714
+ latestControls.current = controls;
7715
+ const [controller] = useState(() => new ɵFeedbackCommentController$1({ getControls: () => latestControls.current }));
8822
7716
  const inputRef = useRef(null);
8823
- const timer = useRef(void 0);
8824
- const editing = useRef(false);
8825
- const focusWaiting = useRef(false);
8826
- const pointerOver = useRef(false);
8827
- const returning = useRef(false);
8828
- const latest = useRef({
8829
- controls,
8830
- draft,
8831
- open
8832
- });
8833
- latest.current = {
8834
- ...latest.current,
8835
- controls,
8836
- draft,
8837
- open
8838
- };
8839
- const takeFocusRequest = useCallback(() => {
8840
- const waiting = focusWaiting.current;
8841
- focusWaiting.current = false;
8842
- return waiting;
8843
- }, []);
8844
- const cancelClose = useCallback(() => {
8845
- if (timer.current === void 0) return;
8846
- clearTimeout(timer.current);
8847
- timer.current = void 0;
8848
- }, []);
8849
- useEffect(() => cancelClose, [cancelClose]);
8850
- const savedComment = useCallback(() => latest.current.controls?.feedback?.comment ?? "", []);
8851
- useEffect(() => () => {
8852
- const { open: wasOpen, controls: current, draft: text } = latest.current;
8853
- if (wasOpen && current?.feedback && text.trim() !== savedComment()) current.comment(text);
8854
- }, []);
8855
- const close = useCallback(({ save = true } = {}) => {
8856
- cancelClose();
8857
- focusWaiting.current = false;
8858
- pointerOver.current = false;
8859
- if (!latest.current.open) return;
8860
- const current = latest.current.controls;
8861
- if (save && current?.feedback && latest.current.draft.trim() !== savedComment()) current.comment(latest.current.draft);
8862
- editing.current = false;
8863
- latest.current = {
8864
- ...latest.current,
8865
- open: false
8866
- };
8867
- setOpen(false);
8868
- }, [cancelClose, savedComment]);
8869
- const show = ({ comment, focus }) => {
8870
- cancelClose();
8871
- latest.current = {
8872
- ...latest.current,
8873
- open: true,
8874
- draft: comment
8875
- };
8876
- setDraft(comment);
8877
- if (focus) {
8878
- focusWaiting.current = true;
8879
- setFocusRequest((request) => request + 1);
8880
- }
8881
- setOpen(true);
8882
- };
7717
+ const state = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
7718
+ useEffect(() => controller.dispose, [controller]);
8883
7719
  return {
8884
- open,
8885
- draft,
8886
- setDraft,
8887
- focusRequest,
8888
- takeFocusRequest,
7720
+ ...state,
7721
+ setDraft: controller.setDraft,
7722
+ takeFocusRequest: controller.takeFocusRequest,
8889
7723
  inputRef,
8890
- show,
8891
- enter: (via = "focus") => {
8892
- cancelClose();
8893
- if (via === "pointer") pointerOver.current = true;
8894
- if (returning.current) return;
8895
- if (!latest.current.open && latest.current.controls?.feedback) show({
8896
- comment: savedComment(),
8897
- focus: false
8898
- });
8899
- },
8900
- leave: (via = "focus") => {
8901
- if (via === "pointer") pointerOver.current = false;
8902
- else if (pointerOver.current) return;
8903
- cancelClose();
8904
- timer.current = setTimeout(() => {
8905
- timer.current = void 0;
8906
- if (!editing.current) close();
8907
- }, FEEDBACK_COMMENT_CLOSE_DELAY_MS);
8908
- },
8909
- setEditing: (value) => {
8910
- editing.current = value;
8911
- },
8912
- close,
8913
- returnFocus: (target) => {
8914
- returning.current = true;
8915
- try {
8916
- target?.focus();
8917
- } finally {
8918
- returning.current = false;
8919
- }
8920
- }
7724
+ show: controller.show,
7725
+ enter: controller.enter,
7726
+ leave: controller.leave,
7727
+ setEditing: controller.setEditing,
7728
+ close: controller.close,
7729
+ returnFocus: controller.returnFocus
7730
+ };
7731
+ }
7732
+
7733
+ //#endregion
7734
+ //#region src/components/chat/use-copy-feedback.ts
7735
+ /**
7736
+ * The "copied" check mark of a copy button, from core's `ɵCopyFeedback`: it
7737
+ * shows for two seconds after `markCopied()`, and a second copy restarts the
7738
+ * wait.
7739
+ */
7740
+ function useCopyFeedback() {
7741
+ const [feedback] = useState(() => new ɵCopyFeedback$1());
7742
+ const copied = useSyncExternalStore(feedback.subscribe, feedback.getSnapshot, feedback.getSnapshot);
7743
+ useEffect(() => feedback.dispose, [feedback]);
7744
+ return {
7745
+ copied,
7746
+ markCopied: feedback.markCopied
8921
7747
  };
8922
7748
  }
8923
7749
 
@@ -9008,7 +7834,7 @@ function nextFocusable(element, skip) {
9008
7834
  * control after the thumb, and Enter or Escape inside it returns to the thumb.
9009
7835
  */
9010
7836
  function FeedbackCommentPopover({ feedbackComment, comment, savedComment, rating, anchor, messageId }) {
9011
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
7837
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
9012
7838
  const contentRef = useRef(null);
9013
7839
  const focusInside = () => contentRef.current?.contains(document.activeElement) ?? false;
9014
7840
  const { focusRequest, takeFocusRequest, inputRef } = comment;
@@ -9080,7 +7906,7 @@ function FeedbackCommentPopover({ feedbackComment, comment, savedComment, rating
9080
7906
  function CopilotChatAssistantMessage({ message, messages, isRunning, isLatest, onThumbsUp, onThumbsDown, onReadAloud, onRegenerate, additionalToolbarItems, toolbarVisible = true, markdownRenderer, toolbar, copyButton, inspectorButton, thumbsUpButton, thumbsDownButton, readAloudButton, regenerateButton, feedbackComment: feedbackCommentSlot, toolCallsView, children, className, ...props }) {
9081
7907
  const providerRenderer = useShallowStableRef(useMarkdownRenderer());
9082
7908
  const DefaultMarkdownRenderer = useMemo(() => resolveMarkdownRenderer(providerRenderer), [providerRenderer]);
9083
- const hasContent = !!(message.content && message.content.trim().length > 0);
7909
+ const hasContent = ɵhasAssistantMessageText$1(message.content);
9084
7910
  const isLatestAssistantMessage = message.role === "assistant" && (isLatest ?? messages?.[messages.length - 1]?.id === message.id);
9085
7911
  const { isInspectorEnabled, openInspector } = useCopilotKitInspector();
9086
7912
  const shortcutsHidden = useInspectorShortcutsHidden();
@@ -9200,7 +8026,13 @@ function CopilotChatAssistantMessage({ message, messages, isRunning, isLatest, o
9200
8026
  message,
9201
8027
  messages
9202
8028
  });
9203
- const shouldShowToolbar = toolbarVisible && (hasContent || showInspectorShortcut) && !(isRunning && isLatestAssistantMessage);
8029
+ const shouldShowToolbar = ɵshouldShowAssistantToolbar$1({
8030
+ toolbarVisible,
8031
+ hasContent,
8032
+ showInspectorShortcut,
8033
+ isRunning: !!isRunning,
8034
+ isLatest: isLatestAssistantMessage
8035
+ });
9204
8036
  const { open: commentOpen, close: closeComment } = comment;
9205
8037
  useEffect(() => {
9206
8038
  if (!commentOpen) return;
@@ -9312,62 +8144,58 @@ function CopilotChatAssistantMessage({ message, messages, isRunning, isLatest, o
9312
8144
  });
9313
8145
  };
9314
8146
  _CopilotChatAssistantMessage.CopyButton = ({ className, title, onClick, ...props }) => {
9315
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
9316
- const [copied, setCopied] = useState(false);
9317
- const timerRef = useRef(null);
9318
- useEffect(() => {
9319
- return () => {
9320
- if (timerRef.current !== null) clearTimeout(timerRef.current);
9321
- };
9322
- }, []);
8147
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
8148
+ const { copied, markCopied } = useCopyFeedback();
9323
8149
  const handleClick = async (event) => {
9324
- let success = false;
9325
- if (onClick) success = await Promise.resolve(onClick(event)) === true;
9326
- if (success) {
9327
- setCopied(true);
9328
- if (timerRef.current !== null) clearTimeout(timerRef.current);
9329
- timerRef.current = setTimeout(() => {
9330
- timerRef.current = null;
9331
- setCopied(false);
9332
- }, 2e3);
9333
- }
8150
+ if (!onClick) return;
8151
+ if (await Promise.resolve(onClick(event)) === true) markCopied();
9334
8152
  };
9335
8153
  return /* @__PURE__ */ jsx(ToolbarButton, {
9336
8154
  "data-testid": "copilot-copy-button",
9337
8155
  title: title || labels.assistantMessageToolbarCopyMessageLabel,
9338
- onClick: handleClick,
8156
+ onClick: (event) => {
8157
+ handleClick(event);
8158
+ },
9339
8159
  className,
9340
8160
  ...props,
9341
- children: copied ? /* @__PURE__ */ jsx(Check, { className: "cpk-assistant-message-toolbar-icon" }) : /* @__PURE__ */ jsx(Copy, { className: "cpk-assistant-message-toolbar-icon" })
8161
+ children: copied ? /* @__PURE__ */ jsx(CopilotIcon, {
8162
+ name: "Check",
8163
+ className: "cpk-assistant-message-toolbar-icon"
8164
+ }) : /* @__PURE__ */ jsx(CopilotIcon, {
8165
+ name: "Copy",
8166
+ className: "cpk-assistant-message-toolbar-icon"
8167
+ })
9342
8168
  });
9343
8169
  };
9344
8170
  _CopilotChatAssistantMessage.InspectorButton = CopilotChatInspectorButton;
9345
8171
  _CopilotChatAssistantMessage.ThumbsUpButton = ({ title, ...props }) => {
9346
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
8172
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
9347
8173
  return /* @__PURE__ */ jsx(ToolbarButton, {
9348
8174
  "data-testid": "copilot-thumbs-up-button",
9349
8175
  title: title || labels.assistantMessageToolbarThumbsUpLabel,
9350
8176
  ...props,
9351
- children: /* @__PURE__ */ jsx(ThumbsUp, {
8177
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
8178
+ name: "ThumbsUp",
9352
8179
  className: "cpk-assistant-message-toolbar-icon",
9353
8180
  fill: props["aria-pressed"] === true ? "currentColor" : "none"
9354
8181
  })
9355
8182
  });
9356
8183
  };
9357
8184
  _CopilotChatAssistantMessage.ThumbsDownButton = ({ title, ...props }) => {
9358
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
8185
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
9359
8186
  return /* @__PURE__ */ jsx(ToolbarButton, {
9360
8187
  "data-testid": "copilot-thumbs-down-button",
9361
8188
  title: title || labels.assistantMessageToolbarThumbsDownLabel,
9362
8189
  ...props,
9363
- children: /* @__PURE__ */ jsx(ThumbsDown, {
8190
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
8191
+ name: "ThumbsDown",
9364
8192
  className: "cpk-assistant-message-toolbar-icon",
9365
8193
  fill: props["aria-pressed"] === true ? "currentColor" : "none"
9366
8194
  })
9367
8195
  });
9368
8196
  };
9369
8197
  _CopilotChatAssistantMessage.FeedbackComment = ({ value, savedComment, inputRef, onChange, onSubmit, onEditingChange, onLeave, className }) => {
9370
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
8198
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
9371
8199
  const changed = value.trim() !== savedComment;
9372
8200
  return /* @__PURE__ */ jsxs("form", {
9373
8201
  "data-testid": "copilot-feedback-comment",
@@ -9387,7 +8215,7 @@ function CopilotChatAssistantMessage({ message, messages, isRunning, isLatest, o
9387
8215
  children: [/* @__PURE__ */ jsx("input", {
9388
8216
  ref: inputRef,
9389
8217
  value,
9390
- maxLength: MESSAGE_FEEDBACK_MAX_COMMENT_LENGTH,
8218
+ maxLength: ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH$1,
9391
8219
  onChange: (event) => onChange(event.target.value),
9392
8220
  placeholder: labels.assistantMessageFeedbackCommentPlaceholder,
9393
8221
  "aria-label": labels.assistantMessageFeedbackCommentPlaceholder,
@@ -9397,26 +8225,35 @@ function CopilotChatAssistantMessage({ message, messages, isRunning, isLatest, o
9397
8225
  variant: "assistantMessageToolbarButton",
9398
8226
  "aria-label": labels.assistantMessageFeedbackCommentSubmitLabel,
9399
8227
  title: labels.assistantMessageFeedbackCommentSubmitLabel,
9400
- children: /* @__PURE__ */ jsx(ArrowUp, { className: "cpk-assistant-message-feedback-comment-submit-icon" })
8228
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
8229
+ name: "ArrowUp",
8230
+ className: "cpk-assistant-message-feedback-comment-submit-icon"
8231
+ })
9401
8232
  })]
9402
8233
  });
9403
8234
  };
9404
8235
  _CopilotChatAssistantMessage.ReadAloudButton = ({ title, ...props }) => {
9405
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
8236
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
9406
8237
  return /* @__PURE__ */ jsx(ToolbarButton, {
9407
8238
  "data-testid": "copilot-read-aloud-button",
9408
8239
  title: title || labels.assistantMessageToolbarReadAloudLabel,
9409
8240
  ...props,
9410
- children: /* @__PURE__ */ jsx(Volume2, { className: "cpk-assistant-message-read-aloud-icon" })
8241
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
8242
+ name: "Volume2",
8243
+ className: "cpk-assistant-message-read-aloud-icon"
8244
+ })
9411
8245
  });
9412
8246
  };
9413
8247
  _CopilotChatAssistantMessage.RegenerateButton = ({ title, ...props }) => {
9414
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
8248
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
9415
8249
  return /* @__PURE__ */ jsx(ToolbarButton, {
9416
8250
  "data-testid": "copilot-regenerate-button",
9417
8251
  title: title || labels.assistantMessageToolbarRegenerateLabel,
9418
8252
  ...props,
9419
- children: /* @__PURE__ */ jsx(RefreshCw, { className: "cpk-assistant-message-toolbar-icon" })
8253
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
8254
+ name: "RefreshCw",
8255
+ className: "cpk-assistant-message-toolbar-icon"
8256
+ })
9420
8257
  });
9421
8258
  };
9422
8259
  })(CopilotChatAssistantMessage || (CopilotChatAssistantMessage = {}));
@@ -9439,7 +8276,7 @@ var CopilotChatAssistantMessage_default = CopilotChatAssistantMessage;
9439
8276
  * `labels.attachmentPreviewCloseButtonLabel`.
9440
8277
  */
9441
8278
  function Lightbox({ onClose, children }) {
9442
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
8279
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
9443
8280
  useEffect(() => {
9444
8281
  const handleKey = (e) => {
9445
8282
  if (e.key === "Escape") onClose();
@@ -9455,7 +8292,10 @@ function Lightbox({ onClose, children }) {
9455
8292
  onClick: onClose,
9456
8293
  className: "cpk-attachment-lightbox-close-button",
9457
8294
  "aria-label": labels.attachmentPreviewCloseButtonLabel,
9458
- children: /* @__PURE__ */ jsx(X, { className: "cpk-attachment-lightbox-close-icon" })
8295
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
8296
+ name: "X",
8297
+ className: "cpk-attachment-lightbox-close-icon"
8298
+ })
9459
8299
  }), /* @__PURE__ */ jsx("div", {
9460
8300
  onClick: (e) => e.stopPropagation(),
9461
8301
  children
@@ -9509,17 +8349,22 @@ function useLightbox() {
9509
8349
 
9510
8350
  //#endregion
9511
8351
  //#region src/components/chat/CopilotChatAttachmentRenderer.tsx
8352
+ /** The chat labels from the nearest chat configuration, or the defaults. */
8353
+ function useLabels() {
8354
+ return useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
8355
+ }
9512
8356
  const ImageAttachment = memo(function ImageAttachment({ src, className }) {
8357
+ const labels = useLabels();
9513
8358
  const [error, setError] = useState(false);
9514
8359
  const { thumbnailRef, vtName, open, openLightbox, closeLightbox } = useLightbox();
9515
8360
  if (error) return /* @__PURE__ */ jsx("div", {
9516
8361
  className: cn("cpk-attachment-renderer cpk-attachment-renderer-image-error", className),
9517
- children: /* @__PURE__ */ jsx("span", { children: "Failed to load image" })
8362
+ children: /* @__PURE__ */ jsx("span", { children: labels.attachmentImageLoadErrorText })
9518
8363
  });
9519
8364
  return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("img", {
9520
8365
  ref: thumbnailRef,
9521
8366
  src,
9522
- alt: "Image attachment",
8367
+ alt: labels.attachmentImageAltText,
9523
8368
  className: cn("cpk-attachment-renderer cpk-attachment-renderer-image", className),
9524
8369
  onClick: openLightbox,
9525
8370
  onError: () => setError(true)
@@ -9528,7 +8373,7 @@ const ImageAttachment = memo(function ImageAttachment({ src, className }) {
9528
8373
  children: /* @__PURE__ */ jsx("img", {
9529
8374
  style: { viewTransitionName: vtName },
9530
8375
  src,
9531
- alt: "Image attachment",
8376
+ alt: labels.attachmentImageAltText,
9532
8377
  className: "cpk-attachment-renderer-lightbox-image"
9533
8378
  })
9534
8379
  })] });
@@ -9556,7 +8401,8 @@ const VideoAttachment = memo(function VideoAttachment({ src, className }) {
9556
8401
  });
9557
8402
  });
9558
8403
  const DocumentAttachment = memo(function DocumentAttachment({ src, source, filename, className }) {
9559
- const label = filename || source.mimeType || "Document attachment";
8404
+ const labels = useLabels();
8405
+ const label = filename || source.mimeType || labels.attachmentDocumentAltText;
9560
8406
  return /* @__PURE__ */ jsxs("a", {
9561
8407
  href: src,
9562
8408
  download: filename ?? "",
@@ -9569,7 +8415,7 @@ const DocumentAttachment = memo(function DocumentAttachment({ src, source, filen
9569
8415
  children: getDocumentIcon(source.mimeType ?? "")
9570
8416
  }), /* @__PURE__ */ jsx("span", {
9571
8417
  className: "cpk-attachment-renderer-document-name",
9572
- children: filename || source.mimeType || "Unknown type"
8418
+ children: filename || source.mimeType || labels.attachmentUnknownTypeText
9573
8419
  })]
9574
8420
  });
9575
8421
  });
@@ -9600,25 +8446,9 @@ const CopilotChatAttachmentRenderer = ({ type, source, filename, className }) =>
9600
8446
 
9601
8447
  //#endregion
9602
8448
  //#region src/components/chat/CopilotChatUserMessage.tsx
9603
- function flattenUserMessageContent(content) {
9604
- if (!content) return "";
9605
- if (typeof content === "string") return content;
9606
- return content.map((part) => {
9607
- if (part && typeof part === "object" && "type" in part && part.type === "text" && typeof part.text === "string") return part.text;
9608
- return "";
9609
- }).filter((text) => text.length > 0).join("\n");
9610
- }
9611
- function getMediaParts(content) {
9612
- if (!content || typeof content === "string") return [];
9613
- return content.filter((part) => part.type === "image" || part.type === "audio" || part.type === "video" || part.type === "document");
9614
- }
9615
- function getFilename(part) {
9616
- const meta = part.metadata;
9617
- if (meta != null && typeof meta === "object" && "filename" in meta && typeof meta.filename === "string") return meta.filename;
9618
- }
9619
8449
  function CopilotChatUserMessage({ message, onEditMessage, branchIndex, numberOfBranches, onSwitchToBranch, additionalToolbarItems, messageRenderer, toolbar, copyButton, editButton, branchNavigation, children, className, ...props }) {
9620
- const flattenedContent = useMemo(() => flattenUserMessageContent(message.content), [message.content]);
9621
- const mediaParts = useMemo(() => getMediaParts(message.content), [message.content]);
8450
+ const flattenedContent = useMemo(() => ɵflattenUserMessageContent$1(message.content), [message.content]);
8451
+ const mediaParts = useMemo(() => ɵgetUserMessageMediaParts$1(message.content), [message.content]);
9622
8452
  const BoundMessageRenderer = renderSlot(messageRenderer, CopilotChatUserMessage.MessageRenderer, { content: flattenedContent });
9623
8453
  const BoundCopyButton = renderSlot(copyButton, CopilotChatUserMessage.CopyButton, { onClick: async () => {
9624
8454
  if (flattenedContent) return await copyToClipboard(flattenedContent);
@@ -9631,7 +8461,11 @@ function CopilotChatUserMessage({ message, onEditMessage, branchIndex, numberOfB
9631
8461
  onSwitchToBranch,
9632
8462
  message
9633
8463
  });
9634
- const showBranchNavigation = numberOfBranches && numberOfBranches > 1 && onSwitchToBranch;
8464
+ const { show: showBranchNavigation } = ɵgetBranchNavState$1({
8465
+ branchIndex: branchIndex ?? 0,
8466
+ numberOfBranches: numberOfBranches ?? 1,
8467
+ canSwitch: onSwitchToBranch !== void 0
8468
+ });
9635
8469
  const BoundToolbar = renderSlot(toolbar, CopilotChatUserMessage.Toolbar, { children: /* @__PURE__ */ jsxs("div", {
9636
8470
  className: "cpk-user-message-toolbar-items",
9637
8471
  children: [
@@ -9668,7 +8502,7 @@ function CopilotChatUserMessage({ message, onEditMessage, branchIndex, numberOfB
9668
8502
  children: mediaParts.map((part, index) => /* @__PURE__ */ jsx(CopilotChatAttachmentRenderer, {
9669
8503
  type: part.type,
9670
8504
  source: part.source,
9671
- filename: getFilename(part)
8505
+ filename: ɵgetUserMessageMediaFilename$1(part)
9672
8506
  }, index))
9673
8507
  }),
9674
8508
  BoundMessageRenderer,
@@ -9708,40 +8542,50 @@ function CopilotChatUserMessage({ message, onEditMessage, branchIndex, numberOfB
9708
8542
  })] });
9709
8543
  };
9710
8544
  _CopilotChatUserMessage.CopyButton = ({ className, title, onClick, ...props }) => {
9711
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
9712
- const [copied, setCopied] = useState(false);
8545
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
8546
+ const { copied, markCopied } = useCopyFeedback();
9713
8547
  const handleClick = async (event) => {
9714
- let success = false;
9715
- if (onClick) success = await Promise.resolve(onClick(event)) === true;
9716
- if (success) {
9717
- setCopied(true);
9718
- setTimeout(() => setCopied(false), 2e3);
9719
- }
8548
+ if (!onClick) return;
8549
+ if (await Promise.resolve(onClick(event)) === true) markCopied();
9720
8550
  };
9721
8551
  return /* @__PURE__ */ jsx(ToolbarButton, {
9722
8552
  "data-testid": "copilot-user-copy-button",
9723
8553
  title: title || labels.userMessageToolbarCopyMessageLabel,
9724
- onClick: handleClick,
8554
+ onClick: (event) => {
8555
+ handleClick(event);
8556
+ },
9725
8557
  className,
9726
8558
  ...props,
9727
- children: copied ? /* @__PURE__ */ jsx(Check, { className: "cpk-user-message-toolbar-icon" }) : /* @__PURE__ */ jsx(Copy, { className: "cpk-user-message-toolbar-icon" })
8559
+ children: copied ? /* @__PURE__ */ jsx(CopilotIcon, {
8560
+ name: "Check",
8561
+ className: "cpk-user-message-toolbar-icon"
8562
+ }) : /* @__PURE__ */ jsx(CopilotIcon, {
8563
+ name: "Copy",
8564
+ className: "cpk-user-message-toolbar-icon"
8565
+ })
9728
8566
  });
9729
8567
  };
9730
8568
  _CopilotChatUserMessage.EditButton = ({ className, title, ...props }) => {
9731
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
8569
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
9732
8570
  return /* @__PURE__ */ jsx(ToolbarButton, {
9733
8571
  "data-testid": "copilot-edit-button",
9734
8572
  title: title || labels.userMessageToolbarEditMessageLabel,
9735
8573
  className,
9736
8574
  ...props,
9737
- children: /* @__PURE__ */ jsx(Edit, { className: "cpk-user-message-toolbar-icon" })
8575
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
8576
+ name: "Edit",
8577
+ className: "cpk-user-message-toolbar-icon"
8578
+ })
9738
8579
  });
9739
8580
  };
9740
8581
  _CopilotChatUserMessage.BranchNavigation = ({ className, currentBranch = 0, numberOfBranches = 1, onSwitchToBranch, message, ...props }) => {
9741
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
9742
- if (!numberOfBranches || numberOfBranches <= 1 || !onSwitchToBranch) return null;
9743
- const canGoPrev = currentBranch > 0;
9744
- const canGoNext = currentBranch < numberOfBranches - 1;
8582
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
8583
+ const { show, canGoPrev, canGoNext } = ɵgetBranchNavState$1({
8584
+ branchIndex: currentBranch,
8585
+ numberOfBranches,
8586
+ canSwitch: onSwitchToBranch !== void 0
8587
+ });
8588
+ if (!show) return null;
9745
8589
  return /* @__PURE__ */ jsxs("div", {
9746
8590
  "data-testid": "copilot-branch-navigation",
9747
8591
  className: cn("cpk-user-message-branch-navigation", className),
@@ -9758,7 +8602,10 @@ function CopilotChatUserMessage({ message, onEditMessage, branchIndex, numberOfB
9758
8602
  disabled: !canGoPrev,
9759
8603
  className: "cpk-user-message-branch-button",
9760
8604
  "aria-label": labels.userMessageToolbarPreviousBranchLabel,
9761
- children: /* @__PURE__ */ jsx(ChevronLeft, { className: "cpk-user-message-branch-icon" })
8605
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
8606
+ name: "ChevronLeft",
8607
+ className: "cpk-user-message-branch-icon"
8608
+ })
9762
8609
  }),
9763
8610
  /* @__PURE__ */ jsxs("span", {
9764
8611
  className: "cpk-user-message-branch-counter",
@@ -9779,7 +8626,10 @@ function CopilotChatUserMessage({ message, onEditMessage, branchIndex, numberOfB
9779
8626
  disabled: !canGoNext,
9780
8627
  className: "cpk-user-message-branch-button",
9781
8628
  "aria-label": labels.userMessageToolbarNextBranchLabel,
9782
- children: /* @__PURE__ */ jsx(ChevronRight, { className: "cpk-user-message-branch-icon" })
8629
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
8630
+ name: "ChevronRight",
8631
+ className: "cpk-user-message-branch-icon"
8632
+ })
9783
8633
  })
9784
8634
  ]
9785
8635
  });
@@ -9797,24 +8647,14 @@ var CopilotChatUserMessage_default = CopilotChatUserMessage;
9797
8647
  //#endregion
9798
8648
  //#region src/components/chat/CopilotChatReasoningMessage.tsx
9799
8649
  /**
9800
- * Formats an elapsed duration (in seconds) to a human-readable string.
9801
- */
9802
- function formatDuration$1(seconds) {
9803
- if (seconds < 1) return "a few seconds";
9804
- if (seconds < 60) return `${Math.round(seconds)} seconds`;
9805
- const mins = Math.floor(seconds / 60);
9806
- const secs = Math.round(seconds % 60);
9807
- if (secs === 0) return `${mins} minute${mins > 1 ? "s" : ""}`;
9808
- return `${mins}m ${secs}s`;
9809
- }
9810
- /**
9811
8650
  * A reasoning message as a collapsible block. While the model reasons it is
9812
8651
  * open and the header shows `labels.reasoningMessageThinkingLabel`; when
9813
- * streaming ends it collapses and the header reads "Thought for …". The
8652
+ * streaming ends it collapses and the header reads
8653
+ * `labels.reasoningMessageThoughtForLabel` ("Thought for 4 seconds"). The
9814
8654
  * `header` slot also receives `elapsedSeconds`.
9815
8655
  */
9816
8656
  function CopilotChatReasoningMessage({ message, messages, isRunning, isLatest: isLatestProp, header, contentView, toggle, children, className, ...props }) {
9817
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
8657
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
9818
8658
  const isLatest = isLatestProp ?? messages?.[messages.length - 1]?.id === message.id;
9819
8659
  const isStreaming = !!(isRunning && isLatest);
9820
8660
  const hasContent = !!(message.content && message.content.length > 0);
@@ -9844,7 +8684,7 @@ function CopilotChatReasoningMessage({ message, messages, isRunning, isLatest: i
9844
8684
  userToggledRef.current = true;
9845
8685
  setIsOpen((prev) => !prev);
9846
8686
  } : void 0;
9847
- const label = isStreaming ? labels.reasoningMessageThinkingLabel : `Thought for ${formatDuration$1(elapsed)}`;
8687
+ const label = isStreaming ? labels.reasoningMessageThinkingLabel : ɵformatLabel$1(labels.reasoningMessageThoughtForLabel, { duration: ɵformatReasoningDurationLabel$1(elapsed, labels) });
9848
8688
  const boundHeader = renderSlot(header, CopilotChatReasoningMessage.Header, {
9849
8689
  isOpen,
9850
8690
  label,
@@ -9899,7 +8739,10 @@ function CopilotChatReasoningMessage({ message, messages, isRunning, isLatest: i
9899
8739
  children: /* @__PURE__ */ jsx("span", { className: "cpk-reasoning-message-indicator-dot" })
9900
8740
  }),
9901
8741
  headerChildren,
9902
- isExpandable && /* @__PURE__ */ jsx(ChevronRight, { className: cn("cpk-reasoning-message-chevron", isOpen && "cpk-reasoning-message-chevron-open") })
8742
+ isExpandable && /* @__PURE__ */ jsx(CopilotIcon, {
8743
+ name: "ChevronRight",
8744
+ className: cn("cpk-reasoning-message-chevron", isOpen && "cpk-reasoning-message-chevron-open")
8745
+ })
9903
8746
  ]
9904
8747
  });
9905
8748
  };
@@ -9953,7 +8796,8 @@ const CopilotChatSuggestionPill = React.forwardRef(function CopilotChatSuggestio
9953
8796
  ...props,
9954
8797
  children: [isLoading ? /* @__PURE__ */ jsx("span", {
9955
8798
  className: "cpk-suggestion-pill-icon",
9956
- children: /* @__PURE__ */ jsx(Loader2, {
8799
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
8800
+ name: "Loader2",
9957
8801
  className: "cpk-suggestion-pill-spinner",
9958
8802
  "aria-hidden": "true"
9959
8803
  })
@@ -10070,14 +8914,6 @@ const ScrollPinnedContext = React.createContext(false);
10070
8914
 
10071
8915
  //#endregion
10072
8916
  //#region src/components/chat/CopilotChatWorkSummary.tsx
10073
- /** "45s", "1m 5s", "2m". Used for the live timer and the final duration. */
10074
- function formatDuration(ms) {
10075
- const seconds = Math.max(0, Math.floor(ms / 1e3));
10076
- if (seconds < 60) return `${seconds}s`;
10077
- const minutes = Math.floor(seconds / 60);
10078
- const rest = seconds % 60;
10079
- return rest ? `${minutes}m ${rest}s` : `${minutes}m`;
10080
- }
10081
8917
  /** Re-renders every second while `active`, returning the current time. */
10082
8918
  function useNow(active) {
10083
8919
  const [now, setNow] = useState(() => Date.now());
@@ -10091,14 +8927,20 @@ function useNow(active) {
10091
8927
  }
10092
8928
  /**
10093
8929
  * The line at the top of a reply in the `"turn"` tool-call display. While the
10094
- * agent works it reads "Working 4s"; once the reply is done it reads "Worked
10095
- * for 9s · 7 tools" and toggles the work it folded away.
8930
+ * agent works it reads "Working 4s". Once the reply is done it reads "Worked
8931
+ * for 9s" and "7 tools", and toggles the work it folded away. The text comes
8932
+ * from the `workSummary...` and `toolCall...` chat labels.
10096
8933
  */
10097
8934
  function CopilotChatWorkSummary({ isWorking, isOpen, calls, elapsedMs, workingSince, className, ...props }) {
10098
- const now = useNow(isWorking);
10099
- const failed = calls.filter((call) => call.toolMessage?.error).length;
10100
- const liveMs = elapsedMs !== void 0 && workingSince !== void 0 ? elapsedMs + Math.max(0, now - workingSince) : void 0;
10101
- const duration = elapsedMs !== void 0 ? formatDuration(Math.max(1e3, elapsedMs)) : void 0;
8935
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
8936
+ const text = ɵgetWorkSummaryText$1({
8937
+ isWorking,
8938
+ calls,
8939
+ elapsedMs,
8940
+ workingSince,
8941
+ now: useNow(isWorking),
8942
+ labels
8943
+ });
10102
8944
  return /* @__PURE__ */ jsxs("button", {
10103
8945
  type: "button",
10104
8946
  "data-copilotkit": true,
@@ -10107,29 +8949,25 @@ function CopilotChatWorkSummary({ isWorking, isOpen, calls, elapsedMs, workingSi
10107
8949
  "aria-expanded": isOpen,
10108
8950
  className: cn("cpk-work-summary", className),
10109
8951
  ...props,
10110
- children: [isWorking ? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("span", {
10111
- className: "cpk-work-summary-label cpk-shimmer",
10112
- children: "Working"
10113
- }), liveMs !== void 0 && /* @__PURE__ */ jsx("span", {
10114
- className: "cpk-work-summary-detail cpk-work-summary-timer",
10115
- children: formatDuration(liveMs)
10116
- })] }) : /* @__PURE__ */ jsxs(Fragment$1, { children: [
8952
+ children: [
10117
8953
  /* @__PURE__ */ jsx("span", {
10118
- className: "cpk-work-summary-label",
10119
- children: duration ? `Worked for ${duration}` : `Used ${pluralize(calls.length, "tool")}`
8954
+ className: cn("cpk-work-summary-label", isWorking && "cpk-shimmer"),
8955
+ children: text.label
10120
8956
  }),
10121
- duration && /* @__PURE__ */ jsx("span", {
10122
- className: "cpk-work-summary-detail",
10123
- children: pluralize(calls.length, "tool")
8957
+ text.detail !== null && /* @__PURE__ */ jsx("span", {
8958
+ className: cn("cpk-work-summary-detail", isWorking && "cpk-work-summary-timer"),
8959
+ children: text.detail
10124
8960
  }),
10125
- failed > 0 && /* @__PURE__ */ jsxs("span", {
8961
+ text.failed !== null && /* @__PURE__ */ jsx("span", {
10126
8962
  className: "cpk-work-summary-failed",
10127
- children: [failed, " failed"]
8963
+ children: text.failed
8964
+ }),
8965
+ /* @__PURE__ */ jsx(CopilotIcon, {
8966
+ name: "ChevronRight",
8967
+ "aria-hidden": "true",
8968
+ className: cn("cpk-work-summary-chevron", isOpen && "cpk-work-summary-chevron-open")
10128
8969
  })
10129
- ] }), /* @__PURE__ */ jsx(ChevronRight, {
10130
- "aria-hidden": "true",
10131
- className: cn("cpk-work-summary-chevron", isOpen && "cpk-work-summary-chevron-open")
10132
- })]
8970
+ ]
10133
8971
  });
10134
8972
  }
10135
8973
 
@@ -10541,68 +9379,6 @@ const MemoizedCustomMessage = React.memo(function MemoizedCustomMessage({ messag
10541
9379
  if (JSON.stringify(prevProps.stateSnapshot) !== JSON.stringify(nextProps.stateSnapshot)) return false;
10542
9380
  return true;
10543
9381
  });
10544
- /**
10545
- * Deduplicates messages by ID. For assistant messages, merges occurrences:
10546
- * recovers non-empty content from any earlier occurrence if the latest wiped it
10547
- * (empty string means the streaming update cleared the field, not blank text),
10548
- * and similarly recovers toolCalls from earlier occurrences if the latest is
10549
- * undefined (an empty array [] is treated as intentional and kept as-is).
10550
- * For all other roles, keeps the last entry.
10551
- *
10552
- * @internal Exported for unit testing only — not part of the public API.
10553
- */
10554
- /**
10555
- * Collapse tool calls that share an id, keeping first-seen order.
10556
- *
10557
- * AG-UI's TOOL_CALL_START handler appends to the parent message's `toolCalls`
10558
- * without checking whether that id is already present. So whenever a start
10559
- * event is applied twice — which the human-in-the-loop flow triggers when the
10560
- * run syncs after `respond()` — the message ends up carrying the same call
10561
- * twice. The second copy has EMPTY `arguments`, because a start event carries
10562
- * none; the args arrive later as TOOL_CALL_ARGS deltas addressed to the first
10563
- * copy.
10564
- *
10565
- * Left alone that renders the same tool call twice: once populated and once
10566
- * blank (an approval card with no transaction id, offering live buttons for an
10567
- * action already taken), and React warns "Encountered two children with the
10568
- * same key" because the call id is the render key.
10569
- *
10570
- * The empty copy is the redundant one, so prefer whichever entry actually
10571
- * carries arguments rather than blindly taking the first.
10572
- */
10573
- function dedupeToolCalls(toolCalls) {
10574
- const byId = /* @__PURE__ */ new Map();
10575
- for (const toolCall of toolCalls) {
10576
- const existing = byId.get(toolCall.id);
10577
- if (!existing) {
10578
- byId.set(toolCall.id, toolCall);
10579
- continue;
10580
- }
10581
- if (!existing.function?.arguments && toolCall.function?.arguments) byId.set(toolCall.id, toolCall);
10582
- }
10583
- return byId.size === toolCalls.length ? toolCalls : [...byId.values()];
10584
- }
10585
- function deduplicateMessages(messages) {
10586
- const acc = /* @__PURE__ */ new Map();
10587
- for (const message of messages) {
10588
- const existing = acc.get(message.id);
10589
- if (existing && message.role === "assistant" && existing.role === "assistant") {
10590
- const content = message.content || existing.content;
10591
- const toolCalls = message.toolCalls ?? existing.toolCalls;
10592
- acc.set(message.id, {
10593
- ...existing,
10594
- ...message,
10595
- content,
10596
- toolCalls: toolCalls ? dedupeToolCalls(toolCalls) : toolCalls
10597
- });
10598
- } else if (message.role === "assistant" && message.toolCalls) acc.set(message.id, {
10599
- ...message,
10600
- toolCalls: dedupeToolCalls(message.toolCalls)
10601
- });
10602
- else acc.set(message.id, message);
10603
- }
10604
- return [...acc.values()];
10605
- }
10606
9382
  /** A row holding a single message, rendered as it would be ungrouped. */
10607
9383
  function messageRow(message) {
10608
9384
  return {
@@ -10651,7 +9427,7 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10651
9427
  if (!resolvedRunId) return void 0;
10652
9428
  return copilotkit.getStateByRun(config.agentId, config.threadId, resolvedRunId);
10653
9429
  };
10654
- const deduplicatedMessages = useMemo(() => deduplicateMessages(messages), [messages]);
9430
+ const deduplicatedMessages = useMemo(() => ɵdeduplicateMessages$1(messages), [messages]);
10655
9431
  const transformedMessages = useMemo(() => transformMessages ? transformMessages(deduplicatedMessages) : deduplicatedMessages, [deduplicatedMessages, transformMessages]);
10656
9432
  const rows = useMemo(() => groupMessages ? groupMessages(transformedMessages) : transformedMessages.map(messageRow), [transformedMessages, groupMessages]);
10657
9433
  const renderedMessages = useMemo(() => groupMessages ? rows.flatMap((row) => row.type === "group" ? row.messages : [row.message]) : transformedMessages, [
@@ -10661,13 +9437,13 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10661
9437
  ]);
10662
9438
  const latestRenderedId = renderedMessages[renderedMessages.length - 1]?.id;
10663
9439
  const rendererNames = useToolCallRendererNames();
10664
- const toolCallLayouts = useMemo(() => toolCallDisplay === "separate" ? /* @__PURE__ */ new Map() : getToolCallLayouts(renderedMessages, messages, rendererNames), [
9440
+ const toolCallLayouts = useMemo(() => toolCallDisplay === "separate" ? /* @__PURE__ */ new Map() : ɵgetToolCallLayouts$1(renderedMessages, messages, rendererNames), [
10665
9441
  toolCallDisplay,
10666
9442
  renderedMessages,
10667
9443
  messages,
10668
9444
  rendererNames
10669
9445
  ]);
10670
- const turnWork = useMemo(() => toolCallDisplay === "turn" ? getTurnWork(renderedMessages, toolCallLayouts) : void 0, [
9446
+ const turnWork = useMemo(() => toolCallDisplay === "turn" ? ɵgetTurnWork$1(renderedMessages, toolCallLayouts) : void 0, [
10671
9447
  toolCallDisplay,
10672
9448
  renderedMessages,
10673
9449
  toolCallLayouts
@@ -10677,46 +9453,25 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10677
9453
  for (const turn of turnWork?.values() ?? []) byFirst.set(turn.firstMessageId, turn);
10678
9454
  return byFirst;
10679
9455
  }, [turnWork]);
10680
- let latestTurnKey = "start";
10681
- for (let i = renderedMessages.length - 1; i >= 0; i--) if (renderedMessages[i].role === "user") {
10682
- latestTurnKey = renderedMessages[i].id;
10683
- break;
10684
- }
10685
- const isWorkingOn = (turnKey) => isRunning && turnKey === latestTurnKey;
9456
+ const latestTurnKey = ɵgetLatestTurnKey$1(renderedMessages);
10686
9457
  const [toggledTurns, setToggledTurns] = useState(() => /* @__PURE__ */ new Map());
10687
- const isWorkOpen = (turnKey) => toggledTurns.get(turnKey) ?? isWorkingOn(turnKey);
9458
+ const turnState = {
9459
+ toggledTurns,
9460
+ isRunning,
9461
+ latestTurnKey
9462
+ };
10688
9463
  const workTimesRef = useRef(/* @__PURE__ */ new Map());
10689
- if (toolCallDisplay === "turn") {
10690
- const now = Date.now();
10691
- const workTimes = workTimesRef.current;
10692
- if (isRunning) {
10693
- const times = workTimes.get(latestTurnKey);
10694
- if (times) times.workingSince ??= now;
10695
- else if (renderedMessages[renderedMessages.length - 1]?.role === "user") workTimes.set(latestTurnKey, {
10696
- elapsedMs: 0,
10697
- workingSince: now
10698
- });
10699
- } else for (const times of workTimes.values()) {
10700
- if (times.workingSince === void 0) continue;
10701
- times.elapsedMs += now - times.workingSince;
10702
- times.workingSince = void 0;
10703
- }
10704
- }
10705
- const { workOpen, workTextOpen } = useMemo(() => {
10706
- const open = /* @__PURE__ */ new Map();
10707
- const textOpen = /* @__PURE__ */ new Map();
10708
- for (const turn of turnWork?.values() ?? []) {
10709
- const turnOpen = toggledTurns.get(turn.key) ?? (isRunning && turn.key === latestTurnKey);
10710
- for (const id of turn.workMessageIds) {
10711
- open.set(id, turnOpen);
10712
- if (id !== turn.replyTextMessageId) textOpen.set(id, turnOpen);
10713
- }
10714
- }
10715
- return {
10716
- workOpen: open,
10717
- workTextOpen: textOpen
10718
- };
10719
- }, [
9464
+ if (toolCallDisplay === "turn") ɵrecordWorkTime$1(workTimesRef.current, {
9465
+ isRunning,
9466
+ latestTurnKey,
9467
+ lastMessageRole: renderedMessages[renderedMessages.length - 1]?.role,
9468
+ now: Date.now()
9469
+ });
9470
+ const { workOpen, workTextOpen } = useMemo(() => ɵgetWorkOpenState$1(turnWork?.values() ?? [], {
9471
+ toggledTurns,
9472
+ isRunning,
9473
+ latestTurnKey
9474
+ }), [
10720
9475
  turnWork,
10721
9476
  toggledTurns,
10722
9477
  isRunning,
@@ -10736,8 +9491,8 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10736
9491
  workTextOpen
10737
9492
  ]);
10738
9493
  const renderWorkSummary = (turnKey, calls) => {
10739
- const working = isWorkingOn(turnKey);
10740
- const open = isWorkOpen(turnKey);
9494
+ const working = ɵisTurnWorking$1(turnKey, turnState);
9495
+ const open = ɵisTurnWorkOpen$1(turnKey, turnState);
10741
9496
  const times = workTimesRef.current.get(turnKey);
10742
9497
  return /* @__PURE__ */ jsx(Collapsible, {
10743
9498
  open: working || calls.length > 0,
@@ -10876,10 +9631,13 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10876
9631
  total: 0,
10877
9632
  sizes: /* @__PURE__ */ new Map()
10878
9633
  });
9634
+ const resizeAnchorRef = React.useRef(null);
9635
+ const restoringVisibilityRef = React.useRef(false);
10879
9636
  const firstMessageId = deduplicatedMessages[0]?.id;
10880
9637
  const measuredThreadRef = React.useRef(firstMessageId);
10881
9638
  if (measuredThreadRef.current !== firstMessageId) {
10882
9639
  measuredThreadRef.current = firstMessageId;
9640
+ resizeAnchorRef.current = null;
10883
9641
  measuredRef.current = {
10884
9642
  total: 0,
10885
9643
  sizes: /* @__PURE__ */ new Map()
@@ -10889,7 +9647,28 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10889
9647
  const { total, sizes } = measuredRef.current;
10890
9648
  return sizes.size > 0 ? Math.max(1, Math.round(total / sizes.size)) : 100;
10891
9649
  }, []);
10892
- const measureRowElement = React.useCallback((el) => {
9650
+ const isPinnedToBottomRef = React.useRef(isPinnedToBottom);
9651
+ const measuredWidthRef = React.useRef(null);
9652
+ const captureResizeAnchor = React.useCallback((instance) => {
9653
+ const width = instance.scrollElement?.clientWidth;
9654
+ if (!width || instance.scrollElement?.clientHeight === 0 || restoringVisibilityRef.current || isPinnedToBottomRef.current || instance.options.count === 0 || measuredWidthRef.current === null || width === measuredWidthRef.current) return;
9655
+ if (resizeAnchorRef.current) {
9656
+ if (resizeAnchorRef.current.ready) resizeAnchorRef.current = {
9657
+ ...resizeAnchorRef.current,
9658
+ ready: false
9659
+ };
9660
+ return;
9661
+ }
9662
+ const offset = instance.scrollElement?.scrollTop ?? 0;
9663
+ const anchor = instance.getVirtualItemForOffset(offset);
9664
+ if (anchor) resizeAnchorRef.current = {
9665
+ index: anchor.index,
9666
+ offset: offset - anchor.start,
9667
+ ready: false
9668
+ };
9669
+ }, []);
9670
+ const measureRowElement = React.useCallback((el, _entry, instance) => {
9671
+ captureResizeAnchor(instance);
10893
9672
  const height = el?.getBoundingClientRect().height ?? 0;
10894
9673
  const index = Number(el?.dataset?.index);
10895
9674
  if (height > 0 && Number.isInteger(index)) {
@@ -10898,16 +9677,70 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10898
9677
  sizes.set(index, height);
10899
9678
  }
10900
9679
  return height > 0 ? height : measuredRef.current.sizes.get(index) ?? 100;
10901
- }, []);
10902
- const isPinnedToBottomRef = React.useRef(isPinnedToBottom);
9680
+ }, [captureResizeAnchor]);
10903
9681
  const shouldAdjustScrollOnResize = React.useCallback((item, _delta, instance) => {
10904
- if (isPinnedToBottomRef.current) return false;
9682
+ if (isPinnedToBottomRef.current || resizeAnchorRef.current || restoringVisibilityRef.current) return false;
10905
9683
  const scrollAdjustments = instance.scrollAdjustments ?? 0;
10906
9684
  return item.start < (instance.scrollOffset ?? 0) + scrollAdjustments;
10907
9685
  }, []);
9686
+ const observeScrollRect = React.useCallback((instance, notify) => {
9687
+ let frame;
9688
+ let pendingRect;
9689
+ const disconnect = observeElementRect(instance, (rect) => {
9690
+ if (instance.scrollElement?.clientHeight === 0) {
9691
+ restoringVisibilityRef.current = true;
9692
+ resizeAnchorRef.current = null;
9693
+ if (frame !== void 0) cancelAnimationFrame(frame);
9694
+ frame = void 0;
9695
+ pendingRect = void 0;
9696
+ notify(rect);
9697
+ return;
9698
+ }
9699
+ const width = instance.scrollElement?.clientWidth ?? rect.width;
9700
+ const previousWidth = measuredWidthRef.current;
9701
+ if (width > 0 && width !== previousWidth) {
9702
+ captureResizeAnchor(instance);
9703
+ if (previousWidth !== null) {
9704
+ pendingRect = rect;
9705
+ if (frame === void 0) frame = requestAnimationFrame(() => {
9706
+ frame = void 0;
9707
+ const nextRect = pendingRect;
9708
+ pendingRect = void 0;
9709
+ if (!instance.scrollElement?.clientHeight) return;
9710
+ measuredWidthRef.current = instance.scrollElement?.clientWidth ?? nextRect.width;
9711
+ if (resizeAnchorRef.current) resizeAnchorRef.current.ready = true;
9712
+ instance.getTotalSize();
9713
+ measuredRef.current = {
9714
+ total: 0,
9715
+ sizes: /* @__PURE__ */ new Map()
9716
+ };
9717
+ instance.elementsCache.forEach((element) => {
9718
+ measureRowElement(element, void 0, instance);
9719
+ });
9720
+ instance.measure();
9721
+ instance.getTotalSize();
9722
+ instance.elementsCache.forEach((element) => {
9723
+ instance.measureElement(element);
9724
+ });
9725
+ notify(nextRect);
9726
+ });
9727
+ return;
9728
+ }
9729
+ measuredWidthRef.current = width;
9730
+ }
9731
+ if (pendingRect) pendingRect = rect;
9732
+ else notify(rect);
9733
+ });
9734
+ return () => {
9735
+ disconnect?.();
9736
+ if (frame !== void 0) cancelAnimationFrame(frame);
9737
+ resizeAnchorRef.current = null;
9738
+ };
9739
+ }, [captureResizeAnchor, measureRowElement]);
10908
9740
  const virtualizer = useVirtualizer({
10909
9741
  count: shouldVirtualize ? rows.length : 0,
10910
9742
  getScrollElement: () => shouldVirtualize ? scrollElement : null,
9743
+ observeElementRect: observeScrollRect,
10911
9744
  estimateSize: estimateRowSize,
10912
9745
  overscan: 5,
10913
9746
  measureElement: measureRowElement,
@@ -10918,6 +9751,19 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
10918
9751
  });
10919
9752
  isPinnedToBottomRef.current = isPinnedToBottom;
10920
9753
  virtualizer.shouldAdjustScrollPositionOnItemSizeChange = shouldAdjustScrollOnResize;
9754
+ useLayoutEffect(() => {
9755
+ const anchor = resizeAnchorRef.current;
9756
+ if (!anchor?.ready || restoringVisibilityRef.current) return;
9757
+ const position = virtualizer.getOffsetForIndex(anchor.index, "start");
9758
+ if (position && !isPinnedToBottomRef.current) {
9759
+ const target = position[0] + anchor.offset;
9760
+ if (Math.abs((scrollElement?.scrollTop ?? 0) - target) > .5) virtualizer.scrollToOffset(target);
9761
+ }
9762
+ const frame = requestAnimationFrame(() => {
9763
+ if (resizeAnchorRef.current === anchor) resizeAnchorRef.current = null;
9764
+ });
9765
+ return () => cancelAnimationFrame(frame);
9766
+ });
10921
9767
  const lastEndAlignedFirstMessageRef = React.useRef(void 0);
10922
9768
  useLayoutEffect(() => {
10923
9769
  if (!shouldVirtualize || !rows.length) return;
@@ -11026,22 +9872,33 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
11026
9872
  const observer = new ResizeObserver(() => {
11027
9873
  if (element.clientHeight === 0) {
11028
9874
  suspended = true;
9875
+ restoringVisibilityRef.current = true;
9876
+ resizeAnchorRef.current = null;
11029
9877
  cancelAnimationFrame(frame);
11030
9878
  return;
11031
9879
  }
11032
9880
  if (!suspended || !anchor) {
11033
9881
  suspended = false;
9882
+ restoringVisibilityRef.current = false;
11034
9883
  remember();
11035
9884
  return;
11036
9885
  }
9886
+ cancelAnimationFrame(frame);
11037
9887
  let attempts = 0;
11038
9888
  let stableFrames = 0;
11039
9889
  const restore = () => {
11040
9890
  if (!anchor || element.clientHeight === 0) return;
9891
+ if (isPinnedToBottomRef.current) {
9892
+ anchor = null;
9893
+ suspended = false;
9894
+ restoringVisibilityRef.current = false;
9895
+ return;
9896
+ }
11041
9897
  const index = rowKeysRef.current.indexOf(anchor.key);
11042
9898
  if (index < 0) {
11043
9899
  anchor = null;
11044
9900
  suspended = false;
9901
+ restoringVisibilityRef.current = false;
11045
9902
  return;
11046
9903
  }
11047
9904
  const row = visibleRows().find((row) => row.dataset.scrollAnchor === anchor.key);
@@ -11057,6 +9914,7 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
11057
9914
  if (++attempts < 60 && stableFrames < 3) frame = requestAnimationFrame(restore);
11058
9915
  else {
11059
9916
  suspended = false;
9917
+ restoringVisibilityRef.current = false;
11060
9918
  remember();
11061
9919
  }
11062
9920
  };
@@ -11066,6 +9924,8 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
11066
9924
  cancelAnimationFrame(frame);
11067
9925
  anchor = null;
11068
9926
  suspended = false;
9927
+ restoringVisibilityRef.current = false;
9928
+ resizeAnchorRef.current = null;
11069
9929
  };
11070
9930
  element.addEventListener("scroll", remember, { passive: true });
11071
9931
  element.addEventListener("wheel", interrupt, { passive: true });
@@ -11076,6 +9936,7 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
11076
9936
  return () => {
11077
9937
  cancelAnimationFrame(frame);
11078
9938
  observer.disconnect();
9939
+ restoringVisibilityRef.current = false;
11079
9940
  element.removeEventListener("scroll", remember);
11080
9941
  element.removeEventListener("wheel", interrupt);
11081
9942
  element.removeEventListener("touchstart", interrupt);
@@ -11119,7 +9980,8 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
11119
9980
  shouldVirtualize ? /* @__PURE__ */ jsx("div", {
11120
9981
  style: {
11121
9982
  height: virtualizer.getTotalSize(),
11122
- position: "relative"
9983
+ position: "relative",
9984
+ overflowAnchor: "none"
11123
9985
  },
11124
9986
  children: virtualizer.getVirtualItems().map((virtualItem) => {
11125
9987
  const row = rows[virtualItem.index];
@@ -11164,7 +10026,7 @@ CopilotChatMessageView.Cursor = function Cursor({ className, ...props }) {
11164
10026
  * button named by `labels.attachmentRemoveButtonLabel`.
11165
10027
  */
11166
10028
  const CopilotChatAttachmentQueue = ({ attachments, onRemoveAttachment, className }) => {
11167
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
10029
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
11168
10030
  if (attachments.length === 0) return null;
11169
10031
  return /* @__PURE__ */ jsx("div", {
11170
10032
  "data-testid": "copilot-attachment-queue",
@@ -11240,7 +10102,7 @@ function AudioPreview({ attachment }) {
11240
10102
  * lightbox.
11241
10103
  */
11242
10104
  function VideoPreview({ attachment }) {
11243
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
10105
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
11244
10106
  const src = getSourceUrl(attachment.source);
11245
10107
  const { thumbnailRef, vtName, open, openLightbox, closeLightbox } = useLightbox();
11246
10108
  return /* @__PURE__ */ jsxs(Fragment$1, { children: [
@@ -11264,7 +10126,10 @@ function VideoPreview({ attachment }) {
11264
10126
  "aria-label": labels.attachmentPlayVideoButtonLabel,
11265
10127
  children: /* @__PURE__ */ jsx("div", {
11266
10128
  className: "cpk-attachment-queue-video-play-badge",
11267
- children: /* @__PURE__ */ jsx(Play, { className: "cpk-attachment-queue-video-play-icon" })
10129
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
10130
+ name: "Play",
10131
+ className: "cpk-attachment-queue-video-play-icon"
10132
+ })
11268
10133
  })
11269
10134
  }),
11270
10135
  open && /* @__PURE__ */ jsx(Lightbox, {
@@ -11317,6 +10182,7 @@ function useBlobUrl(attachment) {
11317
10182
  return url;
11318
10183
  }
11319
10184
  function DocumentLightboxContent({ attachment, vtName }) {
10185
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
11320
10186
  const mimeType = attachment.source.mimeType;
11321
10187
  const blobUrl = useBlobUrl(attachment);
11322
10188
  if (isPdf(mimeType)) {
@@ -11364,20 +10230,21 @@ function DocumentLightboxContent({ attachment, vtName }) {
11364
10230
  className: "cpk-attachment-queue-document-card-details",
11365
10231
  children: [/* @__PURE__ */ jsx("div", {
11366
10232
  className: "cpk-attachment-queue-document-card-name",
11367
- children: attachment.filename || "Document"
10233
+ children: attachment.filename || labels.attachmentDocumentLabel
11368
10234
  }), /* @__PURE__ */ jsxs("div", {
11369
10235
  className: "cpk-attachment-queue-document-card-meta",
11370
- children: [mimeType || "Unknown type", attachment.size != null && ` · ${formatFileSize(attachment.size)}`]
10236
+ children: [mimeType || labels.attachmentUnknownTypeText, attachment.size != null && ` · ${formatFileSize(attachment.size)}`]
11371
10237
  })]
11372
10238
  }),
11373
10239
  /* @__PURE__ */ jsx("div", {
11374
10240
  className: "cpk-attachment-queue-document-card-note",
11375
- children: "No preview available for this file type"
10241
+ children: labels.attachmentNoPreviewText
11376
10242
  })
11377
10243
  ]
11378
10244
  });
11379
10245
  }
11380
10246
  function DocumentPreview({ attachment }) {
10247
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
11381
10248
  const { thumbnailRef, vtName, open, openLightbox, closeLightbox } = useLightbox();
11382
10249
  const mimeType = attachment.source.mimeType;
11383
10250
  const previewable = canPreviewInBrowser(mimeType);
@@ -11392,7 +10259,7 @@ function DocumentPreview({ attachment }) {
11392
10259
  className: "cpk-attachment-queue-document-info",
11393
10260
  children: [/* @__PURE__ */ jsx("span", {
11394
10261
  className: "cpk-attachment-queue-document-name",
11395
- children: attachment.filename || "Document"
10262
+ children: attachment.filename || labels.attachmentDocumentLabel
11396
10263
  }), attachment.size != null && /* @__PURE__ */ jsx("span", {
11397
10264
  className: "cpk-attachment-queue-document-size",
11398
10265
  children: formatFileSize(attachment.size)
@@ -11416,53 +10283,11 @@ function DocumentPreview({ attachment }) {
11416
10283
  * @returns KeyboardState object with keyboard information
11417
10284
  */
11418
10285
  function useKeyboardHeight() {
11419
- const [keyboardState, setKeyboardState] = useState({
11420
- isKeyboardOpen: false,
11421
- keyboardHeight: 0,
11422
- availableHeight: typeof window !== "undefined" ? window.innerHeight : 0,
11423
- viewportHeight: typeof window !== "undefined" ? window.innerHeight : 0
11424
- });
11425
- useEffect(() => {
11426
- if (typeof window === "undefined") return;
11427
- const visualViewport = window.visualViewport;
11428
- if (!visualViewport) return;
11429
- const updateKeyboardState = () => {
11430
- const layoutHeight = window.innerHeight;
11431
- const visualHeight = visualViewport.height;
11432
- const keyboardHeight = Math.max(0, layoutHeight - visualHeight);
11433
- setKeyboardState({
11434
- isKeyboardOpen: keyboardHeight > 150,
11435
- keyboardHeight,
11436
- availableHeight: visualHeight,
11437
- viewportHeight: layoutHeight
11438
- });
11439
- };
11440
- updateKeyboardState();
11441
- visualViewport.addEventListener("resize", updateKeyboardState);
11442
- visualViewport.addEventListener("scroll", updateKeyboardState);
11443
- return () => {
11444
- visualViewport.removeEventListener("resize", updateKeyboardState);
11445
- visualViewport.removeEventListener("scroll", updateKeyboardState);
11446
- };
11447
- }, []);
10286
+ const [keyboardState, setKeyboardState] = useState(ɵinitialKeyboardState$1);
10287
+ useEffect(() => ɵwatchKeyboardState$1(setKeyboardState), []);
11448
10288
  return keyboardState;
11449
10289
  }
11450
10290
 
11451
- //#endregion
11452
- //#region src/components/chat/normalize-auto-scroll.ts
11453
- const VALID = [
11454
- "pin-to-bottom",
11455
- "pin-to-send",
11456
- "none"
11457
- ];
11458
- function normalizeAutoScroll(value) {
11459
- if (value === void 0) return "pin-to-bottom";
11460
- if (value === true) return "pin-to-bottom";
11461
- if (value === false) return "none";
11462
- if (VALID.includes(value)) return value;
11463
- return "pin-to-bottom";
11464
- }
11465
-
11466
10291
  //#endregion
11467
10292
  //#region src/components/chat/last-user-message-context.ts
11468
10293
  const LastUserMessageContext = React.createContext({
@@ -11472,43 +10297,32 @@ const LastUserMessageContext = React.createContext({
11472
10297
 
11473
10298
  //#endregion
11474
10299
  //#region src/hooks/use-pin-to-send.ts
10300
+ /**
10301
+ * Pins the latest sent user message near the top of the chat while the reply
10302
+ * streams below it. Core's `ɵpinMessageToTop` does the measuring and
10303
+ * scrolling; this hook runs it once per send.
10304
+ */
11475
10305
  function usePinToSend({ scrollRef, contentRef, spacerRef, topOffset = 16 }) {
11476
10306
  const { id, sendNonce } = useContext(LastUserMessageContext);
11477
10307
  const lastNonceRef = useRef(-1);
11478
10308
  useEffect(() => {
11479
10309
  if (sendNonce === lastNonceRef.current) return;
10310
+ const previousNonce = lastNonceRef.current;
11480
10311
  lastNonceRef.current = sendNonce;
11481
10312
  if (!id) return;
11482
10313
  const scrollEl = scrollRef.current;
11483
10314
  const contentEl = contentRef.current;
11484
10315
  const spacerEl = spacerRef.current;
11485
10316
  if (!scrollEl || !contentEl || !spacerEl) return;
11486
- const escaped = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(id) : id.replace(/[!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g, "\\$&");
11487
- const targetEl = contentEl.querySelector(`[data-message-id="${escaped}"]`);
11488
- if (!targetEl) return;
11489
- const viewportHeight = scrollEl.clientHeight;
11490
- const userMessageHeight = targetEl.getBoundingClientRect().height;
11491
- const paddingTop = parseFloat(getComputedStyle(targetEl).paddingTop) || 0;
11492
- const bubbleHeight = Math.max(0, userMessageHeight - paddingTop);
11493
- const spacerHeight = Math.max(0, viewportHeight - bubbleHeight - topOffset);
11494
- spacerEl.style.height = `${spacerHeight}px`;
11495
- const raf = requestAnimationFrame(() => {
11496
- const targetTop = computeOffsetTop(targetEl, scrollEl) + paddingTop - topOffset;
11497
- scrollEl.scrollTo({
11498
- top: Math.max(0, targetTop),
11499
- behavior: "smooth"
11500
- });
11501
- });
11502
- const ro = new ResizeObserver(() => {
11503
- if (!contentEl || !spacerEl || !scrollEl) return;
11504
- const consumedBelow = contentEl.getBoundingClientRect().height - computeOffsetTop(targetEl, contentEl) - userMessageHeight;
11505
- const remaining = Math.max(0, spacerHeight - consumedBelow);
11506
- spacerEl.style.height = `${remaining}px`;
10317
+ const unpin = ɵpinMessageToTop$1({
10318
+ scrollEl,
10319
+ contentEl,
10320
+ spacerEl,
10321
+ messageId: id,
10322
+ topOffset
11507
10323
  });
11508
- ro.observe(contentEl);
11509
10324
  return () => {
11510
- cancelAnimationFrame(raf);
11511
- ro.disconnect();
10325
+ if (!unpin()) lastNonceRef.current = previousNonce;
11512
10326
  };
11513
10327
  }, [
11514
10328
  id,
@@ -11519,36 +10333,36 @@ function usePinToSend({ scrollRef, contentRef, spacerRef, topOffset = 16 }) {
11519
10333
  topOffset
11520
10334
  ]);
11521
10335
  }
11522
- function computeOffsetTop(el, stopAt) {
11523
- const elRect = el.getBoundingClientRect();
11524
- const stopRect = stopAt.getBoundingClientRect();
11525
- return elRect.top - stopRect.top + stopAt.scrollTop;
11526
- }
11527
10336
 
11528
10337
  //#endregion
11529
10338
  //#region src/components/chat/CopilotChatView.tsx
11530
10339
  const SCROLL_BUTTON_OFFSET = 16;
11531
10340
  function DropOverlay() {
10341
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
11532
10342
  return /* @__PURE__ */ jsx("div", {
11533
10343
  className: "cpk-chat-view-drop-overlay",
11534
10344
  children: /* @__PURE__ */ jsxs("div", {
11535
10345
  className: "cpk-chat-view-drop-overlay-content",
11536
- children: [/* @__PURE__ */ jsx(Upload, { className: "cpk-chat-view-drop-overlay-icon" }), /* @__PURE__ */ jsx("span", {
10346
+ children: [/* @__PURE__ */ jsx(CopilotIcon, {
10347
+ name: "Upload",
10348
+ className: "cpk-chat-view-drop-overlay-icon"
10349
+ }), /* @__PURE__ */ jsx("span", {
11537
10350
  className: "cpk-chat-view-drop-overlay-label",
11538
- children: "Drop files here"
10351
+ children: labels.chatDropFilesLabel
11539
10352
  })]
11540
10353
  })
11541
10354
  });
11542
10355
  }
11543
- function CopilotChatView({ messageView, input, scrollView, suggestionView, welcomeScreen, messages = [], autoScroll = true, isRunning = false, suggestions, suggestionLoadingIndexes, onSelectSuggestion, onSubmitMessage, onStop, inputMode, inputValue, onInputChange, onStartTranscribe, onCancelTranscribe, onFinishTranscribe, onFinishTranscribeWithAudio, attachments, onRemoveAttachment, onAddFile, dragOver, onDragOver, onDragLeave, onDrop, isConnecting = false, hasExplicitThreadId = false, disclaimer, intelligenceIndicator, children, className, ...props }) {
10356
+ function CopilotChatView({ messageView, input, scrollView, suggestionView, welcomeScreen, messages = [], autoScroll = true, isRunning = false, suggestions, suggestionLoadingIndexes, onSelectSuggestion, onSubmitMessage, onStop, inputMode, inputValue, onInputChange, onStartTranscribe, onCancelTranscribe, onFinishTranscribe, onFinishTranscribeWithAudio, attachments, onRemoveAttachment, onAddFile, dragOver, onDragOver, onDragLeave, onDrop, isConnecting = false, connectingIndicator, hasExplicitThreadId = false, intelligenceIndicator, children, className, ...props }) {
11544
10357
  const configuredThreadId = useCopilotChatConfiguration()?.threadId;
11545
10358
  const [fallbackThreadId, setFallbackThreadId] = useState(messages[0]?.id);
11546
10359
  const previousMessageIds = useRef(/* @__PURE__ */ new Set());
11547
10360
  useEffect(() => {
11548
- if (messages.length === 0) return;
10361
+ const firstMessage = messages[0];
10362
+ if (firstMessage === void 0) return;
11549
10363
  const overlaps = messages.some((message) => previousMessageIds.current.has(message.id));
11550
10364
  previousMessageIds.current = new Set(messages.map((message) => message.id));
11551
- if (!overlaps) setFallbackThreadId(messages[0].id);
10365
+ if (!overlaps) setFallbackThreadId(firstMessage.id);
11552
10366
  }, [messages]);
11553
10367
  const scrollThreadId = configuredThreadId ?? fallbackThreadId;
11554
10368
  const [inputContainerEl, setInputContainerEl] = useState(null);
@@ -11605,8 +10419,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11605
10419
  positioning: "static",
11606
10420
  keyboardHeight: isKeyboardOpen ? keyboardHeight : 0,
11607
10421
  showDisclaimer: true,
11608
- bottomAnchored: true,
11609
- ...disclaimer !== void 0 ? { disclaimer } : {}
10422
+ bottomAnchored: true
11610
10423
  });
11611
10424
  const hasSuggestions = !isConnecting && !isRunning && Array.isArray(suggestions) && suggestions.length > 0;
11612
10425
  const BoundSuggestionView = hasSuggestions ? renderSlot(suggestionView, CopilotChatSuggestionView, {
@@ -11615,6 +10428,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11615
10428
  onSelectSuggestion,
11616
10429
  className: "cpk-chat-view-suggestion-view"
11617
10430
  }) : null;
10431
+ const BoundConnectingIndicator = isConnecting && messages.length === 0 && connectingIndicator !== false ? renderSlot(connectingIndicator === true ? void 0 : connectingIndicator, CopilotChatView.ConnectingIndicator, {}) : null;
11618
10432
  const BoundScrollView = renderSlot(scrollView, CopilotChatView.ScrollView, {
11619
10433
  autoScroll,
11620
10434
  scrollThreadId,
@@ -11625,10 +10439,14 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11625
10439
  style: { paddingBottom: `${inputContainerHeight + (hasSuggestions ? 4 : 32)}px` },
11626
10440
  children: /* @__PURE__ */ jsxs("div", {
11627
10441
  className: "cpk-chat-view-feed",
11628
- children: [BoundMessageView, hasSuggestions ? /* @__PURE__ */ jsx("div", {
11629
- className: "cpk-chat-view-suggestions",
11630
- children: BoundSuggestionView
11631
- }) : null]
10442
+ children: [
10443
+ BoundConnectingIndicator,
10444
+ BoundMessageView,
10445
+ hasSuggestions ? /* @__PURE__ */ jsx("div", {
10446
+ className: "cpk-chat-view-suggestions",
10447
+ children: BoundSuggestionView
10448
+ }) : null
10449
+ ]
11632
10450
  })
11633
10451
  })
11634
10452
  });
@@ -11646,8 +10464,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11646
10464
  onFinishTranscribeWithAudio,
11647
10465
  onAddFile,
11648
10466
  positioning: "static",
11649
- showDisclaimer: true,
11650
- ...disclaimer !== void 0 ? { disclaimer } : {}
10467
+ showDisclaimer: true
11651
10468
  });
11652
10469
  const welcomeScreenSlot = welcomeScreen === true ? void 0 : welcomeScreen;
11653
10470
  const inputWithAttachments = /* @__PURE__ */ jsxs("div", {
@@ -11666,6 +10483,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11666
10483
  "data-copilotkit": true,
11667
10484
  "data-testid": "copilot-chat",
11668
10485
  "data-copilot-running": isRunning ? "true" : "false",
10486
+ "data-copilot-connecting": isConnecting ? "true" : "false",
11669
10487
  onDragOver,
11670
10488
  onDragLeave,
11671
10489
  onDrop,
@@ -11676,6 +10494,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11676
10494
  }
11677
10495
  if (children) return /* @__PURE__ */ jsx("div", {
11678
10496
  "data-copilotkit": true,
10497
+ "data-copilot-connecting": isConnecting ? "true" : "false",
11679
10498
  style: { display: "contents" },
11680
10499
  children: children({
11681
10500
  messageView: BoundMessageView,
@@ -11688,6 +10507,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11688
10507
  "data-copilotkit": true,
11689
10508
  "data-testid": "copilot-chat",
11690
10509
  "data-copilot-running": isRunning ? "true" : "false",
10510
+ "data-copilot-connecting": isConnecting ? "true" : "false",
11691
10511
  onDragOver,
11692
10512
  onDragLeave,
11693
10513
  onDrop,
@@ -11903,13 +10723,15 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11903
10723
  if (mode === "pin-to-bottom") return;
11904
10724
  const scrollElement = nonAutoScrollEl;
11905
10725
  if (!scrollElement) return;
10726
+ const contentElement = contentRef.current;
11906
10727
  const checkScroll = () => {
11907
- setShowScrollButton(!(scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight < 10));
10728
+ setShowScrollButton((contentElement ? contentElement.getBoundingClientRect().bottom - scrollElement.getBoundingClientRect().bottom : scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight) >= 10);
11908
10729
  };
11909
10730
  checkScroll();
11910
10731
  scrollElement.addEventListener("scroll", checkScroll);
11911
10732
  const resizeObserver = new ResizeObserver(checkScroll);
11912
10733
  resizeObserver.observe(scrollElement);
10734
+ if (contentElement) resizeObserver.observe(contentElement);
11913
10735
  return () => {
11914
10736
  scrollElement.removeEventListener("scroll", checkScroll);
11915
10737
  resizeObserver.disconnect();
@@ -11977,7 +10799,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11977
10799
  });
11978
10800
  };
11979
10801
  _CopilotChatView.ScrollToBottomButton = ({ className, ...props }) => {
11980
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
10802
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
11981
10803
  return /* @__PURE__ */ jsx(Button, {
11982
10804
  "data-testid": "copilot-scroll-to-bottom",
11983
10805
  variant: "outline",
@@ -11985,15 +10807,34 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
11985
10807
  className: cn("cpk-chat-view-scroll-to-bottom-button", className),
11986
10808
  "aria-label": labels.chatScrollToBottomLabel,
11987
10809
  ...props,
11988
- children: /* @__PURE__ */ jsx(ChevronDown, { className: "cpk-chat-view-scroll-to-bottom-icon" })
10810
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
10811
+ name: "ChevronDown",
10812
+ className: "cpk-chat-view-scroll-to-bottom-icon"
10813
+ })
11989
10814
  });
11990
10815
  };
11991
10816
  _CopilotChatView.Feather = ({ className, ...props }) => /* @__PURE__ */ jsx("div", {
11992
10817
  className,
11993
10818
  ...props
11994
10819
  });
10820
+ _CopilotChatView.ConnectingIndicator = ({ className, ...props }) => {
10821
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
10822
+ return /* @__PURE__ */ jsxs("div", {
10823
+ "data-testid": "copilot-connecting-indicator",
10824
+ role: "status",
10825
+ className: cn("cpk-chat-view-connecting-indicator", className),
10826
+ ...props,
10827
+ children: [/* @__PURE__ */ jsx(CopilotIcon, {
10828
+ name: "Loader2",
10829
+ className: "cpk-chat-view-connecting-spinner"
10830
+ }), /* @__PURE__ */ jsx("span", {
10831
+ className: "cpk-chat-view-connecting-label",
10832
+ children: labels.chatConnectingLabel
10833
+ })]
10834
+ });
10835
+ };
11995
10836
  _CopilotChatView.WelcomeMessage = ({ className, ...props }) => {
11996
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
10837
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
11997
10838
  return /* @__PURE__ */ jsx("h1", {
11998
10839
  className: cn("cpk-chat-view-welcome-message", className),
11999
10840
  ...props,
@@ -12039,119 +10880,6 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
12039
10880
  })(CopilotChatView || (CopilotChatView = {}));
12040
10881
  var CopilotChatView_default = CopilotChatView;
12041
10882
 
12042
- //#endregion
12043
- //#region src/lib/transcription-client.ts
12044
- /**
12045
- * Convert a Blob to a base64 string
12046
- */
12047
- async function blobToBase64(blob) {
12048
- return new Promise((resolve, reject) => {
12049
- const reader = new FileReader();
12050
- reader.onloadend = () => {
12051
- const base64 = reader.result.split(",")[1];
12052
- resolve(base64 ?? "");
12053
- };
12054
- reader.onerror = () => reject(/* @__PURE__ */ new Error("Failed to read audio data"));
12055
- reader.readAsDataURL(blob);
12056
- });
12057
- }
12058
- /**
12059
- * Check if an error response matches our expected format
12060
- */
12061
- function isTranscriptionErrorResponse(data) {
12062
- return typeof data === "object" && data !== null && "error" in data && "message" in data && typeof data.error === "string" && typeof data.message === "string";
12063
- }
12064
- /**
12065
- * Parse error info from a transcription error response
12066
- */
12067
- function parseTranscriptionError(response) {
12068
- return {
12069
- code: response.error,
12070
- message: response.message,
12071
- retryable: response.retryable ?? false
12072
- };
12073
- }
12074
- /**
12075
- * Custom error type for transcription failures.
12076
- * Extends Error with transcription-specific info for contextual error handling.
12077
- */
12078
- var TranscriptionError = class extends Error {
12079
- constructor(info) {
12080
- super(info.message);
12081
- this.name = "TranscriptionError";
12082
- this.info = info;
12083
- }
12084
- };
12085
- /**
12086
- * Transcribe an audio blob using the CopilotKit runtime
12087
- *
12088
- * Supports both REST mode (multipart/form-data) and single-endpoint mode (base64 JSON)
12089
- *
12090
- * @throws {TranscriptionError} When transcription fails with typed error information
12091
- */
12092
- async function transcribeAudio(core, audioBlob, filename = "recording.webm") {
12093
- const runtimeUrl = core.runtimeUrl;
12094
- if (!runtimeUrl) throw new TranscriptionError({
12095
- code: TranscriptionErrorCode$1.INVALID_REQUEST,
12096
- message: "Runtime URL is not configured",
12097
- retryable: false
12098
- });
12099
- const headers = { ...await core.resolveHeaders() };
12100
- let response;
12101
- try {
12102
- if (core.runtimeTransport === "single") {
12103
- const base64Audio = await blobToBase64(audioBlob);
12104
- headers["Content-Type"] = "application/json";
12105
- response = await fetch(runtimeUrl, {
12106
- method: "POST",
12107
- headers,
12108
- body: JSON.stringify({
12109
- method: "transcribe",
12110
- body: {
12111
- audio: base64Audio,
12112
- mimeType: audioBlob.type || "audio/webm",
12113
- filename
12114
- }
12115
- })
12116
- });
12117
- } else {
12118
- delete headers["Content-Type"];
12119
- const formData = new FormData();
12120
- formData.append("audio", audioBlob, filename);
12121
- response = await fetch(`${runtimeUrl}/transcribe`, {
12122
- method: "POST",
12123
- headers,
12124
- body: formData
12125
- });
12126
- }
12127
- } catch (error) {
12128
- throw new TranscriptionError({
12129
- code: TranscriptionErrorCode$1.NETWORK_ERROR,
12130
- message: error instanceof Error ? error.message : "Network request failed",
12131
- retryable: true
12132
- });
12133
- }
12134
- if (!response.ok) {
12135
- let errorData;
12136
- try {
12137
- errorData = await response.json();
12138
- } catch {
12139
- throw new TranscriptionError({
12140
- code: TranscriptionErrorCode$1.PROVIDER_ERROR,
12141
- message: `HTTP ${response.status}: ${response.statusText}`,
12142
- retryable: response.status >= 500
12143
- });
12144
- }
12145
- if (isTranscriptionErrorResponse(errorData)) throw new TranscriptionError(parseTranscriptionError(errorData));
12146
- throw new TranscriptionError({
12147
- code: TranscriptionErrorCode$1.PROVIDER_ERROR,
12148
- message: typeof errorData === "object" && errorData !== null && "message" in errorData ? String(errorData.message) : "Transcription failed",
12149
- retryable: response.status >= 500
12150
- });
12151
- }
12152
- return await response.json();
12153
- }
12154
-
12155
10883
  //#endregion
12156
10884
  //#region src/providers/use-inspector-thread-override.ts
12157
10885
  function useInspectorThreadOverride(args) {
@@ -12633,7 +11361,7 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12633
11361
  }
12634
11362
  if (!isCurrentSelection()) return false;
12635
11363
  if (failedConnectionsRef.current.has(agent)) {
12636
- setTranscriptionError("Could not load saved conversation. Reopen the thread and try again.");
11364
+ setTranscriptionError({ labelKey: "threadLoadErrorText" });
12637
11365
  return "failed";
12638
11366
  }
12639
11367
  const maybeAware = agent;
@@ -12658,7 +11386,7 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12658
11386
  const onSubmitInput = useCallback(async (value) => {
12659
11387
  if (selectedAttachmentsRef.current.some((a) => a.status === "uploading")) {
12660
11388
  console.error("[CopilotKit] Cannot send while attachments are uploading (pre-await guard)");
12661
- setTranscriptionError("Cannot send while attachments are uploading.");
11389
+ setTranscriptionError({ labelKey: "chatAttachmentsUploadingText" });
12662
11390
  return;
12663
11391
  }
12664
11392
  setInputValue("");
@@ -12670,7 +11398,7 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12670
11398
  }
12671
11399
  if (selectedAttachmentsRef.current.some((a) => a.status === "uploading")) {
12672
11400
  console.error("[CopilotKit] Cannot send while attachments are uploading (post-await re-check)");
12673
- setTranscriptionError("Cannot send while attachments are uploading.");
11401
+ setTranscriptionError({ labelKey: "chatAttachmentsUploadingText" });
12674
11402
  setInputValue(value);
12675
11403
  return;
12676
11404
  }
@@ -12761,6 +11489,18 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12761
11489
  hasNativeIntelligenceRunActivity,
12762
11490
  rememberRecentlyLocalRunId
12763
11491
  ]);
11492
+ const submitMessage = useCallback((value) => {
11493
+ onSubmitInput(value);
11494
+ }, [onSubmitInput]);
11495
+ const selectSuggestion = useCallback((suggestion) => {
11496
+ handleSelectSuggestion(suggestion);
11497
+ }, [handleSelectSuggestion]);
11498
+ const dropFiles = useCallback((e) => {
11499
+ handleDrop(e);
11500
+ }, [handleDrop]);
11501
+ const uploadFiles = useCallback((e) => {
11502
+ handleFileUpload(e);
11503
+ }, [handleFileUpload]);
12764
11504
  const stopCurrentRun = useCallback(() => {
12765
11505
  try {
12766
11506
  copilotkit.stopAgent({ agent });
@@ -12788,7 +11528,7 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12788
11528
  setIsTranscribing(true);
12789
11529
  try {
12790
11530
  setTranscriptionError(null);
12791
- const result = await transcribeAudio(copilotkit, audioBlob);
11531
+ const result = await ɵtranscribeAudio$1(copilotkit, audioBlob);
12792
11532
  setInputValue((prev) => {
12793
11533
  const trimmedPrev = prev.trim();
12794
11534
  if (trimmedPrev) return `${trimmedPrev} ${result.text}`;
@@ -12796,33 +11536,10 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12796
11536
  });
12797
11537
  } catch (error) {
12798
11538
  console.error("CopilotChat: Transcription failed", error);
12799
- if (error instanceof TranscriptionError) {
12800
- const { code, retryable, message } = error.info;
12801
- switch (code) {
12802
- case TranscriptionErrorCode.RATE_LIMITED:
12803
- setTranscriptionError("Too many requests. Please wait a moment.");
12804
- break;
12805
- case TranscriptionErrorCode.AUTH_FAILED:
12806
- setTranscriptionError("Authentication error. Please check your configuration.");
12807
- break;
12808
- case TranscriptionErrorCode.AUDIO_TOO_LONG:
12809
- setTranscriptionError("Recording is too long. Please try a shorter recording.");
12810
- break;
12811
- case TranscriptionErrorCode.AUDIO_TOO_SHORT:
12812
- setTranscriptionError("Recording is too short. Please try again.");
12813
- break;
12814
- case TranscriptionErrorCode.INVALID_AUDIO_FORMAT:
12815
- setTranscriptionError("Audio format not supported.");
12816
- break;
12817
- case TranscriptionErrorCode.SERVICE_NOT_CONFIGURED:
12818
- setTranscriptionError("Transcription service is not available.");
12819
- break;
12820
- case TranscriptionErrorCode.NETWORK_ERROR:
12821
- setTranscriptionError("Network error. Please check your connection.");
12822
- break;
12823
- default: setTranscriptionError(retryable ? "Transcription failed. Please try again." : message);
12824
- }
12825
- } else setTranscriptionError("Transcription failed. Please try again.");
11539
+ if (error instanceof TranscriptionError$1) {
11540
+ const labelKey = ɵtranscriptionErrorMessageKey$1(error.info);
11541
+ setTranscriptionError(labelKey ? { labelKey } : { text: error.info.message });
11542
+ } else setTranscriptionError({ labelKey: "transcriptionErrorGenericText" });
12826
11543
  } finally {
12827
11544
  setIsTranscribing(false);
12828
11545
  }
@@ -12845,7 +11562,7 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12845
11562
  const mergedProps = {
12846
11563
  isRunning: agent.isRunning,
12847
11564
  suggestions: isReady ? autoSuggestions : [],
12848
- onSelectSuggestion: isReady ? handleSelectSuggestion : void 0,
11565
+ onSelectSuggestion: isReady ? selectSuggestion : void 0,
12849
11566
  suggestionView: stableSuggestionView,
12850
11567
  ...restProps
12851
11568
  };
@@ -12854,13 +11571,12 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12854
11571
  const effectiveStopHandler = agent.isRunning && hasMessages ? providedStopHandler ?? stopCurrentRun : providedStopHandler;
12855
11572
  const showTranscription = isTranscriptionEnabled && isMediaRecorderSupported;
12856
11573
  const effectiveMode = isTranscribing ? "processing" : transcribeMode;
12857
- const messages = useMemo(() => [...agent.messages], [agent.messages.map((m) => {
12858
- const contentKey = typeof m.content === "string" ? m.content.length : Array.isArray(m.content) ? m.content.length : m.content && typeof m.content === "object" ? JSON.stringify(m.content) : 0;
12859
- const toolCallsKey = "toolCalls" in m && Array.isArray(m.toolCalls) ? m.toolCalls.map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`).join(";") : "";
12860
- return `${m.id}:${m.role}:${contentKey}:${toolCallsKey}`;
12861
- }).join(",")]);
11574
+ const messages = useMemo(() => [...agent.messages], [ɵmessagesFingerprint$1(agent.messages)]);
12862
11575
  const lastUserMessageId = useMemo(() => {
12863
- for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user") return messages[i].id;
11576
+ for (let i = messages.length - 1; i >= 0; i--) {
11577
+ const message = messages[i];
11578
+ if (message?.role === "user") return message.id;
11579
+ }
12864
11580
  return null;
12865
11581
  }, [messages]);
12866
11582
  const [sendNonce, setSendNonce] = useState(0);
@@ -12878,7 +11594,7 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12878
11594
  const RenderedChatView = renderSlot(chatView, CopilotChatView, {
12879
11595
  ...mergedProps,
12880
11596
  messages,
12881
- onSubmitMessage: isReady ? onSubmitInput : void 0,
11597
+ onSubmitMessage: isReady ? submitMessage : void 0,
12882
11598
  onStop: effectiveStopHandler,
12883
11599
  inputMode: effectiveMode,
12884
11600
  inputValue,
@@ -12893,7 +11609,7 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12893
11609
  dragOver,
12894
11610
  onDragOver: handleDragOver,
12895
11611
  onDragLeave: handleDragLeave,
12896
- onDrop: handleDrop,
11612
+ onDrop: dropFiles,
12897
11613
  isConnecting,
12898
11614
  hasExplicitThreadId
12899
11615
  });
@@ -12912,7 +11628,7 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12912
11628
  type: "file",
12913
11629
  multiple: true,
12914
11630
  ref: fileInputRef,
12915
- onChange: handleFileUpload,
11631
+ onChange: uploadFiles,
12916
11632
  accept: attachmentsConfig?.accept ?? "*/*",
12917
11633
  style: { display: "none" }
12918
11634
  }),
@@ -12930,7 +11646,11 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12930
11646
  fontSize: "14px",
12931
11647
  zIndex: 50
12932
11648
  },
12933
- children: transcriptionError
11649
+ children: "labelKey" in transcriptionError ? {
11650
+ ...CopilotChatDefaultLabels$1,
11651
+ ...existingConfig?.labels,
11652
+ ...labels
11653
+ }[transcriptionError.labelKey] : transcriptionError.text
12934
11654
  }),
12935
11655
  /* @__PURE__ */ jsx(LastUserMessageContext.Provider, {
12936
11656
  value: lastUserMessageState,
@@ -12953,16 +11673,18 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
12953
11673
  //#endregion
12954
11674
  //#region src/components/chat/CopilotChatToggleButton.tsx
12955
11675
  const ICON_CLASS = "cpk-chat-toggle-button-icon";
12956
- const DefaultOpenIcon = ({ className, ...props }) => /* @__PURE__ */ jsx(MessageCircle, {
11676
+ const DefaultOpenIcon = ({ className, ...props }) => /* @__PURE__ */ jsx(CopilotIcon, {
12957
11677
  className: className ?? ICON_CLASS,
12958
11678
  strokeWidth: 1.75,
12959
11679
  fill: "currentColor",
12960
- ...props
11680
+ ...props,
11681
+ name: "MessageCircle"
12961
11682
  });
12962
- const DefaultCloseIcon = ({ className, ...props }) => /* @__PURE__ */ jsx(X, {
11683
+ const DefaultCloseIcon = ({ className, ...props }) => /* @__PURE__ */ jsx(CopilotIcon, {
12963
11684
  className: className ?? ICON_CLASS,
12964
11685
  strokeWidth: 1.75,
12965
- ...props
11686
+ ...props,
11687
+ name: "X"
12966
11688
  });
12967
11689
  DefaultOpenIcon.displayName = "CopilotChatToggleButton.OpenIcon";
12968
11690
  DefaultCloseIcon.displayName = "CopilotChatToggleButton.CloseIcon";
@@ -12971,7 +11693,7 @@ const ICON_WRAPPER_CLASS = "cpk-chat-toggle-button-icon-wrapper";
12971
11693
  const CopilotChatToggleButton = React.forwardRef(function CopilotChatToggleButton({ openIcon, closeIcon, className, ...buttonProps }, ref) {
12972
11694
  const { onClick, type, disabled, ...restProps } = buttonProps;
12973
11695
  const configuration = useCopilotChatConfiguration();
12974
- const labels = configuration?.labels ?? CopilotChatDefaultLabels;
11696
+ const labels = configuration?.labels ?? CopilotChatDefaultLabels$1;
12975
11697
  const [fallbackOpen, setFallbackOpen] = useState(false);
12976
11698
  const isOpen = configuration?.isModalOpen ?? fallbackOpen;
12977
11699
  const setModalOpen = configuration?.setModalOpen ?? setFallbackOpen;
@@ -13076,19 +11798,12 @@ function useModalOpenControl() {
13076
11798
  */
13077
11799
  function useIsMobileViewport() {
13078
11800
  const [isMobile, setIsMobile] = useState(false);
13079
- useEffect(() => {
13080
- if (typeof window === "undefined" || typeof window.matchMedia !== "function") return;
13081
- const mql = window.matchMedia("(max-width: 767px)");
13082
- const update = () => setIsMobile(mql.matches);
13083
- update();
13084
- mql.addEventListener("change", update);
13085
- return () => mql.removeEventListener("change", update);
13086
- }, []);
11801
+ useEffect(() => ɵwatchMobileViewport$1(setIsMobile), []);
13087
11802
  return isMobile;
13088
11803
  }
13089
11804
  function CopilotModalHeader({ title, titleContent, closeButton, drawerLauncher, children, className, ...rest }) {
13090
11805
  const configuration = useCopilotChatConfiguration();
13091
- const fallbackTitle = configuration?.labels.modalHeaderTitle ?? CopilotChatDefaultLabels.modalHeaderTitle;
11806
+ const fallbackTitle = configuration?.labels.modalHeaderTitle ?? CopilotChatDefaultLabels$1.modalHeaderTitle;
13092
11807
  const resolvedTitle = title ?? fallbackTitle;
13093
11808
  const isMobile = useIsMobileViewport();
13094
11809
  const drawerRegistered = (configuration?.drawerRegistered ?? false) && isMobile;
@@ -13144,28 +11859,30 @@ CopilotModalHeader.displayName = "CopilotModalHeader";
13144
11859
  children
13145
11860
  });
13146
11861
  _CopilotModalHeader.CloseButton = ({ className, ...props }) => {
13147
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
11862
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
13148
11863
  return /* @__PURE__ */ jsx("button", {
13149
11864
  type: "button",
13150
11865
  "data-testid": "copilot-close-button",
13151
11866
  className: cn("cpk-modal-header-close-button", className),
13152
11867
  "aria-label": labels.modalHeaderCloseButtonLabel,
13153
11868
  ...props,
13154
- children: /* @__PURE__ */ jsx(X, {
11869
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
11870
+ name: "X",
13155
11871
  className: "cpk-modal-header-close-icon",
13156
11872
  "aria-hidden": "true"
13157
11873
  })
13158
11874
  });
13159
11875
  };
13160
11876
  _CopilotModalHeader.DrawerLauncher = ({ className, ...props }) => {
13161
- const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;
11877
+ const labels = useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels$1;
13162
11878
  return /* @__PURE__ */ jsx("button", {
13163
11879
  type: "button",
13164
11880
  "data-testid": "copilot-threads-drawer-launcher",
13165
11881
  className: cn("cpk-modal-header-drawer-launcher", className),
13166
11882
  "aria-label": labels.modalHeaderThreadsButtonLabel,
13167
11883
  ...props,
13168
- children: /* @__PURE__ */ jsx(PanelLeftOpen, {
11884
+ children: /* @__PURE__ */ jsx(CopilotIcon, {
11885
+ name: "PanelLeftOpen",
13169
11886
  className: "cpk-modal-header-drawer-launcher-icon",
13170
11887
  "aria-hidden": "true"
13171
11888
  })
@@ -13270,7 +11987,7 @@ function CopilotSidebarViewInternal({ header, toggleButton, width, position = "r
13270
11987
  paddingBottom: "env(safe-area-inset-bottom)"
13271
11988
  },
13272
11989
  "aria-hidden": !isSidebarOpen,
13273
- "aria-label": configuration?.labels.sidebarLabel ?? CopilotChatDefaultLabels.sidebarLabel,
11990
+ "aria-label": configuration?.labels.sidebarLabel ?? CopilotChatDefaultLabels$1.sidebarLabel,
13274
11991
  role: "complementary",
13275
11992
  children: /* @__PURE__ */ jsxs("div", {
13276
11993
  className: "cpk-sidebar-view-panel",
@@ -13351,7 +12068,7 @@ function CopilotPopupViewInternal({ header, toggleButton, width, height, clickOu
13351
12068
  const configuration = useCopilotChatConfiguration();
13352
12069
  const isPopupOpen = configuration?.isModalOpen ?? false;
13353
12070
  const setModalOpen = configuration?.setModalOpen;
13354
- const labels = configuration?.labels ?? CopilotChatDefaultLabels;
12071
+ const labels = configuration?.labels ?? CopilotChatDefaultLabels$1;
13355
12072
  const containerRef = useRef(null);
13356
12073
  const [isRendered, setIsRendered] = useState(isPopupOpen);
13357
12074
  const [isAnimatingOut, setIsAnimatingOut] = useState(false);
@@ -13919,5 +12636,5 @@ const WildcardToolCallRender = defineToolCallRenderer({
13919
12636
  });
13920
12637
 
13921
12638
  //#endregion
13922
- export { A2UI_FENCE_LANGUAGE, ACTIVITY_HISTORY_METADATA, AGUIConnectNotImplementedError, AGUIError, AGUI_METADATA_KEY, AbstractAgent, ActivityDeltaEventSchema, ActivityMessageSchema, ActivitySnapshotEventSchema, AddOperationSchema, AgentCapabilitiesSchema, AgentRegistry, AgentThreadLockedError, AssistantMessageSchema, AttributableSchema, AudioInputContentSchema, AudioInputPartSchema, AudioPartSchema, AudioRecorderError, BackwardCompatibility_0_0_39, BackwardCompatibility_0_0_45, BackwardCompatibility_0_0_57, BaseEventSchema, BaseMessageSchema, BasicMarkdownRenderer, CompatibilityBoundary, ContentPartSchema, ContextSchema, ContextStore, CopilotChat, CopilotChatAssistantMessage_default as CopilotChatAssistantMessage, CopilotChatAttachmentQueue, CopilotChatAttachmentRenderer, CopilotChatAudioRecorder, CopilotChatConfigurationProvider, CopilotChatInput_default as CopilotChatInput, CopilotChatMessageView, CopilotChatReasoningMessage_default as CopilotChatReasoningMessage, CopilotChatSuggestionPill, CopilotChatSuggestionView, CopilotChatToggleButton, DefaultCloseIcon as CopilotChatToggleButtonCloseIcon, DefaultOpenIcon as CopilotChatToggleButtonOpenIcon, CopilotChatToolCallGroup, CopilotChatToolCallsView, CopilotChatUserMessage_default as CopilotChatUserMessage, CopilotChatView_default as CopilotChatView, CopilotChatWorkSummary, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreReact, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, CopilotKitInspector, CopilotKitProvider, CopilotKitStyles, CopilotModalHeader, CopilotPopup, CopilotPopupView, CopilotSidebar, CopilotSidebarView, CopilotThreadsDrawer, CopyOperationSchema, CustomEventSchema, DataSourceSchema, DebugLogger, DeveloperMessageSchema, DocumentInputContentSchema, DocumentInputPartSchema, DocumentPartSchema, EventSchema, EventSchemas, EventType, EventTypeSchema, ExecutionCapabilitiesSchema, FileSourceSchema, FilterToolCallsMiddleware, FunctionCallSchema, FunctionMiddleware, GenerateSandboxedUiArgsSchema, HttpAgent, HumanInTheLoopCapabilitiesSchema, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, INTELLIGENCE_TURN_HEAD, INTERRUPT_EVENT_NAME, IdentityCapabilitiesSchema, ImageInputContentSchema, ImageInputPartSchema, ImagePartSchema, InputContentDataSourceSchema, InputContentSchema, InputContentSourceSchema, InputContentUrlSourceSchema, IntelligenceAgent, IntelligenceIndicator, IntelligenceIndicatorView, InterruptSchema, JsonPatchOperationSchema, JsonPatchSchema, JsonPointerSchema, MCPAppsActivityContentSchema, MCPAppsActivityRenderer, MCPAppsActivityType, MEMORY_ERROR_REGISTRY, MarkdownRendererProvider, MemoryError, MessageSchema, MessagesSnapshotEventSchema, MetadataSchema, Middleware, MoveOperationSchema, MultiAgentCapabilitiesSchema, MultimodalCapabilitiesSchema, MultimodalInputCapabilitiesSchema, MultimodalOutputCapabilitiesSchema, OpenGenerativeUIActivityRenderer, OpenGenerativeUIActivityType, OpenGenerativeUIContentSchema, OpenGenerativeUIToolRenderer, OptionalMetadataSchema, OutputCapabilitiesSchema, PROTOCOL_VERSION, PartSourceSchema, ProxiedCopilotRuntimeAgent, RawEventSchema, ReasoningCapabilitiesSchema, ReasoningEncryptedValueEventSchema, ReasoningEncryptedValueSubtypeSchema, ReasoningEndEventSchema, ReasoningMessageChunkEventSchema, ReasoningMessageContentEventSchema, ReasoningMessageEndEventSchema, ReasoningMessageSchema, ReasoningMessageStartEventSchema, ReasoningStartEventSchema, RemoveOperationSchema, ReplaceOperationSchema, ResumeEntrySchema, RoleSchema, RunAgentInputSchema, RunErrorEventSchema, RunFinishedCancelledOutcomeSchema, RunFinishedEventSchema, RunFinishedInterruptOutcomeSchema, RunFinishedOutcomeSchema, RunFinishedSuccessOutcomeSchema, RunHandler, RunStartedEventSchema, SandboxFunctionsContext, StateCapabilitiesSchema, StateDeltaEventSchema, StateManager, StateSchema, StateSnapshotEventSchema, StepFinishedEventSchema, StepStartedEventSchema, StreamingMarkdownDefaultRenderer, SubagentErrorEventSchema, SubagentFinishedEventSchema, SubagentFinishedOutcomeSchema, SubagentFinishedSuccessOutcomeSchema, SubagentFinishedSuspendedOutcomeSchema, SubagentInfoSchema, SubagentRunIdSchema, SubagentStartedEventSchema, SuggestionEngine, SystemMessageSchema, TestOperationSchema, TextInputContentSchema, TextMessageChunkEventSchema, TextMessageContentEventSchema, TextMessageEndEventSchema, TextMessageRoleSchema, TextMessageStartEventSchema, TextPartSchema, TokenUsageSchema, ToolCallArgsEventSchema, ToolCallChunkEventSchema, ToolCallEndEventSchema, ToolCallResultEventSchema, ToolCallSchema, ToolCallStartEventSchema, ToolCallStatus, ToolMessageSchema, ToolSchema, ToolsCapabilitiesSchema, TransportCapabilitiesSchema, UrlSourceSchema, UseAgentUpdate, UserMessageSchema, VideoInputContentSchema, VideoInputPartSchema, VideoPartSchema, WebMCPRegistry, WildcardToolCallRender, a2uiDefaultTheme, aggregateTokenUsage, authoritativeActivityTypes, buildResumeArray, classifySurfaceCards, compactEvents, completePartialMarkdown, contentHasMedia, contentToText, convertToLegacyEvents, createA2UIMessageRenderer, createActionGroup, createDebugLogger, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, defaultApplyEvents, defineToolCallRenderer, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, enforceEvents, enforceOutgoingInput, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getIntelligenceTurnAnchors, getMarkdownOperationSurfaceId, getRunOutcome, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isInterruptExpired, isRecognizedEvent, isRunCompletionAware, mergeMetadata, messageGroup, messageRow, ofType, omitOptionalNulls, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseMarkdown, parseProtoStream, parseSSEStream, parseToolArguments, prepareSurfaceOperations, props, randomUUID, resolveAgentDebugConfig, resolveDebugLogger, runHttpRequest, segmentSurfaceProse, select, splitA2UIMarkdown, structuredClone_, tokenUsageFromAiSdkUsage, tokenUsageFromLangChainMetadata, transformChunks, transformHttpEventStream, useAgent, useAgentContext, useAttachments, useCapabilities, useComponent, useConfigureSuggestions, useCopilotChatConfiguration, useCopilotKit, useDefaultRenderTool, useFrontendTool, useFrontendTools, useHumanInTheLoop, useInterrupt, useLearnFromUserAction, useLearnFromUserActionInCurrentThread, useLearningContainers, useLearningContainersInCurrentThread, useLicenseContext, useMarkdownRenderer, useMemories, useRenderActivityMessage, useRenderCustomMessages, useRenderTool, useRenderToolCall, useSandboxFunctions, useSuggestions, useThreads, verifyEvents, withAuthoritativeActivityTypes, ɵCOPILOTKIT_FEATURES, ɵInterruptState, ɵMAX_SOCKET_RETRIES, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, ɵcreateMemoryStore, ɵcreateThreadSelectors, ɵcreateThreadStore, ɵgetAgentInterruptState, ɵisCopilotKitFeature, ɵisHttpAgent, ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵrunMcpFollowUp, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents, ɵwithHeaderDefaults };
12639
+ export { A2UI_FENCE_LANGUAGE, ACTIVITY_HISTORY_METADATA, AGUIConnectNotImplementedError, AGUIError, AGUI_METADATA_KEY, AbstractAgent, ActivityDeltaEventSchema, ActivityMessageSchema, ActivitySnapshotEventSchema, AddOperationSchema, AgentCapabilitiesSchema, AgentRegistry, AgentThreadLockedError, AssistantMessageSchema, AttributableSchema, AudioInputContentSchema, AudioInputPartSchema, AudioPartSchema, AudioRecorderError, BackwardCompatibility_0_0_39, BackwardCompatibility_0_0_45, BackwardCompatibility_0_0_57, BaseEventSchema, BaseMessageSchema, CompatibilityBoundary, ContentPartSchema, ContextSchema, ContextStore, CopilotChat, CopilotChatAssistantMessage_default as CopilotChatAssistantMessage, CopilotChatAttachmentQueue, CopilotChatAttachmentRenderer, CopilotChatAudioRecorder, CopilotChatConfigurationProvider, CopilotChatDefaultLabels, CopilotChatInput_default as CopilotChatInput, CopilotChatMessageView, CopilotChatReasoningMessage_default as CopilotChatReasoningMessage, CopilotChatSuggestionPill, CopilotChatSuggestionView, CopilotChatToggleButton, DefaultCloseIcon as CopilotChatToggleButtonCloseIcon, DefaultOpenIcon as CopilotChatToggleButtonOpenIcon, CopilotChatToolCallGroup, CopilotChatToolCallsView, CopilotChatUserMessage_default as CopilotChatUserMessage, CopilotChatView_default as CopilotChatView, CopilotChatWorkSummary, CopilotKitCore, CopilotKitCoreErrorCode, CopilotKitCoreReact, CopilotKitCoreRuntimeConnectionStatus, CopilotKitHeaderResolutionError, CopilotKitInspector, CopilotKitProvider, CopilotKitStyles, CopilotModalHeader, CopilotPopup, CopilotPopupView, CopilotSidebar, CopilotSidebarView, CopilotThreadsDrawer, CopyOperationSchema, CustomEventSchema, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL, DataSourceSchema, DebugLogger, DeveloperMessageSchema, DocumentInputContentSchema, DocumentInputPartSchema, DocumentPartSchema, EventSchema, EventSchemas, EventType, EventTypeSchema, ExecutionCapabilitiesSchema, FileSourceSchema, FilterToolCallsMiddleware, FunctionCallSchema, FunctionMiddleware, GENERATE_SANDBOXED_UI_TOOL_NAME, GenerateSandboxedUiArgsSchema, HttpAgent, HumanInTheLoopCapabilitiesSchema, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, INTELLIGENCE_TURN_HEAD, INTERRUPT_EVENT_NAME, IdentityCapabilitiesSchema, ImageInputContentSchema, ImageInputPartSchema, ImagePartSchema, InputContentDataSourceSchema, InputContentSchema, InputContentSourceSchema, InputContentUrlSourceSchema, IntelligenceAgent, IntelligenceIndicator, IntelligenceIndicatorView, InterruptSchema, JsonPatchOperationSchema, JsonPatchSchema, JsonPointerSchema, MCPAppsActivityContentSchema, MCPAppsActivityRenderer, MCPAppsActivityType, MEMORY_ERROR_REGISTRY, MarkdownRendererProvider, MemoryError, MessageSchema, MessagesSnapshotEventSchema, MetadataSchema, Middleware, MoveOperationSchema, MultiAgentCapabilitiesSchema, MultimodalCapabilitiesSchema, MultimodalInputCapabilitiesSchema, MultimodalOutputCapabilitiesSchema, OPEN_GENERATIVE_UI_ACTIVITY_TYPE, OpenGenerativeUIActivityRenderer, OpenGenerativeUIActivityType, OpenGenerativeUIContentSchema, OpenGenerativeUIToolRenderer, OptionalMetadataSchema, OutputCapabilitiesSchema, PROTOCOL_VERSION, PartSourceSchema, ProxiedCopilotRuntimeAgent, RawEventSchema, ReasoningCapabilitiesSchema, ReasoningEncryptedValueEventSchema, ReasoningEncryptedValueSubtypeSchema, ReasoningEndEventSchema, ReasoningMessageChunkEventSchema, ReasoningMessageContentEventSchema, ReasoningMessageEndEventSchema, ReasoningMessageSchema, ReasoningMessageStartEventSchema, ReasoningStartEventSchema, RemoveOperationSchema, ReplaceOperationSchema, ResumeEntrySchema, RoleSchema, RunAgentInputSchema, RunErrorEventSchema, RunFinishedCancelledOutcomeSchema, RunFinishedEventSchema, RunFinishedInterruptOutcomeSchema, RunFinishedOutcomeSchema, RunFinishedSuccessOutcomeSchema, RunHandler, RunStartedEventSchema, SandboxFunctionsContext, StateCapabilitiesSchema, StateDeltaEventSchema, StateManager, StateSchema, StateSnapshotEventSchema, StepFinishedEventSchema, StepStartedEventSchema, StreamingMarkdownDefaultRenderer, SubagentErrorEventSchema, SubagentFinishedEventSchema, SubagentFinishedOutcomeSchema, SubagentFinishedSuccessOutcomeSchema, SubagentFinishedSuspendedOutcomeSchema, SubagentInfoSchema, SubagentRunIdSchema, SubagentStartedEventSchema, SuggestionEngine, SystemMessageSchema, TestOperationSchema, TextInputContentSchema, TextMessageChunkEventSchema, TextMessageContentEventSchema, TextMessageEndEventSchema, TextMessageRoleSchema, TextMessageStartEventSchema, TextPartSchema, TokenUsageSchema, ToolCallArgsEventSchema, ToolCallChunkEventSchema, ToolCallEndEventSchema, ToolCallResultEventSchema, ToolCallSchema, ToolCallStartEventSchema, ToolCallStatus, ToolMessageSchema, ToolSchema, ToolsCapabilitiesSchema, TranscriptionError, TranscriptionErrorCode, TransportCapabilitiesSchema, UrlSourceSchema, UseAgentUpdate, UserMessageSchema, VideoInputContentSchema, VideoInputPartSchema, VideoPartSchema, WebMCPRegistry, WildcardToolCallRender, a2uiDefaultTheme, aggregateTokenUsage, authoritativeActivityTypes, buildResumeArray, classifySurfaceCards, compactEvents, completePartialMarkdown, contentHasMedia, contentToText, convertToLegacyEvents, createA2UIMessageRenderer, createActionGroup, createDebugLogger, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, defaultApplyEvents, defineToolCallRenderer, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, enforceEvents, enforceOutgoingInput, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getIntelligenceTurnAnchors, getMarkdownOperationSurfaceId, getRunOutcome, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isInterruptExpired, isRecognizedEvent, isRunCompletionAware, mergeMetadata, messageGroup, messageRow, ofType, omitOptionalNulls, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseProtoStream, parseSSEStream, parseToolArguments, prepareSurfaceOperations, props, randomUUID, resolveAgentDebugConfig, resolveDebugLogger, runHttpRequest, segmentSurfaceProse, select, splitA2UIMarkdown, structuredClone_, tokenUsageFromAiSdkUsage, tokenUsageFromLangChainMetadata, transformChunks, transformHttpEventStream, useAgent, useAgentContext, useAttachments, useCapabilities, useComponent, useConfigureSuggestions, useCopilotChatConfiguration, useCopilotKit, useDefaultRenderTool, useFrontendTool, useFrontendTools, useHumanInTheLoop, useInterrupt, useLearnFromUserAction, useLearnFromUserActionInCurrentThread, useLicenseContext, useMarkdownRenderer, useMemories, useRenderActivityMessage, useRenderCustomMessages, useRenderTool, useRenderToolCall, useSandboxFunctions, useSuggestions, useThreads, verifyEvents, withAuthoritativeActivityTypes, ɵCOPILOTKIT_FEATURES, ɵCOPY_FEEDBACK_RESET_MS, ɵCopyFeedback, ɵFEEDBACK_COMMENT_CLOSE_DELAY_MS, ɵFeedbackCommentController, ɵHOVER_MENU_CLOSE_DELAY_MS, ɵHoverMenuController, ɵINLINE_FEATURE_WARNING_STYLE, ɵInterruptState, ɵKEYBOARD_OPEN_THRESHOLD_PX, ɵLICENSE_BANNER_OFFSET, ɵLICENSE_BANNER_STYLE, ɵMAX_SOCKET_RETRIES, ɵMESSAGE_FEEDBACK_EVENT_NAME, ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH, ɵMOBILE_MAX_WIDTH_QUERY, ɵOpenGenerativeUIController, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵclearAgentInterruptState, ɵcn, ɵcomposerButtonState, ɵcopilotIconSvgAttributes, ɵcopilotIcons, ɵcountFailedToolCalls, ɵcreateMemoryStore, ɵcreateThreadSelectors, ɵcreateThreadStore, ɵdeduplicateMessages, ɵextractCompleteStyles, ɵflattenUserMessageContent, ɵformatCountLabel, ɵformatLabel, ɵformatReasoningDuration, ɵformatReasoningDurationLabel, ɵformatToolNames, ɵformatWorkDuration, ɵgetAgentInterruptState, ɵgetArgumentPreview, ɵgetBranchNavState, ɵgetInlineFeatureWarningSpec, ɵgetLatestTurnKey, ɵgetLicenseBannerSpec, ɵgetMessageFeedback, ɵgetMessageFeedbackControls, ɵgetToolCallLayouts, ɵgetToolCallPreview, ɵgetToolCallRendererNames, ɵgetToolCallRowStatus, ɵgetToolResults, ɵgetTurnWork, ɵgetUserMessageMediaFilename, ɵgetUserMessageMediaParts, ɵgetWorkOpenState, ɵgetWorkSummaryText, ɵhasAssistantMessageText, ɵinitialKeyboardState, ɵinspectorKiteFill, ɵinspectorKiteIcon, ɵinspectorShortcuts, ɵisCopilotKitFeature, ɵisHttpAgent, ɵisLearningFeedbackEnabled, ɵisMobileViewport, ɵisRetryableMemoryStatus, ɵisTurnWorkOpen, ɵisTurnWorking, ɵjoinPhoenixChannel$, ɵloadWebsandbox, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵmessagesFingerprint, ɵnormalizeAutoScroll, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵpinMessageToTop, ɵpluralize, ɵprocessPartialHtml, ɵreadKeyboardState, ɵrecordWorkTime, ɵreserveLicenseBannerOffset, ɵresetMessageFeedbackCache, ɵresolveActivityRenderer, ɵresolveComposerKey, ɵresolveCustomMessageRenderers, ɵresolveLicenseState, ɵresolveThreadsLicense, ɵresolveToolCallRenderer, ɵrunMcpFollowUp, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵsetMessageFeedback, ɵshallowEqualRecord, ɵshouldShowAssistantToolbar, ɵstringifyToolCallPayload, ɵsubscribeToLearningFeedbackEnabled, ɵsubscribeToMessageFeedback, ɵthreadAdapterEvents, ɵtranscribeAudio, ɵtranscriptionErrorMessageKey, ɵwatchKeyboardState, ɵwatchMobileViewport, ɵwithHeaderDefaults };
13923
12640
  //# sourceMappingURL=index.mjs.map