@copilotkit/react-core 1.84.2-canary.1793807121 → 1.84.2-canary.openbot-intel-fixes

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 (48) hide show
  1. package/README.md +1 -1
  2. package/dist/MarkdownSurfaces-3cGU5_0H.cjs +1619 -0
  3. package/dist/MarkdownSurfaces-3cGU5_0H.cjs.map +1 -0
  4. package/dist/MarkdownSurfaces-D-W4f9Dy.mjs +1442 -0
  5. package/dist/MarkdownSurfaces-D-W4f9Dy.mjs.map +1 -0
  6. package/dist/{copilotkit-OVo9Xjmp.d.cts → copilotkit-CuTAoQF2.d.cts} +5 -5
  7. package/dist/{copilotkit-OVo9Xjmp.d.cts.map → copilotkit-CuTAoQF2.d.cts.map} +1 -1
  8. package/dist/{copilotkit-CP8oYU3L.cjs → copilotkit-DYtl9zj0.cjs} +56 -1347
  9. package/dist/copilotkit-DYtl9zj0.cjs.map +1 -0
  10. package/dist/{copilotkit-CFqSAotl.d.mts → copilotkit-Dn4PbHJV.d.mts} +5 -5
  11. package/dist/{copilotkit-CFqSAotl.d.mts.map → copilotkit-Dn4PbHJV.d.mts.map} +1 -1
  12. package/dist/{copilotkit-CdZ3W0B2.mjs → copilotkit-UHD9sXsS.mjs} +44 -1335
  13. package/dist/copilotkit-UHD9sXsS.mjs.map +1 -0
  14. package/dist/index.cjs +2 -2
  15. package/dist/index.d.cts +2 -2
  16. package/dist/index.d.mts +2 -2
  17. package/dist/index.mjs +2 -2
  18. package/dist/index.umd.js +165 -3347
  19. package/dist/index.umd.js.map +1 -1
  20. package/dist/runtime-context-DrVNUYLi.d.cts +228 -0
  21. package/dist/runtime-context-DrVNUYLi.d.cts.map +1 -0
  22. package/dist/runtime-context-Er5UIbZA.d.mts +228 -0
  23. package/dist/runtime-context-Er5UIbZA.d.mts.map +1 -0
  24. package/dist/v2/generative-ui.cjs +687 -2963
  25. package/dist/v2/generative-ui.cjs.map +1 -1
  26. package/dist/v2/generative-ui.d.cts +4506 -4712
  27. package/dist/v2/generative-ui.d.cts.map +1 -1
  28. package/dist/v2/generative-ui.d.mts +4506 -4712
  29. package/dist/v2/generative-ui.d.mts.map +1 -1
  30. package/dist/v2/generative-ui.mjs +299 -2585
  31. package/dist/v2/generative-ui.mjs.map +1 -1
  32. package/dist/v2/index.cjs +2 -20
  33. package/dist/v2/index.d.cts +3 -3
  34. package/dist/v2/index.d.mts +3 -3
  35. package/dist/v2/index.mjs +3 -3
  36. package/dist/v2/index.umd.js +149 -3349
  37. package/dist/v2/index.umd.js.map +1 -1
  38. package/package.json +11 -11
  39. package/dist/MarkdownSurfaces-DV9P0Gi9.mjs +0 -3573
  40. package/dist/MarkdownSurfaces-DV9P0Gi9.mjs.map +0 -1
  41. package/dist/MarkdownSurfaces-IUaWSJ0E.cjs +0 -3858
  42. package/dist/MarkdownSurfaces-IUaWSJ0E.cjs.map +0 -1
  43. package/dist/copilotkit-CP8oYU3L.cjs.map +0 -1
  44. package/dist/copilotkit-CdZ3W0B2.mjs.map +0 -1
  45. package/dist/runtime-context-CrHq-iTf.d.mts +0 -924
  46. package/dist/runtime-context-CrHq-iTf.d.mts.map +0 -1
  47. package/dist/runtime-context-D3NcP9oE.d.cts +0 -924
  48. package/dist/runtime-context-D3NcP9oE.d.cts.map +0 -1
