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

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-S4wfUl3J.cjs → MarkdownSurfaces-CGW92DCL.cjs} +244 -331
  6. package/dist/MarkdownSurfaces-CGW92DCL.cjs.map +1 -0
  7. package/dist/{MarkdownSurfaces-Bd--93O1.mjs → MarkdownSurfaces-DveOwhaW.mjs} +224 -312
  8. package/dist/MarkdownSurfaces-DveOwhaW.mjs.map +1 -0
  9. package/dist/context.cjs +62 -63
  10. package/dist/context.cjs.map +1 -1
  11. package/dist/context.d.cts +53 -109
  12. package/dist/context.d.cts.map +1 -1
  13. package/dist/context.d.mts +53 -109
  14. package/dist/context.d.mts.map +1 -1
  15. package/dist/context.mjs +63 -64
  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 +286 -1021
  26. package/dist/headless.cjs.map +1 -1
  27. package/dist/headless.d.cts +143 -277
  28. package/dist/headless.d.cts.map +1 -1
  29. package/dist/headless.d.mts +107 -216
  30. package/dist/headless.d.mts.map +1 -1
  31. package/dist/headless.mjs +280 -1021
  32. package/dist/headless.mjs.map +1 -1
  33. package/dist/index.cjs +3351 -5707
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.cts +314 -808
  36. package/dist/index.d.cts.map +1 -1
  37. package/dist/index.d.mts +311 -805
  38. package/dist/index.d.mts.map +1 -1
  39. package/dist/index.mjs +1827 -5565
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/index.umd.js +3571 -5978
  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
