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