@@ -0,0 +1,1442 @@
1
+ import React, { Component, createContext, memo, useCallback, useContext, useEffect, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
2
+ import { splitA2UIMarkdown } from "@copilotkit/core";
3
+ import { A2UI_COMPONENT_ENVELOPE_KEYS, DEFAULT_AGENT_ID, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_CHAT_TARGET, GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE, GENERATIVE_UI_RENDER_TOOL, GENERATIVE_UI_ROOT_ID, isActionBinding, isPathBinding, mapAtChildRef, randomUUID } from "@copilotkit/shared";
4
+ import { CopilotKitContext, useCopilotKit, useDefaultAgentId } from "@copilotkit/react-core/v2/context";
5
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
6
+ import { Streamdown } from "streamdown";
7
+ import { z } from "zod";
8
+ import { accessibilityAttributes, accessibilityAttributes as accessibilityAttributes$1, controlAria, getMarkdownSurfaceSource, invokeBoundEvent, invokeMatchedEvent, joinPath, namedRole, readAccessibility, reportErrorSafely, resolvePath, tryResolveDynamicValue, wrapperAria } from "@copilotkit/core/generative-ui";
9
+ import { catalogIdsOf, createGenerativeUI, formatIssues, isAsyncIssue, issueKey, setterNameOf, themeStyleSheet, validateSchema, validateSchemaSync, withoutRejectedNulls } from "@copilotkit/shared/generative-ui";
10
+
11
+ //#region src/v2/lib/shallow-stable-ref.ts
12
+ /**
13
+ * Shallow equality comparison for objects.
14
+ */
15
+ function shallowEqual(obj1, obj2) {
16
+ const keys1 = Object.keys(obj1);
17
+ const keys2 = Object.keys(obj2);
18
+ if (keys1.length !== keys2.length) return false;
19
+ for (const key of keys1) if (obj1[key] !== obj2[key]) return false;
20
+ return true;
21
+ }
22
+ /**
23
+ * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
24
+ * class instances, and other exotic objects that happen to have typeof "object".
25
+ */
26
+ function isPlainObject(obj) {
27
+ return obj !== null && typeof obj === "object" && Object.prototype.toString.call(obj) === "[object Object]";
28
+ }
29
+ /**
30
+ * Returns the same reference as long as the value is shallowly equal to the
31
+ * previous render's value.
32
+ *
33
+ * - Identical references bail out immediately (O(1)).
34
+ * - Plain objects ({}) are shallow-compared key-by-key.
35
+ * - Arrays, Dates, class instances, functions, and primitives are compared by
36
+ * reference only — shallowEqual is never called on non-plain objects, which
37
+ * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).
38
+ *
39
+ * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow
40
+ * equality check isn't defeated by a new object reference on every render.
41
+ */
42
+ function useShallowStableRef(value) {
43
+ const ref = useRef(value);
44
+ if (ref.current === value) return ref.current;
45
+ if (isPlainObject(ref.current) && isPlainObject(value)) {
46
+ if (shallowEqual(ref.current, value)) return ref.current;
47
+ }
48
+ ref.current = value;
49
+ return ref.current;
50
+ }
51
+
52
+ //#endregion
53
+ //#region src/v2/providers/CopilotChatConfigurationProvider.tsx
54
+ const CopilotChatDefaultLabels = {
55
+ chatInputPlaceholder: "Type a message...",
56
+ chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
57
+ chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
58
+ chatInputToolbarFinishTranscribeButtonLabel: "Finish",
59
+ chatInputToolbarAddButtonLabel: "Add attachments",
60
+ chatInputToolbarToolsButtonLabel: "Tools",
61
+ chatInputToolbarSendButtonLabel: "Send message",
62
+ chatInputToolbarStopButtonLabel: "Stop",
63
+ assistantMessageToolbarCopyCodeLabel: "Copy",
64
+ assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
65
+ assistantMessageToolbarCopyMessageLabel: "Copy",
66
+ assistantMessageToolbarInspectorLabel: "View in Inspector",
67
+ assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
68
+ assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
69
+ assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
70
+ assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
71
+ assistantMessageToolbarInspectorHideLabel: "Hide this icon",
72
+ assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
73
+ assistantMessageToolbarThumbsUpLabel: "Good response",
74
+ assistantMessageToolbarThumbsDownLabel: "Bad response",
75
+ assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
76
+ assistantMessageFeedbackCommentSubmitLabel: "Send comment",
77
+ assistantMessageToolbarReadAloudLabel: "Read aloud",
78
+ assistantMessageToolbarRegenerateLabel: "Regenerate",
79
+ userMessageToolbarCopyMessageLabel: "Copy",
80
+ userMessageToolbarEditMessageLabel: "Edit",
81
+ userMessageToolbarPreviousBranchLabel: "Previous branch",
82
+ userMessageToolbarNextBranchLabel: "Next branch",
83
+ chatDisclaimerText: "AI can make mistakes. Please verify important information.",
84
+ chatToggleOpenLabel: "Open chat",
85
+ chatToggleCloseLabel: "Close chat",
86
+ chatScrollToBottomLabel: "Scroll to bottom",
87
+ chatConnectingLabel: "Loading conversation",
88
+ modalHeaderTitle: "CopilotKit Chat",
89
+ welcomeMessageText: "How can I help you today?",
90
+ reasoningMessageThinkingLabel: "Thinking…",
91
+ chatInputSlashMenuLabel: "Slash commands",
92
+ chatInputSlashMenuEmptyText: "No commands found",
93
+ attachmentRemoveButtonLabel: "Remove attachment",
94
+ attachmentPlayVideoButtonLabel: "Play video",
95
+ attachmentPreviewCloseButtonLabel: "Close preview",
96
+ modalHeaderCloseButtonLabel: "Close",
97
+ modalHeaderThreadsButtonLabel: "Open threads",
98
+ sidebarLabel: "Copilot chat sidebar"
99
+ };
100
+ /**
101
+ * Mobile breakpoint below which the chat modal and the thread-list drawer are
102
+ * mutually exclusive. At or above this width both surfaces may coexist. This
103
+ * mirrors the `(max-width: 767px)` / `(min-width: 768px)` split already used by
104
+ * CopilotChatInput and CopilotSidebarView.
105
+ */
106
+ const MOBILE_MAX_WIDTH_PX = 767;
107
+ /**
108
+ * Reports whether the current viewport is in the mobile range (`<768px`), where
109
+ * the chat modal and drawer must not be open simultaneously. SSR-safe and
110
+ * defensive against environments without `matchMedia` (treated as desktop, so
111
+ * no mutual-exclusion constraint is applied).
112
+ *
113
+ * @returns `true` when the viewport is mobile-width, `false` otherwise.
114
+ */
115
+ function isMobileViewport() {
116
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
117
+ return window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH_PX}px)`).matches;
118
+ }
119
+ const CopilotChatConfiguration = createContext(null);
120
+ const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
121
+ const parentConfig = useContext(CopilotChatConfiguration);
122
+ const stableLabels = useShallowStableRef(labels);
123
+ const mergedLabels = useMemo(() => ({
124
+ ...CopilotChatDefaultLabels,
125
+ ...parentConfig?.labels,
126
+ ...stableLabels
127
+ }), [stableLabels, parentConfig?.labels]);
128
+ const providerAgentId = useDefaultAgentId();
129
+ const resolvedAgentId = agentId ?? parentConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;
130
+ const threadIdPropIsAuthoritative = threadId !== void 0 && hasExplicitThreadId !== false;
131
+ const isThreadIdControlled = threadIdPropIsAuthoritative;
132
+ const [activeThreadOverride, setActiveThreadOverride] = useState(null);
133
+ const resolvedThreadId = useMemo(() => {
134
+ if (threadIdPropIsAuthoritative) return threadId;
135
+ if (activeThreadOverride) return activeThreadOverride.threadId;
136
+ if (parentConfig?.threadId) return parentConfig.threadId;
137
+ if (threadId) return threadId;
138
+ return randomUUID();
139
+ }, [
140
+ threadIdPropIsAuthoritative,
141
+ threadId,
142
+ parentConfig?.threadId,
143
+ activeThreadOverride
144
+ ]);
145
+ const copilotkit = useContext(CopilotKitContext)?.copilotkit;
146
+ const openThreadRef = useRef(null);
147
+ const latestThreadIdRef = useRef(resolvedThreadId);
148
+ latestThreadIdRef.current = resolvedThreadId;
149
+ useEffect(() => {
150
+ if (copilotkit === void 0) return;
151
+ const registration = copilotkit.registerOpenThread({
152
+ agentId: resolvedAgentId,
153
+ threadId: latestThreadIdRef.current
154
+ });
155
+ openThreadRef.current = registration;
156
+ return () => {
157
+ registration.unregister();
158
+ openThreadRef.current = null;
159
+ };
160
+ }, [copilotkit, resolvedAgentId]);
161
+ useEffect(() => {
162
+ openThreadRef.current?.update(resolvedThreadId);
163
+ }, [resolvedThreadId]);
164
+ const resolvedHasExplicitThreadId = (threadIdPropIsAuthoritative ? true : activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false) || !!parentConfig?.hasExplicitThreadId;
165
+ const [internalModalOpen, setInternalModalOpen] = useState(isModalDefaultOpen ?? true);
166
+ const hasExplicitDefault = isModalDefaultOpen !== void 0;
167
+ const setAndSync = useCallback((open) => {
168
+ setInternalModalOpen(open);
169
+ parentConfig?.setModalOpen(open);
170
+ }, [parentConfig?.setModalOpen]);
171
+ const isMounted = useRef(false);
172
+ useEffect(() => {
173
+ if (!hasExplicitDefault) return;
174
+ if (!isMounted.current) {
175
+ isMounted.current = true;
176
+ return;
177
+ }
178
+ if (parentConfig?.isModalOpen === void 0) return;
179
+ setInternalModalOpen(parentConfig.isModalOpen);
180
+ }, [parentConfig?.isModalOpen, hasExplicitDefault]);
181
+ const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : parentConfig?.isModalOpen ?? internalModalOpen;
182
+ const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : parentConfig?.setModalOpen ?? setInternalModalOpen;
183
+ const [ownDrawerOpen, setOwnDrawerOpen] = useState(false);
184
+ const [ownDrawerCount, setOwnDrawerCount] = useState(0);
185
+ const modalCloseRef = useRef(() => {});
186
+ modalCloseRef.current = resolvedSetModalOpen;
187
+ const registeredModalClosersRef = useRef([]);
188
+ const ownRegisterModalCloser = useCallback((closeModal) => {
189
+ registeredModalClosersRef.current.push(closeModal);
190
+ return () => {
191
+ registeredModalClosersRef.current = registeredModalClosersRef.current.filter((entry) => entry !== closeModal);
192
+ };
193
+ }, []);
194
+ const ownSetDrawerOpen = useCallback((open) => {
195
+ setOwnDrawerOpen(open);
196
+ if (open && isMobileViewport()) {
197
+ const registered = registeredModalClosersRef.current;
198
+ (registered.length > 0 ? registered[registered.length - 1] : modalCloseRef.current)(false);
199
+ }
200
+ }, []);
201
+ const ownRegisterDrawer = useCallback(() => {
202
+ setOwnDrawerCount((count) => count + 1);
203
+ return () => {
204
+ setOwnDrawerCount((count) => Math.max(0, count - 1));
205
+ };
206
+ }, []);
207
+ const resolvedDrawerOpen = parentConfig ? parentConfig.drawerOpen : ownDrawerOpen;
208
+ const resolvedSetDrawerOpen = parentConfig ? parentConfig.setDrawerOpen : ownSetDrawerOpen;
209
+ const resolvedDrawerRegistered = parentConfig ? parentConfig.drawerRegistered : ownDrawerCount > 0;
210
+ const resolvedRegisterDrawer = parentConfig ? parentConfig.registerDrawer : ownRegisterDrawer;
211
+ const resolvedRegisterModalCloser = parentConfig ? parentConfig.ɵregisterModalCloser : ownRegisterModalCloser;
212
+ useEffect(() => {
213
+ if (!hasExplicitDefault) return;
214
+ return resolvedRegisterModalCloser(resolvedSetModalOpen);
215
+ }, [
216
+ hasExplicitDefault,
217
+ resolvedRegisterModalCloser,
218
+ resolvedSetModalOpen
219
+ ]);
220
+ const isThreadIdControlledRef = useRef(isThreadIdControlled);
221
+ isThreadIdControlledRef.current = isThreadIdControlled;
222
+ const ownSetActiveThreadId = useCallback((id, options) => {
223
+ setActiveThreadOverride({
224
+ threadId: id,
225
+ explicit: options?.explicit ?? true
226
+ });
227
+ }, []);
228
+ const ownStartNewThread = useCallback(() => {
229
+ setActiveThreadOverride({
230
+ threadId: randomUUID(),
231
+ explicit: false
232
+ });
233
+ }, []);
234
+ const parentSetActiveThreadId = parentConfig?.setActiveThreadId;
235
+ const parentStartNewThread = parentConfig?.startNewThread;
236
+ const resolvedSetActiveThreadId = useCallback((id, options) => {
237
+ if (isThreadIdControlledRef.current) {
238
+ console.warn("[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
239
+ return;
240
+ }
241
+ if (parentSetActiveThreadId) {
242
+ parentSetActiveThreadId(id, options);
243
+ return;
244
+ }
245
+ ownSetActiveThreadId(id, options);
246
+ }, [parentSetActiveThreadId, ownSetActiveThreadId]);
247
+ const resolvedStartNewThread = useCallback(() => {
248
+ if (isThreadIdControlledRef.current) {
249
+ console.warn("[CopilotKit] Ignoring startNewThread(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
250
+ return;
251
+ }
252
+ if (parentStartNewThread) {
253
+ parentStartNewThread();
254
+ return;
255
+ }
256
+ ownStartNewThread();
257
+ }, [parentStartNewThread, ownStartNewThread]);
258
+ const setModalOpenWithDrawerExclusion = useCallback((open) => {
259
+ if (open && isMobileViewport()) resolvedSetDrawerOpen(false);
260
+ resolvedSetModalOpen(open);
261
+ }, [resolvedSetModalOpen, resolvedSetDrawerOpen]);
262
+ const configurationValue = useMemo(() => ({
263
+ labels: mergedLabels,
264
+ agentId: resolvedAgentId,
265
+ threadId: resolvedThreadId,
266
+ hasExplicitThreadId: resolvedHasExplicitThreadId,
267
+ isModalOpen: resolvedIsModalOpen,
268
+ setModalOpen: setModalOpenWithDrawerExclusion,
269
+ drawerOpen: resolvedDrawerOpen,
270
+ setDrawerOpen: resolvedSetDrawerOpen,
271
+ drawerRegistered: resolvedDrawerRegistered,
272
+ registerDrawer: resolvedRegisterDrawer,
273
+ ɵregisterModalCloser: resolvedRegisterModalCloser,
274
+ setActiveThreadId: resolvedSetActiveThreadId,
275
+ startNewThread: resolvedStartNewThread
276
+ }), [
277
+ mergedLabels,
278
+ resolvedAgentId,
279
+ resolvedThreadId,
280
+ resolvedHasExplicitThreadId,
281
+ resolvedIsModalOpen,
282
+ setModalOpenWithDrawerExclusion,
283
+ resolvedDrawerOpen,
284
+ resolvedSetDrawerOpen,
285
+ resolvedDrawerRegistered,
286
+ resolvedRegisterDrawer,
287
+ resolvedRegisterModalCloser,
288
+ resolvedSetActiveThreadId,
289
+ resolvedStartNewThread
290
+ ]);
291
+ return /* @__PURE__ */ jsx(CopilotChatConfiguration.Provider, {
292
+ value: configurationValue,
293
+ children
294
+ });
295
+ };
296
+ const useCopilotChatConfiguration = () => {
297
+ return useContext(CopilotChatConfiguration);
298
+ };
299
+ /**
300
+ * Reports modal open/close requests to the host, and — when `open` is
301
+ * supplied — makes the modal state of an already-established chat
302
+ * configuration **controlled** for the subtree it wraps.
303
+ *
304
+ * This is deliberately a scope component rather than another mode inside
305
+ * {@link CopilotChatConfigurationProvider}. The provider resolves modal state
306
+ * across a nested chain (own state, parent sync, drawer mutual-exclusion, the
307
+ * modal-closer registry); a controlled branch inside that resolution would add
308
+ * a fourth interacting mode. Overriding the context for the subtree instead
309
+ * leaves every one of those paths untouched:
310
+ *
311
+ * - `isModalOpen` is replaced with the host's `open`, so the rendered surface
312
+ * follows the prop from the very first frame (no open-then-close flash).
313
+ * - `setModalOpen` still calls the underlying setter, so the existing
314
+ * parent-sync and drawer mutual-exclusion side effects continue to run, and
315
+ * *then* reports the request through `onOpenChange`.
316
+ * - The wrapped setter is registered as the modal closer, so the drawer's
317
+ * mobile mutual-exclusion reaches the host instead of silently flipping
318
+ * state that nothing displays.
319
+ *
320
+ * A host that supplies `open` and ignores `onOpenChange` gets a modal pinned
321
+ * to `open`, which is the standard controlled-component contract. A host that
322
+ * supplies only `onOpenChange` is notified while the modal keeps managing
323
+ * itself.
324
+ *
325
+ * Renders `children` unchanged when no chat configuration is in scope.
326
+ */
327
+ const ControlledModalOpenScope = ({ children, open, onOpenChange }) => {
328
+ const parentConfig = useContext(CopilotChatConfiguration);
329
+ const parentSetModalOpen = parentConfig?.setModalOpen;
330
+ const registerModalCloser = parentConfig?.ɵregisterModalCloser;
331
+ const setModalOpen = useCallback((next) => {
332
+ parentSetModalOpen?.(next);
333
+ onOpenChange?.(next);
334
+ }, [parentSetModalOpen, onOpenChange]);
335
+ useEffect(() => {
336
+ if (!registerModalCloser) return;
337
+ return registerModalCloser(setModalOpen);
338
+ }, [registerModalCloser, setModalOpen]);
339
+ const configurationValue = useMemo(() => parentConfig ? {
340
+ ...parentConfig,
341
+ isModalOpen: open ?? parentConfig.isModalOpen,
342
+ setModalOpen
343
+ } : null, [
344
+ parentConfig,
345
+ open,
346
+ setModalOpen
347
+ ]);
348
+ if (!configurationValue) return /* @__PURE__ */ jsx(Fragment$1, { children });
349
+ return /* @__PURE__ */ jsx(CopilotChatConfiguration.Provider, {
350
+ value: configurationValue,
351
+ children
352
+ });
353
+ };
354
+ ControlledModalOpenScope.displayName = "ControlledModalOpenScope";
355
+
356
+ //#endregion
357
+ //#region src/v2/hooks/useKatexStyles.ts
358
+ let injected = false;
359
+ /**
360
+ * Dynamically injects KaTeX CSS at runtime to avoid the Next.js
361
+ * "Global CSS cannot be imported from within node_modules" build error.
362
+ *
363
+ * Uses a singleton flag so the stylesheet is only injected once.
364
+ */
365
+ function useKatexStyles() {
366
+ useEffect(() => {
367
+ if (injected || typeof document === "undefined") return;
368
+ injected = true;
369
+ import("katex/dist/katex.min.css").catch(() => {
370
+ console.warn("[CopilotKit] Failed to load katex styles — math content may render without formatting");
371
+ });
372
+ }, []);
373
+ }
374
+
375
+ //#endregion
376
+ //#region src/v2/types/defineToolCallRenderer.ts
377
+ function defineToolCallRenderer(def) {
378
+ const argsSchema = def.name === "*" && !def.args ? z.any() : def.args;
379
+ return {
380
+ name: def.name,
381
+ args: argsSchema,
382
+ render: def.render,
383
+ ...def.agentId ? { agentId: def.agentId } : {},
384
+ ...def.group ? { group: true } : {}
385
+ };
386
+ }
387
+
388
+ //#endregion
389
+ //#region src/v2/generative-ui/catalog.ts
390
+ /**
391
+ * Experimental. Declares the components the model can render, the app state
392
+ * they read, and the functions they call.
393
+ *
394
+ * - A prop with the name of a top-level state key is bound to that state.
395
+ * - `bind: { prop: (state, props) => value }` binds a prop to a selector.
396
+ * - An event binds to the function with its name, else to the name without
397
+ * `on` (`onAddToCart` calls `addToCart`).
398
+ * - `writable: ["value"]` gives the component a `setValue` prop. See
399
+ * `GenerativeUIComponentDefinition.writable`.
400
+ *
401
+ * The model does not see bound props or matched events.
402
+ *
403
+ * @param config - `id`, then optional `extends`, `state`, `functions` and
404
+ * `overrides`, then `components`. Put `state` before `components`, so the selectors
405
+ * get typed state.
406
+ * @throws Error when a name comes from two places, an override names no
407
+ * component of the bases, `props` is not an object
408
+ * schema with a JSON Schema, a key is reserved or used
409
+ * twice on a component, an event matches two functions, an unmatched event
410
+ * has no `parameters`, a `bind` key is not a prop, a `writable` key is not
411
+ * a prop or is a bound prop, or a setter name is already a key of the
412
+ * component. Also throws when `parameterOrder` contains duplicate or unknown
413
+ * keys, or an ordered component declares integer-index keys whose JSON object
414
+ * enumeration order cannot be controlled.
415
+ *
416
+ * @example
417
+ * ```ts
418
+ * const ui = createGenerativeUI({
419
+ * id: "acme/store@1",
420
+ * state: { cart: cartSchema },
421
+ * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },
422
+ * components: {
423
+ * CartSummary: {
424
+ * component: CartSummary,
425
+ * props: z.object({ count: z.number() }),
426
+ * bind: { count: (state) => state.cart.count },
427
+ * },
428
+ * },
429
+ * });
430
+ * ```
431
+ */
432
+ function createGenerativeUI$1(config) {
433
+ return createGenerativeUI(config);
434
+ }
435
+
436
+ //#endregion
437
+ //#region src/v2/generative-ui/runtime-context.ts
438
+ const GenerativeUIRuntimeContext = createContext(null);
439
+ function useGenerativeUIRuntime() {
440
+ return useContext(GenerativeUIRuntimeContext);
441
+ }
442
+ function useRequiredGenerativeUIRuntime() {
443
+ const runtime = useContext(GenerativeUIRuntimeContext);
444
+ if (!runtime) throw new Error("Generative UI components must be rendered inside <CopilotKitProvider generativeUI={{ ui }}>.");
445
+ return runtime;
446
+ }
447
+ const GenerativeUINodeContext = createContext(null);
448
+
449
+ //#endregion
450
+ //#region src/v2/generative-ui/hooks.ts
451
+ const noopSubscribe$1 = () => () => {};
452
+ const zero = () => 0;
453
+ /** Re-renders on any surface-manager change. */
454
+ function useManagerVersion(runtime) {
455
+ return useSyncExternalStore(runtime?.manager.subscribe ?? noopSubscribe$1, runtime?.manager.getVersion ?? zero, zero);
456
+ }
457
+ /**
458
+ * Experimental. Gives one key of the app state declared in
459
+ * `createGenerativeUI({ state })` its value. Bound props of generated
460
+ * components read it. The model does not see it.
461
+ *
462
+ * The key is set on mount and when the value changes (compared as JSON). It
463
+ * is removed on unmount.
464
+ *
465
+ * @param ui - The object from `createGenerativeUI`. It gives the key and the
466
+ * value their types.
467
+ * @param key - A top-level key of `state`.
468
+ * @param value - The value of that key. It must fit the key's schema.
469
+ *
470
+ * @example
471
+ * ```tsx
472
+ * useGenerativeUIState(storeUI, "cart", { count, total, coupon, items });
473
+ * ```
474
+ */
475
+ function useGenerativeUIState(ui, key, value) {
476
+ const runtime = useRequiredGenerativeUIRuntime();
477
+ const serialized = JSON.stringify(value);
478
+ useEffect(() => {
479
+ const raw = JSON.parse(serialized ?? "null");
480
+ let current = true;
481
+ const apply = (parsed) => {
482
+ if (!current) return;
483
+ if (parsed.success) {
484
+ runtime.manager.setState(key, parsed.data);
485
+ return;
486
+ }
487
+ runtime.manager.removeState(key);
488
+ if (process.env.NODE_ENV !== "production") console.error(`[generativeUI] useGenerativeUIState: invalid value for "${key}": ${formatIssues(parsed.issues, "value")}`);
489
+ };
490
+ const schema = runtime.ui.state.get(key);
491
+ const parsed = schema ? validateSchema(schema, raw) : {
492
+ success: true,
493
+ data: raw
494
+ };
495
+ if (parsed instanceof Promise) parsed.then(apply);
496
+ else apply(parsed);
497
+ return () => {
498
+ current = false;
499
+ };
500
+ }, [
501
+ runtime,
502
+ key,
503
+ serialized
504
+ ]);
505
+ useEffect(() => () => runtime.manager.removeState(key), [runtime, key]);
506
+ }
507
+ /**
508
+ * Experimental. Mounts the handler of a function declared in
509
+ * `createGenerativeUI({ functions })`. Generated UI can call the function
510
+ * only while exactly one handler for it is mounted.
511
+ *
512
+ * The handler gets the parsed arguments: schema defaults are set. It can
513
+ * change on each render. The latest handler always runs, and the hook does
514
+ * not register again.
515
+ *
516
+ * @param ui - The object from `createGenerativeUI`. It gives the name and the
517
+ * handler arguments their types.
518
+ * @param name - A key of `functions`.
519
+ * @param handler - Runs when generated UI calls the function. Its return
520
+ * value goes back to the caller as `{ ok: true, result }`.
521
+ *
522
+ * @example
523
+ * ```tsx
524
+ * useGenerativeUIFunction(storeUI, "addToCart", ({ productId, quantity }) =>
525
+ * cart.addItem(productId, quantity),
526
+ * );
527
+ * ```
528
+ */
529
+ function useGenerativeUIFunction(ui, name, handler) {
530
+ const runtime = useRequiredGenerativeUIRuntime();
531
+ const latest = useRef(handler);
532
+ latest.current = handler;
533
+ useEffect(() => runtime.dispatcher.register(name, latest), [runtime, name]);
534
+ }
535
+
536
+ //#endregion
537
+ //#region src/v2/generative-ui/boundaries.tsx
538
+ function DefaultNodeFallback({ message, componentId, retry }) {
539
+ return /* @__PURE__ */ jsxs("div", {
540
+ role: "alert",
541
+ "data-generative-ui-error": componentId,
542
+ style: {
543
+ border: "1px solid #fca5a5",
544
+ background: "#fef2f2",
545
+ color: "#991b1b",
546
+ borderRadius: 8,
547
+ padding: "8px 12px",
548
+ fontSize: 13
549
+ },
550
+ children: [
551
+ "Couldn’t display this part: ",
552
+ message,
553
+ retry && /* @__PURE__ */ jsx("button", {
554
+ type: "button",
555
+ onClick: retry,
556
+ style: {
557
+ marginLeft: 8,
558
+ textDecoration: "underline"
559
+ },
560
+ children: "Retry"
561
+ })
562
+ ]
563
+ });
564
+ }
565
+ /**
566
+ * A child that has not streamed yet renders nothing. The prose keeps
567
+ * streaming above the surface, and each component appears as soon as it is
568
+ * complete. A grey block in its place would read as a broken layout.
569
+ */
570
+ function NodePlaceholder(_props) {
571
+ return null;
572
+ }
573
+ /** Per-node boundary. Resets on retry or a new agent revision, not on data ticks. */
574
+ var NodeBoundary = class extends Component {
575
+ constructor(..._args) {
576
+ super(..._args);
577
+ this.state = {
578
+ error: null,
579
+ revision: this.props.revision
580
+ };
581
+ this.retry = () => this.setState({ error: null });
582
+ }
583
+ static getDerivedStateFromError(error) {
584
+ return { error };
585
+ }
586
+ static getDerivedStateFromProps(props, state) {
587
+ return props.revision !== state.revision ? {
588
+ error: null,
589
+ revision: props.revision
590
+ } : null;
591
+ }
592
+ componentDidCatch(error) {
593
+ const { runtime, surfaceId, componentId } = this.props;
594
+ reportErrorSafely(runtime, {
595
+ kind: "render",
596
+ surfaceId,
597
+ componentId,
598
+ error
599
+ });
600
+ }
601
+ render() {
602
+ const { error } = this.state;
603
+ if (!error) return this.props.children;
604
+ const { runtime, surfaceId, componentId } = this.props;
605
+ const fallback = runtime.errorFallback;
606
+ return fallback ? fallback({
607
+ error,
608
+ retry: this.retry,
609
+ surfaceId,
610
+ componentId
611
+ }) : /* @__PURE__ */ jsx(DefaultNodeFallback, {
612
+ message: error.message,
613
+ componentId,
614
+ retry: this.retry
615
+ });
616
+ }
617
+ };
618
+ /** Outer boundary: a failure here must not reach the chat or the host page. */
619
+ var SurfaceBoundary = class extends Component {
620
+ constructor(..._args2) {
621
+ super(..._args2);
622
+ this.state = { error: null };
623
+ }
624
+ static getDerivedStateFromError(error) {
625
+ return { error };
626
+ }
627
+ componentDidCatch(error) {
628
+ reportErrorSafely(this.props.runtime, {
629
+ kind: "render",
630
+ surfaceId: this.props.surfaceId,
631
+ error
632
+ });
633
+ }
634
+ render() {
635
+ if (!this.state.error) return this.props.children;
636
+ return /* @__PURE__ */ jsx(DefaultNodeFallback, {
637
+ message: "this generated UI failed to render",
638
+ componentId: "surface"
639
+ });
640
+ }
641
+ };
642
+
643
+ //#endregion
644
+ //#region src/v2/generative-ui/accessibility.ts
645
+ /**
646
+ * Experimental. The ARIA attributes of the `accessibility` that the model
647
+ * gave the component being rendered, to spread on its root element. The
648
+ * standard components do this; a custom component does it itself:
649
+ *
650
+ * @example
651
+ * ```tsx
652
+ * function Panel({ children }: { children?: ReactNode }) {
653
+ * const aria = useGenerativeUIAccessibility();
654
+ * return <section {...aria}>{children}</section>;
655
+ * }
656
+ * ```
657
+ *
658
+ * Outside of generated UI it gives `{}`.
659
+ */
660
+ function useGenerativeUIAccessibility() {
661
+ const accessibility = useContext(GenerativeUINodeContext)?.accessibility;
662
+ return useMemo(() => accessibilityAttributes(accessibility), [accessibility]);
663
+ }
664
+
665
+ //#endregion
666
+ //#region src/v2/generative-ui/SurfaceView.tsx
667
+ const NO_ANCESTORS = [];
668
+ const ROOT_STYLE = { display: "contents" };
669
+ const undefinedSnapshot = () => void 0;
670
+ const noopSubscribe = () => () => {};
671
+ const zeroSnapshot = () => 0;
672
+ /** A "multiple" slot value that repeats a component for each list item. */
673
+ function isTemplateChildren(value) {
674
+ return typeof value === "object" && value !== null && "componentId" in value && typeof value.componentId === "string" && "path" in value && typeof value.path === "string";
675
+ }
676
+ function SurfaceView({ surface }) {
677
+ const runtime = useRequiredGenerativeUIRuntime();
678
+ const { theme } = runtime;
679
+ const sheet = useMemo(() => themeStyleSheet(theme), [theme]);
680
+ return /* @__PURE__ */ jsxs("div", {
681
+ className: "a2ui-surface",
682
+ "data-generative-ui-root": surface.surfaceId,
683
+ "data-a2ui-theme": sheet?.id,
684
+ style: ROOT_STYLE,
685
+ children: [sheet ? /* @__PURE__ */ jsx("style", { dangerouslySetInnerHTML: { __html: sheet.css } }) : null, /* @__PURE__ */ jsx(SurfaceBoundary, {
686
+ surfaceId: surface.surfaceId,
687
+ runtime,
688
+ children: /* @__PURE__ */ jsx(NodeView, {
689
+ surface,
690
+ componentId: GENERATIVE_UI_ROOT_ID,
691
+ basePath: void 0,
692
+ ancestors: NO_ANCESTORS
693
+ })
694
+ })]
695
+ });
696
+ }
697
+ /**
698
+ * Resolves a component by id. Subscribes to the manager rather than web_core's
699
+ * `onCreated`/`onDeleted`: web_core's EventEmitter awaits each listener in turn,
700
+ * so with several subscribers (one per slotted child, or one per mount of the
701
+ * same surface) all but the first are notified a microtask late. That is only
702
+ * visible inside synchronous flushes such as `act()` / `flushSync`, where the
703
+ * old tree would still be on screen, but it makes updates order-dependent.
704
+ * The manager notifies synchronously once an ingest has been fully applied.
705
+ */
706
+ function useComponentModel(manager, model, id) {
707
+ return useSyncExternalStore(manager.subscribe, () => model.componentsModel.get(id), undefinedSnapshot);
708
+ }
709
+ /** Same reasoning as `useComponentModel`: never rely on web_core's emitters. */
710
+ function useComponentProperties(manager, component) {
711
+ return useSyncExternalStore(manager.subscribe, () => component?.properties, undefinedSnapshot);
712
+ }
713
+ /**
714
+ * The id of a node in the ancestor list. A template renders the same
715
+ * component once per item, so the item path is part of the id. A real cycle
716
+ * repeats both.
717
+ */
718
+ function scopedId(componentId, basePath) {
719
+ return `${basePath ?? ""}#${componentId}`;
720
+ }
721
+ const NodeView = memo(function NodeView({ surface, componentId, basePath, ancestors }) {
722
+ const runtime = useRequiredGenerativeUIRuntime();
723
+ const component = useComponentModel(runtime.manager, surface.model, componentId);
724
+ const properties = useComponentProperties(runtime.manager, component);
725
+ if (ancestors.includes(scopedId(componentId, basePath))) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
726
+ message: `cyclic reference to ${componentId}`,
727
+ componentId
728
+ });
729
+ if (!component || !properties) return /* @__PURE__ */ jsx(NodePlaceholder, { componentId });
730
+ const definition = runtime.ui.components.get(component.type);
731
+ if (!definition) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
732
+ message: `unknown component "${component.type}"`,
733
+ componentId
734
+ });
735
+ return /* @__PURE__ */ jsx(NodeBoundary, {
736
+ surfaceId: surface.surfaceId,
737
+ componentId,
738
+ revision: properties,
739
+ runtime,
740
+ children: /* @__PURE__ */ jsx(ResolvedNode, {
741
+ surface,
742
+ componentId,
743
+ definition,
744
+ properties,
745
+ runtime,
746
+ basePath,
747
+ ancestors
748
+ })
749
+ }, component.type);
750
+ });
751
+ /**
752
+ * Renders the component of a template once for each item of the list at the
753
+ * template path, keyed by index. Renders nothing when there is no list.
754
+ */
755
+ function TemplateChildren({ surface, template, basePath, ancestors }) {
756
+ const dataModel = surface.model.dataModel;
757
+ const listPath = resolvePath(template.path, basePath);
758
+ const subscribe = useCallback((onChange) => {
759
+ const subscription = dataModel.subscribe(listPath, onChange);
760
+ return () => subscription.unsubscribe();
761
+ }, [dataModel, listPath]);
762
+ const getCount = () => {
763
+ const list = dataModel.get(listPath);
764
+ return Array.isArray(list) ? list.length : 0;
765
+ };
766
+ const count = useSyncExternalStore(subscribe, getCount, zeroSnapshot);
767
+ return /* @__PURE__ */ jsx(Fragment$1, { children: Array.from({ length: count }, (_, index) => index).map((index) => /* @__PURE__ */ jsx(NodeView, {
768
+ surface,
769
+ componentId: template.componentId,
770
+ basePath: joinPath(listPath, String(index)),
771
+ ancestors
772
+ }, index)) });
773
+ }
774
+ /**
775
+ * The props the model sets, with their dynamic values resolved from the
776
+ * surface data model: `{"@path"}` bindings, `{"@call"}` function values and
777
+ * `{"@call":"@index"}` in a template, at any depth. A literal writable prop
778
+ * that the component set shows the local value from `overrides`. Bound
779
+ * props, events and slots are left out, and so are the keys of the A2UI
780
+ * component envelope; `accessibility` is resolved the same way and given
781
+ * on its own.
782
+ *
783
+ * A prop is resolved again only when its raw value or a data model value it
784
+ * read has changed, so the result keeps its identity otherwise. A function
785
+ * value that cannot be computed gives a problem instead of values.
786
+ */
787
+ function useModelDataProps(surface, definition, properties, basePath, overrides) {
788
+ const dataModel = surface.model.dataModel;
789
+ const units = useMemo(() => {
790
+ const list = [];
791
+ for (const key of Object.keys(properties)) {
792
+ if (definition.events?.[key] || definition.slots?.[key] || Object.hasOwn(definition.selectors, key) || A2UI_COMPONENT_ENVELOPE_KEYS.has(key)) continue;
793
+ list.push({
794
+ key,
795
+ raw: properties[key]
796
+ });
797
+ }
798
+ const a11y = properties.accessibility;
799
+ if (typeof a11y === "object" && a11y !== null && !Array.isArray(a11y)) for (const [field, raw] of Object.entries(a11y)) list.push({
800
+ key: `accessibility/${field}`,
801
+ raw,
802
+ field
803
+ });
804
+ return list;
805
+ }, [properties, definition]);
806
+ const [, rerender] = useReducer((n) => n + 1, 0);
807
+ const cache = useRef(/* @__PURE__ */ new Map());
808
+ const values = {};
809
+ const a11yValues = {};
810
+ const paths = /* @__PURE__ */ new Set();
811
+ let problem;
812
+ const next = /* @__PURE__ */ new Map();
813
+ for (const { key, raw, field } of units) {
814
+ const cached = cache.current.get(key);
815
+ const isFresh = cached !== void 0 && cached.raw === raw && cached.basePath === basePath && [...cached.reads].every(([path, value]) => Object.is(dataModel.get(path), value));
816
+ const resolve = () => {
817
+ const resolved = tryResolveDynamicValue(raw, {
818
+ data: dataModel,
819
+ basePath
820
+ }, { isChecks: key === "checks" });
821
+ const reads = /* @__PURE__ */ new Map();
822
+ for (const path of resolved.paths) reads.set(path, dataModel.get(path));
823
+ return {
824
+ raw,
825
+ basePath,
826
+ reads,
827
+ outcome: resolved.ok ? {
828
+ ok: true,
829
+ value: resolved.value
830
+ } : {
831
+ ok: false,
832
+ message: resolved.error.message
833
+ }
834
+ };
835
+ };
836
+ const entry = isFresh && cached ? cached : resolve();
837
+ next.set(key, entry);
838
+ if (field !== void 0) {
839
+ if (entry.outcome.ok) a11yValues[field] = entry.outcome.value;
840
+ } else if (entry.outcome.ok) values[key] = entry.outcome.value;
841
+ else problem ??= `${key}: ${entry.outcome.message}`;
842
+ for (const path of entry.reads.keys()) paths.add(path);
843
+ }
844
+ cache.current = next;
845
+ const accessibility = readAccessibility(a11yValues);
846
+ for (const [key, value] of Object.entries(overrides)) if (!isPathBinding(properties[key])) values[key] = value;
847
+ const rendered = useRef(next);
848
+ rendered.current = next;
849
+ const pathKey = [...paths].sort().join("\n");
850
+ useEffect(() => {
851
+ const list = pathKey === "" ? [] : pathKey.split("\n");
852
+ const onChange = () => {
853
+ cache.current = /* @__PURE__ */ new Map();
854
+ rerender();
855
+ };
856
+ const subscriptions = list.map((path) => dataModel.subscribe(path, onChange));
857
+ if ([...rendered.current.values()].some((entry) => [...entry.reads].some(([path, value]) => !Object.is(dataModel.get(path), value)))) rerender();
858
+ return () => subscriptions.forEach((s) => s.unsubscribe());
859
+ }, [dataModel, pathKey]);
860
+ const stable = useRef({
861
+ ok: true,
862
+ values: {},
863
+ accessibility: void 0
864
+ });
865
+ const result = problem === void 0 ? {
866
+ ok: true,
867
+ values,
868
+ accessibility
869
+ } : {
870
+ ok: false,
871
+ problem
872
+ };
873
+ const last = stable.current;
874
+ if (!(result.ok && last.ok ? shallowEqual(last.values, result.values) && shallowEqual(last.accessibility ?? {}, result.accessibility ?? {}) : !result.ok && !last.ok && last.problem === result.problem)) stable.current = result;
875
+ return stable.current;
876
+ }
877
+ const NO_SELECTION = {
878
+ ok: true,
879
+ values: {}
880
+ };
881
+ function isSameSelection(a, b) {
882
+ if (a.ok && b.ok) return shallowEqual(a.values, b.values);
883
+ if (!a.ok && !b.ok) return a.problem === b.problem;
884
+ return false;
885
+ }
886
+ /** Runs every selector of a node. A selector that throws gives a problem. */
887
+ function select(definition, state, modelProps) {
888
+ const values = {};
889
+ const selectors = Object.entries(definition.selectors);
890
+ for (const [key, selector] of selectors) try {
891
+ values[key] = selector(state, modelProps);
892
+ } catch (error) {
893
+ return {
894
+ ok: false,
895
+ problem: `${key}: selector threw: ${error instanceof Error ? error.message : String(error)}`
896
+ };
897
+ }
898
+ return {
899
+ ok: true,
900
+ values
901
+ };
902
+ }
903
+ /**
904
+ * The values of the bound props of a node, read from the app state.
905
+ *
906
+ * The selectors run again only when the state object or the parsed model
907
+ * props change. When the new values are shallow-equal to the last ones, the
908
+ * last snapshot is kept. So the node re-renders only when a selected value
909
+ * changes. A selector that returns a new array on each call cannot cause a
910
+ * render loop: with the same inputs, the cached snapshot comes back.
911
+ *
912
+ * A node without bound props does not subscribe to the state.
913
+ */
914
+ function useSelection(manager, definition, modelProps) {
915
+ const hasSelectors = Object.keys(definition.selectors).length > 0;
916
+ const cache = useRef(void 0);
917
+ const getSnapshot = () => {
918
+ if (!hasSelectors || modelProps === void 0) return NO_SELECTION;
919
+ const state = manager.getState();
920
+ const cached = cache.current;
921
+ if (cached !== void 0 && cached.state === state && cached.modelProps === modelProps) return cached.selection;
922
+ const next = select(definition, state, modelProps);
923
+ const selection = cached !== void 0 && isSameSelection(cached.selection, next) ? cached.selection : next;
924
+ cache.current = {
925
+ state,
926
+ modelProps,
927
+ selection
928
+ };
929
+ return selection;
930
+ };
931
+ return useSyncExternalStore(hasSelectors ? manager.subscribe : noopSubscribe, getSnapshot, getSnapshot);
932
+ }
933
+ /**
934
+ * Checks the model-set props with the props schema before the selectors run.
935
+ * The bound props are not set yet, so their issues do not count. Neither do
936
+ * issues with no path (a check over several props), which the full check
937
+ * after the selectors reports.
938
+ */
939
+ function checkModelProps(definition, modelData) {
940
+ if (!definition.props) return {
941
+ ok: true,
942
+ values: {}
943
+ };
944
+ let values = modelData;
945
+ let result = validateSchemaSync(definition.props, values);
946
+ if (!result.success) {
947
+ const unset = withoutRejectedNulls(values, result.issues);
948
+ if (unset) {
949
+ values = unset;
950
+ result = validateSchemaSync(definition.props, values);
951
+ }
952
+ }
953
+ if (!result.success) {
954
+ const issues = result.issues.filter((issue) => {
955
+ const key = issueKey(issue);
956
+ return key === void 0 ? isAsyncIssue(issue) : !Object.hasOwn(definition.selectors, key);
957
+ });
958
+ if (issues.length > 0) return {
959
+ ok: false,
960
+ problem: formatIssues(issues)
961
+ };
962
+ }
963
+ return {
964
+ ok: true,
965
+ values
966
+ };
967
+ }
968
+ /**
969
+ * The data props of a node, in three steps: check the model-set props with
970
+ * the props schema, run the selectors with them, then parse all props with
971
+ * the props schema. Gives the reason when a step fails.
972
+ */
973
+ function useDataProps(runtime, surface, definition, properties, basePath, overrides) {
974
+ const modelData = useModelDataProps(surface, definition, properties, basePath, overrides);
975
+ const modelCheck = useMemo(() => modelData.ok ? checkModelProps(definition, modelData.values) : modelData, [definition, modelData]);
976
+ const selection = useSelection(runtime.manager, definition, modelCheck.ok ? modelCheck.values : void 0);
977
+ const accessibility = modelData.ok ? modelData.accessibility : void 0;
978
+ return useMemo(() => {
979
+ if (!modelCheck.ok) return modelCheck;
980
+ if (!selection.ok) return selection;
981
+ if (!definition.props) return {
982
+ ok: true,
983
+ props: {},
984
+ accessibility
985
+ };
986
+ const input = {
987
+ ...modelCheck.values,
988
+ ...selection.values
989
+ };
990
+ let parsed = validateSchemaSync(definition.props, input);
991
+ if (!parsed.success) {
992
+ const unset = withoutRejectedNulls(input, parsed.issues);
993
+ if (unset) parsed = validateSchemaSync(definition.props, unset);
994
+ }
995
+ if (!parsed.success) return {
996
+ ok: false,
997
+ problem: formatIssues(parsed.issues)
998
+ };
999
+ return {
1000
+ ok: true,
1001
+ props: parsed.data,
1002
+ accessibility
1003
+ };
1004
+ }, [
1005
+ definition,
1006
+ modelCheck,
1007
+ selection,
1008
+ accessibility
1009
+ ]);
1010
+ }
1011
+ /**
1012
+ * The event props of a node. A matched event (one that matches a declared
1013
+ * function) is always bound. An unmatched event is bound only when the model
1014
+ * bound it.
1015
+ */
1016
+ function useEventProps(runtime, surface, componentId, definition, properties, basePath) {
1017
+ const latest = useRef(properties);
1018
+ latest.current = properties;
1019
+ const boundNames = Object.keys(definition.events ?? {}).filter((name) => Object.hasOwn(definition.eventFunctions, name) || isActionBinding(properties[name])).join("|");
1020
+ return useMemo(() => {
1021
+ const handlers = {};
1022
+ const names = boundNames ? boundNames.split("|") : [];
1023
+ for (const name of names) {
1024
+ const call = {
1025
+ runtime,
1026
+ surface,
1027
+ componentId,
1028
+ name,
1029
+ parameters: definition.events?.[name]?.parameters
1030
+ };
1031
+ const functionName = Object.hasOwn(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
1032
+ handlers[name] = functionName === void 0 ? (args) => invokeBoundEvent({
1033
+ ...call,
1034
+ binding: latest.current[name],
1035
+ basePath,
1036
+ args
1037
+ }) : (args) => invokeMatchedEvent({
1038
+ ...call,
1039
+ functionName,
1040
+ args
1041
+ });
1042
+ }
1043
+ return handlers;
1044
+ }, [
1045
+ boundNames,
1046
+ runtime,
1047
+ surface,
1048
+ componentId,
1049
+ definition,
1050
+ basePath
1051
+ ]);
1052
+ }
1053
+ /**
1054
+ * The setter props of a node: `setValue` for the writable prop `value`. For
1055
+ * a prop the model bound to `{"@path"}`, the setter writes the data model
1056
+ * and makes the path user-owned. For a literal prop, it sets `overrides`, a
1057
+ * local value of this mounted node. The setters keep their identity.
1058
+ */
1059
+ function useSetterProps(runtime, surface, componentId, definition, properties, basePath) {
1060
+ const [overrides, setOverrides] = useState({});
1061
+ const latest = useRef(properties);
1062
+ latest.current = properties;
1063
+ return {
1064
+ overrides,
1065
+ setters: useMemo(() => {
1066
+ const result = {};
1067
+ const writable = definition.writable ?? [];
1068
+ for (const key of writable) result[setterNameOf(key)] = (value) => {
1069
+ const binding = latest.current[key];
1070
+ if (!isPathBinding(binding)) {
1071
+ setOverrides((current) => ({
1072
+ ...current,
1073
+ [key]: value
1074
+ }));
1075
+ return;
1076
+ }
1077
+ try {
1078
+ runtime.manager.setOwnedValue(surface.key, resolvePath(binding["@path"], basePath), value);
1079
+ } catch (cause) {
1080
+ const message = cause instanceof Error ? cause.message : String(cause);
1081
+ reportErrorSafely(runtime, {
1082
+ kind: "props",
1083
+ surfaceId: surface.surfaceId,
1084
+ componentId,
1085
+ error: /* @__PURE__ */ new Error(`${setterNameOf(key)}: ${message}`)
1086
+ });
1087
+ }
1088
+ };
1089
+ return result;
1090
+ }, [
1091
+ runtime,
1092
+ surface,
1093
+ componentId,
1094
+ definition,
1095
+ basePath
1096
+ ])
1097
+ };
1098
+ }
1099
+ function useSlotProps(surface, definition, properties, componentId, basePath, ancestors) {
1100
+ return useMemo(() => {
1101
+ const childAncestors = [...ancestors, scopedId(componentId, basePath)];
1102
+ const slots = {};
1103
+ for (const [name, kind] of Object.entries(definition.slots ?? {})) {
1104
+ const value = properties[name];
1105
+ if (kind === "single" && typeof value === "string") slots[name] = /* @__PURE__ */ jsx(NodeView, {
1106
+ surface,
1107
+ componentId: value,
1108
+ basePath,
1109
+ ancestors: childAncestors
1110
+ });
1111
+ else if (kind === "multiple" && isTemplateChildren(value)) slots[name] = /* @__PURE__ */ jsx(TemplateChildren, {
1112
+ surface,
1113
+ template: value,
1114
+ basePath,
1115
+ ancestors: childAncestors
1116
+ });
1117
+ else if (kind === "multiple" && Array.isArray(value)) slots[name] = [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ jsx(NodeView, {
1118
+ surface,
1119
+ componentId: id,
1120
+ basePath,
1121
+ ancestors: childAncestors
1122
+ }, id));
1123
+ }
1124
+ return slots;
1125
+ }, [
1126
+ surface,
1127
+ definition,
1128
+ properties,
1129
+ componentId,
1130
+ basePath,
1131
+ ancestors
1132
+ ]);
1133
+ }
1134
+ /**
1135
+ * The parsed data props with every typed child reference (`child()`,
1136
+ * `childList()`, at any depth) replaced by the rendered component. Without
1137
+ * references, the parsed props come back as they are.
1138
+ */
1139
+ function useChildRefProps(surface, refs, props, componentId, basePath, ancestors) {
1140
+ return useMemo(() => {
1141
+ if (props === void 0 || refs.length === 0) return props;
1142
+ const childAncestors = [...ancestors, scopedId(componentId, basePath)];
1143
+ const render = (kind, value) => {
1144
+ if (kind === "single") return typeof value === "string" ? /* @__PURE__ */ jsx(NodeView, {
1145
+ surface,
1146
+ componentId: value,
1147
+ basePath,
1148
+ ancestors: childAncestors
1149
+ }) : void 0;
1150
+ if (isTemplateChildren(value)) return /* @__PURE__ */ jsx(TemplateChildren, {
1151
+ surface,
1152
+ template: value,
1153
+ basePath,
1154
+ ancestors: childAncestors
1155
+ });
1156
+ if (!Array.isArray(value)) return void 0;
1157
+ return [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ jsx(NodeView, {
1158
+ surface,
1159
+ componentId: id,
1160
+ basePath,
1161
+ ancestors: childAncestors
1162
+ }, id));
1163
+ };
1164
+ let result = props;
1165
+ for (const ref of refs) result = mapAtChildRef(result, ref.path, (found) => render(ref.kind, found));
1166
+ return result;
1167
+ }, [
1168
+ surface,
1169
+ refs,
1170
+ props,
1171
+ componentId,
1172
+ basePath,
1173
+ ancestors
1174
+ ]);
1175
+ }
1176
+ function ResolvedNode({ surface, componentId, definition, properties, runtime, basePath, ancestors }) {
1177
+ const { overrides, setters } = useSetterProps(runtime, surface, componentId, definition, properties, basePath);
1178
+ const dataProps = useDataProps(runtime, surface, definition, properties, basePath, overrides);
1179
+ const eventProps = useEventProps(runtime, surface, componentId, definition, properties, basePath);
1180
+ const slotProps = useSlotProps(surface, definition, properties, componentId, basePath, ancestors);
1181
+ const childRefProps = useChildRefProps(surface, definition.childRefs, dataProps.ok ? dataProps.props : void 0, componentId, basePath, ancestors);
1182
+ const accessibility = dataProps.ok ? dataProps.accessibility : void 0;
1183
+ const nodeContext = useMemo(() => ({
1184
+ surfaceKey: surface.key,
1185
+ surfaceId: surface.surfaceId,
1186
+ componentId,
1187
+ accessibility
1188
+ }), [
1189
+ surface.key,
1190
+ surface.surfaceId,
1191
+ componentId,
1192
+ accessibility
1193
+ ]);
1194
+ const problem = dataProps.ok ? void 0 : dataProps.problem;
1195
+ useEffect(() => {
1196
+ if (problem) reportErrorSafely(runtime, {
1197
+ kind: "props",
1198
+ surfaceId: surface.surfaceId,
1199
+ componentId,
1200
+ error: /* @__PURE__ */ new Error(`Invalid props: ${problem}`)
1201
+ });
1202
+ }, [
1203
+ problem,
1204
+ runtime,
1205
+ surface.surfaceId,
1206
+ componentId
1207
+ ]);
1208
+ if (!dataProps.ok) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
1209
+ message: `invalid props (${problem})`,
1210
+ componentId
1211
+ });
1212
+ const Component = definition.component;
1213
+ const rendered = /* @__PURE__ */ jsx(Component, {
1214
+ ...childRefProps,
1215
+ ...eventProps,
1216
+ ...slotProps,
1217
+ ...setters
1218
+ });
1219
+ const hasEnvelope = properties.accessibility !== void 0 && definition.accessibility !== "self";
1220
+ return /* @__PURE__ */ jsx(GenerativeUINodeContext.Provider, {
1221
+ value: nodeContext,
1222
+ children: hasEnvelope ? /* @__PURE__ */ jsx("span", {
1223
+ "data-a2ui-accessibility": "",
1224
+ style: ROOT_STYLE,
1225
+ ...wrapperAria(accessibilityAttributes$1(accessibility)),
1226
+ children: rendered
1227
+ }) : rendered
1228
+ });
1229
+ }
1230
+
1231
+ //#endregion
1232
+ //#region src/v2/generative-ui/chat.tsx
1233
+ const GenerativeUIChatSlotContext = createContext(void 0);
1234
+ function DefaultGenerativeUIChatCard({ surfaceId, isStreaming, error, children }) {
1235
+ return /* @__PURE__ */ jsxs("div", {
1236
+ "data-generative-ui-chat-surface": surfaceId,
1237
+ className: "cpk:my-2 cpk:w-full cpk:rounded-xl cpk:border cpk:border-gray-200 cpk:p-3",
1238
+ children: [children, error && /* @__PURE__ */ jsx("div", {
1239
+ role: "alert",
1240
+ className: "cpk:mt-2 cpk:text-xs cpk:text-red-600",
1241
+ children: "Part of this UI couldn't be shown."
1242
+ })]
1243
+ });
1244
+ }
1245
+ const ContentSchema = z.object({
1246
+ surfaceId: z.string(),
1247
+ target: z.string(),
1248
+ catalogId: z.string(),
1249
+ operations: z.array(z.any()),
1250
+ status: z.enum([
1251
+ "streaming",
1252
+ "ready",
1253
+ "error"
1254
+ ]),
1255
+ rejected: z.array(z.object({
1256
+ index: z.number(),
1257
+ reason: z.string()
1258
+ })).default([])
1259
+ }).passthrough();
1260
+ function GenerativeUIChatActivity({ content, agent }) {
1261
+ const runtime = useGenerativeUIRuntime();
1262
+ const threadId = useCopilotChatConfiguration()?.threadId ?? agent?.threadId;
1263
+ const Wrapper = useContext(GenerativeUIChatSlotContext) ?? DefaultGenerativeUIChatCard;
1264
+ useManagerVersion(runtime);
1265
+ useLayoutEffect(() => {
1266
+ if (runtime && threadId) runtime.manager.ingest(threadId, agent?.agentId, content);
1267
+ }, [
1268
+ runtime,
1269
+ threadId,
1270
+ agent?.agentId,
1271
+ content
1272
+ ]);
1273
+ if (!runtime || !threadId || content.target !== GENERATIVE_UI_CHAT_TARGET) return null;
1274
+ const surface = runtime.manager.getSurface(threadId, content.surfaceId) ?? runtime.manager.getFailedSurface(threadId, content.surfaceId);
1275
+ if (!surface) return null;
1276
+ const rejected = [...content.rejected ?? [], ...surface.clientRejected];
1277
+ const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
1278
+ return /* @__PURE__ */ jsx(Wrapper, {
1279
+ surfaceId: content.surfaceId,
1280
+ isStreaming: content.status === "streaming",
1281
+ error,
1282
+ rejected,
1283
+ children: surface.failed ? null : /* @__PURE__ */ jsx(SurfaceView, { surface })
1284
+ });
1285
+ }
1286
+ function createGenerativeUIActivityRenderer() {
1287
+ return {
1288
+ activityType: GENERATIVE_UI_ACTIVITY_TYPE,
1289
+ content: ContentSchema,
1290
+ render: GenerativeUIChatActivity
1291
+ };
1292
+ }
1293
+ /**
1294
+ * Shows nothing in the chat for an agent-called function. The root reads the
1295
+ * function-call activities from the messages and runs them. This renderer
1296
+ * only keeps a wildcard ("*") activity renderer from showing them.
1297
+ */
1298
+ function createGenerativeUIFunctionCallActivityRenderer() {
1299
+ return {
1300
+ activityType: GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,
1301
+ content: z.unknown(),
1302
+ render: () => null
1303
+ };
1304
+ }
1305
+ /** Hides the raw `render_ui` tool call; the surface activity owns the UX. */
1306
+ function GenerativeUIToolCallRenderer() {
1307
+ const { copilotkit } = useCopilotKit();
1308
+ useEffect(() => {
1309
+ const renderer = defineToolCallRenderer({
1310
+ name: GENERATIVE_UI_RENDER_TOOL,
1311
+ args: z.any(),
1312
+ render: () => /* @__PURE__ */ jsx(Fragment$1, {})
1313
+ });
1314
+ const existing = copilotkit._renderToolCalls ?? [];
1315
+ copilotkit.setRenderToolCalls([...existing.filter((rc) => rc.name !== GENERATIVE_UI_RENDER_TOOL), renderer]);
1316
+ }, [copilotkit]);
1317
+ return null;
1318
+ }
1319
+
1320
+ //#endregion
1321
+ //#region src/v2/generative-ui/markdown/MarkdownSurfaces.tsx
1322
+ const FADE_STYLE_ID = "a2ui-markdown-fade";
1323
+ /**
1324
+ * Components fade in as they stream: each element that appears under a
1325
+ * markdown surface runs the keyframes once on mount. React keeps the keys
1326
+ * stable per component id, so an element that is already there never
1327
+ * animates again. SVG internals are left out: a chart library re-creates
1328
+ * its nodes on each render, and a fade on each of them would read as the
1329
+ * chart flashing whenever a sibling arrives. The fade runs under reduced
1330
+ * motion too, because it moves nothing.
1331
+ */
1332
+ const FADE_CSS = ["@keyframes a2ui-fade-in{from{opacity:0}}", "[data-a2ui-markdown-surface] .a2ui-surface *:not(svg):not(svg *){animation:a2ui-fade-in .35s ease-out backwards}"].join("\n");
1333
+ const noEffect = () => {};
1334
+ const useInjectEffect = typeof document === "undefined" ? noEffect : useInsertionEffect;
1335
+ function useFadeStyles() {
1336
+ useInjectEffect(() => {
1337
+ if (document.getElementById(FADE_STYLE_ID)) return;
1338
+ const style = document.createElement("style");
1339
+ style.id = FADE_STYLE_ID;
1340
+ style.textContent = FADE_CSS;
1341
+ document.head.appendChild(style);
1342
+ }, []);
1343
+ }
1344
+ /**
1345
+ * The default wrapper of a chat surface in the markdown transport. It draws
1346
+ * no box: a surface sits in the flow of the reply like a paragraph, and a
1347
+ * Card draws its own box when it is interactive. Nothing shows while the
1348
+ * surface streams. A rejected operation gets one line.
1349
+ */
1350
+ function DefaultMarkdownChatSurface({ surfaceId, error, children }) {
1351
+ useFadeStyles();
1352
+ return /* @__PURE__ */ jsxs("div", {
1353
+ "data-generative-ui-chat-surface": surfaceId,
1354
+ "data-a2ui-markdown-surface": surfaceId,
1355
+ className: "cpk:relative cpk:my-4 cpk:flex cpk:w-full cpk:min-w-0 cpk:max-w-full cpk:flex-col",
1356
+ children: [children, error && /* @__PURE__ */ jsx("div", {
1357
+ role: "alert",
1358
+ className: "cpk:mt-2 cpk:text-xs cpk:text-red-600",
1359
+ children: "Part of this UI couldn't be shown."
1360
+ })]
1361
+ });
1362
+ }
1363
+ /**
1364
+ * One chat surface in the chat wrapper. Nothing renders until the surface
1365
+ * has its root component, so a half-streamed fence shows no empty card.
1366
+ */
1367
+ function ChatSurface({ runtime, threadId, surfaceId, Wrapper }) {
1368
+ const surface = runtime.manager.getSurface(threadId, surfaceId) ?? runtime.manager.getFailedSurface(threadId, surfaceId);
1369
+ const root = surface?.model.componentsModel.get(GENERATIVE_UI_ROOT_ID);
1370
+ if (!surface || !root && !surface.failed) return null;
1371
+ const rejected = [...surface.serverRejected, ...surface.clientRejected];
1372
+ const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
1373
+ return /* @__PURE__ */ jsx(Wrapper, {
1374
+ surfaceId,
1375
+ isStreaming: surface.status === "streaming",
1376
+ error,
1377
+ rejected,
1378
+ children: surface.failed ? null : /* @__PURE__ */ jsx(SurfaceView, { surface })
1379
+ });
1380
+ }
1381
+ /** The blocks of one fence: lifted prose and chat surfaces, in order. */
1382
+ function FenceBlocks({ blocks, runtime, threadId, markdownProps }) {
1383
+ const Wrapper = useContext(GenerativeUIChatSlotContext) ?? DefaultMarkdownChatSurface;
1384
+ let surfaceCount = 0;
1385
+ return /* @__PURE__ */ jsx(Fragment$1, { children: blocks.map((block) => {
1386
+ if (block.kind === "markdown") return /* @__PURE__ */ jsx(Streamdown, {
1387
+ ...markdownProps,
1388
+ children: block.markdown
1389
+ }, `md-${surfaceCount}`);
1390
+ surfaceCount++;
1391
+ return /* @__PURE__ */ jsx(ChatSurface, {
1392
+ runtime,
1393
+ threadId,
1394
+ surfaceId: block.surfaceId,
1395
+ Wrapper
1396
+ }, block.surfaceId);
1397
+ }) });
1398
+ }
1399
+ /**
1400
+ * Experimental. Renders an assistant message of the markdown transport.
1401
+ * Prose renders as markdown. In place of each ```a2ui fence:
1402
+ *
1403
+ * - the fence that created a chat surface renders that surface (and the
1404
+ * prose lifted out of it) in the chat wrapper;
1405
+ * - every other fence renders nothing: a fence that updates the surface of
1406
+ * an earlier fence, or a fence for a named target, which
1407
+ * `<GenerativeUISurface id>` renders.
1408
+ *
1409
+ * Use it inside `<CopilotKitProvider generativeUI={{ ui, transport: "markdown" }}>`.
1410
+ * `CopilotChatAssistantMessage` uses it there on its own.
1411
+ *
1412
+ * @example
1413
+ * ```tsx
1414
+ * <MarkdownSurfaces content={message.content} messageId={message.id} />
1415
+ * ```
1416
+ */
1417
+ function MarkdownSurfaces({ content, messageId, ...markdownProps }) {
1418
+ const runtime = useRequiredGenerativeUIRuntime();
1419
+ const chatThreadId = useCopilotChatConfiguration()?.threadId;
1420
+ useManagerVersion(runtime);
1421
+ const segments = useMemo(() => splitA2UIMarkdown(content), [content]);
1422
+ const threadId = chatThreadId ?? runtime.manager.getActiveThread();
1423
+ const source = getMarkdownSurfaceSource(runtime);
1424
+ return /* @__PURE__ */ jsx(Fragment$1, { children: segments.map((segment, index) => {
1425
+ if (segment.type === "markdown") return /* @__PURE__ */ jsx(Streamdown, {
1426
+ ...markdownProps,
1427
+ children: segment.text
1428
+ }, `md-${index}`);
1429
+ const blocks = threadId ? source.getFenceBlocks(threadId, messageId, segment.index) : void 0;
1430
+ if (!threadId || !blocks) return null;
1431
+ return /* @__PURE__ */ jsx(FenceBlocks, {
1432
+ blocks,
1433
+ runtime,
1434
+ threadId,
1435
+ markdownProps
1436
+ }, `a2ui-${segment.index}`);
1437
+ }) });
1438
+ }
1439
+
1440
+ //#endregion
1441
+ export { ControlledModalOpenScope as C, shallowEqual as D, useCopilotChatConfiguration as E, useShallowStableRef as O, useKatexStyles as S, CopilotChatDefaultLabels as T, useGenerativeUIRuntime as _, createGenerativeUIActivityRenderer as a, createGenerativeUI$1 as b, controlAria as c, wrapperAria as d, useGenerativeUIFunction as f, GenerativeUIRuntimeContext as g, GenerativeUINodeContext as h, GenerativeUIToolCallRenderer as i, namedRole as l, useManagerVersion as m, DefaultGenerativeUIChatCard as n, createGenerativeUIFunctionCallActivityRenderer as o, useGenerativeUIState as p, GenerativeUIChatSlotContext as r, SurfaceView as s, MarkdownSurfaces as t, useGenerativeUIAccessibility as u, useRequiredGenerativeUIRuntime as v, CopilotChatConfigurationProvider as w, defineToolCallRenderer as x, catalogIdsOf as y };
1442
+ //# sourceMappingURL=MarkdownSurfaces-D-W4f9Dy.mjs.map