@@ -1,40 +1,29 @@
1
- import { extractFenceOperations, flattenInformationalCards, getMarkdownOperationSurfaceId, prepareSurfaceOperations, segmentSurfaceProse, splitA2UIMarkdown } from "@copilotkit/core";
2
- import React, { Component, createContext, memo, useCallback, useContext, useEffect, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
1
+ import { CopilotChatDefaultLabels, extractFenceOperations, flattenInformationalCards, getMarkdownOperationSurfaceId, prepareSurfaceOperations, segmentSurfaceProse, splitA2UIMarkdown, ɵChatConfigurationStore, ɵcn as cn, ɵcopilotIconSvgAttributes, ɵcopilotIcons, ɵshallowEqualRecord } from "@copilotkit/core";
2
+ import React, { Component, createContext, createElement, forwardRef, memo, useCallback, useContext, useEffect, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
3
+ import { StreamingMarkdownRenderer } from "@copilotkit/markdown/react";
4
+ import { CHAT_MARKDOWN_NODE_CLASS_NAMES, warnUnsupportedRichSyntaxOnce } from "@copilotkit/markdown";
3
5
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
4
- import { StreamingMarkdownRenderer, createStreamingMarkdownNodeRenderers } from "@copilotkit/markdown-renderer/react";
5
- import { warnUnsupportedRichSyntaxOnce } from "@copilotkit/markdown-renderer";
6
- import { A2UI_COMPONENT_ENVELOPE_KEYS, A2UI_INDEX_FUNCTION, A2UI_VERSION, DEFAULT_AGENT_ID, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_CHAT_TARGET, GENERATIVE_UI_FUNCTIONS, GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE, GENERATIVE_UI_RENDER_TOOL, GENERATIVE_UI_ROOT_ID, applyChildRefMarks, childIdsAtRefs, collectChildRefs, functionCallers, getOperationKind, hasBoundChildRef, isActionBinding, isCallBinding, isPathBinding, isValidationResult, mapAtChildRef, randomUUID, schemaToJsonSchema, validateOperation } from "@copilotkit/shared";
7
6
  import { CopilotKitContext, useCopilotKit, useDefaultAgentId } from "@copilotkit/react-core/context";
8
- import { z } from "zod";
9
- import { zodToJsonSchema } from "zod-to-json-schema";
7
+ import { A2UI_COMPONENT_ENVELOPE_KEYS, A2UI_INDEX_FUNCTION, A2UI_VERSION, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_CHAT_TARGET, GENERATIVE_UI_FUNCTIONS, GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE, GENERATIVE_UI_RENDER_TOOL, GENERATIVE_UI_ROOT_ID, applyChildRefMarks, childIdsAtRefs, collectChildRefs, functionCallers, getOperationKind, hasBoundChildRef, isActionBinding, isCallBinding, isPathBinding, isValidationResult, mapAtChildRef, schemaToJsonSchema, validateOperation, ɵanySchema } from "@copilotkit/shared";
8
+ import * as z from "zod";
10
9
 
11
10
  //#region src/components/chat/StreamingMarkdownDefaultRenderer.tsx
12
- const defaultNodeRenderers = createStreamingMarkdownNodeRenderers({ codeBlock: ({ node }) => /* @__PURE__ */ jsx("pre", {
13
- className: "cpk-markdown-code-block",
14
- children: /* @__PURE__ */ jsx("code", {
15
- "data-code-info": node.info ?? void 0,
16
- children: node.text
17
- })
18
- }) });
19
11
  /**
20
12
  * react-core's built-in default markdown renderer — a thin adapter over
21
- * `@copilotkit/markdown-renderer`'s streaming renderer. Maps the pluggable
13
+ * `@copilotkit/markdown`'s streaming renderer. Maps the pluggable
22
14
  * renderer contract (`{ content, isStreaming, className }`) onto the streaming
23
15
  * renderer for streaming-safe incremental rendering + per-token animation.
24
16
  * Still overridable via the slot/provider pluggable interface.
25
17
  */
26
18
  function StreamingMarkdownDefaultRenderer({ content, isStreaming, className, nodeRenderers, caret, options, onLinkClick, onCitationClick }) {
27
- const mergedNodeRenderers = useMemo(() => nodeRenderers ? createStreamingMarkdownNodeRenderers({
28
- ...defaultNodeRenderers,
29
- ...nodeRenderers
30
- }) : defaultNodeRenderers, [nodeRenderers]);
31
19
  if (!content) return null;
32
20
  warnUnsupportedRichSyntaxOnce(content);
33
21
  return /* @__PURE__ */ jsx(StreamingMarkdownRenderer, {
34
22
  className,
35
23
  isComplete: !isStreaming,
36
24
  caret: caret ?? !!isStreaming,
37
- nodeRenderers: mergedNodeRenderers,
25
+ nodeRenderers,
26
+ nodeClassNames: CHAT_MARKDOWN_NODE_CLASS_NAMES,
38
27
  options,
39
28
  onLinkClick,
40
29
  onCitationClick,
@@ -43,17 +32,76 @@ function StreamingMarkdownDefaultRenderer({ content, isStreaming, className, nod
43
32
  }
44
33
  StreamingMarkdownDefaultRenderer.displayName = "StreamingMarkdownDefaultRenderer";
45
34
 
35
+ //#endregion
36
+ //#region src/components/icons/CopilotIcon.tsx
37
+ /** Turns SVG attribute names such as `stroke-width` into React's `strokeWidth`. */
38
+ function toReactAttributes(attributes) {
39
+ return Object.fromEntries(Object.entries(attributes).map(([key, value]) => [key.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase()), value]));
40
+ }
41
+ const svgDefaults = toReactAttributes(ɵcopilotIconSvgAttributes);
42
+ /** True when the props give the icon an accessible name or role. */
43
+ function hasAccessibleProp(props) {
44
+ return Object.keys(props).some((key) => key.startsWith("aria-") || key === "role" || key === "title");
45
+ }
46
+ /**
47
+ * Internal. Draws a Lucide icon from its node data, the way Lucide's React package
48
+ * does: Lucide's default SVG attributes, the `lucide lucide-<name>` classes,
49
+ * and `aria-hidden="true"` when no `aria-*`, `role` or `title` prop names it.
50
+ */
51
+ const IconSvg = forwardRef(function IconSvg({ lucideName, nodes, size = 24, color = "currentColor", strokeWidth = 2, className, children, ...props }, ref) {
52
+ const isDecorative = !children && !hasAccessibleProp(props);
53
+ return /* @__PURE__ */ jsxs("svg", {
54
+ ref,
55
+ ...svgDefaults,
56
+ width: size,
57
+ height: size,
58
+ stroke: color,
59
+ strokeWidth,
60
+ className: cn("lucide", `lucide-${lucideName}`, className),
61
+ "aria-hidden": isDecorative || void 0,
62
+ ...props,
63
+ children: [nodes.map((node, index) => createElement(node.tag, {
64
+ key: index,
65
+ ...node.attributes
66
+ })), children]
67
+ });
68
+ });
69
+ /**
70
+ * Draws one of the chat icons as an inline `<svg>`.
71
+ *
72
+ * The `<svg>` has the classes `lucide lucide-<icon name>`, so CSS that selects
73
+ * them (for example `svg.lucide-arrow-up`) keeps working. The icon is hidden
74
+ * from screen readers unless you give it an `aria-label`, `role` or `title`.
75
+ *
76
+ * @param props.name - The chat icon, for example `"ArrowUp"` or `"X"`.
77
+ * @param props.size - Width and height. Defaults to `24`.
78
+ * @param props.strokeWidth - Line width. Defaults to `2`.
79
+ * @param props.color - Line color. Defaults to `currentColor`.
80
+ *
81
+ * @example
82
+ * ```tsx
83
+ * <CopilotIcon name="ArrowUp" className="cpk-chat-input-send-icon" />
84
+ * <CopilotIcon name="X" aria-label="Close" />
85
+ * ```
86
+ */
87
+ const CopilotIcon = forwardRef(function CopilotIcon({ name, ...props }, ref) {
88
+ const icon = ɵcopilotIcons[name];
89
+ return /* @__PURE__ */ jsx(IconSvg, {
90
+ ref,
91
+ lucideName: icon.name,
92
+ nodes: icon.nodes,
93
+ ...props
94
+ });
95
+ });
96
+
46
97
  //#endregion
47
98
  //#region src/lib/shallow-stable-ref.ts
48
99
  /**
49
- * Shallow equality comparison for objects.
100
+ * Shallow equality comparison for objects: same own keys, each holding the
101
+ * same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.
50
102
  */
51
103
  function shallowEqual(obj1, obj2) {
52
- const keys1 = Object.keys(obj1);
53
- const keys2 = Object.keys(obj2);
54
- if (keys1.length !== keys2.length) return false;
55
- for (const key of keys1) if (obj1[key] !== obj2[key]) return false;
56
- return true;
104
+ return ɵshallowEqualRecord(obj1, obj2);
57
105
  }
58
106
  /**
59
107
  * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
@@ -87,70 +135,6 @@ function useShallowStableRef(value) {
87
135
 
88
136
  //#endregion
89
137
  //#region src/providers/CopilotChatConfigurationProvider.tsx
90
- const CopilotChatDefaultLabels = {
91
- chatInputPlaceholder: "Type a message...",
92
- chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
93
- chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
94
- chatInputToolbarFinishTranscribeButtonLabel: "Finish",
95
- chatInputToolbarAddButtonLabel: "Add attachments",
96
- chatInputToolbarToolsButtonLabel: "Tools",
97
- chatInputToolbarSendButtonLabel: "Send message",
98
- chatInputToolbarStopButtonLabel: "Stop",
99
- assistantMessageToolbarCopyCodeLabel: "Copy",
100
- assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
101
- assistantMessageToolbarCopyMessageLabel: "Copy",
102
- assistantMessageToolbarInspectorLabel: "View in Inspector",
103
- assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
104
- assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
105
- assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
106
- assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
107
- assistantMessageToolbarInspectorHideLabel: "Hide this icon",
108
- assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
109
- assistantMessageToolbarThumbsUpLabel: "Good response",
110
- assistantMessageToolbarThumbsDownLabel: "Bad response",
111
- assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
112
- assistantMessageFeedbackCommentSubmitLabel: "Send comment",
113
- assistantMessageToolbarReadAloudLabel: "Read aloud",
114
- assistantMessageToolbarRegenerateLabel: "Regenerate",
115
- userMessageToolbarCopyMessageLabel: "Copy",
116
- userMessageToolbarEditMessageLabel: "Edit",
117
- userMessageToolbarPreviousBranchLabel: "Previous branch",
118
- userMessageToolbarNextBranchLabel: "Next branch",
119
- chatDisclaimerText: "AI can make mistakes. Please verify important information.",
120
- chatToggleOpenLabel: "Open chat",
121
- chatToggleCloseLabel: "Close chat",
122
- chatScrollToBottomLabel: "Scroll to bottom",
123
- modalHeaderTitle: "CopilotKit Chat",
124
- welcomeMessageText: "How can I help you today?",
125
- reasoningMessageThinkingLabel: "Thinking…",
126
- chatInputSlashMenuLabel: "Slash commands",
127
- chatInputSlashMenuEmptyText: "No commands found",
128
- attachmentRemoveButtonLabel: "Remove attachment",
129
- attachmentPlayVideoButtonLabel: "Play video",
130
- attachmentPreviewCloseButtonLabel: "Close preview",
131
- modalHeaderCloseButtonLabel: "Close",
132
- modalHeaderThreadsButtonLabel: "Open threads",
133
- sidebarLabel: "Copilot chat sidebar"
134
- };
135
- /**
136
- * Mobile breakpoint below which the chat modal and the thread-list drawer are
137
- * mutually exclusive. At or above this width both surfaces may coexist. This
138
- * mirrors the `(max-width: 767px)` / `(min-width: 768px)` split already used by
139
- * CopilotChatInput and CopilotSidebarView.
140
- */
141
- const MOBILE_MAX_WIDTH_PX = 767;
142
- /**
143
- * Reports whether the current viewport is in the mobile range (`<768px`), where
144
- * the chat modal and drawer must not be open simultaneously. SSR-safe and
145
- * defensive against environments without `matchMedia` (treated as desktop, so
146
- * no mutual-exclusion constraint is applied).
147
- *
148
- * @returns `true` when the viewport is mobile-width, `false` otherwise.
149
- */
150
- function isMobileViewport() {
151
- if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
152
- return window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH_PX}px)`).matches;
153
- }
154
138
  const CopilotChatConfiguration = createContext(null);
155
139
  const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
156
140
  const parentConfig = useContext(CopilotChatConfiguration);
@@ -161,167 +145,67 @@ const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId,
161
145
  ...stableLabels
162
146
  }), [stableLabels, parentConfig?.labels]);
163
147
  const providerAgentId = useDefaultAgentId();
164
- const resolvedAgentId = agentId ?? parentConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;
165
- const threadIdPropIsAuthoritative = threadId !== void 0 && hasExplicitThreadId !== false;
166
- const isThreadIdControlled = threadIdPropIsAuthoritative;
167
- const [activeThreadOverride, setActiveThreadOverride] = useState(null);
168
- const resolvedThreadId = useMemo(() => {
169
- if (threadIdPropIsAuthoritative) return threadId;
170
- if (activeThreadOverride) return activeThreadOverride.threadId;
171
- if (parentConfig?.threadId) return parentConfig.threadId;
172
- if (threadId) return threadId;
173
- return randomUUID();
148
+ const options = {
149
+ agentId,
150
+ threadId,
151
+ hasExplicitThreadId,
152
+ isModalDefaultOpen,
153
+ providerAgentId
154
+ };
155
+ const parentStore = parentConfig?.ɵstore ?? null;
156
+ const [store] = useState(() => new ɵChatConfigurationStore(options, parentStore));
157
+ store.ɵsetOptions(options);
158
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
159
+ useEffect(() => {
160
+ store.update({
161
+ agentId,
162
+ threadId,
163
+ hasExplicitThreadId,
164
+ isModalDefaultOpen,
165
+ providerAgentId
166
+ });
174
167
  }, [
175
- threadIdPropIsAuthoritative,
168
+ store,
169
+ agentId,
176
170
  threadId,
177
- parentConfig?.threadId,
178
- activeThreadOverride
171
+ hasExplicitThreadId,
172
+ isModalDefaultOpen,
173
+ providerAgentId
179
174
  ]);
180
175
  const copilotkit = useContext(CopilotKitContext)?.copilotkit;
181
- const openThreadRef = useRef(null);
182
- const latestThreadIdRef = useRef(resolvedThreadId);
183
- latestThreadIdRef.current = resolvedThreadId;
184
176
  useEffect(() => {
185
177
  if (copilotkit === void 0) return;
186
- const registration = copilotkit.registerOpenThread({
187
- agentId: resolvedAgentId,
188
- threadId: latestThreadIdRef.current
189
- });
190
- openThreadRef.current = registration;
191
- return () => {
192
- registration.unregister();
193
- openThreadRef.current = null;
194
- };
195
- }, [copilotkit, resolvedAgentId]);
196
- useEffect(() => {
197
- openThreadRef.current?.update(resolvedThreadId);
198
- }, [resolvedThreadId]);
199
- const resolvedHasExplicitThreadId = (threadIdPropIsAuthoritative ? true : activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false) || !!parentConfig?.hasExplicitThreadId;
200
- const [internalModalOpen, setInternalModalOpen] = useState(isModalDefaultOpen ?? true);
201
- const hasExplicitDefault = isModalDefaultOpen !== void 0;
202
- const setAndSync = useCallback((open) => {
203
- setInternalModalOpen(open);
204
- parentConfig?.setModalOpen(open);
205
- }, [parentConfig?.setModalOpen]);
206
- const isMounted = useRef(false);
207
- useEffect(() => {
208
- if (!hasExplicitDefault) return;
209
- if (!isMounted.current) {
210
- isMounted.current = true;
211
- return;
212
- }
213
- if (parentConfig?.isModalOpen === void 0) return;
214
- setInternalModalOpen(parentConfig.isModalOpen);
215
- }, [parentConfig?.isModalOpen, hasExplicitDefault]);
216
- const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : parentConfig?.isModalOpen ?? internalModalOpen;
217
- const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : parentConfig?.setModalOpen ?? setInternalModalOpen;
218
- const [ownDrawerOpen, setOwnDrawerOpen] = useState(false);
219
- const [ownDrawerCount, setOwnDrawerCount] = useState(0);
220
- const modalCloseRef = useRef(() => {});
221
- modalCloseRef.current = resolvedSetModalOpen;
222
- const registeredModalClosersRef = useRef([]);
223
- const ownRegisterModalCloser = useCallback((closeModal) => {
224
- registeredModalClosersRef.current.push(closeModal);
225
- return () => {
226
- registeredModalClosersRef.current = registeredModalClosersRef.current.filter((entry) => entry !== closeModal);
227
- };
228
- }, []);
229
- const ownSetDrawerOpen = useCallback((open) => {
230
- setOwnDrawerOpen(open);
231
- if (open && isMobileViewport()) {
232
- const registered = registeredModalClosersRef.current;
233
- (registered.length > 0 ? registered[registered.length - 1] : modalCloseRef.current)(false);
234
- }
235
- }, []);
236
- const ownRegisterDrawer = useCallback(() => {
237
- setOwnDrawerCount((count) => count + 1);
238
- return () => {
239
- setOwnDrawerCount((count) => Math.max(0, count - 1));
240
- };
241
- }, []);
242
- const resolvedDrawerOpen = parentConfig ? parentConfig.drawerOpen : ownDrawerOpen;
243
- const resolvedSetDrawerOpen = parentConfig ? parentConfig.setDrawerOpen : ownSetDrawerOpen;
244
- const resolvedDrawerRegistered = parentConfig ? parentConfig.drawerRegistered : ownDrawerCount > 0;
245
- const resolvedRegisterDrawer = parentConfig ? parentConfig.registerDrawer : ownRegisterDrawer;
246
- const resolvedRegisterModalCloser = parentConfig ? parentConfig.ɵregisterModalCloser : ownRegisterModalCloser;
247
- useEffect(() => {
248
- if (!hasExplicitDefault) return;
249
- return resolvedRegisterModalCloser(resolvedSetModalOpen);
250
- }, [
251
- hasExplicitDefault,
252
- resolvedRegisterModalCloser,
253
- resolvedSetModalOpen
254
- ]);
255
- const isThreadIdControlledRef = useRef(isThreadIdControlled);
256
- isThreadIdControlledRef.current = isThreadIdControlled;
257
- const ownSetActiveThreadId = useCallback((id, options) => {
258
- setActiveThreadOverride({
259
- threadId: id,
260
- explicit: options?.explicit ?? true
261
- });
262
- }, []);
263
- const ownStartNewThread = useCallback(() => {
264
- setActiveThreadOverride({
265
- threadId: randomUUID(),
266
- explicit: false
267
- });
268
- }, []);
269
- const parentSetActiveThreadId = parentConfig?.setActiveThreadId;
270
- const parentStartNewThread = parentConfig?.startNewThread;
271
- const resolvedSetActiveThreadId = useCallback((id, options) => {
272
- if (isThreadIdControlledRef.current) {
273
- console.warn("[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
274
- return;
275
- }
276
- if (parentSetActiveThreadId) {
277
- parentSetActiveThreadId(id, options);
278
- return;
279
- }
280
- ownSetActiveThreadId(id, options);
281
- }, [parentSetActiveThreadId, ownSetActiveThreadId]);
282
- const resolvedStartNewThread = useCallback(() => {
283
- if (isThreadIdControlledRef.current) {
284
- console.warn("[CopilotKit] Ignoring startNewThread(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
285
- return;
286
- }
287
- if (parentStartNewThread) {
288
- parentStartNewThread();
289
- return;
290
- }
291
- ownStartNewThread();
292
- }, [parentStartNewThread, ownStartNewThread]);
293
- const setModalOpenWithDrawerExclusion = useCallback((open) => {
294
- if (open && isMobileViewport()) resolvedSetDrawerOpen(false);
295
- resolvedSetModalOpen(open);
296
- }, [resolvedSetModalOpen, resolvedSetDrawerOpen]);
178
+ return store.bindOpenThread(copilotkit);
179
+ }, [copilotkit, store]);
180
+ const ownsModal = isModalDefaultOpen !== void 0;
181
+ const isModalOpen = ownsModal || !parentConfig ? snapshot.isModalOpen : parentConfig.isModalOpen;
182
+ const setModalOpen = ownsModal || !parentConfig ? store.setModalOpen : parentConfig.setModalOpen;
183
+ const { agentId: resolvedAgentId, threadId: resolvedThreadId, hasExplicitThreadId: resolvedHasExplicitThreadId, drawerOpen, drawerRegistered } = snapshot;
297
184
  const configurationValue = useMemo(() => ({
298
185
  labels: mergedLabels,
299
186
  agentId: resolvedAgentId,
300
187
  threadId: resolvedThreadId,
301
188
  hasExplicitThreadId: resolvedHasExplicitThreadId,
302
- isModalOpen: resolvedIsModalOpen,
303
- setModalOpen: setModalOpenWithDrawerExclusion,
304
- drawerOpen: resolvedDrawerOpen,
305
- setDrawerOpen: resolvedSetDrawerOpen,
306
- drawerRegistered: resolvedDrawerRegistered,
307
- registerDrawer: resolvedRegisterDrawer,
308
- ɵregisterModalCloser: resolvedRegisterModalCloser,
309
- setActiveThreadId: resolvedSetActiveThreadId,
310
- startNewThread: resolvedStartNewThread
189
+ isModalOpen,
190
+ setModalOpen,
191
+ drawerOpen,
192
+ setDrawerOpen: store.setDrawerOpen,
193
+ drawerRegistered,
194
+ registerDrawer: store.registerDrawer,
195
+ ɵregisterModalCloser: store.registerModalCloser,
196
+ setActiveThreadId: store.setActiveThreadId,
197
+ startNewThread: store.startNewThread,
198
+ ɵstore: store
311
199
  }), [
312
200
  mergedLabels,
313
201
  resolvedAgentId,
314
202
  resolvedThreadId,
315
203
  resolvedHasExplicitThreadId,
316
- resolvedIsModalOpen,
317
- setModalOpenWithDrawerExclusion,
318
- resolvedDrawerOpen,
319
- resolvedSetDrawerOpen,
320
- resolvedDrawerRegistered,
321
- resolvedRegisterDrawer,
322
- resolvedRegisterModalCloser,
323
- resolvedSetActiveThreadId,
324
- resolvedStartNewThread
204
+ isModalOpen,
205
+ setModalOpen,
206
+ drawerOpen,
207
+ drawerRegistered,
208
+ store
325
209
  ]);
326
210
  return /* @__PURE__ */ jsx(CopilotChatConfiguration.Provider, {
327
211
  value: configurationValue,
@@ -388,28 +272,6 @@ const ControlledModalOpenScope = ({ children, open, onOpenChange }) => {
388
272
  };
389
273
  ControlledModalOpenScope.displayName = "ControlledModalOpenScope";
390
274
 
391
- //#endregion
392
- //#region src/lib/utils.ts
393
- /**
394
- * Joins class names, skipping falsy values. Takes the same inputs as `clsx`.
395
- * Classes are not merged: every rule CopilotKit ships sits in `:where()`, so a
396
- * class the app adds wins without removing ours.
397
- */
398
- function cn(...inputs) {
399
- const out = [];
400
- for (const input of inputs) {
401
- if (!input) continue;
402
- if (typeof input === "string" || typeof input === "number" || typeof input === "bigint") out.push(String(input));
403
- else if (Array.isArray(input)) {
404
- const nested = cn(...input);
405
- if (nested) out.push(nested);
406
- } else if (typeof input === "object") {
407
- for (const key in input) if (input[key]) out.push(key);
408
- }
409
- }
410
- return out.join(" ");
411
- }
412
-
413
275
  //#endregion
414
276
  //#region src/lib/slots.tsx
415
277
  /**
@@ -491,7 +353,7 @@ function useMarkdownRenderer() {
491
353
  //#endregion
492
354
  //#region src/types/defineToolCallRenderer.ts
493
355
  function defineToolCallRenderer(def) {
494
- const argsSchema = def.name === "*" && !def.args ? z.any() : def.args;
356
+ const argsSchema = def.name === "*" && !def.args ? ɵanySchema : def.args;
495
357
  return {
496
358
  name: def.name,
497
359
  args: argsSchema,
@@ -504,12 +366,11 @@ function defineToolCallRenderer(def) {
504
366
  //#endregion
505
367
  //#region src/generative-ui/json-schema.ts
506
368
  /**
507
- * JSON Schema for a Standard Schema (zod v3 via zod-to-json-schema),
508
- * inlined, no `$schema`. A prop marked by `child()` or `childList()`
369
+ * JSON Schema for a Standard Schema, without `$schema`. A prop marked by `child()` or `childList()`
509
370
  * becomes an A2UI `$ref` to `ComponentId` or `ChildList`.
510
371
  */
511
372
  function toJsonSchema(schema) {
512
- const { $schema: _omit, ...rest } = schemaToJsonSchema(schema, { zodToJsonSchema: (s) => zodToJsonSchema(s, { $refStrategy: "none" }) });
373
+ const { $schema: _omit, ...rest } = schemaToJsonSchema(schema);
513
374
  return applyChildRefMarks(rest);
514
375
  }
515
376
 
@@ -816,16 +677,10 @@ function toManifest(definition, modelProps, modelEvents) {
816
677
  return manifest;
817
678
  }
818
679
 
819
- //#endregion
820
- //#region src/generative-ui/is-record.ts
821
- /** True for a plain object: not null, not an array. Internal, not exported. */
822
- function isRecord(value) {
823
- return typeof value === "object" && value !== null && !Array.isArray(value);
824
- }
825
-
826
680
  //#endregion
827
681
  //#region src/generative-ui/errors.ts
828
682
  var GenerativeUIError = class extends Error {
683
+ code;
829
684
  constructor(code, message) {
830
685
  super(message);
831
686
  this.name = "GenerativeUIError";
@@ -925,6 +780,7 @@ function formatDatePattern(date, pattern) {
925
780
  case "m": return pad(date.getMinutes(), 2);
926
781
  case "s": return pad(date.getSeconds(), 2);
927
782
  case "a": return date.getHours() < 12 ? "AM" : "PM";
783
+ case void 0:
928
784
  default: return token;
929
785
  }
930
786
  });
@@ -1028,6 +884,13 @@ function givesValidationResult(name) {
1028
884
  return GENERATIVE_UI_FUNCTIONS[name]?.returnType === "validationResult";
1029
885
  }
1030
886
 
887
+ //#endregion
888
+ //#region src/generative-ui/is-record.ts
889
+ /** True for a plain object: not null, not an array. Internal, not exported. */
890
+ function isRecord(value) {
891
+ return typeof value === "object" && value !== null && !Array.isArray(value);
892
+ }
893
+
1031
894
  //#endregion
1032
895
  //#region src/generative-ui/markdown/source.ts
1033
896
  /**
@@ -1035,10 +898,8 @@ function givesValidationResult(name) {
1035
898
  * is dropped at the end of that build, so the cache does not grow.
1036
899
  */
1037
900
  var BuildMemo = class {
1038
- constructor() {
1039
- this.previous = /* @__PURE__ */ new Map();
1040
- this.current = /* @__PURE__ */ new Map();
1041
- }
901
+ previous = /* @__PURE__ */ new Map();
902
+ current = /* @__PURE__ */ new Map();
1042
903
  /**
1043
904
  * The value of `key`. It is computed when no earlier value is there, or
1044
905
  * when `isFresh` says that the earlier value is out of date.
@@ -1056,12 +917,11 @@ var BuildMemo = class {
1056
917
  };
1057
918
  /** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */
1058
919
  var MarkdownBuildCache = class {
1059
- constructor() {
1060
- this.segments = new BuildMemo();
1061
- this.fences = new BuildMemo();
1062
- this.drafts = new BuildMemo();
1063
- this.readdressed = /* @__PURE__ */ new WeakMap();
1064
- }
920
+ segments = new BuildMemo();
921
+ fences = new BuildMemo();
922
+ drafts = new BuildMemo();
923
+ /** The copies of an operation for other surface ids, by operation. */
924
+ readdressed = /* @__PURE__ */ new WeakMap();
1065
925
  endBuild() {
1066
926
  this.segments.endBuild();
1067
927
  this.fences.endBuild();
@@ -1572,13 +1432,18 @@ function removalContent(surfaceId, catalogId) {
1572
1432
  * that each fence renders.
1573
1433
  */
1574
1434
  var MarkdownSurfaceSource = class {
1435
+ functions;
1436
+ /** By thread: the blocks of each fence, from the latest sync. */
1437
+ fences = /* @__PURE__ */ new Map();
1438
+ /** By thread, then surface: the operations last ingested, as JSON. */
1439
+ ingested = /* @__PURE__ */ new Map();
1440
+ /** By thread, then surface: the content last ingested. */
1441
+ contents = /* @__PURE__ */ new Map();
1442
+ /** By thread: the results of the earlier builds. */
1443
+ caches = /* @__PURE__ */ new Map();
1575
1444
  constructor(manager, ui) {
1576
1445
  this.manager = manager;
1577
1446
  this.ui = ui;
1578
- this.fences = /* @__PURE__ */ new Map();
1579
- this.ingested = /* @__PURE__ */ new Map();
1580
- this.contents = /* @__PURE__ */ new Map();
1581
- this.caches = /* @__PURE__ */ new Map();
1582
1447
  this.functions = declaredFunctions(ui);
1583
1448
  }
1584
1449
  /**
@@ -1676,6 +1541,7 @@ const OPERATORS = [
1676
1541
  "*",
1677
1542
  "/",
1678
1543
  "%",
1544
+ "^",
1679
1545
  "(",
1680
1546
  ")",
1681
1547
  ",",
@@ -1756,27 +1622,58 @@ function describe(value) {
1756
1622
  const MATH = {
1757
1623
  min: (args) => Math.min(...args),
1758
1624
  max: (args) => Math.max(...args),
1759
- abs: ([x]) => Math.abs(x),
1760
- floor: ([x]) => Math.floor(x),
1761
- ceil: ([x]) => Math.ceil(x),
1762
- round: ([x, decimals = 0]) => {
1625
+ abs: ([x = NaN]) => Math.abs(x),
1626
+ floor: ([x = NaN]) => Math.floor(x),
1627
+ ceil: ([x = NaN]) => Math.ceil(x),
1628
+ round: ([x = NaN, decimals = 0]) => {
1763
1629
  const factor = 10 ** Math.trunc(decimals);
1764
1630
  return Math.round(x * factor) / factor;
1765
- }
1631
+ },
1632
+ pow: ([x = NaN, y = NaN]) => x ** y,
1633
+ sqrt: ([x = NaN]) => Math.sqrt(x),
1634
+ exp: ([x = NaN]) => Math.exp(x),
1635
+ ln: ([x = NaN]) => Math.log(x),
1636
+ log10: ([x = NaN]) => Math.log10(x)
1637
+ };
1638
+ /** How many args a function takes, at least and at most; min and max take any. */
1639
+ const ARITY = {
1640
+ abs: [1, 1],
1641
+ floor: [1, 1],
1642
+ ceil: [1, 1],
1643
+ round: [1, 2],
1644
+ pow: [2, 2],
1645
+ sqrt: [1, 1],
1646
+ exp: [1, 1],
1647
+ ln: [1, 1],
1648
+ log10: [1, 1]
1649
+ };
1650
+ /** Named constants, when no arg of the same name is passed. */
1651
+ const CONSTANTS = {
1652
+ pi: Math.PI,
1653
+ e: Math.E
1766
1654
  };
1767
1655
  var CalcParser = class {
1656
+ pos = 0;
1768
1657
  constructor(tokens, scope, source) {
1769
1658
  this.tokens = tokens;
1770
1659
  this.scope = scope;
1771
1660
  this.source = source;
1772
- this.pos = 0;
1773
- this.skipDepth = 0;
1774
1661
  }
1775
1662
  parse() {
1776
1663
  const value = this.ternary();
1777
- if (this.tokens[this.pos].kind !== "end") this.fail(`unexpected "${this.text(this.tokens[this.pos])}"`);
1664
+ const token = this.peek();
1665
+ if (token.kind !== "end") this.fail(`unexpected "${this.text(token)}"`);
1778
1666
  return value;
1779
1667
  }
1668
+ /**
1669
+ * The token at `pos`. The parser never moves past the "end" token, which
1670
+ * `tokenize` always adds last, so there is always one.
1671
+ */
1672
+ peek() {
1673
+ const token = this.tokens[this.pos];
1674
+ if (token === void 0) throw new Error(`calc: no token at ${this.pos} in "${this.source}"`);
1675
+ return token;
1676
+ }
1780
1677
  fail(what) {
1781
1678
  throw new ExpressionError(`calc: ${what} in "${this.source}"`);
1782
1679
  }
@@ -1784,11 +1681,11 @@ var CalcParser = class {
1784
1681
  return token.kind === "end" ? "end" : String(token.value);
1785
1682
  }
1786
1683
  peekOp(...ops) {
1787
- const token = this.tokens[this.pos];
1684
+ const token = this.peek();
1788
1685
  return token.kind === "op" && ops.includes(token.value) ? token.value : void 0;
1789
1686
  }
1790
1687
  expectOp(op) {
1791
- if (this.peekOp(op) === void 0) this.fail(`expected "${op}" but found "${this.text(this.tokens[this.pos])}"`);
1688
+ if (this.peekOp(op) === void 0) this.fail(`expected "${op}" but found "${this.text(this.peek())}"`);
1792
1689
  this.pos++;
1793
1690
  }
1794
1691
  /**
@@ -1807,6 +1704,8 @@ var CalcParser = class {
1807
1704
  }
1808
1705
  return null;
1809
1706
  }
1707
+ /** Above 0 while parsing a part whose value is not needed. */
1708
+ skipDepth = 0;
1810
1709
  /** The number of a value, or 0 while skipping. */
1811
1710
  num(value, what) {
1812
1711
  return this.skipDepth > 0 ? 0 : numberOf(value, what);
@@ -1897,10 +1796,24 @@ var CalcParser = class {
1897
1796
  this.pos++;
1898
1797
  return !truthOf(this.unary());
1899
1798
  }
1900
- return this.primary();
1799
+ return this.power();
1800
+ }
1801
+ /** `a ^ b`: binds tighter than `*` and unary minus, right to left. */
1802
+ power() {
1803
+ const base = this.primary();
1804
+ if (!this.peekOp("^")) return base;
1805
+ this.pos++;
1806
+ const exponent = this.unary();
1807
+ if (this.skipDepth > 0) return null;
1808
+ return this.finite(this.num(base, "the left side of ^") ** this.num(exponent, "the right side of ^"), "^");
1809
+ }
1810
+ finite(value, what) {
1811
+ if (!Number.isFinite(value)) this.fail(`${what} has no finite result`);
1812
+ return value;
1901
1813
  }
1902
1814
  primary() {
1903
- const token = this.tokens[this.pos++];
1815
+ const token = this.peek();
1816
+ this.pos++;
1904
1817
  switch (token.kind) {
1905
1818
  case "number": return token.value;
1906
1819
  case "string": return token.value;
@@ -1932,10 +1845,15 @@ var CalcParser = class {
1932
1845
  const fn = Object.prototype.hasOwnProperty.call(MATH, name) ? MATH[name] : void 0;
1933
1846
  if (!fn) this.fail(`unknown function ${name}`);
1934
1847
  if (args.length === 0) this.fail(`${name} needs an argument`);
1935
- return fn(args);
1848
+ const [least, most] = ARITY[name] ?? [1, Infinity];
1849
+ if (args.length < least || args.length > most) this.fail(`${name} takes ${least === most ? least : `${least} or ${most}`} argument${most === 1 ? "" : "s"}`);
1850
+ return this.finite(fn(args), name);
1936
1851
  }
1937
1852
  if (this.skipDepth > 0) return null;
1938
- if (!Object.prototype.hasOwnProperty.call(this.scope, name)) this.fail(`unknown name ${name}; pass it as an arg`);
1853
+ if (!Object.prototype.hasOwnProperty.call(this.scope, name)) {
1854
+ if (Object.prototype.hasOwnProperty.call(CONSTANTS, name)) return CONSTANTS[name];
1855
+ this.fail(`unknown name ${name}; pass it as an arg`);
1856
+ }
1939
1857
  const value = this.scope[name];
1940
1858
  if (value !== null && typeof value !== "number" && typeof value !== "string" && typeof value !== "boolean") this.fail(`${name} is not a number, text or boolean (${describe(value)})`);
1941
1859
  return value;
@@ -2175,10 +2093,10 @@ const IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;
2175
2093
  const NUMBER = /-?\d+(?:\.\d+)?/y;
2176
2094
  const PATH_SEGMENT = /[^\s,():'"]+/y;
2177
2095
  var ExpressionParser = class {
2096
+ pos = 0;
2178
2097
  constructor(source, state) {
2179
2098
  this.source = source;
2180
2099
  this.state = state;
2181
- this.pos = 0;
2182
2100
  }
2183
2101
  parse() {
2184
2102
  const value = this.expression();
@@ -2480,14 +2398,10 @@ function NodePlaceholder(_props) {
2480
2398
  }
2481
2399
  /** Per-node boundary. Resets on retry or a new agent revision, not on data ticks. */
2482
2400
  var NodeBoundary = class extends Component {
2483
- constructor(..._args) {
2484
- super(..._args);
2485
- this.state = {
2486
- error: null,
2487
- revision: this.props.revision
2488
- };
2489
- this.retry = () => this.setState({ error: null });
2490
- }
2401
+ state = {
2402
+ error: null,
2403
+ revision: this.props.revision
2404
+ };
2491
2405
  static getDerivedStateFromError(error) {
2492
2406
  return { error };
2493
2407
  }
@@ -2506,6 +2420,7 @@ var NodeBoundary = class extends Component {
2506
2420
  error
2507
2421
  });
2508
2422
  }
2423
+ retry = () => this.setState({ error: null });
2509
2424
  render() {
2510
2425
  const { error } = this.state;
2511
2426
  if (!error) return this.props.children;
@@ -2525,10 +2440,7 @@ var NodeBoundary = class extends Component {
2525
2440
  };
2526
2441
  /** Outer boundary: a failure here must not reach the chat or the host page. */
2527
2442
  var SurfaceBoundary = class extends Component {
2528
- constructor(..._args2) {
2529
- super(..._args2);
2530
- this.state = { error: null };
2531
- }
2443
+ state = { error: null };
2532
2444
  static getDerivedStateFromError(error) {
2533
2445
  return { error };
2534
2446
  }
@@ -3463,7 +3375,7 @@ const ContentSchema = z.object({
3463
3375
  index: z.number(),
3464
3376
  reason: z.string()
3465
3377
  })).default([])
3466
- }).passthrough();
3378
+ }).loose();
3467
3379
  function GenerativeUIChatActivity({ content, agent }) {
3468
3380
  const runtime = useGenerativeUIRuntime();
3469
3381
  const threadId = useCopilotChatConfiguration()?.threadId ?? agent?.threadId;
@@ -3672,5 +3584,5 @@ function MarkdownSurfaces({ content, messageId, isStreaming = false, ...markdown
3672
3584
  }
3673
3585
 
3674
3586
  //#endregion
3675
- export { GenerativeUIError as A, renderSlot as B, issueKey as C, getMarkdownSurfaceSource as D, containsDynamicValue as E, toJsonSchema as F, useCopilotChatConfiguration as G, ControlledModalOpenScope as H, defineToolCallRenderer as I, useShallowStableRef as K, MarkdownRendererProvider as L, catalogIdsOf as M, componentCatalogIds as N, BASIC_FUNCTIONS as O, createGenerativeUI as P, useMarkdownRenderer as R, isAsyncIssue as S, withoutRejectedNulls as T, CopilotChatConfigurationProvider as U, cn as V, CopilotChatDefaultLabels as W, GenerativeUINodeContext as _, GenerativeUIToolCallRenderer as a, useRequiredGenerativeUIRuntime as b, SurfaceView as c, namedRole as d, useGenerativeUIAccessibility as f, useManagerVersion as g, useGenerativeUIState as h, GenerativeUIChatSlotContext as i, isRecord as j, ExpressionError as k, DARK_THEME_CSS as l, useGenerativeUIFunction as m, ProviderMarkdown as n, createGenerativeUIActivityRenderer as o, wrapperAria as p, StreamingMarkdownDefaultRenderer as q, DefaultGenerativeUIChatCard as r, createGenerativeUIFunctionCallActivityRenderer as s, MarkdownSurfaces as t, controlAria as u, GenerativeUIRuntimeContext as v, validateSchemaSync as w, formatIssues as x, useGenerativeUIRuntime as y, isReactComponentType as z };
3676
- //# sourceMappingURL=MarkdownSurfaces-Bd--93O1.mjs.map
3587
+ export { ExpressionError as A, renderSlot as B, issueKey as C, getMarkdownSurfaceSource as D, containsDynamicValue as E, toJsonSchema as F, CopilotIcon as G, CopilotChatConfigurationProvider as H, defineToolCallRenderer as I, StreamingMarkdownDefaultRenderer as J, IconSvg as K, MarkdownRendererProvider as L, catalogIdsOf as M, componentCatalogIds as N, isRecord as O, createGenerativeUI as P, useMarkdownRenderer as R, isAsyncIssue as S, withoutRejectedNulls as T, useCopilotChatConfiguration as U, ControlledModalOpenScope as V, useShallowStableRef as W, GenerativeUINodeContext as _, GenerativeUIToolCallRenderer as a, useRequiredGenerativeUIRuntime as b, SurfaceView as c, namedRole as d, useGenerativeUIAccessibility as f, useManagerVersion as g, useGenerativeUIState as h, GenerativeUIChatSlotContext as i, GenerativeUIError as j, BASIC_FUNCTIONS as k, DARK_THEME_CSS as l, useGenerativeUIFunction as m, ProviderMarkdown as n, createGenerativeUIActivityRenderer as o, wrapperAria as p, cn as q, DefaultGenerativeUIChatCard as r, createGenerativeUIFunctionCallActivityRenderer as s, MarkdownSurfaces as t, controlAria as u, GenerativeUIRuntimeContext as v, validateSchemaSync as w, formatIssues as x, useGenerativeUIRuntime as y, isReactComponentType as z };
3588
+ //# sourceMappingURL=MarkdownSurfaces-DveOwhaW.mjs.map