@copilotkit/react-core 2.0.0-rc.6 → 2.0.0-rc.60

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 (115) hide show
  1. package/README.md +1 -1
  2. package/dist/MarkdownRendererContext-QFCldfW_.d.cts +34 -0
  3. package/dist/MarkdownRendererContext-QFCldfW_.d.cts.map +1 -0
  4. package/dist/MarkdownRendererContext-aK63ZFd-.d.mts +34 -0
  5. package/dist/MarkdownRendererContext-aK63ZFd-.d.mts.map +1 -0
  6. package/dist/MarkdownSurfaces-Do948N1P.cjs +141 -0
  7. package/dist/MarkdownSurfaces-Do948N1P.cjs.map +1 -0
  8. package/dist/MarkdownSurfaces-rtE9wRUP.mjs +135 -0
  9. package/dist/MarkdownSurfaces-rtE9wRUP.mjs.map +1 -0
  10. package/dist/ProviderMarkdown-D0eI0aPo.cjs +268 -0
  11. package/dist/ProviderMarkdown-D0eI0aPo.cjs.map +1 -0
  12. package/dist/ProviderMarkdown-epL7F3Vt.mjs +214 -0
  13. package/dist/ProviderMarkdown-epL7F3Vt.mjs.map +1 -0
  14. package/dist/accessibility-BLK-gE0R.mjs +129 -0
  15. package/dist/accessibility-BLK-gE0R.mjs.map +1 -0
  16. package/dist/accessibility-GnodqxkH.cjs +228 -0
  17. package/dist/accessibility-GnodqxkH.cjs.map +1 -0
  18. package/dist/chat-B1zczXUD.mjs +1476 -0
  19. package/dist/chat-B1zczXUD.mjs.map +1 -0
  20. package/dist/chat-BZ_bvAkg.d.mts +38 -0
  21. package/dist/chat-BZ_bvAkg.d.mts.map +1 -0
  22. package/dist/chat-CkFZMo5E.cjs +1579 -0
  23. package/dist/chat-CkFZMo5E.cjs.map +1 -0
  24. package/dist/chat-CpZVyF_t.d.cts +38 -0
  25. package/dist/chat-CpZVyF_t.d.cts.map +1 -0
  26. package/dist/context.cjs +75 -63
  27. package/dist/context.cjs.map +1 -1
  28. package/dist/context.d.cts +62 -107
  29. package/dist/context.d.cts.map +1 -1
  30. package/dist/context.d.mts +62 -107
  31. package/dist/context.d.mts.map +1 -1
  32. package/dist/context.mjs +76 -64
  33. package/dist/context.mjs.map +1 -1
  34. package/dist/generative-ui/map.cjs +26 -0
  35. package/dist/generative-ui/map.cjs.map +1 -0
  36. package/dist/generative-ui/map.d.cts +23 -0
  37. package/dist/generative-ui/map.d.cts.map +1 -0
  38. package/dist/generative-ui/map.d.mts +23 -0
  39. package/dist/generative-ui/map.d.mts.map +1 -0
  40. package/dist/generative-ui/map.mjs +24 -0
  41. package/dist/generative-ui/map.mjs.map +1 -0
  42. package/dist/generative-ui/native.cjs +67 -0
  43. package/dist/generative-ui/native.cjs.map +1 -0
  44. package/dist/generative-ui/native.d.cts +156 -0
  45. package/dist/generative-ui/native.d.cts.map +1 -0
  46. package/dist/generative-ui/native.d.mts +156 -0
  47. package/dist/generative-ui/native.d.mts.map +1 -0
  48. package/dist/generative-ui/native.mjs +25 -0
  49. package/dist/generative-ui/native.mjs.map +1 -0
  50. package/dist/generative-ui.cjs +33 -8088
  51. package/dist/generative-ui.cjs.map +1 -1
  52. package/dist/generative-ui.d.cts +2472 -4789
  53. package/dist/generative-ui.d.cts.map +1 -1
  54. package/dist/generative-ui.d.mts +2472 -4789
  55. package/dist/generative-ui.d.mts.map +1 -1
  56. package/dist/generative-ui.mjs +9 -8074
  57. package/dist/generative-ui.mjs.map +1 -1
  58. package/dist/headless.cjs +289 -1054
  59. package/dist/headless.cjs.map +1 -1
  60. package/dist/headless.d.cts +149 -372
  61. package/dist/headless.d.cts.map +1 -1
  62. package/dist/headless.d.mts +123 -237
  63. package/dist/headless.d.mts.map +1 -1
  64. package/dist/headless.mjs +283 -1054
  65. package/dist/headless.mjs.map +1 -1
  66. package/dist/hooks-D2H3iL0N.d.mts +84 -0
  67. package/dist/hooks-D2H3iL0N.d.mts.map +1 -0
  68. package/dist/hooks-Dy8HeEdr.d.cts +84 -0
  69. package/dist/hooks-Dy8HeEdr.d.cts.map +1 -0
  70. package/dist/index.cjs +8702 -13238
  71. package/dist/index.cjs.map +1 -1
  72. package/dist/index.d.cts +312 -872
  73. package/dist/index.d.cts.map +1 -1
  74. package/dist/index.d.mts +311 -871
  75. package/dist/index.d.mts.map +1 -1
  76. package/dist/index.mjs +1790 -7803
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/index.umd.js +14075 -13828
  79. package/dist/index.umd.js.map +1 -1
  80. package/dist/refs-B5Dn59Pn.cjs +43 -0
  81. package/dist/refs-B5Dn59Pn.cjs.map +1 -0
  82. package/dist/refs-BW15wX_V.mjs +31 -0
  83. package/dist/refs-BW15wX_V.mjs.map +1 -0
  84. package/dist/runtime-context-B7f4M85q.d.mts +215 -0
  85. package/dist/runtime-context-B7f4M85q.d.mts.map +1 -0
  86. package/dist/runtime-context-CIkZS0ap.d.cts +215 -0
  87. package/dist/runtime-context-CIkZS0ap.d.cts.map +1 -0
  88. package/dist/standard-CSBR4FhM.mjs +5800 -0
  89. package/dist/standard-CSBR4FhM.mjs.map +1 -0
  90. package/dist/standard-DBjcBGyd.cjs +5796 -0
  91. package/dist/standard-DBjcBGyd.cjs.map +1 -0
  92. package/dist/use-generative-ui-root-CIp0ytE6.cjs +390 -0
  93. package/dist/use-generative-ui-root-CIp0ytE6.cjs.map +1 -0
  94. package/dist/use-generative-ui-root-oBqPa6uy.mjs +386 -0
  95. package/dist/use-generative-ui-root-oBqPa6uy.mjs.map +1 -0
  96. package/dist/v2/context.d.cts +28 -0
  97. package/dist/v2/context.d.mts +28 -0
  98. package/dist/v2/generative-ui/native.d.cts +112 -0
  99. package/dist/v2/generative-ui/native.d.mts +112 -0
  100. package/dist/v2/generative-ui.d.cts +96 -0
  101. package/dist/v2/generative-ui.d.mts +96 -0
  102. package/dist/v2/headless.d.cts +96 -0
  103. package/dist/v2/headless.d.mts +96 -0
  104. package/dist/v2/index.d.cts +2220 -0
  105. package/dist/v2/index.d.mts +2220 -0
  106. package/dist/v2/styles.css +5 -0
  107. package/package.json +116 -24
  108. package/dist/MarkdownRendererContext-B4Us6mwL.d.cts +0 -954
  109. package/dist/MarkdownRendererContext-B4Us6mwL.d.cts.map +0 -1
  110. package/dist/MarkdownRendererContext-CRKFzsEB.d.mts +0 -954
  111. package/dist/MarkdownRendererContext-CRKFzsEB.d.mts.map +0 -1
  112. package/dist/MarkdownSurfaces-Bd--93O1.mjs +0 -3676
  113. package/dist/MarkdownSurfaces-Bd--93O1.mjs.map +0 -1
  114. package/dist/MarkdownSurfaces-S4wfUl3J.cjs +0 -3991
  115. package/dist/MarkdownSurfaces-S4wfUl3J.cjs.map +0 -1
@@ -1,3991 +0,0 @@
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 _copilotkit_core = require("@copilotkit/core");
29
- let react = require("react");
30
- react = __toESM(react);
31
- let react_jsx_runtime = require("react/jsx-runtime");
32
- let _copilotkit_markdown_renderer_react = require("@copilotkit/markdown-renderer/react");
33
- let _copilotkit_markdown_renderer = require("@copilotkit/markdown-renderer");
34
- let _copilotkit_shared = require("@copilotkit/shared");
35
- let _copilotkit_react_core_context = require("@copilotkit/react-core/context");
36
- let zod = require("zod");
37
- let zod_to_json_schema = require("zod-to-json-schema");
38
-
39
- //#region src/components/chat/StreamingMarkdownDefaultRenderer.tsx
40
- const defaultNodeRenderers = (0, _copilotkit_markdown_renderer_react.createStreamingMarkdownNodeRenderers)({ codeBlock: ({ node }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
41
- className: "cpk-markdown-code-block",
42
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
43
- "data-code-info": node.info ?? void 0,
44
- children: node.text
45
- })
46
- }) });
47
- /**
48
- * react-core's built-in default markdown renderer — a thin adapter over
49
- * `@copilotkit/markdown-renderer`'s streaming renderer. Maps the pluggable
50
- * renderer contract (`{ content, isStreaming, className }`) onto the streaming
51
- * renderer for streaming-safe incremental rendering + per-token animation.
52
- * Still overridable via the slot/provider pluggable interface.
53
- */
54
- function StreamingMarkdownDefaultRenderer({ content, isStreaming, className, nodeRenderers, caret, options, onLinkClick, onCitationClick }) {
55
- const mergedNodeRenderers = (0, react.useMemo)(() => nodeRenderers ? (0, _copilotkit_markdown_renderer_react.createStreamingMarkdownNodeRenderers)({
56
- ...defaultNodeRenderers,
57
- ...nodeRenderers
58
- }) : defaultNodeRenderers, [nodeRenderers]);
59
- if (!content) return null;
60
- (0, _copilotkit_markdown_renderer.warnUnsupportedRichSyntaxOnce)(content);
61
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkit_markdown_renderer_react.StreamingMarkdownRenderer, {
62
- className,
63
- isComplete: !isStreaming,
64
- caret: caret ?? !!isStreaming,
65
- nodeRenderers: mergedNodeRenderers,
66
- options,
67
- onLinkClick,
68
- onCitationClick,
69
- children: content
70
- });
71
- }
72
- StreamingMarkdownDefaultRenderer.displayName = "StreamingMarkdownDefaultRenderer";
73
-
74
- //#endregion
75
- //#region src/lib/shallow-stable-ref.ts
76
- /**
77
- * Shallow equality comparison for objects.
78
- */
79
- function shallowEqual(obj1, obj2) {
80
- const keys1 = Object.keys(obj1);
81
- const keys2 = Object.keys(obj2);
82
- if (keys1.length !== keys2.length) return false;
83
- for (const key of keys1) if (obj1[key] !== obj2[key]) return false;
84
- return true;
85
- }
86
- /**
87
- * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
88
- * class instances, and other exotic objects that happen to have typeof "object".
89
- */
90
- function isPlainObject(obj) {
91
- return obj !== null && typeof obj === "object" && Object.prototype.toString.call(obj) === "[object Object]";
92
- }
93
- /**
94
- * Returns the same reference as long as the value is shallowly equal to the
95
- * previous render's value.
96
- *
97
- * - Identical references bail out immediately (O(1)).
98
- * - Plain objects ({}) are shallow-compared key-by-key.
99
- * - Arrays, Dates, class instances, functions, and primitives are compared by
100
- * reference only — shallowEqual is never called on non-plain objects, which
101
- * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).
102
- *
103
- * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow
104
- * equality check isn't defeated by a new object reference on every render.
105
- */
106
- function useShallowStableRef(value) {
107
- const ref = (0, react.useRef)(value);
108
- if (ref.current === value) return ref.current;
109
- if (isPlainObject(ref.current) && isPlainObject(value)) {
110
- if (shallowEqual(ref.current, value)) return ref.current;
111
- }
112
- ref.current = value;
113
- return ref.current;
114
- }
115
-
116
- //#endregion
117
- //#region src/providers/CopilotChatConfigurationProvider.tsx
118
- const CopilotChatDefaultLabels = {
119
- chatInputPlaceholder: "Type a message...",
120
- chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
121
- chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
122
- chatInputToolbarFinishTranscribeButtonLabel: "Finish",
123
- chatInputToolbarAddButtonLabel: "Add attachments",
124
- chatInputToolbarToolsButtonLabel: "Tools",
125
- chatInputToolbarSendButtonLabel: "Send message",
126
- chatInputToolbarStopButtonLabel: "Stop",
127
- assistantMessageToolbarCopyCodeLabel: "Copy",
128
- assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
129
- assistantMessageToolbarCopyMessageLabel: "Copy",
130
- assistantMessageToolbarInspectorLabel: "View in Inspector",
131
- assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
132
- assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
133
- assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
134
- assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
135
- assistantMessageToolbarInspectorHideLabel: "Hide this icon",
136
- assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
137
- assistantMessageToolbarThumbsUpLabel: "Good response",
138
- assistantMessageToolbarThumbsDownLabel: "Bad response",
139
- assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
140
- assistantMessageFeedbackCommentSubmitLabel: "Send comment",
141
- assistantMessageToolbarReadAloudLabel: "Read aloud",
142
- assistantMessageToolbarRegenerateLabel: "Regenerate",
143
- userMessageToolbarCopyMessageLabel: "Copy",
144
- userMessageToolbarEditMessageLabel: "Edit",
145
- userMessageToolbarPreviousBranchLabel: "Previous branch",
146
- userMessageToolbarNextBranchLabel: "Next branch",
147
- chatDisclaimerText: "AI can make mistakes. Please verify important information.",
148
- chatToggleOpenLabel: "Open chat",
149
- chatToggleCloseLabel: "Close chat",
150
- chatScrollToBottomLabel: "Scroll to bottom",
151
- modalHeaderTitle: "CopilotKit Chat",
152
- welcomeMessageText: "How can I help you today?",
153
- reasoningMessageThinkingLabel: "Thinking…",
154
- chatInputSlashMenuLabel: "Slash commands",
155
- chatInputSlashMenuEmptyText: "No commands found",
156
- attachmentRemoveButtonLabel: "Remove attachment",
157
- attachmentPlayVideoButtonLabel: "Play video",
158
- attachmentPreviewCloseButtonLabel: "Close preview",
159
- modalHeaderCloseButtonLabel: "Close",
160
- modalHeaderThreadsButtonLabel: "Open threads",
161
- sidebarLabel: "Copilot chat sidebar"
162
- };
163
- /**
164
- * Mobile breakpoint below which the chat modal and the thread-list drawer are
165
- * mutually exclusive. At or above this width both surfaces may coexist. This
166
- * mirrors the `(max-width: 767px)` / `(min-width: 768px)` split already used by
167
- * CopilotChatInput and CopilotSidebarView.
168
- */
169
- const MOBILE_MAX_WIDTH_PX = 767;
170
- /**
171
- * Reports whether the current viewport is in the mobile range (`<768px`), where
172
- * the chat modal and drawer must not be open simultaneously. SSR-safe and
173
- * defensive against environments without `matchMedia` (treated as desktop, so
174
- * no mutual-exclusion constraint is applied).
175
- *
176
- * @returns `true` when the viewport is mobile-width, `false` otherwise.
177
- */
178
- function isMobileViewport() {
179
- if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
180
- return window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH_PX}px)`).matches;
181
- }
182
- const CopilotChatConfiguration = (0, react.createContext)(null);
183
- const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
184
- const parentConfig = (0, react.useContext)(CopilotChatConfiguration);
185
- const stableLabels = useShallowStableRef(labels);
186
- const mergedLabels = (0, react.useMemo)(() => ({
187
- ...CopilotChatDefaultLabels,
188
- ...parentConfig?.labels,
189
- ...stableLabels
190
- }), [stableLabels, parentConfig?.labels]);
191
- const providerAgentId = (0, _copilotkit_react_core_context.useDefaultAgentId)();
192
- const resolvedAgentId = agentId ?? parentConfig?.agentId ?? providerAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
193
- const threadIdPropIsAuthoritative = threadId !== void 0 && hasExplicitThreadId !== false;
194
- const isThreadIdControlled = threadIdPropIsAuthoritative;
195
- const [activeThreadOverride, setActiveThreadOverride] = (0, react.useState)(null);
196
- const resolvedThreadId = (0, react.useMemo)(() => {
197
- if (threadIdPropIsAuthoritative) return threadId;
198
- if (activeThreadOverride) return activeThreadOverride.threadId;
199
- if (parentConfig?.threadId) return parentConfig.threadId;
200
- if (threadId) return threadId;
201
- return (0, _copilotkit_shared.randomUUID)();
202
- }, [
203
- threadIdPropIsAuthoritative,
204
- threadId,
205
- parentConfig?.threadId,
206
- activeThreadOverride
207
- ]);
208
- const copilotkit = (0, react.useContext)(_copilotkit_react_core_context.CopilotKitContext)?.copilotkit;
209
- const openThreadRef = (0, react.useRef)(null);
210
- const latestThreadIdRef = (0, react.useRef)(resolvedThreadId);
211
- latestThreadIdRef.current = resolvedThreadId;
212
- (0, react.useEffect)(() => {
213
- if (copilotkit === void 0) return;
214
- const registration = copilotkit.registerOpenThread({
215
- agentId: resolvedAgentId,
216
- threadId: latestThreadIdRef.current
217
- });
218
- openThreadRef.current = registration;
219
- return () => {
220
- registration.unregister();
221
- openThreadRef.current = null;
222
- };
223
- }, [copilotkit, resolvedAgentId]);
224
- (0, react.useEffect)(() => {
225
- openThreadRef.current?.update(resolvedThreadId);
226
- }, [resolvedThreadId]);
227
- const resolvedHasExplicitThreadId = (threadIdPropIsAuthoritative ? true : activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false) || !!parentConfig?.hasExplicitThreadId;
228
- const [internalModalOpen, setInternalModalOpen] = (0, react.useState)(isModalDefaultOpen ?? true);
229
- const hasExplicitDefault = isModalDefaultOpen !== void 0;
230
- const setAndSync = (0, react.useCallback)((open) => {
231
- setInternalModalOpen(open);
232
- parentConfig?.setModalOpen(open);
233
- }, [parentConfig?.setModalOpen]);
234
- const isMounted = (0, react.useRef)(false);
235
- (0, react.useEffect)(() => {
236
- if (!hasExplicitDefault) return;
237
- if (!isMounted.current) {
238
- isMounted.current = true;
239
- return;
240
- }
241
- if (parentConfig?.isModalOpen === void 0) return;
242
- setInternalModalOpen(parentConfig.isModalOpen);
243
- }, [parentConfig?.isModalOpen, hasExplicitDefault]);
244
- const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : parentConfig?.isModalOpen ?? internalModalOpen;
245
- const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : parentConfig?.setModalOpen ?? setInternalModalOpen;
246
- const [ownDrawerOpen, setOwnDrawerOpen] = (0, react.useState)(false);
247
- const [ownDrawerCount, setOwnDrawerCount] = (0, react.useState)(0);
248
- const modalCloseRef = (0, react.useRef)(() => {});
249
- modalCloseRef.current = resolvedSetModalOpen;
250
- const registeredModalClosersRef = (0, react.useRef)([]);
251
- const ownRegisterModalCloser = (0, react.useCallback)((closeModal) => {
252
- registeredModalClosersRef.current.push(closeModal);
253
- return () => {
254
- registeredModalClosersRef.current = registeredModalClosersRef.current.filter((entry) => entry !== closeModal);
255
- };
256
- }, []);
257
- const ownSetDrawerOpen = (0, react.useCallback)((open) => {
258
- setOwnDrawerOpen(open);
259
- if (open && isMobileViewport()) {
260
- const registered = registeredModalClosersRef.current;
261
- (registered.length > 0 ? registered[registered.length - 1] : modalCloseRef.current)(false);
262
- }
263
- }, []);
264
- const ownRegisterDrawer = (0, react.useCallback)(() => {
265
- setOwnDrawerCount((count) => count + 1);
266
- return () => {
267
- setOwnDrawerCount((count) => Math.max(0, count - 1));
268
- };
269
- }, []);
270
- const resolvedDrawerOpen = parentConfig ? parentConfig.drawerOpen : ownDrawerOpen;
271
- const resolvedSetDrawerOpen = parentConfig ? parentConfig.setDrawerOpen : ownSetDrawerOpen;
272
- const resolvedDrawerRegistered = parentConfig ? parentConfig.drawerRegistered : ownDrawerCount > 0;
273
- const resolvedRegisterDrawer = parentConfig ? parentConfig.registerDrawer : ownRegisterDrawer;
274
- const resolvedRegisterModalCloser = parentConfig ? parentConfig.ɵregisterModalCloser : ownRegisterModalCloser;
275
- (0, react.useEffect)(() => {
276
- if (!hasExplicitDefault) return;
277
- return resolvedRegisterModalCloser(resolvedSetModalOpen);
278
- }, [
279
- hasExplicitDefault,
280
- resolvedRegisterModalCloser,
281
- resolvedSetModalOpen
282
- ]);
283
- const isThreadIdControlledRef = (0, react.useRef)(isThreadIdControlled);
284
- isThreadIdControlledRef.current = isThreadIdControlled;
285
- const ownSetActiveThreadId = (0, react.useCallback)((id, options) => {
286
- setActiveThreadOverride({
287
- threadId: id,
288
- explicit: options?.explicit ?? true
289
- });
290
- }, []);
291
- const ownStartNewThread = (0, react.useCallback)(() => {
292
- setActiveThreadOverride({
293
- threadId: (0, _copilotkit_shared.randomUUID)(),
294
- explicit: false
295
- });
296
- }, []);
297
- const parentSetActiveThreadId = parentConfig?.setActiveThreadId;
298
- const parentStartNewThread = parentConfig?.startNewThread;
299
- const resolvedSetActiveThreadId = (0, react.useCallback)((id, options) => {
300
- if (isThreadIdControlledRef.current) {
301
- console.warn("[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
302
- return;
303
- }
304
- if (parentSetActiveThreadId) {
305
- parentSetActiveThreadId(id, options);
306
- return;
307
- }
308
- ownSetActiveThreadId(id, options);
309
- }, [parentSetActiveThreadId, ownSetActiveThreadId]);
310
- const resolvedStartNewThread = (0, react.useCallback)(() => {
311
- if (isThreadIdControlledRef.current) {
312
- console.warn("[CopilotKit] Ignoring startNewThread(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
313
- return;
314
- }
315
- if (parentStartNewThread) {
316
- parentStartNewThread();
317
- return;
318
- }
319
- ownStartNewThread();
320
- }, [parentStartNewThread, ownStartNewThread]);
321
- const setModalOpenWithDrawerExclusion = (0, react.useCallback)((open) => {
322
- if (open && isMobileViewport()) resolvedSetDrawerOpen(false);
323
- resolvedSetModalOpen(open);
324
- }, [resolvedSetModalOpen, resolvedSetDrawerOpen]);
325
- const configurationValue = (0, react.useMemo)(() => ({
326
- labels: mergedLabels,
327
- agentId: resolvedAgentId,
328
- threadId: resolvedThreadId,
329
- hasExplicitThreadId: resolvedHasExplicitThreadId,
330
- isModalOpen: resolvedIsModalOpen,
331
- setModalOpen: setModalOpenWithDrawerExclusion,
332
- drawerOpen: resolvedDrawerOpen,
333
- setDrawerOpen: resolvedSetDrawerOpen,
334
- drawerRegistered: resolvedDrawerRegistered,
335
- registerDrawer: resolvedRegisterDrawer,
336
- ɵregisterModalCloser: resolvedRegisterModalCloser,
337
- setActiveThreadId: resolvedSetActiveThreadId,
338
- startNewThread: resolvedStartNewThread
339
- }), [
340
- mergedLabels,
341
- resolvedAgentId,
342
- resolvedThreadId,
343
- resolvedHasExplicitThreadId,
344
- resolvedIsModalOpen,
345
- setModalOpenWithDrawerExclusion,
346
- resolvedDrawerOpen,
347
- resolvedSetDrawerOpen,
348
- resolvedDrawerRegistered,
349
- resolvedRegisterDrawer,
350
- resolvedRegisterModalCloser,
351
- resolvedSetActiveThreadId,
352
- resolvedStartNewThread
353
- ]);
354
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfiguration.Provider, {
355
- value: configurationValue,
356
- children
357
- });
358
- };
359
- const useCopilotChatConfiguration = () => {
360
- return (0, react.useContext)(CopilotChatConfiguration);
361
- };
362
- /**
363
- * Reports modal open/close requests to the host, and — when `open` is
364
- * supplied — makes the modal state of an already-established chat
365
- * configuration **controlled** for the subtree it wraps.
366
- *
367
- * This is deliberately a scope component rather than another mode inside
368
- * {@link CopilotChatConfigurationProvider}. The provider resolves modal state
369
- * across a nested chain (own state, parent sync, drawer mutual-exclusion, the
370
- * modal-closer registry); a controlled branch inside that resolution would add
371
- * a fourth interacting mode. Overriding the context for the subtree instead
372
- * leaves every one of those paths untouched:
373
- *
374
- * - `isModalOpen` is replaced with the host's `open`, so the rendered surface
375
- * follows the prop from the very first frame (no open-then-close flash).
376
- * - `setModalOpen` still calls the underlying setter, so the existing
377
- * parent-sync and drawer mutual-exclusion side effects continue to run, and
378
- * *then* reports the request through `onOpenChange`.
379
- * - The wrapped setter is registered as the modal closer, so the drawer's
380
- * mobile mutual-exclusion reaches the host instead of silently flipping
381
- * state that nothing displays.
382
- *
383
- * A host that supplies `open` and ignores `onOpenChange` gets a modal pinned
384
- * to `open`, which is the standard controlled-component contract. A host that
385
- * supplies only `onOpenChange` is notified while the modal keeps managing
386
- * itself.
387
- *
388
- * Renders `children` unchanged when no chat configuration is in scope.
389
- */
390
- const ControlledModalOpenScope = ({ children, open, onOpenChange }) => {
391
- const parentConfig = (0, react.useContext)(CopilotChatConfiguration);
392
- const parentSetModalOpen = parentConfig?.setModalOpen;
393
- const registerModalCloser = parentConfig?.ɵregisterModalCloser;
394
- const setModalOpen = (0, react.useCallback)((next) => {
395
- parentSetModalOpen?.(next);
396
- onOpenChange?.(next);
397
- }, [parentSetModalOpen, onOpenChange]);
398
- (0, react.useEffect)(() => {
399
- if (!registerModalCloser) return;
400
- return registerModalCloser(setModalOpen);
401
- }, [registerModalCloser, setModalOpen]);
402
- const configurationValue = (0, react.useMemo)(() => parentConfig ? {
403
- ...parentConfig,
404
- isModalOpen: open ?? parentConfig.isModalOpen,
405
- setModalOpen
406
- } : null, [
407
- parentConfig,
408
- open,
409
- setModalOpen
410
- ]);
411
- if (!configurationValue) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children });
412
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfiguration.Provider, {
413
- value: configurationValue,
414
- children
415
- });
416
- };
417
- ControlledModalOpenScope.displayName = "ControlledModalOpenScope";
418
-
419
- //#endregion
420
- //#region src/lib/utils.ts
421
- /**
422
- * Joins class names, skipping falsy values. Takes the same inputs as `clsx`.
423
- * Classes are not merged: every rule CopilotKit ships sits in `:where()`, so a
424
- * class the app adds wins without removing ours.
425
- */
426
- function cn(...inputs) {
427
- const out = [];
428
- for (const input of inputs) {
429
- if (!input) continue;
430
- if (typeof input === "string" || typeof input === "number" || typeof input === "bigint") out.push(String(input));
431
- else if (Array.isArray(input)) {
432
- const nested = cn(...input);
433
- if (nested) out.push(nested);
434
- } else if (typeof input === "object") {
435
- for (const key in input) if (input[key]) out.push(key);
436
- }
437
- }
438
- return out.join(" ");
439
- }
440
-
441
- //#endregion
442
- //#region src/lib/slots.tsx
443
- /**
444
- * Check if a value is a React component type (function, class, forwardRef, memo, etc.)
445
- */
446
- function isReactComponentType(value) {
447
- if (typeof value === "function") return true;
448
- if (value && typeof value === "object" && "$$typeof" in value && !react.default.isValidElement(value)) return true;
449
- return false;
450
- }
451
- /**
452
- * Internal function to render a slot value as a React element (non-memoized).
453
- */
454
- function renderSlotElement(slot, DefaultComponent, props) {
455
- if (typeof slot === "string") {
456
- const existingClassName = props.className;
457
- return react.default.createElement(DefaultComponent, {
458
- ...props,
459
- className: cn(existingClassName, slot)
460
- });
461
- }
462
- if (isReactComponentType(slot)) return react.default.createElement(slot, props);
463
- if (slot && typeof slot === "object" && !react.default.isValidElement(slot)) return react.default.createElement(DefaultComponent, {
464
- ...props,
465
- ...slot
466
- });
467
- return react.default.createElement(DefaultComponent, props);
468
- }
469
- /**
470
- * Internal memoized wrapper component for renderSlot.
471
- * Uses forwardRef to support ref forwarding.
472
- */
473
- const MemoizedSlotWrapper = react.default.memo(react.default.forwardRef(function MemoizedSlotWrapper(props, ref) {
474
- const { $slot, $component, ...rest } = props;
475
- return renderSlotElement($slot, $component, ref !== null ? {
476
- ...rest,
477
- ref
478
- } : rest);
479
- }), (prev, next) => {
480
- if (prev.$slot !== next.$slot) return false;
481
- if (prev.$component !== next.$component) return false;
482
- const { $slot: _ps, $component: _pc, ...prevRest } = prev;
483
- const { $slot: _ns, $component: _nc, ...nextRest } = next;
484
- return shallowEqual(prevRest, nextRest);
485
- });
486
- /**
487
- * Renders a slot value as a memoized React element.
488
- * Automatically prevents unnecessary re-renders using shallow prop comparison.
489
- * Supports ref forwarding.
490
- *
491
- * @example
492
- * renderSlot(customInput, CopilotChatInput, { onSubmit: handleSubmit })
493
- */
494
- function renderSlot(slot, DefaultComponent, props) {
495
- return react.default.createElement(MemoizedSlotWrapper, {
496
- ...props,
497
- $slot: slot,
498
- $component: DefaultComponent
499
- });
500
- }
501
-
502
- //#endregion
503
- //#region src/providers/MarkdownRendererContext.tsx
504
- const MarkdownRendererContext = (0, react.createContext)(void 0);
505
- const MarkdownRendererProvider = ({ renderer, children }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MarkdownRendererContext.Provider, {
506
- value: renderer,
507
- children
508
- });
509
- /**
510
- * The markdown renderer set at the provider level, or `undefined` when none was
511
- * supplied. Message components fall back to the built-in
512
- * `StreamingMarkdownDefaultRenderer` (via `CopilotChatAssistantMessage.MarkdownRenderer`)
513
- * when this is `undefined`.
514
- */
515
- function useMarkdownRenderer() {
516
- return (0, react.useContext)(MarkdownRendererContext);
517
- }
518
-
519
- //#endregion
520
- //#region src/types/defineToolCallRenderer.ts
521
- function defineToolCallRenderer(def) {
522
- const argsSchema = def.name === "*" && !def.args ? zod.z.any() : def.args;
523
- return {
524
- name: def.name,
525
- args: argsSchema,
526
- render: def.render,
527
- ...def.agentId ? { agentId: def.agentId } : {},
528
- ...def.group ? { group: true } : {}
529
- };
530
- }
531
-
532
- //#endregion
533
- //#region src/generative-ui/json-schema.ts
534
- /**
535
- * JSON Schema for a Standard Schema (zod v3 via zod-to-json-schema),
536
- * inlined, no `$schema`. A prop marked by `child()` or `childList()`
537
- * becomes an A2UI `$ref` to `ComponentId` or `ChildList`.
538
- */
539
- function toJsonSchema(schema) {
540
- const { $schema: _omit, ...rest } = (0, _copilotkit_shared.schemaToJsonSchema)(schema, { zodToJsonSchema: (s) => (0, zod_to_json_schema.zodToJsonSchema)(s, { $refStrategy: "none" }) });
541
- return (0, _copilotkit_shared.applyChildRefMarks)(rest);
542
- }
543
-
544
- //#endregion
545
- //#region src/generative-ui/catalog.ts
546
- /** The A2UI component envelope: `id`, `component`, `catalogId`, `accessibility`, `metadata`. */
547
- const RESERVED_KEYS = new Set([
548
- "id",
549
- "component",
550
- ..._copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS
551
- ]);
552
- /** The id of the catalog that declared each component, for the inspector. */
553
- const componentCatalogs = /* @__PURE__ */ new WeakMap();
554
- /**
555
- * The id of the catalog that declared each component of `ui`. A component
556
- * from `extends` keeps the id of its base. Not exported from the package.
557
- */
558
- function componentCatalogIds(ui) {
559
- return componentCatalogs.get(ui) ?? /* @__PURE__ */ new Map();
560
- }
561
- /**
562
- * The catalogs that an operation can name: the id of `ui`, then the ids of
563
- * the catalogs in its `extends` that declared a component. Not exported
564
- * from the package.
565
- */
566
- function catalogIdsOf(ui) {
567
- const declared = componentCatalogs.get(ui)?.values() ?? [];
568
- return [...new Set([ui.id, ...declared])];
569
- }
570
- /**
571
- * Experimental. Declares the components the model can render, the app state
572
- * they read, and the functions they call.
573
- *
574
- * - A prop with the name of a top-level state key is bound to that state.
575
- * - `bind: { prop: (state, props) => value }` binds a prop to a selector.
576
- * - An event binds to the function with its name, else to the name without
577
- * `on` (`onAddToCart` calls `addToCart`).
578
- * - `writable: ["value"]` gives the component a `setValue` prop. See
579
- * `GenerativeUIComponentDefinition.writable`.
580
- *
581
- * The model does not see bound props or matched events.
582
- *
583
- * @param config - `id`, then optional `extends`, `state`, `functions` and
584
- * `overrides`, then `components`. Put `state` before `components`, so the selectors
585
- * get typed state.
586
- * @throws Error when a name comes from two places, an override names no
587
- * component of the bases, `props` is not an object
588
- * schema with a JSON Schema, a key is reserved or used
589
- * twice on a component, an event matches two functions, an unmatched event
590
- * has no `parameters`, a `bind` key is not a prop, a `writable` key is not
591
- * a prop or is a bound prop, or a setter name is already a key of the
592
- * component. Also throws when `parameterOrder` contains duplicate or unknown
593
- * keys, or an ordered component declares integer-index keys whose JSON object
594
- * enumeration order cannot be controlled.
595
- *
596
- * @example
597
- * ```ts
598
- * const ui = createGenerativeUI({
599
- * id: "acme/store@1",
600
- * state: { cart: cartSchema },
601
- * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },
602
- * components: {
603
- * CartSummary: {
604
- * component: CartSummary,
605
- * props: z.object({ count: z.number() }),
606
- * bind: { count: (state) => state.cart.count },
607
- * },
608
- * },
609
- * });
610
- * ```
611
- */
612
- function createGenerativeUI(config) {
613
- return buildGenerativeUI(config);
614
- }
615
- function buildGenerativeUI(config) {
616
- const where = `generative UI "${config.id}"`;
617
- const state = /* @__PURE__ */ new Map();
618
- const functions = /* @__PURE__ */ new Map();
619
- const definitions = /* @__PURE__ */ new Map();
620
- const catalogs = /* @__PURE__ */ new Map();
621
- function add(map, kind, name, value) {
622
- if (map.has(name)) throw new Error(`[generativeUI] ${kind} "${name}" is defined more than once in ${where}.`);
623
- map.set(name, value);
624
- }
625
- const bases = config.extends ?? [];
626
- for (const base of bases) {
627
- for (const [name, schema] of base.state) add(state, "State key", name, schema);
628
- for (const [name, fn] of base.functions) add(functions, "Function", name, fn);
629
- const baseCatalogs = componentCatalogIds(base);
630
- for (const [name, component] of base.components) {
631
- add(definitions, "Component", name, component);
632
- catalogs.set(name, baseCatalogs.get(name) ?? base.id);
633
- }
634
- }
635
- for (const [name, override] of Object.entries(config.overrides ?? {})) {
636
- const base = definitions.get(name);
637
- if (!base) throw new Error(`[generativeUI] Override "${name}" is not a component of the bases of ${where}.`);
638
- definitions.set(name, {
639
- ...base,
640
- component: override.component
641
- });
642
- }
643
- for (const [name, schema] of Object.entries(config.state ?? {})) add(state, "State key", name, schema);
644
- for (const [name, fn] of Object.entries(config.functions ?? {})) add(functions, "Function", name, fn);
645
- for (const [name, fn] of functions) if (fn.requiresUserActivation === true && fn.allowedCallers !== void 0 && fn.allowedCallers !== "rendererOnly") throw new Error(`[generativeUI] Function "${name}" in ${where} requires user activation, so its allowedCallers must be "rendererOnly", not "${fn.allowedCallers}".`);
646
- for (const [name, component] of Object.entries(config.components)) {
647
- add(definitions, "Component", name, component);
648
- catalogs.set(name, config.id);
649
- }
650
- const components = /* @__PURE__ */ new Map();
651
- const manifestComponents = {};
652
- for (const [name, definition] of definitions) {
653
- const { component, manifest } = resolveComponent(name, definition, {
654
- state,
655
- functions,
656
- where
657
- });
658
- components.set(name, component);
659
- manifestComponents[name] = manifest;
660
- }
661
- return withOmit({
662
- id: config.id,
663
- state,
664
- functions,
665
- components,
666
- manifestComponents
667
- }, catalogs);
668
- }
669
- /** Adds the `omit` method to the data of a generative UI. */
670
- function withOmit(data, catalogs) {
671
- const omit = (names) => {
672
- for (const name of names) if (!data.components.has(name)) throw new Error(`[generativeUI] Cannot omit "${name}": it is not a component of generative UI "${data.id}".`);
673
- const isKept = (name) => !names.includes(name);
674
- return withOmit({
675
- id: data.id,
676
- state: data.state,
677
- functions: data.functions,
678
- components: new Map([...data.components].filter(([name]) => isKept(name))),
679
- manifestComponents: Object.fromEntries(Object.entries(data.manifestComponents).filter(([name]) => isKept(name)))
680
- }, catalogs);
681
- };
682
- const ui = {
683
- ...data,
684
- omit
685
- };
686
- componentCatalogs.set(ui, catalogs);
687
- return ui;
688
- }
689
- /** Builds the selectors, the event map and the manifest of one component. */
690
- function resolveComponent(name, definition, context) {
691
- const propsJson = propsJsonSchema(name, definition, context.where);
692
- const propKeys = Object.keys(propsJson.properties);
693
- assertDisjointKeys(name, definition, propKeys);
694
- assertParameterOrder(name, definition, propKeys);
695
- const selectors = {};
696
- for (const key of propKeys) if (context.state.has(key)) selectors[key] = (state) => state[key];
697
- const bind = definition.bind ?? {};
698
- for (const [key, selector] of Object.entries(bind)) {
699
- if (!propKeys.includes(key)) throw new Error(`[generativeUI] bind key "${key}" is not a prop of component "${name}" in ${context.where}.`);
700
- selectors[key] = selector;
701
- }
702
- const eventFunctions = {};
703
- const modelEvents = {};
704
- const events = definition.events ?? {};
705
- for (const [eventName, event] of Object.entries(events)) {
706
- const functionName = matchFunction(eventName, name, context);
707
- if (functionName !== void 0) {
708
- const matched = context.functions.get(functionName);
709
- if (matched && !(0, _copilotkit_shared.functionCallers)(matched).renderer) throw new Error(`[generativeUI] Event "${eventName}" of component "${name}" matches function "${functionName}", which the UI cannot call (allowedCallers "agentOnly") in ${context.where}.`);
710
- eventFunctions[eventName] = functionName;
711
- continue;
712
- }
713
- if (!event.parameters) throw new Error(`[generativeUI] Event "${eventName}" of component "${name}" matches no function in ${context.where}, so it needs "parameters".`);
714
- modelEvents[eventName] = {
715
- ...event.description ? { description: event.description } : {},
716
- parameters: toJsonSchema(event.parameters)
717
- };
718
- }
719
- assertWritable(name, definition, propKeys, selectors, context.where);
720
- return {
721
- component: {
722
- component: definition.component,
723
- description: definition.description,
724
- parameterOrder: definition.parameterOrder?.slice(),
725
- props: definition.props,
726
- bind: definition.bind,
727
- events: definition.events,
728
- slots: definition.slots,
729
- writable: definition.writable,
730
- accessibility: definition.accessibility ?? "wrapper",
731
- selectors,
732
- eventFunctions,
733
- propKeys,
734
- childRefs: (0, _copilotkit_shared.collectChildRefs)(propsJson)
735
- },
736
- manifest: toManifest(definition, modelPropsJsonSchema(propsJson, selectors), modelEvents)
737
- };
738
- }
739
- /** The JSON Schema of `props`. A component without `props` has none. */
740
- function propsJsonSchema(name, definition, where) {
741
- if (!definition.props) return {
742
- type: "object",
743
- properties: {}
744
- };
745
- const json = toJsonSchema(definition.props);
746
- const { properties } = json;
747
- if (!(typeof properties === "object" && properties !== null && !Array.isArray(properties))) throw new Error(`[generativeUI] the props of component "${name}" in ${where} must be an object schema.`);
748
- return json;
749
- }
750
- /**
751
- * What the model sees of the props: the JSON Schema without the bound props,
752
- * and with no other keys allowed.
753
- */
754
- function modelPropsJsonSchema(json, bound) {
755
- const isModelKey = (key) => !Object.hasOwn(bound, key);
756
- const { properties, required, additionalProperties: _additionalProperties, ...rest } = json;
757
- const modelRequired = Array.isArray(required) ? required.filter((key) => isModelKey(String(key))) : [];
758
- return {
759
- ...rest,
760
- type: "object",
761
- properties: Object.fromEntries(Object.entries(properties).filter(([key]) => isModelKey(key))),
762
- ...modelRequired.length > 0 ? { required: modelRequired } : {},
763
- additionalProperties: false
764
- };
765
- }
766
- /** `onAddToCart` to `addToCart`. `undefined` when the name has no `on` prefix. */
767
- function withoutOnPrefix(eventName) {
768
- if (!(eventName.length > 2 && eventName.startsWith("on"))) return void 0;
769
- return eventName.charAt(2).toLowerCase() + eventName.slice(3);
770
- }
771
- /** The declared function an event calls, or `undefined` when none matches. */
772
- function matchFunction(eventName, componentName, context) {
773
- const exact = context.functions.has(eventName) ? eventName : void 0;
774
- const stripped = withoutOnPrefix(eventName);
775
- const fromPrefix = stripped !== void 0 && context.functions.has(stripped) ? stripped : void 0;
776
- if (exact !== void 0 && fromPrefix !== void 0) throw new Error(`[generativeUI] Event "${eventName}" of component "${componentName}" matches two functions, "${exact}" and "${fromPrefix}", in ${context.where}.`);
777
- return exact ?? fromPrefix;
778
- }
779
- /** The setter prop of a writable prop: `value` gives `setValue`. */
780
- function setterNameOf(key) {
781
- return `set${key.charAt(0).toUpperCase()}${key.slice(1)}`;
782
- }
783
- /** Why a `writable` key is not valid, or `undefined` when it is valid. */
784
- function writableProblem(key, definition, propKeys, selectors) {
785
- if (Object.hasOwn(definition.events ?? {}, key)) return "an event";
786
- if (Object.hasOwn(definition.slots ?? {}, key)) return "a slot";
787
- if (!propKeys.includes(key)) return "not a prop";
788
- if (Object.hasOwn(selectors, key)) return "a bound prop";
789
- }
790
- function assertWritable(name, definition, propKeys, selectors, where) {
791
- const writable = definition.writable ?? [];
792
- const keys = new Set([
793
- ...propKeys,
794
- ...Object.keys(definition.events ?? {}),
795
- ...Object.keys(definition.slots ?? {})
796
- ]);
797
- for (const key of writable) {
798
- const problem = writableProblem(key, definition, propKeys, selectors);
799
- if (problem) throw new Error(`[generativeUI] writable key "${key}" of component "${name}" is ${problem} in ${where}.`);
800
- const setter = setterNameOf(key);
801
- if (keys.has(setter)) throw new Error(`[generativeUI] the setter "${setter}" of writable key "${key}" is already a key of component "${name}" in ${where}.`);
802
- }
803
- }
804
- function assertDisjointKeys(name, definition, propKeys) {
805
- const seen = /* @__PURE__ */ new Set();
806
- const keys = [
807
- ...propKeys,
808
- ...Object.keys(definition.events ?? {}),
809
- ...Object.keys(definition.slots ?? {})
810
- ];
811
- for (const key of keys) {
812
- if (RESERVED_KEYS.has(key)) throw new Error(`[generativeUI] "${key}" is reserved by A2UI and cannot be a prop, event or slot of component "${name}".`);
813
- if (seen.has(key)) throw new Error(`[generativeUI] "${key}" is declared as more than one of prop, event, slot on component "${name}".`);
814
- seen.add(key);
815
- }
816
- }
817
- function assertParameterOrder(name, definition, propKeys) {
818
- const order = definition.parameterOrder;
819
- if (order === void 0) return;
820
- const keys = new Set([
821
- ...propKeys,
822
- ...Object.keys(definition.slots ?? {}),
823
- ...Object.keys(definition.events ?? {})
824
- ]);
825
- if ([...keys].some((key) => {
826
- const index = Number(key);
827
- return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === key;
828
- })) throw new Error(`[generativeUI] Component "${name}" with parameterOrder cannot declare integer-index keys: JSON object enumeration sorts them numerically before other keys, ignoring the requested order.`);
829
- if (!Array.isArray(order) || new Set(order).size !== order.length || order.some((key) => !keys.has(key))) throw new Error(`[generativeUI] parameterOrder of component "${name}" must contain unique declared prop, slot or event names.`);
830
- }
831
- function toManifest(definition, modelProps, modelEvents) {
832
- const manifest = { props: modelProps };
833
- if (definition.description) manifest.description = definition.description;
834
- if (Object.keys(modelEvents).length > 0) manifest.events = modelEvents;
835
- if (definition.slots) manifest.slots = { ...definition.slots };
836
- if (definition.parameterOrder !== void 0) {
837
- const visible = new Set([
838
- ...Object.keys(modelProps.properties ?? {}),
839
- ...Object.keys(definition.slots ?? {}),
840
- ...Object.keys(modelEvents)
841
- ]);
842
- manifest.parameterOrder = [...new Set([...definition.parameterOrder.filter((key) => visible.has(key)), ...visible])];
843
- }
844
- return manifest;
845
- }
846
-
847
- //#endregion
848
- //#region src/generative-ui/is-record.ts
849
- /** True for a plain object: not null, not an array. Internal, not exported. */
850
- function isRecord(value) {
851
- return typeof value === "object" && value !== null && !Array.isArray(value);
852
- }
853
-
854
- //#endregion
855
- //#region src/generative-ui/errors.ts
856
- var GenerativeUIError = class extends Error {
857
- constructor(code, message) {
858
- super(message);
859
- this.name = "GenerativeUIError";
860
- this.code = code;
861
- }
862
- };
863
-
864
- //#endregion
865
- //#region src/generative-ui/functions.ts
866
- /**
867
- * The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes
868
- * resolved args (no bindings left in them) and gives a plain value. They
869
- * run synchronously, so a prop bound to one updates in the same render as
870
- * the data it reads. The signatures the model sees are in
871
- * `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).
872
- */
873
- /** Thrown for a bad call: an unknown function, bad args, or a bad value. */
874
- var ExpressionError = class extends Error {
875
- constructor(message) {
876
- super(message);
877
- this.name = "ExpressionError";
878
- }
879
- };
880
- /** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */
881
- function truthOf(value) {
882
- if ((0, _copilotkit_shared.isValidationResult)(value)) return value.valid;
883
- return Boolean(value);
884
- }
885
- const valid = () => ({ valid: true });
886
- /** A failed result. `code` names the failure, the same for every locale. */
887
- const invalid = (message, code) => ({
888
- valid: false,
889
- message,
890
- code
891
- });
892
- function text(value) {
893
- if (value === void 0 || value === null) return "";
894
- return typeof value === "string" ? value : String(value);
895
- }
896
- function numberOf$1(value) {
897
- if (typeof value === "number") return value;
898
- if (typeof value === "string" && value.trim() !== "") return Number(value);
899
- return NaN;
900
- }
901
- function optionalNumber(value, name) {
902
- if (value === void 0 || value === null) return void 0;
903
- const parsed = numberOf$1(value);
904
- if (Number.isNaN(parsed)) throw new ExpressionError(`${name} must be a number`);
905
- return parsed;
906
- }
907
- const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
908
- /** The locale of the user. `undefined` lets Intl pick the default. */
909
- function locale() {
910
- return typeof navigator !== "undefined" ? navigator.language : void 0;
911
- }
912
- function numberFormat(args, options) {
913
- const decimals = optionalNumber(args.decimals, "decimals");
914
- return new Intl.NumberFormat(locale(), {
915
- ...options,
916
- useGrouping: args.grouping !== false,
917
- ...decimals === void 0 ? {} : {
918
- minimumFractionDigits: decimals,
919
- maximumFractionDigits: decimals
920
- }
921
- });
922
- }
923
- /** A date from an ISO string, a timestamp, or a Date. */
924
- function dateOf(value) {
925
- const date = value instanceof Date ? value : typeof value === "number" ? new Date(value) : typeof value === "string" ? new Date(/^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00` : value) : void 0;
926
- if (date === void 0 || Number.isNaN(date.getTime())) throw new ExpressionError("value must be a date");
927
- return date;
928
- }
929
- const pad = (value, width) => String(value).padStart(width, "0");
930
- /**
931
- * A TR35 field is a run of one letter ("EEE" is one abbreviated weekday,
932
- * not three), and text in single quotes is literal. Letters that are not
933
- * fields stay as they are.
934
- */
935
- const DATE_FIELD = /([A-Za-z])\1*|'(?:[^']|'')*'/g;
936
- function formatDatePattern(date, pattern) {
937
- const parts = (options) => new Intl.DateTimeFormat(locale(), options).format(date);
938
- const hours12 = date.getHours() % 12 || 12;
939
- const numeric = (value, width) => width >= 2 ? pad(value, 2) : String(value);
940
- return pattern.replace(DATE_FIELD, (token) => {
941
- if (token.startsWith("'")) return token.slice(1, -1).replace(/''/g, "'");
942
- const width = token.length;
943
- switch (token[0]) {
944
- case "y": return width === 2 ? pad(date.getFullYear() % 100, 2) : String(date.getFullYear());
945
- case "M":
946
- if (width >= 4) return parts({ month: "long" });
947
- if (width === 3) return parts({ month: "short" });
948
- return numeric(date.getMonth() + 1, width);
949
- case "d": return numeric(date.getDate(), width);
950
- case "E": return parts({ weekday: width >= 4 ? "long" : "short" });
951
- case "H": return numeric(date.getHours(), width);
952
- case "h": return numeric(hours12, width);
953
- case "m": return pad(date.getMinutes(), 2);
954
- case "s": return pad(date.getSeconds(), 2);
955
- case "a": return date.getHours() < 12 ? "AM" : "PM";
956
- default: return token;
957
- }
958
- });
959
- }
960
- /** Opens an http(s) URL in a new tab. Any other scheme is refused. */
961
- function openUrlSafely(url) {
962
- if (typeof url !== "string" || url === "") throw new ExpressionError("url must be a string");
963
- if (typeof window === "undefined") return;
964
- let parsed;
965
- try {
966
- parsed = new URL(url, window.location.href);
967
- } catch {
968
- throw new ExpressionError(`"${url}" is not a URL`);
969
- }
970
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new ExpressionError(`openUrl takes only http(s) URLs, not ${parsed.protocol}`);
971
- window.open(parsed.href, "_blank", "noopener,noreferrer");
972
- }
973
- /**
974
- * The basic functions, except `formatString`, which needs the resolver.
975
- * `calc` and `series` are added by `resolve.ts`, which imports both.
976
- */
977
- const BASIC_FUNCTIONS = {
978
- required: ({ value }) => {
979
- return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0 ? invalid("Required", "required") : valid();
980
- },
981
- regex: ({ value, pattern }) => {
982
- if (typeof pattern !== "string") throw new ExpressionError("pattern must be a string");
983
- let expression;
984
- try {
985
- expression = new RegExp(pattern, "u");
986
- } catch {
987
- throw new ExpressionError(`"${pattern}" is not a regular expression`);
988
- }
989
- return expression.test(text(value)) ? valid() : invalid("Invalid format", "pattern");
990
- },
991
- length: ({ value, min, max }) => {
992
- const size = text(value).length;
993
- const low = optionalNumber(min, "min");
994
- const high = optionalNumber(max, "max");
995
- if (low !== void 0 && size < low) return invalid(`At least ${low} characters`, "tooShort");
996
- if (high !== void 0 && size > high) return invalid(`At most ${high} characters`, "tooLong");
997
- return valid();
998
- },
999
- numeric: ({ value, min, max }) => {
1000
- const parsed = numberOf$1(value);
1001
- if (Number.isNaN(parsed)) return invalid("Must be a number", "notANumber");
1002
- const low = optionalNumber(min, "min");
1003
- const high = optionalNumber(max, "max");
1004
- if (low !== void 0 && parsed < low) return invalid(`At least ${low}`, "tooSmall");
1005
- if (high !== void 0 && parsed > high) return invalid(`At most ${high}`, "tooLarge");
1006
- return valid();
1007
- },
1008
- email: ({ value }) => EMAIL.test(text(value)) ? valid() : invalid("Invalid email address", "email"),
1009
- formatNumber: (args) => {
1010
- const parsed = numberOf$1(args.value);
1011
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
1012
- return numberFormat(args, {}).format(parsed);
1013
- },
1014
- formatCurrency: (args) => {
1015
- const parsed = numberOf$1(args.value);
1016
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
1017
- if (typeof args.currency !== "string" || args.currency === "") throw new ExpressionError("currency must be an ISO 4217 code");
1018
- try {
1019
- return numberFormat(args, {
1020
- style: "currency",
1021
- currency: args.currency
1022
- }).format(parsed);
1023
- } catch {
1024
- throw new ExpressionError(`"${args.currency}" is not a currency code`);
1025
- }
1026
- },
1027
- formatDate: ({ value, format }) => {
1028
- if (typeof format !== "string") throw new ExpressionError("format must be a string");
1029
- return formatDatePattern(dateOf(value), format);
1030
- },
1031
- pluralize: (args) => {
1032
- const parsed = numberOf$1(args.value);
1033
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
1034
- const category = new Intl.PluralRules(locale()).select(parsed);
1035
- return text((parsed === 0 ? args.zero : void 0) ?? args[category] ?? args.other);
1036
- },
1037
- and: ({ values }) => {
1038
- if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
1039
- return values.every(truthOf);
1040
- },
1041
- or: ({ values }) => {
1042
- if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
1043
- return values.some(truthOf);
1044
- },
1045
- not: ({ value }) => !truthOf(value),
1046
- openUrl: ({ url }) => {
1047
- openUrlSafely(url);
1048
- }
1049
- };
1050
- /** True when the basic function `name` must run from a user gesture. */
1051
- function requiresUserActivation(name) {
1052
- return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.requiresUserActivation === true;
1053
- }
1054
- /** True when a basic function gives a ValidationResult. */
1055
- function givesValidationResult(name) {
1056
- return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.returnType === "validationResult";
1057
- }
1058
-
1059
- //#endregion
1060
- //#region src/generative-ui/markdown/source.ts
1061
- /**
1062
- * Values by key, from the latest build. A value that a build does not use
1063
- * is dropped at the end of that build, so the cache does not grow.
1064
- */
1065
- var BuildMemo = class {
1066
- constructor() {
1067
- this.previous = /* @__PURE__ */ new Map();
1068
- this.current = /* @__PURE__ */ new Map();
1069
- }
1070
- /**
1071
- * The value of `key`. It is computed when no earlier value is there, or
1072
- * when `isFresh` says that the earlier value is out of date.
1073
- */
1074
- get(key, compute, isFresh = () => true) {
1075
- let value = this.current.get(key) ?? this.previous.get(key);
1076
- if (value === void 0 || !isFresh(value)) value = compute();
1077
- this.current.set(key, value);
1078
- return value;
1079
- }
1080
- endBuild() {
1081
- this.previous = this.current;
1082
- this.current = /* @__PURE__ */ new Map();
1083
- }
1084
- };
1085
- /** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */
1086
- var MarkdownBuildCache = class {
1087
- constructor() {
1088
- this.segments = new BuildMemo();
1089
- this.fences = new BuildMemo();
1090
- this.drafts = new BuildMemo();
1091
- this.readdressed = /* @__PURE__ */ new WeakMap();
1092
- }
1093
- endBuild() {
1094
- this.segments.endBuild();
1095
- this.fences.endBuild();
1096
- this.drafts.endBuild();
1097
- }
1098
- };
1099
- /** True when both lists hold the same objects in the same order. */
1100
- function sameItems(a, b) {
1101
- return a.length === b.length && a.every((item, index) => item === b[index]);
1102
- }
1103
- function isString(value) {
1104
- return typeof value === "string";
1105
- }
1106
- /** The key of one fence of one message. */
1107
- function fenceKey(messageId, fenceIndex) {
1108
- return `${messageId}:${fenceIndex}`;
1109
- }
1110
- /**
1111
- * The operations of a fence body. While the fence streams, the last object
1112
- * can be unfinished. Of an unfinished updateComponents or createSurface, the
1113
- * components that are complete render at once (a createSurface also keeps
1114
- * its data model when all of it arrived). Any other unfinished object is
1115
- * left out, because a part of a data model value can still change. A final
1116
- * fence keeps what can be saved from an unfinished object.
1117
- */
1118
- function fenceOperations(text, isStreaming) {
1119
- const parsed = (0, _copilotkit_core.extractFenceOperations)(text);
1120
- if (!isStreaming || parsed.partialObject === null) return parsed.operations;
1121
- const complete = (0, _copilotkit_core.extractFenceOperations)(text.slice(0, text.length - parsed.partialObject.length)).operations;
1122
- const partial = parsed.operations.length > complete.length ? parsed.operations[parsed.operations.length - 1] : void 0;
1123
- return partial !== void 0 && (isRecord(partial.updateComponents) || isRecord(partial.createSurface)) ? [...complete, partial] : complete;
1124
- }
1125
- /**
1126
- * An inline createSurface becomes a createSurface with only its surfaceId
1127
- * and catalog, then an updateDataModel for its data model, then an
1128
- * updateComponents for its components. The prose lift and the split per
1129
- * component read only updateComponents, so they then work for an inline
1130
- * surface too. A createSurface with a data model or components of a wrong
1131
- * shape does not change, so that validation rejects it with the reason.
1132
- */
1133
- function expandInlineCreate(operations) {
1134
- return operations.flatMap((op) => {
1135
- const create = op.createSurface;
1136
- if (!isRecord(create)) return [op];
1137
- const { dataModel, components, ...rest } = create;
1138
- const hasData = isRecord(dataModel);
1139
- const hasComponents = Array.isArray(components) && components.length > 0;
1140
- if (!((dataModel === void 0 || hasData) && (components === void 0 || hasComponents)) || !hasData && !hasComponents) return [op];
1141
- const { surfaceId } = create;
1142
- const expanded = [{
1143
- ...op,
1144
- createSurface: rest
1145
- }];
1146
- if (hasData) expanded.push({
1147
- version: op.version,
1148
- updateDataModel: {
1149
- surfaceId,
1150
- path: "/",
1151
- value: dataModel
1152
- }
1153
- });
1154
- if (hasComponents) expanded.push({
1155
- version: op.version,
1156
- updateComponents: {
1157
- surfaceId,
1158
- components
1159
- }
1160
- });
1161
- return expanded;
1162
- });
1163
- }
1164
- /**
1165
- * Each updateComponents becomes one operation per component, in order. The
1166
- * complete components of a streaming line then give the same first
1167
- * operations as the finished line, so the operation list only grows and the
1168
- * manager never has to start the surface again.
1169
- */
1170
- function splitComponentUpdates(operations) {
1171
- return operations.flatMap((op) => {
1172
- const update = op.updateComponents;
1173
- if (!isRecord(update) || !Array.isArray(update.components)) return [op];
1174
- if (update.components.length <= 1) return [op];
1175
- return update.components.map((component) => ({
1176
- ...op,
1177
- updateComponents: {
1178
- ...update,
1179
- components: [component]
1180
- }
1181
- }));
1182
- });
1183
- }
1184
- /** createSurface first, the other operations after it in their order. */
1185
- function createSurfaceFirst(operations) {
1186
- const creates = operations.filter((op) => isRecord(op.createSurface));
1187
- const others = operations.filter((op) => !isRecord(op.createSurface));
1188
- return [...creates, ...others];
1189
- }
1190
- /** True when the component of `name` has the prop `prop`. */
1191
- function hasProp(ui, name, prop) {
1192
- const properties = ui.manifestComponents[name]?.props.properties;
1193
- return isRecord(properties) && Object.hasOwn(properties, prop);
1194
- }
1195
- const childRefCache = /* @__PURE__ */ new WeakMap();
1196
- /** The ids in a slot value: an id, a list of ids, or a template. */
1197
- function slotIds(value) {
1198
- if (typeof value === "string") return [value];
1199
- if (Array.isArray(value)) return value.filter(isString);
1200
- return isRecord(value) && isString(value.componentId) ? [value.componentId] : [];
1201
- }
1202
- /**
1203
- * A reader of the ids a component renders beyond `child` and `children`:
1204
- * its declared slots (the `trigger` and `content` of a Modal) and its typed
1205
- * child references (the `child` of each entry of `tabs`), from its catalog
1206
- * entry. The prose lift follows these ids like `children`, so a panel is
1207
- * never cut off from its Tabs. A reference that is bound to the data
1208
- * model is "unknown": its ids exist only at render time.
1209
- */
1210
- function childIdsReader(ui) {
1211
- return (component) => {
1212
- const name = component.component;
1213
- const entry = typeof name === "string" && Object.hasOwn(ui.manifestComponents, name) ? ui.manifestComponents[name] : void 0;
1214
- if (!entry) return [];
1215
- const ids = [];
1216
- for (const slot of Object.keys(entry.slots ?? {})) if (slot !== "child" && slot !== "children") ids.push(...slotIds(component[slot]));
1217
- let refs = childRefCache.get(entry.props);
1218
- if (!refs) {
1219
- refs = (0, _copilotkit_shared.collectChildRefs)(entry.props);
1220
- childRefCache.set(entry.props, refs);
1221
- }
1222
- if (refs.length === 0) return ids;
1223
- if ((0, _copilotkit_shared.hasBoundChildRef)(component, refs)) return "unknown";
1224
- return [...ids, ...(0, _copilotkit_shared.childIdsAtRefs)(component, refs)];
1225
- };
1226
- }
1227
- /** Every component of the operations by id, last definition wins. */
1228
- function collectComponents(operations) {
1229
- const byId = /* @__PURE__ */ new Map();
1230
- for (const op of operations) {
1231
- const update = op.updateComponents;
1232
- const list = isRecord(update) ? update.components : void 0;
1233
- if (!Array.isArray(list)) continue;
1234
- for (const component of list) if (isRecord(component) && isString(component.id)) byId.set(component.id, component);
1235
- }
1236
- return [...byId.values()];
1237
- }
1238
- /**
1239
- * The data model must not be shared between two surfaces. A data model
1240
- * keeps the object it gets, so an input in one surface would change the
1241
- * data of the other one.
1242
- */
1243
- function cloneData(value) {
1244
- return value === void 0 ? void 0 : structuredClone(value);
1245
- }
1246
- /** The operation sent to `surfaceId`, with a copy of its data model value. */
1247
- function readdress(op, surfaceId) {
1248
- const kind = (0, _copilotkit_shared.getOperationKind)(op);
1249
- const payload = kind ? op[kind] : void 0;
1250
- if (!kind || !isRecord(payload)) return op;
1251
- const next = {
1252
- ...payload,
1253
- surfaceId
1254
- };
1255
- if (kind === "updateDataModel" && "value" in payload) next.value = cloneData(payload.value);
1256
- return {
1257
- ...op,
1258
- [kind]: next
1259
- };
1260
- }
1261
- /**
1262
- * The operations of one sub-surface. Each updateComponents keeps only the
1263
- * components of the sub-surface, with its own root. The other operations
1264
- * are sent to the sub-surface. The order stays the same, so a new operation
1265
- * of the fence only adds operations at the end.
1266
- */
1267
- function subSurfaceOperations(operations, components, surfaceId) {
1268
- const root = components.find((c) => c.id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID);
1269
- const ids = new Set(components.map((c) => c.id));
1270
- const out = [];
1271
- for (const op of operations) {
1272
- const update = op.updateComponents;
1273
- if (!isRecord(update) || !Array.isArray(update.components)) {
1274
- out.push(readdress(op, surfaceId));
1275
- continue;
1276
- }
1277
- const kept = update.components.filter((c) => isRecord(c) && ids.has(c.id)).map((c) => isRecord(c) && c.id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID ? root : c);
1278
- if (kept.length === 0) continue;
1279
- out.push({
1280
- ...op,
1281
- updateComponents: {
1282
- ...update,
1283
- surfaceId,
1284
- components: kept
1285
- }
1286
- });
1287
- }
1288
- return out;
1289
- }
1290
- /**
1291
- * Prose lift. Text components in the main stack of the surface (titles,
1292
- * paragraphs, text lists and the dividers between them) become chat
1293
- * markdown. The surface splits around them: the first surface keeps
1294
- * `surfaceId`, the next ones are `<surfaceId>#1`, `<surfaceId>#2`, and so
1295
- * on. A surface with no prose comes back as one part with the same
1296
- * operations.
1297
- */
1298
- function liftProse(operations, surfaceId, childIds) {
1299
- const components = collectComponents(operations);
1300
- const segments = (0, _copilotkit_core.segmentSurfaceProse)(components, { childIds });
1301
- const [first] = segments;
1302
- if (segments.length === 1 && first?.kind === "surface" && first.components === components) return [{
1303
- kind: "surface",
1304
- surfaceId,
1305
- operations
1306
- }];
1307
- let surfaceIndex = 0;
1308
- return segments.map((segment) => {
1309
- if (segment.kind === "markdown") return segment;
1310
- const id = surfaceIndex === 0 ? surfaceId : `${surfaceId}#${surfaceIndex}`;
1311
- surfaceIndex++;
1312
- return {
1313
- kind: "surface",
1314
- surfaceId: id,
1315
- operations: subSurfaceOperations(operations, segment.components, id)
1316
- };
1317
- });
1318
- }
1319
- /** `validateOperation`, with the operation typed when it is valid. */
1320
- function checkOperation(op, options) {
1321
- const validation = (0, _copilotkit_shared.validateOperation)(op, options);
1322
- if (!validation.ok) return validation;
1323
- return {
1324
- ok: true,
1325
- operation: op
1326
- };
1327
- }
1328
- /**
1329
- * The content of one surface. Each operation is validated against the
1330
- * manifest. A valid operation goes in `operations`. A rejected one goes in
1331
- * `rejected`, with its position and the reason.
1332
- */
1333
- function surfaceContent(surfaceId, draft, operations, options) {
1334
- const { ui, functions } = options;
1335
- const knownSurfaces = /* @__PURE__ */ new Set();
1336
- const manifest = {
1337
- catalogId: ui.id,
1338
- catalogIds: catalogIdsOf(ui),
1339
- components: ui.manifestComponents
1340
- };
1341
- const valid = [];
1342
- const rejected = [];
1343
- operations.forEach((op, index) => {
1344
- const result = checkOperation(op, {
1345
- manifest,
1346
- knownSurfaces,
1347
- functions
1348
- });
1349
- if (!result.ok) {
1350
- rejected.push({
1351
- index,
1352
- reason: result.reason
1353
- });
1354
- return;
1355
- }
1356
- valid.push(result.operation);
1357
- const kind = (0, _copilotkit_shared.getOperationKind)(result.operation);
1358
- if (kind === "createSurface") knownSurfaces.add(surfaceId);
1359
- if (kind === "deleteSurface") knownSurfaces.delete(surfaceId);
1360
- });
1361
- const create = valid.find((op) => "createSurface" in op);
1362
- return {
1363
- surfaceId,
1364
- target: draft.target,
1365
- catalogId: create?.createSurface.catalogId ?? ui.id,
1366
- operations: valid,
1367
- status: draft.streaming ? "streaming" : "ready",
1368
- rejected
1369
- };
1370
- }
1371
- /**
1372
- * Builds the surfaces of a thread from the ```a2ui fences of its assistant
1373
- * messages, in message order.
1374
- *
1375
- * - Operations are grouped by surfaceId across all messages. An operation
1376
- * with no surfaceId goes to the first surface of its fence, else to
1377
- * `<messageId>-<fenceIndex>`.
1378
- * - The fence that first writes a surface creates it. The `target=<id>` of
1379
- * that fence sets the target. With no target, the surface goes to the
1380
- * chat.
1381
- * - A later fence of the same reply for the same surfaceId updates it. A
1382
- * later reply that reuses the id of a chat surface gets a surface of its
1383
- * own, `<id>@<messageId>`. A page target is updated from any reply.
1384
- * - The status is "streaming" while the creating fence streams, else
1385
- * "ready".
1386
- * - Each operation is validated with `validateOperation`. Rejected ones are
1387
- * left out and listed in `rejected`.
1388
- * - Chat surfaces get the prose lift: informational cards lose their box,
1389
- * and prose becomes markdown that renders between sub-surfaces
1390
- * (`<surfaceId>#<n>`). An inline createSurface is split into its
1391
- * createSurface, updateDataModel and updateComponents first.
1392
- * - A `callRendererFunction` line is not part of a surface. It goes to
1393
- * `functionCalls`. A streaming line gives nothing, so a function never
1394
- * runs with a part of its args.
1395
- *
1396
- * The function is pure. Call it again on each stream update. The manager
1397
- * applies only the new operations, so unchanged surfaces do not render
1398
- * again.
1399
- *
1400
- * @param messages - The messages of one thread.
1401
- * @param options - The generative UI, its declared functions, and whether
1402
- * the last message can still grow.
1403
- * @returns `surfaces`, one content for each surface and sub-surface;
1404
- * `fences`, the blocks that each fence renders, by `fenceKey` (a fence
1405
- * that is not in `fences` renders nothing); `functionCalls`, the function
1406
- * calls of the fences in order; and `parts`, the surface ids of the parts
1407
- * of each surface, by surface id.
1408
- *
1409
- * @example
1410
- * ```ts
1411
- * const { surfaces } = buildMarkdownSurfaces(agent.messages, {
1412
- * ui,
1413
- * functions: {},
1414
- * running: agent.isRunning,
1415
- * });
1416
- * for (const content of surfaces) manager.ingest(threadId, agentId, content);
1417
- * ```
1418
- */
1419
- function buildMarkdownSurfaces(messages, options) {
1420
- const { ui, cache } = options;
1421
- const drafts = /* @__PURE__ */ new Map();
1422
- const readdressOnce = (op, surfaceId) => {
1423
- if (!cache) return readdress(op, surfaceId);
1424
- let copies = cache.readdressed.get(op);
1425
- if (!copies) {
1426
- copies = /* @__PURE__ */ new Map();
1427
- cache.readdressed.set(op, copies);
1428
- }
1429
- let copy = copies.get(surfaceId);
1430
- if (!copy) {
1431
- copy = readdress(op, surfaceId);
1432
- copies.set(surfaceId, copy);
1433
- }
1434
- return copy;
1435
- };
1436
- /** The surfaces that each fence created, in order. */
1437
- const created = /* @__PURE__ */ new Map();
1438
- const functionCalls = [];
1439
- /** The message that owns each chat surface id, by the id the model wrote. */
1440
- const chatOwners = /* @__PURE__ */ new Map();
1441
- const lastMessage = messages[messages.length - 1];
1442
- /**
1443
- * A chat surface belongs to the reply that wrote it: the chat is a
1444
- * transcript, so a later reply that reuses an id gets a surface of its
1445
- * own (`<id>@<messageId>`) instead of changing the earlier reply. A fence
1446
- * for a page target keeps its id, because a target is a place on the
1447
- * page that a later reply updates on purpose.
1448
- */
1449
- const scopedSurfaceId = (requested, messageId, target) => {
1450
- if (target !== void 0) return requested;
1451
- const owner = chatOwners.get(requested);
1452
- if (owner === void 0) {
1453
- chatOwners.set(requested, messageId);
1454
- return requested;
1455
- }
1456
- return owner === messageId ? requested : `${requested}@${messageId}`;
1457
- };
1458
- for (const message of messages) {
1459
- if (message.role !== "assistant" || !isString(message.content)) continue;
1460
- const isLastMessage = message === lastMessage;
1461
- const content = message.content;
1462
- const segments = cache ? cache.segments.get(content, () => (0, _copilotkit_core.splitA2UIMarkdown)(content)) : (0, _copilotkit_core.splitA2UIMarkdown)(content);
1463
- for (const segment of segments) {
1464
- if (segment.type !== "a2ui") continue;
1465
- const isStreaming = !segment.closed && isLastMessage && options.running;
1466
- const parseFence = () => {
1467
- const parsed = fenceOperations(segment.text, isStreaming);
1468
- const { functionCalls } = (0, _copilotkit_core.prepareSurfaceOperations)({
1469
- operations: parsed,
1470
- fallbackSurfaceId: "",
1471
- catalogId: ui.id
1472
- });
1473
- return {
1474
- operations: parsed,
1475
- functionCalls
1476
- };
1477
- };
1478
- const fence = cache ? cache.fences.get(`${isStreaming}:${segment.text}`, parseFence) : parseFence();
1479
- const { operations } = fence;
1480
- const key = fenceKey(message.id, segment.index);
1481
- const fenceSurfaceId = operations.map(_copilotkit_core.getMarkdownOperationSurfaceId).find(isString) ?? `${message.id}-${segment.index}`;
1482
- for (const operation of fence.functionCalls) functionCalls.push({
1483
- messageId: message.id,
1484
- fenceIndex: segment.index,
1485
- operation
1486
- });
1487
- const surfaceOperations = operations.filter((op) => (0, _copilotkit_shared.getOperationKind)(op) !== "callRendererFunction");
1488
- for (const op of surfaceOperations) {
1489
- const requested = (0, _copilotkit_core.getMarkdownOperationSurfaceId)(op) ?? fenceSurfaceId;
1490
- const surfaceId = scopedSurfaceId(requested, message.id, segment.target);
1491
- let draft = drafts.get(surfaceId);
1492
- if (!draft) {
1493
- draft = {
1494
- surfaceId,
1495
- target: segment.target ?? _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
1496
- operations: [],
1497
- streaming: isStreaming
1498
- };
1499
- drafts.set(surfaceId, draft);
1500
- created.set(key, [...created.get(key) ?? [], surfaceId]);
1501
- }
1502
- draft.operations.push(surfaceId === requested ? op : readdressOnce(op, surfaceId));
1503
- }
1504
- }
1505
- }
1506
- const canFlattenCards = hasProp(ui, "Card", "variant");
1507
- const surfaces = [];
1508
- const partsBySurface = /* @__PURE__ */ new Map();
1509
- const childIds = childIdsReader(ui);
1510
- const buildDraft = (draft) => {
1511
- const operations = splitComponentUpdates(expandInlineCreate(createSurfaceFirst((0, _copilotkit_core.prepareSurfaceOperations)({
1512
- operations: draft.operations,
1513
- fallbackSurfaceId: draft.surfaceId,
1514
- catalogId: ui.id,
1515
- catalogIds: catalogIdsOf(ui)
1516
- }).operations)));
1517
- const parts = draft.target === _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET ? liftProse(canFlattenCards ? (0, _copilotkit_core.flattenInformationalCards)(operations, { childIds }) : operations, draft.surfaceId, childIds) : [{
1518
- kind: "surface",
1519
- surfaceId: draft.surfaceId,
1520
- operations
1521
- }];
1522
- const contents = parts.flatMap((part) => part.kind === "surface" ? [surfaceContent(part.surfaceId, draft, part.operations, options)] : []);
1523
- return {
1524
- ...draft,
1525
- parts,
1526
- contents
1527
- };
1528
- };
1529
- for (const draft of drafts.values()) {
1530
- const built = cache ? cache.drafts.get(draft.surfaceId, () => buildDraft(draft), (last) => last.target === draft.target && last.streaming === draft.streaming && sameItems(last.operations, draft.operations)) : buildDraft(draft);
1531
- partsBySurface.set(draft.surfaceId, built.parts);
1532
- surfaces.push(...built.contents);
1533
- }
1534
- cache?.endBuild();
1535
- /** The surface ids of the parts of each split surface, by surface id. */
1536
- const parts = /* @__PURE__ */ new Map();
1537
- for (const [surfaceId, surfaceParts] of partsBySurface) {
1538
- const ids = surfaceParts.flatMap((part) => part.kind === "surface" ? [part.surfaceId] : []);
1539
- parts.set(surfaceId, ids);
1540
- }
1541
- const fences = /* @__PURE__ */ new Map();
1542
- for (const [key, surfaceIds] of created) {
1543
- const blocks = [];
1544
- for (const surfaceId of surfaceIds) {
1545
- if (drafts.get(surfaceId)?.target !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET) continue;
1546
- for (const part of partsBySurface.get(surfaceId) ?? []) blocks.push(part.kind === "markdown" ? part : {
1547
- kind: "surface",
1548
- surfaceId: part.surfaceId
1549
- });
1550
- }
1551
- if (blocks.length > 0) fences.set(key, blocks);
1552
- }
1553
- return {
1554
- surfaces,
1555
- fences,
1556
- functionCalls,
1557
- parts
1558
- };
1559
- }
1560
- /** The declared functions, as `validateOperation` takes them. */
1561
- function declaredFunctions(ui) {
1562
- const functions = {};
1563
- for (const [name, fn] of ui.functions) try {
1564
- functions[name] = {
1565
- ...fn.description ? { description: fn.description } : {},
1566
- parameters: toJsonSchema(fn.parameters)
1567
- };
1568
- } catch {
1569
- functions[name] = { parameters: {} };
1570
- }
1571
- return functions;
1572
- }
1573
- /** True when `list` starts with all the items of `prefix`. */
1574
- function startsWith(list, prefix) {
1575
- return list.length >= prefix.length && prefix.every((item, index) => item === list[index]);
1576
- }
1577
- /** A content that deletes a surface that the fences no longer write. */
1578
- function removalContent(surfaceId, catalogId) {
1579
- return {
1580
- surfaceId,
1581
- target: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
1582
- catalogId,
1583
- status: "ready",
1584
- rejected: [],
1585
- operations: [{
1586
- version: _copilotkit_shared.A2UI_VERSION,
1587
- createSurface: {
1588
- surfaceId,
1589
- catalogId
1590
- }
1591
- }, {
1592
- version: _copilotkit_shared.A2UI_VERSION,
1593
- deleteSurface: { surfaceId }
1594
- }]
1595
- };
1596
- }
1597
- /**
1598
- * The markdown transport source of one surface manager. It turns the
1599
- * messages of a thread into surfaces in the manager, and keeps the blocks
1600
- * that each fence renders.
1601
- */
1602
- var MarkdownSurfaceSource = class {
1603
- constructor(manager, ui) {
1604
- this.manager = manager;
1605
- this.ui = ui;
1606
- this.fences = /* @__PURE__ */ new Map();
1607
- this.ingested = /* @__PURE__ */ new Map();
1608
- this.contents = /* @__PURE__ */ new Map();
1609
- this.caches = /* @__PURE__ */ new Map();
1610
- this.functions = declaredFunctions(ui);
1611
- }
1612
- /**
1613
- * Builds the surfaces of `threadId` from `messages` and gives them to the
1614
- * manager. A surface that an earlier sync of the thread made, and that the
1615
- * messages no longer write, is deleted. Other threads do not change.
1616
- *
1617
- * @param threadId - The thread of the messages.
1618
- * @param agentId - The agent that owns the thread.
1619
- * @param messages - All messages of the thread.
1620
- * @param options - `running`: the last message can still grow.
1621
- * @returns The function calls of the fences, in order. The source does
1622
- * not run them.
1623
- */
1624
- sync(threadId, agentId, messages, options) {
1625
- let cache = this.caches.get(threadId);
1626
- if (!cache) {
1627
- cache = new MarkdownBuildCache();
1628
- this.caches.set(threadId, cache);
1629
- }
1630
- const result = buildMarkdownSurfaces(messages, {
1631
- ui: this.ui,
1632
- functions: this.functions,
1633
- running: options.running,
1634
- cache
1635
- });
1636
- this.fences.set(threadId, result.fences);
1637
- for (const parts of result.parts.values()) this.manager.linkSurfaces(threadId, parts);
1638
- const previous = this.ingested.get(threadId) ?? /* @__PURE__ */ new Map();
1639
- const previousContents = this.contents.get(threadId) ?? /* @__PURE__ */ new Map();
1640
- const next = /* @__PURE__ */ new Map();
1641
- const nextContents = /* @__PURE__ */ new Map();
1642
- for (const content of result.surfaces) {
1643
- nextContents.set(content.surfaceId, content);
1644
- const before = previous.get(content.surfaceId);
1645
- if (before && previousContents.get(content.surfaceId) === content) {
1646
- next.set(content.surfaceId, before);
1647
- continue;
1648
- }
1649
- const fingerprints = content.operations.map((op) => JSON.stringify(op));
1650
- if (before && !startsWith(fingerprints, before)) this.manager.ingest(threadId, agentId, {
1651
- ...content,
1652
- operations: []
1653
- });
1654
- this.manager.ingest(threadId, agentId, content);
1655
- next.set(content.surfaceId, fingerprints);
1656
- }
1657
- for (const surfaceId of previous.keys()) {
1658
- if (next.has(surfaceId)) continue;
1659
- this.manager.ingest(threadId, agentId, removalContent(surfaceId, this.ui.id));
1660
- }
1661
- this.ingested.set(threadId, next);
1662
- this.contents.set(threadId, nextContents);
1663
- return result.functionCalls;
1664
- }
1665
- /**
1666
- * The blocks that a fence renders in the chat, from the latest sync of the
1667
- * thread. `undefined` when the fence renders nothing: it updates a surface
1668
- * of an earlier fence, its surface is for a named target, or it has no
1669
- * complete operation yet.
1670
- */
1671
- getFenceBlocks(threadId, messageId, fenceIndex) {
1672
- return this.fences.get(threadId)?.get(fenceKey(messageId, fenceIndex));
1673
- }
1674
- };
1675
- const sources = /* @__PURE__ */ new WeakMap();
1676
- /**
1677
- * The markdown source of a generative UI runtime. There is one source for
1678
- * each surface manager. The root syncs it, and the chat messages read the
1679
- * fence blocks from it.
1680
- */
1681
- function getMarkdownSurfaceSource(runtime) {
1682
- let source = sources.get(runtime.manager);
1683
- if (!source) {
1684
- source = new MarkdownSurfaceSource(runtime.manager, runtime.ui);
1685
- sources.set(runtime.manager, source);
1686
- }
1687
- return source;
1688
- }
1689
-
1690
- //#endregion
1691
- //#region src/generative-ui/calc.ts
1692
- const MAX_SERIES = 1e3;
1693
- const OPERATORS = [
1694
- "&&",
1695
- "||",
1696
- "==",
1697
- "!=",
1698
- "<=",
1699
- ">=",
1700
- "<",
1701
- ">",
1702
- "+",
1703
- "-",
1704
- "*",
1705
- "/",
1706
- "%",
1707
- "(",
1708
- ")",
1709
- ",",
1710
- "?",
1711
- ":",
1712
- "!"
1713
- ];
1714
- function tokenize(source) {
1715
- const tokens = [];
1716
- let i = 0;
1717
- while (i < source.length) {
1718
- const char = source[i];
1719
- if (/\s/.test(char)) {
1720
- i++;
1721
- continue;
1722
- }
1723
- if (/[0-9.]/.test(char)) {
1724
- const match = /^\d*\.?\d+(?:[eE][-+]?\d+)?|^\d+\.?/.exec(source.slice(i));
1725
- if (!match) throw new ExpressionError(`calc: bad number at "${source.slice(i, i + 8)}"`);
1726
- tokens.push({
1727
- kind: "number",
1728
- value: Number(match[0])
1729
- });
1730
- i += match[0].length;
1731
- continue;
1732
- }
1733
- if (char === "'" || char === "\"") {
1734
- let value = "";
1735
- i++;
1736
- while (i < source.length && source[i] !== char) {
1737
- if (source[i] === "\\" && i + 1 < source.length) i++;
1738
- value += source[i++];
1739
- }
1740
- if (i >= source.length) throw new ExpressionError("calc: unclosed string");
1741
- i++;
1742
- tokens.push({
1743
- kind: "string",
1744
- value
1745
- });
1746
- continue;
1747
- }
1748
- if (/[A-Za-z_]/.test(char)) {
1749
- const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));
1750
- tokens.push({
1751
- kind: "name",
1752
- value: match[0]
1753
- });
1754
- i += match[0].length;
1755
- continue;
1756
- }
1757
- const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));
1758
- if (!op) throw new ExpressionError(`calc: unexpected "${char}"`);
1759
- tokens.push({
1760
- kind: "op",
1761
- value: op
1762
- });
1763
- i += op.length;
1764
- }
1765
- tokens.push({ kind: "end" });
1766
- return tokens;
1767
- }
1768
- function numberOf(value, what) {
1769
- if (typeof value === "number") {
1770
- if (!Number.isFinite(value)) throw new ExpressionError(`calc: ${what} is not finite`);
1771
- return value;
1772
- }
1773
- if (typeof value === "boolean") return value ? 1 : 0;
1774
- if (typeof value === "string" && value.trim() !== "") {
1775
- const parsed = Number(value);
1776
- if (Number.isFinite(parsed)) return parsed;
1777
- }
1778
- if (value === null || value === void 0) throw new ExpressionError(`calc: ${what} has no value`);
1779
- throw new ExpressionError(`calc: ${what} is not a number`);
1780
- }
1781
- function describe(value) {
1782
- return typeof value === "string" ? `"${value}"` : String(value);
1783
- }
1784
- const MATH = {
1785
- min: (args) => Math.min(...args),
1786
- max: (args) => Math.max(...args),
1787
- abs: ([x]) => Math.abs(x),
1788
- floor: ([x]) => Math.floor(x),
1789
- ceil: ([x]) => Math.ceil(x),
1790
- round: ([x, decimals = 0]) => {
1791
- const factor = 10 ** Math.trunc(decimals);
1792
- return Math.round(x * factor) / factor;
1793
- }
1794
- };
1795
- var CalcParser = class {
1796
- constructor(tokens, scope, source) {
1797
- this.tokens = tokens;
1798
- this.scope = scope;
1799
- this.source = source;
1800
- this.pos = 0;
1801
- this.skipDepth = 0;
1802
- }
1803
- parse() {
1804
- const value = this.ternary();
1805
- if (this.tokens[this.pos].kind !== "end") this.fail(`unexpected "${this.text(this.tokens[this.pos])}"`);
1806
- return value;
1807
- }
1808
- fail(what) {
1809
- throw new ExpressionError(`calc: ${what} in "${this.source}"`);
1810
- }
1811
- text(token) {
1812
- return token.kind === "end" ? "end" : String(token.value);
1813
- }
1814
- peekOp(...ops) {
1815
- const token = this.tokens[this.pos];
1816
- return token.kind === "op" && ops.includes(token.value) ? token.value : void 0;
1817
- }
1818
- expectOp(op) {
1819
- if (this.peekOp(op) === void 0) this.fail(`expected "${op}" but found "${this.text(this.tokens[this.pos])}"`);
1820
- this.pos++;
1821
- }
1822
- /**
1823
- * Parses a part of the expression that the result does not need (the
1824
- * other branch of `?:`, the right side of a decided `&&` or `||`). It
1825
- * still has to be parsed to find where it ends, so syntax errors are
1826
- * reported, but no value is checked or computed: `n == 0 ? 0 : 10 / n`
1827
- * is a valid guard.
1828
- */
1829
- skipped(parse) {
1830
- this.skipDepth++;
1831
- try {
1832
- parse();
1833
- } finally {
1834
- this.skipDepth--;
1835
- }
1836
- return null;
1837
- }
1838
- /** The number of a value, or 0 while skipping. */
1839
- num(value, what) {
1840
- return this.skipDepth > 0 ? 0 : numberOf(value, what);
1841
- }
1842
- ternary() {
1843
- const condition = this.or();
1844
- if (this.peekOp("?") === void 0) return condition;
1845
- this.pos++;
1846
- const takesFirst = truthOf(condition);
1847
- const whenTrue = takesFirst ? this.ternary() : this.skipped(() => this.ternary());
1848
- this.expectOp(":");
1849
- const whenFalse = takesFirst ? this.skipped(() => this.ternary()) : this.ternary();
1850
- return takesFirst ? whenTrue : whenFalse;
1851
- }
1852
- or() {
1853
- let left = this.and();
1854
- while (this.peekOp("||")) {
1855
- this.pos++;
1856
- if (truthOf(left)) {
1857
- this.skipped(() => this.and());
1858
- left = true;
1859
- } else left = truthOf(this.and());
1860
- }
1861
- return left;
1862
- }
1863
- and() {
1864
- let left = this.equality();
1865
- while (this.peekOp("&&")) {
1866
- this.pos++;
1867
- if (!truthOf(left)) {
1868
- this.skipped(() => this.equality());
1869
- left = false;
1870
- } else left = truthOf(this.equality());
1871
- }
1872
- return left;
1873
- }
1874
- equality() {
1875
- let left = this.comparison();
1876
- for (let op = this.peekOp("==", "!="); op; op = this.peekOp("==", "!=")) {
1877
- this.pos++;
1878
- const right = this.comparison();
1879
- const isEqual = typeof left === "number" || typeof right === "number" ? this.num(left, "the left side of ==") === this.num(right, "the right side of ==") : left === right;
1880
- left = op === "==" ? isEqual : !isEqual;
1881
- }
1882
- return left;
1883
- }
1884
- comparison() {
1885
- let left = this.additive();
1886
- for (let op = this.peekOp("<", "<=", ">", ">="); op; op = this.peekOp("<", "<=", ">", ">=")) {
1887
- this.pos++;
1888
- const a = this.num(left, `the left side of ${op}`);
1889
- const b = this.num(this.additive(), `the right side of ${op}`);
1890
- left = op === "<" ? a < b : op === "<=" ? a <= b : op === ">" ? a > b : a >= b;
1891
- }
1892
- return left;
1893
- }
1894
- additive() {
1895
- let left = this.multiplicative();
1896
- for (let op = this.peekOp("+", "-"); op; op = this.peekOp("+", "-")) {
1897
- this.pos++;
1898
- const right = this.multiplicative();
1899
- if (op === "+" && (typeof left === "string" || typeof right === "string")) left = `${left ?? ""}${right ?? ""}`;
1900
- else {
1901
- const a = this.num(left, `the left side of ${op}`);
1902
- const b = this.num(right, `the right side of ${op}`);
1903
- left = op === "+" ? a + b : a - b;
1904
- }
1905
- }
1906
- return left;
1907
- }
1908
- multiplicative() {
1909
- let left = this.unary();
1910
- for (let op = this.peekOp("*", "/", "%"); op; op = this.peekOp("*", "/", "%")) {
1911
- this.pos++;
1912
- const a = this.num(left, `the left side of ${op}`);
1913
- const b = this.num(this.unary(), `the right side of ${op}`);
1914
- if (op !== "*" && b === 0 && this.skipDepth === 0) this.fail("division by zero");
1915
- left = op === "*" ? a * b : op === "/" ? a / b : a % b;
1916
- }
1917
- return left;
1918
- }
1919
- unary() {
1920
- if (this.peekOp("-")) {
1921
- this.pos++;
1922
- return -this.num(this.unary(), "the operand of -");
1923
- }
1924
- if (this.peekOp("!")) {
1925
- this.pos++;
1926
- return !truthOf(this.unary());
1927
- }
1928
- return this.primary();
1929
- }
1930
- primary() {
1931
- const token = this.tokens[this.pos++];
1932
- switch (token.kind) {
1933
- case "number": return token.value;
1934
- case "string": return token.value;
1935
- case "name": return this.name(token.value);
1936
- case "op":
1937
- if (token.value === "(") {
1938
- const value = this.ternary();
1939
- this.expectOp(")");
1940
- return value;
1941
- }
1942
- return this.fail(`unexpected "${token.value}"`);
1943
- case "end": return this.fail("missing value");
1944
- }
1945
- }
1946
- name(name) {
1947
- if (name === "true") return true;
1948
- if (name === "false") return false;
1949
- if (name === "null") return null;
1950
- if (this.peekOp("(")) {
1951
- this.pos++;
1952
- const args = [];
1953
- if (this.peekOp(")") === void 0) for (;;) {
1954
- args.push(this.num(this.ternary(), `an argument of ${name}`));
1955
- if (this.peekOp(",") === void 0) break;
1956
- this.pos++;
1957
- }
1958
- this.expectOp(")");
1959
- if (this.skipDepth > 0) return null;
1960
- const fn = Object.prototype.hasOwnProperty.call(MATH, name) ? MATH[name] : void 0;
1961
- if (!fn) this.fail(`unknown function ${name}`);
1962
- if (args.length === 0) this.fail(`${name} needs an argument`);
1963
- return fn(args);
1964
- }
1965
- if (this.skipDepth > 0) return null;
1966
- if (!Object.prototype.hasOwnProperty.call(this.scope, name)) this.fail(`unknown name ${name}; pass it as an arg`);
1967
- const value = this.scope[name];
1968
- if (value !== null && typeof value !== "number" && typeof value !== "string" && typeof value !== "boolean") this.fail(`${name} is not a number, text or boolean (${describe(value)})`);
1969
- return value;
1970
- }
1971
- };
1972
- /**
1973
- * Evaluates `expression` with the names in `scope`. Gives a number, a
1974
- * string, a boolean or null. Throws an {@link ExpressionError} for a bad
1975
- * expression or a missing name.
1976
- */
1977
- function evaluateCalc(expression, scope) {
1978
- if (typeof expression !== "string" || expression.trim() === "") throw new ExpressionError("calc: expression must be a string");
1979
- return new CalcParser(tokenize(expression), scope, expression).parse();
1980
- }
1981
- /** The `calc` function: the expression is `args.expression`, the rest is the scope. */
1982
- function calc(args) {
1983
- const { expression, ...scope } = args;
1984
- return evaluateCalc(expression, scope);
1985
- }
1986
- const WHOLE_EXPRESSION = /^\$\{([^}]*)\}$/;
1987
- /**
1988
- * Fills `item` for one iteration: a string that is one `${...}` gives the
1989
- * typed value of the expression, a string with `${...}` inside it is
1990
- * interpolated as text, and objects and arrays are walked.
1991
- */
1992
- function fillItem(item, scope) {
1993
- if (typeof item === "string") {
1994
- const whole = WHOLE_EXPRESSION.exec(item);
1995
- if (whole) return evaluateCalc(whole[1], scope);
1996
- return item.replace(/\$\{([^}]*)\}/g, (_, expression) => {
1997
- const value = evaluateCalc(expression, scope);
1998
- return value === null ? "" : String(value);
1999
- });
2000
- }
2001
- if (Array.isArray(item)) return item.map((entry) => fillItem(entry, scope));
2002
- if (typeof item === "object" && item !== null) return Object.fromEntries(Object.entries(item).map(([key, value]) => [key, fillItem(value, scope)]));
2003
- return item;
2004
- }
2005
- /**
2006
- * The `series` function: `count` copies of `item`, with the loop variable
2007
- * (`variable`, default "i") counting from `start` (default 1) and the other
2008
- * args in scope of the `${...}` expressions of the item.
2009
- */
2010
- function series(args) {
2011
- const { count, item, variable, start, ...scope } = args;
2012
- const length = numberOf(count, "count");
2013
- if (!Number.isInteger(length) || length < 0) throw new ExpressionError("series: count must be a whole number");
2014
- if (length > MAX_SERIES) throw new ExpressionError(`series: count is at most ${MAX_SERIES}`);
2015
- if (item === void 0) throw new ExpressionError("series: item is required");
2016
- const name = variable === void 0 ? "i" : variable;
2017
- if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new ExpressionError("series: variable must be a name");
2018
- const first = start === void 0 ? 1 : numberOf(start, "start");
2019
- return Array.from({ length }, (_, index) => fillItem(item, {
2020
- ...scope,
2021
- [name]: first + index
2022
- }));
2023
- }
2024
-
2025
- //#endregion
2026
- //#region src/generative-ui/resolve.ts
2027
- BASIC_FUNCTIONS.calc = calc;
2028
- BASIC_FUNCTIONS.series = series;
2029
- const NO_DATA = { get: () => void 0 };
2030
- BASIC_FUNCTIONS.formatString = (args) => resolveDynamicValue({
2031
- "@call": "formatString",
2032
- args
2033
- }, {
2034
- data: NO_DATA,
2035
- basePath: void 0
2036
- }).value;
2037
- /** Adds one segment to a JSON pointer: ("/items", "0") gives "/items/0". */
2038
- function joinPath(base, segment) {
2039
- return base === "/" ? `/${segment}` : `${base}/${segment}`;
2040
- }
2041
- /**
2042
- * The absolute data model path of a binding. A path without a leading "/"
2043
- * is relative to the current template item, or to the root outside of one.
2044
- */
2045
- function resolvePath(path, basePath) {
2046
- if (path.startsWith("/")) return path;
2047
- return joinPath(basePath ?? "/", path);
2048
- }
2049
- /**
2050
- * The index of the template item at `basePath`: its last segment.
2051
- * `undefined` outside of a template.
2052
- */
2053
- function templateIndex(basePath) {
2054
- if (basePath === void 0) return void 0;
2055
- const index = Number(basePath.slice(basePath.lastIndexOf("/") + 1));
2056
- return Number.isInteger(index) ? index : void 0;
2057
- }
2058
- /** The value of a ValidationResult where a boolean is expected. */
2059
- function coerce(value, keep) {
2060
- return !keep && (0, _copilotkit_shared.isValidationResult)(value) ? value.valid : value;
2061
- }
2062
- /**
2063
- * Resolves `value`. `keepValidation` keeps a ValidationResult as it is; by
2064
- * default it becomes its `valid` boolean, which is what every prop except
2065
- * a check condition wants.
2066
- */
2067
- function walk(value, state, keepValidation, scope = "outside") {
2068
- if (Array.isArray(value)) {
2069
- let changed = false;
2070
- const itemScope = scope === "list" ? "check" : "outside";
2071
- const items = value.map((item) => {
2072
- const next = walk(item, state, keepValidation, itemScope);
2073
- if (next !== item) changed = true;
2074
- return next;
2075
- });
2076
- return changed ? items : value;
2077
- }
2078
- if (!isRecord(value)) return value;
2079
- if ((0, _copilotkit_shared.isPathBinding)(value)) {
2080
- const path = resolvePath(value["@path"], state.context.basePath);
2081
- state.paths.add(path);
2082
- return state.context.data.get(path);
2083
- }
2084
- if ((0, _copilotkit_shared.isCallBinding)(value)) return call(value, state, keepValidation);
2085
- if ((0, _copilotkit_shared.isActionBinding)(value)) return value;
2086
- let changed = false;
2087
- const entries = Object.entries(value).map(([key, item]) => {
2088
- const next = walk(item, state, keepValidation || scope === "check" && key === "condition", key === "checks" ? "list" : "outside");
2089
- if (next !== item) changed = true;
2090
- return [key, next];
2091
- });
2092
- return changed ? Object.fromEntries(entries) : value;
2093
- }
2094
- function call(binding, state, keepValidation) {
2095
- const name = binding["@call"];
2096
- const rawArgs = binding.args ?? {};
2097
- if (!isRecord(rawArgs)) throw new ExpressionError(`the args of "${name}" must be an object`);
2098
- if (name === _copilotkit_shared.A2UI_INDEX_FUNCTION) {
2099
- const index = templateIndex(state.context.basePath);
2100
- if (index === void 0) return void 0;
2101
- const offset = walk(rawArgs.offset, state, false);
2102
- return index + (typeof offset === "number" ? offset : 0);
2103
- }
2104
- if (name === "formatString") {
2105
- const template = walk(rawArgs.value, state, false);
2106
- if (typeof template !== "string") throw new ExpressionError("formatString takes a string value");
2107
- return formatString(template, state);
2108
- }
2109
- const fn = Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name) ? BASIC_FUNCTIONS[name] : void 0;
2110
- if (!fn) throw new ExpressionError(`"${name}" is not a basic function`);
2111
- if (requiresUserActivation(name)) throw new ExpressionError(`"${name}" is not a value; bind it as the functionCall of an event`);
2112
- const result = fn(walk(rawArgs, state, false));
2113
- return givesValidationResult(name) ? coerce(result, keepValidation) : result;
2114
- }
2115
- function resolveDynamicValue(value, context, options = {}) {
2116
- const result = tryResolveDynamicValue(value, context, options);
2117
- if (!result.ok) throw result.error;
2118
- return result;
2119
- }
2120
- /**
2121
- * Like {@link resolveDynamicValue}, but a failure comes back as a result
2122
- * with the paths read so far, so the caller can keep watching them: a
2123
- * function that fails on an empty field works once the user fills it.
2124
- */
2125
- function tryResolveDynamicValue(value, context, options = {}) {
2126
- const state = {
2127
- context,
2128
- paths: /* @__PURE__ */ new Set()
2129
- };
2130
- try {
2131
- return {
2132
- ok: true,
2133
- value: walk(value, state, options.keepValidation ?? false, options.isChecks ? "list" : "outside"),
2134
- paths: state.paths
2135
- };
2136
- } catch (error) {
2137
- return {
2138
- ok: false,
2139
- error: error instanceof Error ? error : new Error(String(error)),
2140
- paths: state.paths
2141
- };
2142
- }
2143
- }
2144
- /** True when `value` holds a `{"@path"}` or `{"@call"}` at any depth. */
2145
- function containsDynamicValue(value) {
2146
- if (Array.isArray(value)) return value.some(containsDynamicValue);
2147
- if (!isRecord(value)) return false;
2148
- if ((0, _copilotkit_shared.isPathBinding)(value) || (0, _copilotkit_shared.isCallBinding)(value)) return true;
2149
- if ((0, _copilotkit_shared.isActionBinding)(value)) return false;
2150
- return Object.values(value).some(containsDynamicValue);
2151
- }
2152
- /**
2153
- * The `${...}` grammar of `formatString`:
2154
- *
2155
- * expression := path | literal | call
2156
- * path := "/" segments | identifier ("/" segments)*
2157
- * literal := 'text' | "text" | number | true | false | null
2158
- * call := identifier "(" [ name ":" expression ("," name ":" expression)* ] ")"
2159
- *
2160
- * A `\${` in the template is a literal `${`.
2161
- */
2162
- function formatString(template, state) {
2163
- let out = "";
2164
- let index = 0;
2165
- while (index < template.length) {
2166
- const start = template.indexOf("${", index);
2167
- if (start === -1) {
2168
- out += template.slice(index);
2169
- break;
2170
- }
2171
- if (start > 0 && template[start - 1] === "\\") {
2172
- out += `${template.slice(index, start - 1)}\${`;
2173
- index = start + 2;
2174
- continue;
2175
- }
2176
- out += template.slice(index, start);
2177
- const end = matchingBrace(template, start + 2);
2178
- if (end === -1) throw new ExpressionError("formatString: unclosed ${");
2179
- const value = new ExpressionParser(template.slice(start + 2, end).trim(), state).parse();
2180
- out += value === void 0 || value === null ? "" : String(value);
2181
- index = end + 1;
2182
- }
2183
- return out;
2184
- }
2185
- /** The index of the `}` that closes the block opened at `from`, or -1. */
2186
- function matchingBrace(template, from) {
2187
- let depth = 1;
2188
- let quote;
2189
- for (let i = from; i < template.length; i++) {
2190
- const char = template[i];
2191
- if (quote) {
2192
- if (char === "\\") i++;
2193
- else if (char === quote) quote = void 0;
2194
- continue;
2195
- }
2196
- if (char === "'" || char === "\"") quote = char;
2197
- else if (char === "{") depth++;
2198
- else if (char === "}" && --depth === 0) return i;
2199
- }
2200
- return -1;
2201
- }
2202
- const IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;
2203
- const NUMBER = /-?\d+(?:\.\d+)?/y;
2204
- const PATH_SEGMENT = /[^\s,():'"]+/y;
2205
- var ExpressionParser = class {
2206
- constructor(source, state) {
2207
- this.source = source;
2208
- this.state = state;
2209
- this.pos = 0;
2210
- }
2211
- parse() {
2212
- const value = this.expression();
2213
- this.skipSpace();
2214
- if (this.pos < this.source.length) throw new ExpressionError(`formatString: unexpected "${this.source.slice(this.pos)}" in \${${this.source}}`);
2215
- return value;
2216
- }
2217
- fail(what) {
2218
- throw new ExpressionError(`formatString: ${what} in \${${this.source}}`);
2219
- }
2220
- skipSpace() {
2221
- while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) this.pos++;
2222
- }
2223
- match(pattern) {
2224
- pattern.lastIndex = this.pos;
2225
- const found = pattern.exec(this.source);
2226
- if (!found) return void 0;
2227
- this.pos = pattern.lastIndex;
2228
- return found[0];
2229
- }
2230
- expression() {
2231
- this.skipSpace();
2232
- const char = this.source[this.pos];
2233
- if (char === void 0) this.fail("missing expression");
2234
- if (char === "'" || char === "\"") return this.quoted(char);
2235
- if (char === "/") return this.path(this.match(PATH_SEGMENT) ?? "/");
2236
- const number = this.match(NUMBER);
2237
- if (number !== void 0) return Number(number);
2238
- const name = this.match(IDENTIFIER);
2239
- if (name === void 0) this.fail(`unexpected "${char}"`);
2240
- if (name === "true") return true;
2241
- if (name === "false") return false;
2242
- if (name === "null") return null;
2243
- this.skipSpace();
2244
- if (this.source[this.pos] === "(") return this.call(name);
2245
- if (name.startsWith("@")) return call({ "@call": name }, this.state, false);
2246
- const rest = this.source[this.pos] === "/" ? this.match(PATH_SEGMENT) : "";
2247
- return this.path(`${name}${rest ?? ""}`);
2248
- }
2249
- quoted(quote) {
2250
- let value = "";
2251
- this.pos++;
2252
- while (this.pos < this.source.length) {
2253
- const char = this.source[this.pos++];
2254
- if (char === "\\" && this.pos < this.source.length) value += this.source[this.pos++];
2255
- else if (char === quote) return value;
2256
- else value += char;
2257
- }
2258
- return this.fail("unclosed string");
2259
- }
2260
- path(path) {
2261
- const absolute = resolvePath(path, this.state.context.basePath);
2262
- this.state.paths.add(absolute);
2263
- return this.state.context.data.get(absolute);
2264
- }
2265
- call(name) {
2266
- this.pos++;
2267
- const args = {};
2268
- this.skipSpace();
2269
- if (this.source[this.pos] === ")") {
2270
- this.pos++;
2271
- return call({
2272
- "@call": name,
2273
- args
2274
- }, this.state, false);
2275
- }
2276
- for (;;) {
2277
- this.skipSpace();
2278
- const key = this.match(IDENTIFIER);
2279
- if (key === void 0) this.fail("expected an argument name");
2280
- this.skipSpace();
2281
- if (this.source[this.pos] !== ":") this.fail(`expected ":" after ${key}`);
2282
- this.pos++;
2283
- args[key] = this.expression();
2284
- this.skipSpace();
2285
- const next = this.source[this.pos++];
2286
- if (next === ")") break;
2287
- if (next !== ",") this.fail(`expected "," or ")" after ${key}`);
2288
- }
2289
- return call({
2290
- "@call": name,
2291
- args
2292
- }, this.state, false);
2293
- }
2294
- };
2295
-
2296
- //#endregion
2297
- //#region src/generative-ui/schema.ts
2298
- const ASYNC_ISSUE = { message: "the schema validates asynchronously; component props and state need a schema that validates synchronously" };
2299
- function toResult(result) {
2300
- return result.issues ? {
2301
- success: false,
2302
- issues: result.issues
2303
- } : {
2304
- success: true,
2305
- data: result.value
2306
- };
2307
- }
2308
- /**
2309
- * Validates `value` with `schema`. The result comes back at once when the
2310
- * schema validates synchronously, else as a promise.
2311
- */
2312
- function validateSchema(schema, value) {
2313
- const result = schema["~standard"].validate(value);
2314
- return result instanceof Promise ? result.then(toResult) : toResult(result);
2315
- }
2316
- /**
2317
- * Validates `value` synchronously, for code that runs during render. A
2318
- * schema that validates asynchronously fails with an issue that says so.
2319
- */
2320
- function validateSchemaSync(schema, value) {
2321
- const result = validateSchema(schema, value);
2322
- if (!(result instanceof Promise)) return result;
2323
- result.catch(() => {});
2324
- return {
2325
- success: false,
2326
- issues: [ASYNC_ISSUE]
2327
- };
2328
- }
2329
- /** True for the issue that `validateSchemaSync` gives for an async schema. */
2330
- function isAsyncIssue(issue) {
2331
- return issue === ASYNC_ISSUE;
2332
- }
2333
- /** The first key of an issue path: the prop the issue is about. */
2334
- function issueKey(issue) {
2335
- const first = issue.path?.[0];
2336
- const key = typeof first === "object" ? first.key : first;
2337
- return key === void 0 ? void 0 : String(key);
2338
- }
2339
- /**
2340
- * `props` without the top-level props whose `null` the schema rejected, or
2341
- * `undefined` when there are none. A model writes `null` for "not set" (an
2342
- * empty selection, a value it has not filled yet), and A2UI deletes a data
2343
- * model key that is set to `null`, so a rejected `null` is read as an unset
2344
- * prop. A prop whose schema accepts `null` keeps it.
2345
- */
2346
- function withoutRejectedNulls(props, issues) {
2347
- const rejected = /* @__PURE__ */ new Set();
2348
- for (const issue of issues) {
2349
- const key = issueKey(issue);
2350
- if (key !== void 0 && issue.path?.length === 1 && props[key] === null) rejected.add(key);
2351
- }
2352
- if (rejected.size === 0) return void 0;
2353
- return Object.fromEntries(Object.entries(props).filter(([key]) => !rejected.has(key)));
2354
- }
2355
- /** `"a.b: message; c: message"`. A path-less issue gets `fallback`. */
2356
- function formatIssues(issues, fallback = "props") {
2357
- return issues.map((issue) => {
2358
- return `${(issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".") || fallback}: ${issue.message}`;
2359
- }).join("; ");
2360
- }
2361
-
2362
- //#endregion
2363
- //#region src/generative-ui/runtime-context.ts
2364
- const GenerativeUIRuntimeContext = (0, react.createContext)(null);
2365
- function useGenerativeUIRuntime() {
2366
- return (0, react.useContext)(GenerativeUIRuntimeContext);
2367
- }
2368
- function useRequiredGenerativeUIRuntime() {
2369
- const runtime = (0, react.useContext)(GenerativeUIRuntimeContext);
2370
- if (!runtime) throw new Error("Generative UI components must be rendered inside <CopilotKitProvider generativeUI={{ ui }}>.");
2371
- return runtime;
2372
- }
2373
- /**
2374
- * Reports an error without ever throwing: `reportError` reaches host code
2375
- * (`onError`), and a throwing host callback must not break rendering or an
2376
- * event handler.
2377
- */
2378
- function reportErrorSafely(runtime, info) {
2379
- try {
2380
- runtime.reportError(info);
2381
- } catch {}
2382
- }
2383
- const GenerativeUINodeContext = (0, react.createContext)(null);
2384
-
2385
- //#endregion
2386
- //#region src/generative-ui/hooks.ts
2387
- const noopSubscribe$1 = () => () => {};
2388
- const zero = () => 0;
2389
- /** Re-renders on any surface-manager change. */
2390
- function useManagerVersion(runtime) {
2391
- return (0, react.useSyncExternalStore)(runtime?.manager.subscribe ?? noopSubscribe$1, runtime?.manager.getVersion ?? zero, zero);
2392
- }
2393
- /**
2394
- * Experimental. Gives one key of the app state declared in
2395
- * `createGenerativeUI({ state })` its value. Bound props of generated
2396
- * components read it. The model does not see it.
2397
- *
2398
- * The key is set on mount and when the value changes (compared as JSON). It
2399
- * is removed on unmount.
2400
- *
2401
- * @param ui - The object from `createGenerativeUI`. It gives the key and the
2402
- * value their types.
2403
- * @param key - A top-level key of `state`.
2404
- * @param value - The value of that key. It must fit the key's schema.
2405
- *
2406
- * @example
2407
- * ```tsx
2408
- * useGenerativeUIState(storeUI, "cart", { count, total, coupon, items });
2409
- * ```
2410
- */
2411
- function useGenerativeUIState(ui, key, value) {
2412
- const runtime = useRequiredGenerativeUIRuntime();
2413
- const serialized = JSON.stringify(value);
2414
- (0, react.useEffect)(() => {
2415
- const raw = JSON.parse(serialized ?? "null");
2416
- let current = true;
2417
- const apply = (parsed) => {
2418
- if (!current) return;
2419
- if (parsed.success) {
2420
- runtime.manager.setState(key, parsed.data);
2421
- return;
2422
- }
2423
- runtime.manager.removeState(key);
2424
- if (process.env.NODE_ENV !== "production") console.error(`[generativeUI] useGenerativeUIState: invalid value for "${key}": ${formatIssues(parsed.issues, "value")}`);
2425
- };
2426
- const schema = runtime.ui.state.get(key);
2427
- const parsed = schema ? validateSchema(schema, raw) : {
2428
- success: true,
2429
- data: raw
2430
- };
2431
- if (parsed instanceof Promise) parsed.then(apply);
2432
- else apply(parsed);
2433
- return () => {
2434
- current = false;
2435
- };
2436
- }, [
2437
- runtime,
2438
- key,
2439
- serialized
2440
- ]);
2441
- (0, react.useEffect)(() => () => runtime.manager.removeState(key), [runtime, key]);
2442
- }
2443
- /**
2444
- * Experimental. Mounts the handler of a function declared in
2445
- * `createGenerativeUI({ functions })`. Generated UI can call the function
2446
- * only while exactly one handler for it is mounted.
2447
- *
2448
- * The handler gets the parsed arguments: schema defaults are set. It can
2449
- * change on each render. The latest handler always runs, and the hook does
2450
- * not register again.
2451
- *
2452
- * @param ui - The object from `createGenerativeUI`. It gives the name and the
2453
- * handler arguments their types.
2454
- * @param name - A key of `functions`.
2455
- * @param handler - Runs when generated UI calls the function. Its return
2456
- * value goes back to the caller as `{ ok: true, result }`.
2457
- *
2458
- * @example
2459
- * ```tsx
2460
- * useGenerativeUIFunction(storeUI, "addToCart", ({ productId, quantity }) =>
2461
- * cart.addItem(productId, quantity),
2462
- * );
2463
- * ```
2464
- */
2465
- function useGenerativeUIFunction(ui, name, handler) {
2466
- const runtime = useRequiredGenerativeUIRuntime();
2467
- const latest = (0, react.useRef)(handler);
2468
- latest.current = handler;
2469
- (0, react.useEffect)(() => runtime.dispatcher.register(name, latest), [runtime, name]);
2470
- }
2471
-
2472
- //#endregion
2473
- //#region src/generative-ui/boundaries.tsx
2474
- function DefaultNodeFallback({ message, componentId, retry }) {
2475
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2476
- role: "alert",
2477
- "data-generative-ui-error": componentId,
2478
- style: {
2479
- border: "1px solid #fca5a5",
2480
- background: "#fef2f2",
2481
- color: "#991b1b",
2482
- borderRadius: 8,
2483
- padding: "8px 12px",
2484
- fontSize: 13
2485
- },
2486
- children: [
2487
- "Couldn’t display this part: ",
2488
- message,
2489
- retry && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2490
- type: "button",
2491
- onClick: retry,
2492
- style: {
2493
- marginLeft: 8,
2494
- textDecoration: "underline"
2495
- },
2496
- children: "Retry"
2497
- })
2498
- ]
2499
- });
2500
- }
2501
- /**
2502
- * A child that has not streamed yet renders nothing. The prose keeps
2503
- * streaming above the surface, and each component appears as soon as it is
2504
- * complete. A grey block in its place would read as a broken layout.
2505
- */
2506
- function NodePlaceholder(_props) {
2507
- return null;
2508
- }
2509
- /** Per-node boundary. Resets on retry or a new agent revision, not on data ticks. */
2510
- var NodeBoundary = class extends react.Component {
2511
- constructor(..._args) {
2512
- super(..._args);
2513
- this.state = {
2514
- error: null,
2515
- revision: this.props.revision
2516
- };
2517
- this.retry = () => this.setState({ error: null });
2518
- }
2519
- static getDerivedStateFromError(error) {
2520
- return { error };
2521
- }
2522
- static getDerivedStateFromProps(props, state) {
2523
- return props.revision !== state.revision ? {
2524
- error: null,
2525
- revision: props.revision
2526
- } : null;
2527
- }
2528
- componentDidCatch(error) {
2529
- const { runtime, surfaceId, componentId } = this.props;
2530
- reportErrorSafely(runtime, {
2531
- kind: "render",
2532
- surfaceId,
2533
- componentId,
2534
- error
2535
- });
2536
- }
2537
- render() {
2538
- const { error } = this.state;
2539
- if (!error) return this.props.children;
2540
- const { runtime, surfaceId, componentId } = this.props;
2541
- const fallback = runtime.errorFallback;
2542
- return fallback ? fallback({
2543
- error,
2544
- retry: this.retry,
2545
- surfaceId,
2546
- componentId
2547
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
2548
- message: error.message,
2549
- componentId,
2550
- retry: this.retry
2551
- });
2552
- }
2553
- };
2554
- /** Outer boundary: a failure here must not reach the chat or the host page. */
2555
- var SurfaceBoundary = class extends react.Component {
2556
- constructor(..._args2) {
2557
- super(..._args2);
2558
- this.state = { error: null };
2559
- }
2560
- static getDerivedStateFromError(error) {
2561
- return { error };
2562
- }
2563
- componentDidCatch(error) {
2564
- reportErrorSafely(this.props.runtime, {
2565
- kind: "render",
2566
- surfaceId: this.props.surfaceId,
2567
- error
2568
- });
2569
- }
2570
- render() {
2571
- if (!this.state.error) return this.props.children;
2572
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
2573
- message: "this generated UI failed to render",
2574
- componentId: "surface"
2575
- });
2576
- }
2577
- };
2578
-
2579
- //#endregion
2580
- //#region src/generative-ui/accessibility.ts
2581
- const LIVE = new Set([
2582
- "off",
2583
- "polite",
2584
- "assertive"
2585
- ]);
2586
- /**
2587
- * The accessibility of a component from its resolved `accessibility`
2588
- * value. Fields of the wrong type are left out: a label that is still a
2589
- * binding, or a list, names nothing.
2590
- */
2591
- function readAccessibility(value) {
2592
- if (typeof value !== "object" || value === null || Array.isArray(value)) return;
2593
- const { label, description, live, hidden } = value;
2594
- const result = {};
2595
- if (typeof label === "string" && label !== "") result.label = label;
2596
- if (typeof description === "string" && description !== "") result.description = description;
2597
- if (typeof live === "string" && LIVE.has(live)) result.live = live;
2598
- if (typeof hidden === "boolean") result.hidden = hidden;
2599
- return Object.keys(result).length > 0 ? result : void 0;
2600
- }
2601
- /**
2602
- * The ARIA attributes for an `accessibility`. `live: "off"` is written out:
2603
- * a region inherits the live setting of its ancestors, and a `status` role
2604
- * is live on its own, so only the explicit value silences it.
2605
- *
2606
- * @example
2607
- * ```ts
2608
- * accessibilityAttributes({ label: "Totals", live: "polite" });
2609
- * // { "aria-label": "Totals", "aria-live": "polite" }
2610
- * ```
2611
- */
2612
- function accessibilityAttributes(accessibility) {
2613
- if (!accessibility) return {};
2614
- const { label, description, live, hidden } = accessibility;
2615
- return {
2616
- ...label === void 0 ? {} : { "aria-label": label },
2617
- ...description === void 0 ? {} : { "aria-description": description },
2618
- ...live === void 0 ? {} : { "aria-live": live },
2619
- ...hidden ? { "aria-hidden": true } : {}
2620
- };
2621
- }
2622
- /**
2623
- * Experimental. The ARIA attributes of the `accessibility` that the model
2624
- * gave the component being rendered, to spread on its root element. The
2625
- * standard components do this; a custom component does it itself:
2626
- *
2627
- * @example
2628
- * ```tsx
2629
- * function Panel({ children }: { children?: ReactNode }) {
2630
- * const aria = useGenerativeUIAccessibility();
2631
- * return <section {...aria}>{children}</section>;
2632
- * }
2633
- * ```
2634
- *
2635
- * Outside of generated UI it gives `{}`.
2636
- */
2637
- function useGenerativeUIAccessibility() {
2638
- const accessibility = (0, react.useContext)(GenerativeUINodeContext)?.accessibility;
2639
- return (0, react.useMemo)(() => accessibilityAttributes(accessibility), [accessibility]);
2640
- }
2641
- /**
2642
- * The role of a container that the envelope names. A generic element
2643
- * cannot carry a name, so a label or a description makes it a `group`,
2644
- * unless the component has a role of its own.
2645
- */
2646
- function namedRole(aria, explicit) {
2647
- if (explicit !== void 0) return explicit;
2648
- return aria["aria-label"] !== void 0 || aria["aria-description"] !== void 0 ? "group" : void 0;
2649
- }
2650
- /**
2651
- * The part of the attributes for the focusable control of a labelled pair:
2652
- * its name and its description. ARIA names are not inherited, so the
2653
- * wrapper of a control cannot name it.
2654
- */
2655
- function controlAria(aria) {
2656
- const { "aria-label": label, "aria-description": description } = aria;
2657
- return {
2658
- ...label === void 0 ? {} : { "aria-label": label },
2659
- ...description === void 0 ? {} : { "aria-description": description }
2660
- };
2661
- }
2662
- /**
2663
- * The part of the attributes for the wrapper around a control: hidden and
2664
- * live cover the label and the control together.
2665
- */
2666
- function wrapperAria(aria) {
2667
- const { "aria-hidden": hidden, "aria-live": live } = aria;
2668
- return {
2669
- ...hidden === void 0 ? {} : { "aria-hidden": hidden },
2670
- ...live === void 0 ? {} : { "aria-live": live }
2671
- };
2672
- }
2673
-
2674
- //#endregion
2675
- //#region src/generative-ui/events.ts
2676
- /**
2677
- * The context of a running event binding: it reads the surface data model
2678
- * and resolves relative paths against the template item of the component.
2679
- * A function that needs a user gesture (openUrl) is not a value here
2680
- * either; it runs through the dispatcher as the binding's functionCall.
2681
- */
2682
- function eventContext(surface, basePath) {
2683
- return {
2684
- data: surface.model.dataModel,
2685
- basePath
2686
- };
2687
- }
2688
- /**
2689
- * A value of an event binding with its dynamic values resolved: `{"@path"}`
2690
- * bindings and function values, at any depth.
2691
- */
2692
- function resolveValue(surface, basePath, value) {
2693
- return resolveDynamicValue(value, eventContext(surface, basePath)).value;
2694
- }
2695
- /**
2696
- * The entries of an args or context record, each resolved on its own. The
2697
- * record is not resolved as a whole, because a record with one `event` or
2698
- * `functionCall` key would look like an action binding and stay as it is.
2699
- */
2700
- function resolveValues(surface, basePath, values) {
2701
- return Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [key, resolveValue(surface, basePath, value)]));
2702
- }
2703
- /**
2704
- * The `userMessage` of an event binding, as text. A `{"@path"}` or a
2705
- * function value is resolved. `undefined` when there is no message, or
2706
- * the value is not a string.
2707
- */
2708
- function resolveUserMessage(surface, basePath, userMessage) {
2709
- const value = resolveValue(surface, basePath, userMessage);
2710
- return typeof value === "string" ? value : void 0;
2711
- }
2712
- /**
2713
- * Validates the component's args with the event `parameters`, then runs
2714
- * `send` with them. Never throws: every failure is reported and becomes
2715
- * `{ ok: false, error }`.
2716
- */
2717
- async function runEvent(call, send) {
2718
- const { runtime, surface, componentId, name, parameters, args } = call;
2719
- const origin = {
2720
- surfaceId: surface.surfaceId,
2721
- componentId
2722
- };
2723
- try {
2724
- if (!parameters) return await send(args ?? {}, origin);
2725
- const result = validateSchema(parameters, args ?? {});
2726
- const parsed = result instanceof Promise ? await result : result;
2727
- if (!parsed.success) {
2728
- const error = new GenerativeUIError("invalid_event_args", `${name}: ${formatIssues(parsed.issues, "args")}`);
2729
- reportErrorSafely(runtime, {
2730
- kind: "event",
2731
- ...origin,
2732
- error
2733
- });
2734
- return {
2735
- ok: false,
2736
- error
2737
- };
2738
- }
2739
- return await send(parsed.data ?? {}, origin);
2740
- } catch (cause) {
2741
- const error = new GenerativeUIError("event_forward_failed", `${name}: ${cause instanceof Error ? cause.message : String(cause)}`);
2742
- reportErrorSafely(runtime, {
2743
- kind: "event",
2744
- ...origin,
2745
- error
2746
- });
2747
- return {
2748
- ok: false,
2749
- error
2750
- };
2751
- }
2752
- }
2753
- /**
2754
- * Runs one call of an event that the model bound: validates the component's
2755
- * args, merges them with the args from the binding (binding literals win),
2756
- * then calls a declared function or forwards an agent event. Never throws.
2757
- */
2758
- function invokeBoundEvent(params) {
2759
- const { runtime, surface, binding, basePath } = params;
2760
- return runEvent(params, (args, origin) => {
2761
- const componentArgs = args;
2762
- if ("functionCall" in binding) return runtime.dispatcher.invoke(binding.functionCall["@call"], {
2763
- ...componentArgs,
2764
- ...resolveValues(surface, basePath, binding.functionCall.args)
2765
- }, origin);
2766
- const { event } = binding;
2767
- const forwarded = {
2768
- name: event.name,
2769
- ...origin,
2770
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2771
- userMessage: resolveUserMessage(surface, basePath, event.userMessage),
2772
- context: {
2773
- ...componentArgs,
2774
- ...resolveValues(surface, basePath, event.context)
2775
- }
2776
- };
2777
- return runtime.forwardEvent(forwarded, surface.agentId);
2778
- });
2779
- }
2780
- /**
2781
- * Runs one call of an event that matches a declared function: validates the
2782
- * component's args with the event `parameters` (if any), then calls the
2783
- * function, which validates them with its own schema. Never throws.
2784
- */
2785
- function invokeMatchedEvent(params) {
2786
- const { runtime, functionName } = params;
2787
- return runEvent(params, (componentArgs, origin) => runtime.dispatcher.invoke(functionName, componentArgs, origin));
2788
- }
2789
-
2790
- //#endregion
2791
- //#region src/generative-ui/theme.ts
2792
- /**
2793
- * The built-in dark values. The light values are the fallbacks in the
2794
- * components, so a surface is light when no variable is set.
2795
- */
2796
- const DARK_THEME = {
2797
- "--a2ui-color-text-default": "#ececec",
2798
- "--a2ui-color-text-prose": "#ececec",
2799
- "--a2ui-color-text-primary": "#ececec",
2800
- "--a2ui-color-text-emphasis": "#fff",
2801
- "--a2ui-color-text-secondary": "#b4b4b4",
2802
- "--a2ui-color-text-tertiary": "#8e8e8e",
2803
- "--a2ui-color-text-success": "#4fd1a5",
2804
- "--a2ui-color-text-info": "#6cb6ff",
2805
- "--a2ui-color-text-warning": "#e3b341",
2806
- "--a2ui-color-text-caution": "#e3b341",
2807
- "--a2ui-color-text-danger": "#ff7b72",
2808
- "--a2ui-color-text-discovery": "#bc9cff",
2809
- "--a2ui-color-surface": "#1f1f1f",
2810
- "--a2ui-color-surface-secondary": "#2a2a2a",
2811
- "--a2ui-color-surface-tertiary": "#3a3a3a",
2812
- "--a2ui-color-surface-elevated": "#262626",
2813
- "--a2ui-color-surface-elevated-secondary": "#2f2f2f",
2814
- "--a2ui-color-surface-inverted": "#f2f2f2",
2815
- "--a2ui-color-surface-soft": "#232323",
2816
- "--a2ui-color-info": "rgba(80, 160, 255, 0.14)",
2817
- "--a2ui-color-warning": "rgba(240, 180, 60, 0.14)",
2818
- "--a2ui-color-caution": "rgba(240, 180, 60, 0.14)",
2819
- "--a2ui-color-success": "rgba(60, 200, 150, 0.14)",
2820
- "--a2ui-color-danger": "rgba(255, 110, 100, 0.14)",
2821
- "--a2ui-color-discovery": "rgba(170, 130, 255, 0.14)",
2822
- "--a2ui-color-info-soft": "rgba(80, 160, 255, 0.08)",
2823
- "--a2ui-color-warning-soft": "rgba(240, 180, 60, 0.08)",
2824
- "--a2ui-color-caution-soft": "rgba(240, 180, 60, 0.08)",
2825
- "--a2ui-color-success-soft": "rgba(60, 200, 150, 0.08)",
2826
- "--a2ui-color-danger-soft": "rgba(255, 110, 100, 0.08)",
2827
- "--a2ui-color-discovery-soft": "rgba(170, 130, 255, 0.08)",
2828
- "--a2ui-color-info-solid": "#3b8eea",
2829
- "--a2ui-color-warning-solid": "#c99a2e",
2830
- "--a2ui-color-caution-solid": "#c99a2e",
2831
- "--a2ui-color-success-solid": "#2fae86",
2832
- "--a2ui-color-danger-solid": "#e5534b",
2833
- "--a2ui-color-discovery-solid": "#9a6ff0",
2834
- "--a2ui-color-border-default": "rgba(255, 255, 255, 0.12)",
2835
- "--a2ui-color-border-subtle": "rgba(255, 255, 255, 0.06)",
2836
- "--a2ui-color-border-strong": "#4a4a4a",
2837
- "--a2ui-color-border-info": "#2f5f8f",
2838
- "--a2ui-color-border-warning": "#6b5420",
2839
- "--a2ui-color-border-caution": "#6b5420",
2840
- "--a2ui-color-border-success": "#1f5f4b",
2841
- "--a2ui-color-border-danger": "#7a2f2b",
2842
- "--a2ui-color-border-discovery": "#4f3a80",
2843
- "--a2ui-color-border-control": "rgba(255, 255, 255, 0.2)",
2844
- "--a2ui-color-accent": "#f2f2f2",
2845
- "--a2ui-color-on-accent": "#0d0d0d",
2846
- "--a2ui-color-panel": "#262626",
2847
- "--a2ui-color-control": "#2f2f2f",
2848
- "--a2ui-color-focus": "#3b9bff",
2849
- "--a2ui-color-shimmer": "rgba(255, 255, 255, 0.12)",
2850
- "--a2ui-color-chart-cursor": "rgba(255, 255, 255, 0.06)",
2851
- "--a2ui-color-slider-track": "rgba(255, 255, 255, 0.1)",
2852
- "--a2ui-color-badge-secondary": "rgba(255, 255, 255, 0.08)",
2853
- "--a2ui-color-highlight-green": "#1d4a37",
2854
- "--a2ui-color-highlight-orange": "#4d3418",
2855
- "--a2ui-color-highlight-pink": "#4d2338",
2856
- "--a2ui-shadow-xs": "0 1px 2px rgba(0, 0, 0, 0.5)",
2857
- "--a2ui-shadow-sm": "0 1px 3px rgba(0, 0, 0, 0.5)",
2858
- "--a2ui-shadow-soft": "0 1px 3px rgba(0, 0, 0, 0.3)",
2859
- "--a2ui-shadow-md": "0 4px 12px rgba(0, 0, 0, 0.4)"
2860
- };
2861
- const VARIABLE_NAME = /^--a2ui-[a-z0-9-]+$/;
2862
- const UNSAFE_VALUE = /[{};<>]/;
2863
- /** Matches the `dark` class on an ancestor of a surface, or on the surface. */
2864
- const DARK = ":where(.dark)";
2865
- /** The default dark values, as a rule that any theme rule beats. */
2866
- const DARK_THEME_CSS = `:where(.dark .a2ui-surface,.a2ui-surface.dark){${declarations(DARK_THEME)}}`;
2867
- function declarations(values) {
2868
- return Object.entries(values ?? {}).filter(([name, value]) => VARIABLE_NAME.test(name) && typeof value === "string" && !UNSAFE_VALUE.test(value)).map(([name, value]) => `${name}:${value}`).join(";");
2869
- }
2870
- /** A short, stable id for a stylesheet. */
2871
- function hashOf(text) {
2872
- let hash = 5381;
2873
- for (let index = 0; index < text.length; index++) hash = hash * 33 ^ text.charCodeAt(index);
2874
- return `t${(hash >>> 0).toString(36)}`;
2875
- }
2876
- /**
2877
- * The stylesheet of a theme: its values on the surfaces that carry its id,
2878
- * then its dark values in dark mode. `undefined` when the theme sets no
2879
- * variable. Values that could break out of the rule are left out.
2880
- *
2881
- * @example
2882
- * ```ts
2883
- * themeStyleSheet({ "--a2ui-color-accent": "red" });
2884
- * // { id: "t…", css: '.a2ui-surface[data-a2ui-theme="t…"]{--a2ui-color-accent:red}' }
2885
- * ```
2886
- */
2887
- function themeStyleSheet(theme) {
2888
- const { dark, ...base } = theme ?? {};
2889
- const both = declarations(base);
2890
- const darkOnly = declarations(dark);
2891
- if (!both && !darkOnly) return void 0;
2892
- const id = hashOf(`${both}|${darkOnly}`);
2893
- const self = `.a2ui-surface[data-a2ui-theme="${id}"]`;
2894
- return {
2895
- id,
2896
- css: [both && `${self}{${both}}`, darkOnly && `${DARK} ${self},${self}${DARK}{${darkOnly}}`].filter(Boolean).join("")
2897
- };
2898
- }
2899
-
2900
- //#endregion
2901
- //#region src/generative-ui/SurfaceView.tsx
2902
- const NO_ANCESTORS = [];
2903
- const ROOT_STYLE = { display: "contents" };
2904
- const undefinedSnapshot = () => void 0;
2905
- const noopSubscribe = () => () => {};
2906
- const zeroSnapshot = () => 0;
2907
- /** A "multiple" slot value that repeats a component for each list item. */
2908
- function isTemplateChildren(value) {
2909
- return typeof value === "object" && value !== null && "componentId" in value && typeof value.componentId === "string" && "path" in value && typeof value.path === "string";
2910
- }
2911
- function SurfaceView({ surface }) {
2912
- const runtime = useRequiredGenerativeUIRuntime();
2913
- const { theme } = runtime;
2914
- const sheet = (0, react.useMemo)(() => themeStyleSheet(theme), [theme]);
2915
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2916
- className: "a2ui-surface",
2917
- "data-generative-ui-root": surface.surfaceId,
2918
- "data-a2ui-theme": sheet?.id,
2919
- style: ROOT_STYLE,
2920
- children: [sheet ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { dangerouslySetInnerHTML: { __html: sheet.css } }) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceBoundary, {
2921
- surfaceId: surface.surfaceId,
2922
- runtime,
2923
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
2924
- surface,
2925
- componentId: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
2926
- basePath: void 0,
2927
- ancestors: NO_ANCESTORS
2928
- })
2929
- })]
2930
- });
2931
- }
2932
- /**
2933
- * Resolves a component by id. Subscribes to the manager rather than web_core's
2934
- * `onCreated`/`onDeleted`: web_core's EventEmitter awaits each listener in turn,
2935
- * so with several subscribers (one per slotted child, or one per mount of the
2936
- * same surface) all but the first are notified a microtask late. That is only
2937
- * visible inside synchronous flushes such as `act()` / `flushSync`, where the
2938
- * old tree would still be on screen, but it makes updates order-dependent.
2939
- * The manager notifies synchronously once an ingest has been fully applied.
2940
- */
2941
- function useComponentModel(manager, model, id) {
2942
- return (0, react.useSyncExternalStore)(manager.subscribe, () => model.componentsModel.get(id), undefinedSnapshot);
2943
- }
2944
- /** Same reasoning as `useComponentModel`: never rely on web_core's emitters. */
2945
- function useComponentProperties(manager, component) {
2946
- return (0, react.useSyncExternalStore)(manager.subscribe, () => component?.properties, undefinedSnapshot);
2947
- }
2948
- /**
2949
- * The id of a node in the ancestor list. A template renders the same
2950
- * component once per item, so the item path is part of the id. A real cycle
2951
- * repeats both.
2952
- */
2953
- function scopedId(componentId, basePath) {
2954
- return `${basePath ?? ""}#${componentId}`;
2955
- }
2956
- const NodeView = (0, react.memo)(function NodeView({ surface, componentId, basePath, ancestors }) {
2957
- const runtime = useRequiredGenerativeUIRuntime();
2958
- const component = useComponentModel(runtime.manager, surface.model, componentId);
2959
- const properties = useComponentProperties(runtime.manager, component);
2960
- if (ancestors.includes(scopedId(componentId, basePath))) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
2961
- message: `cyclic reference to ${componentId}`,
2962
- componentId
2963
- });
2964
- if (!component || !properties) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodePlaceholder, { componentId });
2965
- const definition = runtime.ui.components.get(component.type);
2966
- if (!definition) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
2967
- message: `unknown component "${component.type}"`,
2968
- componentId
2969
- });
2970
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeBoundary, {
2971
- surfaceId: surface.surfaceId,
2972
- componentId,
2973
- revision: properties,
2974
- runtime,
2975
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ResolvedNode, {
2976
- surface,
2977
- componentId,
2978
- definition,
2979
- properties,
2980
- runtime,
2981
- basePath,
2982
- ancestors
2983
- })
2984
- }, component.type);
2985
- });
2986
- /**
2987
- * Renders the component of a template once for each item of the list at the
2988
- * template path, keyed by index. Renders nothing when there is no list.
2989
- */
2990
- function TemplateChildren({ surface, template, basePath, ancestors }) {
2991
- const dataModel = surface.model.dataModel;
2992
- const listPath = resolvePath(template.path, basePath);
2993
- const subscribe = (0, react.useCallback)((onChange) => {
2994
- const subscription = dataModel.subscribe(listPath, onChange);
2995
- return () => subscription.unsubscribe();
2996
- }, [dataModel, listPath]);
2997
- const getCount = () => {
2998
- const list = dataModel.get(listPath);
2999
- return Array.isArray(list) ? list.length : 0;
3000
- };
3001
- const count = (0, react.useSyncExternalStore)(subscribe, getCount, zeroSnapshot);
3002
- 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, {
3003
- surface,
3004
- componentId: template.componentId,
3005
- basePath: joinPath(listPath, String(index)),
3006
- ancestors
3007
- }, index)) });
3008
- }
3009
- /**
3010
- * The props the model sets, with their dynamic values resolved from the
3011
- * surface data model: `{"@path"}` bindings, `{"@call"}` function values and
3012
- * `{"@call":"@index"}` in a template, at any depth. A literal writable prop
3013
- * that the component set shows the local value from `overrides`. Bound
3014
- * props, events and slots are left out, and so are the keys of the A2UI
3015
- * component envelope; `accessibility` is resolved the same way and given
3016
- * on its own.
3017
- *
3018
- * A prop is resolved again only when its raw value or a data model value it
3019
- * read has changed, so the result keeps its identity otherwise. A function
3020
- * value that cannot be computed gives a problem instead of values.
3021
- */
3022
- function useModelDataProps(surface, definition, properties, basePath, overrides) {
3023
- const dataModel = surface.model.dataModel;
3024
- const units = (0, react.useMemo)(() => {
3025
- const list = [];
3026
- for (const key of Object.keys(properties)) {
3027
- if (definition.events?.[key] || definition.slots?.[key] || Object.hasOwn(definition.selectors, key) || _copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS.has(key)) continue;
3028
- list.push({
3029
- key,
3030
- raw: properties[key]
3031
- });
3032
- }
3033
- const a11y = properties.accessibility;
3034
- if (typeof a11y === "object" && a11y !== null && !Array.isArray(a11y)) for (const [field, raw] of Object.entries(a11y)) list.push({
3035
- key: `accessibility/${field}`,
3036
- raw,
3037
- field
3038
- });
3039
- return list;
3040
- }, [properties, definition]);
3041
- const [, rerender] = (0, react.useReducer)((n) => n + 1, 0);
3042
- const cache = (0, react.useRef)(/* @__PURE__ */ new Map());
3043
- const values = {};
3044
- const a11yValues = {};
3045
- const paths = /* @__PURE__ */ new Set();
3046
- let problem;
3047
- const next = /* @__PURE__ */ new Map();
3048
- for (const { key, raw, field } of units) {
3049
- const cached = cache.current.get(key);
3050
- const isFresh = cached !== void 0 && cached.raw === raw && cached.basePath === basePath && [...cached.reads].every(([path, value]) => Object.is(dataModel.get(path), value));
3051
- const resolve = () => {
3052
- const resolved = tryResolveDynamicValue(raw, {
3053
- data: dataModel,
3054
- basePath
3055
- }, { isChecks: key === "checks" });
3056
- const reads = /* @__PURE__ */ new Map();
3057
- for (const path of resolved.paths) reads.set(path, dataModel.get(path));
3058
- return {
3059
- raw,
3060
- basePath,
3061
- reads,
3062
- outcome: resolved.ok ? {
3063
- ok: true,
3064
- value: resolved.value
3065
- } : {
3066
- ok: false,
3067
- message: resolved.error.message
3068
- }
3069
- };
3070
- };
3071
- const entry = isFresh && cached ? cached : resolve();
3072
- next.set(key, entry);
3073
- if (field !== void 0) {
3074
- if (entry.outcome.ok) a11yValues[field] = entry.outcome.value;
3075
- } else if (entry.outcome.ok) values[key] = entry.outcome.value;
3076
- else problem ??= `${key}: ${entry.outcome.message}`;
3077
- for (const path of entry.reads.keys()) paths.add(path);
3078
- }
3079
- cache.current = next;
3080
- const accessibility = readAccessibility(a11yValues);
3081
- for (const [key, value] of Object.entries(overrides)) if (!(0, _copilotkit_shared.isPathBinding)(properties[key])) values[key] = value;
3082
- const rendered = (0, react.useRef)(next);
3083
- rendered.current = next;
3084
- const pathKey = [...paths].sort().join("\n");
3085
- (0, react.useEffect)(() => {
3086
- const list = pathKey === "" ? [] : pathKey.split("\n");
3087
- const onChange = () => {
3088
- cache.current = /* @__PURE__ */ new Map();
3089
- rerender();
3090
- };
3091
- const subscriptions = list.map((path) => dataModel.subscribe(path, onChange));
3092
- if ([...rendered.current.values()].some((entry) => [...entry.reads].some(([path, value]) => !Object.is(dataModel.get(path), value)))) rerender();
3093
- return () => subscriptions.forEach((s) => s.unsubscribe());
3094
- }, [dataModel, pathKey]);
3095
- const stable = (0, react.useRef)({
3096
- ok: true,
3097
- values: {},
3098
- accessibility: void 0
3099
- });
3100
- const result = problem === void 0 ? {
3101
- ok: true,
3102
- values,
3103
- accessibility
3104
- } : {
3105
- ok: false,
3106
- problem
3107
- };
3108
- const last = stable.current;
3109
- 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;
3110
- return stable.current;
3111
- }
3112
- const NO_SELECTION = {
3113
- ok: true,
3114
- values: {}
3115
- };
3116
- function isSameSelection(a, b) {
3117
- if (a.ok && b.ok) return shallowEqual(a.values, b.values);
3118
- if (!a.ok && !b.ok) return a.problem === b.problem;
3119
- return false;
3120
- }
3121
- /** Runs every selector of a node. A selector that throws gives a problem. */
3122
- function select(definition, state, modelProps) {
3123
- const values = {};
3124
- const selectors = Object.entries(definition.selectors);
3125
- for (const [key, selector] of selectors) try {
3126
- values[key] = selector(state, modelProps);
3127
- } catch (error) {
3128
- return {
3129
- ok: false,
3130
- problem: `${key}: selector threw: ${error instanceof Error ? error.message : String(error)}`
3131
- };
3132
- }
3133
- return {
3134
- ok: true,
3135
- values
3136
- };
3137
- }
3138
- /**
3139
- * The values of the bound props of a node, read from the app state.
3140
- *
3141
- * The selectors run again only when the state object or the parsed model
3142
- * props change. When the new values are shallow-equal to the last ones, the
3143
- * last snapshot is kept. So the node re-renders only when a selected value
3144
- * changes. A selector that returns a new array on each call cannot cause a
3145
- * render loop: with the same inputs, the cached snapshot comes back.
3146
- *
3147
- * A node without bound props does not subscribe to the state.
3148
- */
3149
- function useSelection(manager, definition, modelProps) {
3150
- const hasSelectors = Object.keys(definition.selectors).length > 0;
3151
- const cache = (0, react.useRef)(void 0);
3152
- const getSnapshot = () => {
3153
- if (!hasSelectors || modelProps === void 0) return NO_SELECTION;
3154
- const state = manager.getState();
3155
- const cached = cache.current;
3156
- if (cached !== void 0 && cached.state === state && cached.modelProps === modelProps) return cached.selection;
3157
- const next = select(definition, state, modelProps);
3158
- const selection = cached !== void 0 && isSameSelection(cached.selection, next) ? cached.selection : next;
3159
- cache.current = {
3160
- state,
3161
- modelProps,
3162
- selection
3163
- };
3164
- return selection;
3165
- };
3166
- return (0, react.useSyncExternalStore)(hasSelectors ? manager.subscribe : noopSubscribe, getSnapshot, getSnapshot);
3167
- }
3168
- /**
3169
- * Checks the model-set props with the props schema before the selectors run.
3170
- * The bound props are not set yet, so their issues do not count. Neither do
3171
- * issues with no path (a check over several props), which the full check
3172
- * after the selectors reports.
3173
- */
3174
- function checkModelProps(definition, modelData) {
3175
- if (!definition.props) return {
3176
- ok: true,
3177
- values: {}
3178
- };
3179
- let values = modelData;
3180
- let result = validateSchemaSync(definition.props, values);
3181
- if (!result.success) {
3182
- const unset = withoutRejectedNulls(values, result.issues);
3183
- if (unset) {
3184
- values = unset;
3185
- result = validateSchemaSync(definition.props, values);
3186
- }
3187
- }
3188
- if (!result.success) {
3189
- const issues = result.issues.filter((issue) => {
3190
- const key = issueKey(issue);
3191
- return key === void 0 ? isAsyncIssue(issue) : !Object.hasOwn(definition.selectors, key);
3192
- });
3193
- if (issues.length > 0) return {
3194
- ok: false,
3195
- problem: formatIssues(issues)
3196
- };
3197
- }
3198
- return {
3199
- ok: true,
3200
- values
3201
- };
3202
- }
3203
- /**
3204
- * The data props of a node, in three steps: check the model-set props with
3205
- * the props schema, run the selectors with them, then parse all props with
3206
- * the props schema. Gives the reason when a step fails.
3207
- */
3208
- function useDataProps(runtime, surface, definition, properties, basePath, overrides) {
3209
- const modelData = useModelDataProps(surface, definition, properties, basePath, overrides);
3210
- const modelCheck = (0, react.useMemo)(() => modelData.ok ? checkModelProps(definition, modelData.values) : modelData, [definition, modelData]);
3211
- const selection = useSelection(runtime.manager, definition, modelCheck.ok ? modelCheck.values : void 0);
3212
- const accessibility = modelData.ok ? modelData.accessibility : void 0;
3213
- return (0, react.useMemo)(() => {
3214
- if (!modelCheck.ok) return modelCheck;
3215
- if (!selection.ok) return selection;
3216
- if (!definition.props) return {
3217
- ok: true,
3218
- props: {},
3219
- accessibility
3220
- };
3221
- const input = {
3222
- ...modelCheck.values,
3223
- ...selection.values
3224
- };
3225
- let parsed = validateSchemaSync(definition.props, input);
3226
- if (!parsed.success) {
3227
- const unset = withoutRejectedNulls(input, parsed.issues);
3228
- if (unset) parsed = validateSchemaSync(definition.props, unset);
3229
- }
3230
- if (!parsed.success) return {
3231
- ok: false,
3232
- problem: formatIssues(parsed.issues)
3233
- };
3234
- return {
3235
- ok: true,
3236
- props: parsed.data,
3237
- accessibility
3238
- };
3239
- }, [
3240
- definition,
3241
- modelCheck,
3242
- selection,
3243
- accessibility
3244
- ]);
3245
- }
3246
- /**
3247
- * The event props of a node. A matched event (one that matches a declared
3248
- * function) is always bound. An unmatched event is bound only when the model
3249
- * bound it.
3250
- */
3251
- function useEventProps(runtime, surface, componentId, definition, properties, basePath) {
3252
- const latest = (0, react.useRef)(properties);
3253
- latest.current = properties;
3254
- const boundNames = Object.keys(definition.events ?? {}).filter((name) => Object.hasOwn(definition.eventFunctions, name) || (0, _copilotkit_shared.isActionBinding)(properties[name])).join("|");
3255
- return (0, react.useMemo)(() => {
3256
- const handlers = {};
3257
- const names = boundNames ? boundNames.split("|") : [];
3258
- for (const name of names) {
3259
- const call = {
3260
- runtime,
3261
- surface,
3262
- componentId,
3263
- name,
3264
- parameters: definition.events?.[name]?.parameters
3265
- };
3266
- const functionName = Object.hasOwn(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
3267
- handlers[name] = functionName === void 0 ? (args) => invokeBoundEvent({
3268
- ...call,
3269
- binding: latest.current[name],
3270
- basePath,
3271
- args
3272
- }) : (args) => invokeMatchedEvent({
3273
- ...call,
3274
- functionName,
3275
- args
3276
- });
3277
- }
3278
- return handlers;
3279
- }, [
3280
- boundNames,
3281
- runtime,
3282
- surface,
3283
- componentId,
3284
- definition,
3285
- basePath
3286
- ]);
3287
- }
3288
- /**
3289
- * The setter props of a node: `setValue` for the writable prop `value`. For
3290
- * a prop the model bound to `{"@path"}`, the setter writes the data model
3291
- * and makes the path user-owned. For a literal prop, it sets `overrides`, a
3292
- * local value of this mounted node. The setters keep their identity.
3293
- */
3294
- function useSetterProps(runtime, surface, componentId, definition, properties, basePath) {
3295
- const [overrides, setOverrides] = (0, react.useState)({});
3296
- const latest = (0, react.useRef)(properties);
3297
- latest.current = properties;
3298
- return {
3299
- overrides,
3300
- setters: (0, react.useMemo)(() => {
3301
- const result = {};
3302
- const writable = definition.writable ?? [];
3303
- for (const key of writable) result[setterNameOf(key)] = (value) => {
3304
- const binding = latest.current[key];
3305
- if (!(0, _copilotkit_shared.isPathBinding)(binding)) {
3306
- setOverrides((current) => ({
3307
- ...current,
3308
- [key]: value
3309
- }));
3310
- return;
3311
- }
3312
- try {
3313
- runtime.manager.setOwnedValue(surface.key, resolvePath(binding["@path"], basePath), value);
3314
- } catch (cause) {
3315
- const message = cause instanceof Error ? cause.message : String(cause);
3316
- reportErrorSafely(runtime, {
3317
- kind: "props",
3318
- surfaceId: surface.surfaceId,
3319
- componentId,
3320
- error: /* @__PURE__ */ new Error(`${setterNameOf(key)}: ${message}`)
3321
- });
3322
- }
3323
- };
3324
- return result;
3325
- }, [
3326
- runtime,
3327
- surface,
3328
- componentId,
3329
- definition,
3330
- basePath
3331
- ])
3332
- };
3333
- }
3334
- function useSlotProps(surface, definition, properties, componentId, basePath, ancestors) {
3335
- return (0, react.useMemo)(() => {
3336
- const childAncestors = [...ancestors, scopedId(componentId, basePath)];
3337
- const slots = {};
3338
- for (const [name, kind] of Object.entries(definition.slots ?? {})) {
3339
- const value = properties[name];
3340
- if (kind === "single" && typeof value === "string") slots[name] = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
3341
- surface,
3342
- componentId: value,
3343
- basePath,
3344
- ancestors: childAncestors
3345
- });
3346
- else if (kind === "multiple" && isTemplateChildren(value)) slots[name] = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TemplateChildren, {
3347
- surface,
3348
- template: value,
3349
- basePath,
3350
- ancestors: childAncestors
3351
- });
3352
- 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, {
3353
- surface,
3354
- componentId: id,
3355
- basePath,
3356
- ancestors: childAncestors
3357
- }, id));
3358
- }
3359
- return slots;
3360
- }, [
3361
- surface,
3362
- definition,
3363
- properties,
3364
- componentId,
3365
- basePath,
3366
- ancestors
3367
- ]);
3368
- }
3369
- /**
3370
- * The parsed data props with every typed child reference (`child()`,
3371
- * `childList()`, at any depth) replaced by the rendered component. Without
3372
- * references, the parsed props come back as they are.
3373
- */
3374
- function useChildRefProps(surface, refs, props, componentId, basePath, ancestors) {
3375
- return (0, react.useMemo)(() => {
3376
- if (props === void 0 || refs.length === 0) return props;
3377
- const childAncestors = [...ancestors, scopedId(componentId, basePath)];
3378
- const render = (kind, value) => {
3379
- if (kind === "single") return typeof value === "string" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
3380
- surface,
3381
- componentId: value,
3382
- basePath,
3383
- ancestors: childAncestors
3384
- }) : void 0;
3385
- if (isTemplateChildren(value)) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TemplateChildren, {
3386
- surface,
3387
- template: value,
3388
- basePath,
3389
- ancestors: childAncestors
3390
- });
3391
- if (!Array.isArray(value)) return void 0;
3392
- return [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
3393
- surface,
3394
- componentId: id,
3395
- basePath,
3396
- ancestors: childAncestors
3397
- }, id));
3398
- };
3399
- let result = props;
3400
- for (const ref of refs) result = (0, _copilotkit_shared.mapAtChildRef)(result, ref.path, (found) => render(ref.kind, found));
3401
- return result;
3402
- }, [
3403
- surface,
3404
- refs,
3405
- props,
3406
- componentId,
3407
- basePath,
3408
- ancestors
3409
- ]);
3410
- }
3411
- function ResolvedNode({ surface, componentId, definition, properties, runtime, basePath, ancestors }) {
3412
- const { overrides, setters } = useSetterProps(runtime, surface, componentId, definition, properties, basePath);
3413
- const dataProps = useDataProps(runtime, surface, definition, properties, basePath, overrides);
3414
- const eventProps = useEventProps(runtime, surface, componentId, definition, properties, basePath);
3415
- const slotProps = useSlotProps(surface, definition, properties, componentId, basePath, ancestors);
3416
- const childRefProps = useChildRefProps(surface, definition.childRefs, dataProps.ok ? dataProps.props : void 0, componentId, basePath, ancestors);
3417
- const accessibility = dataProps.ok ? dataProps.accessibility : void 0;
3418
- const nodeContext = (0, react.useMemo)(() => ({
3419
- surfaceKey: surface.key,
3420
- surfaceId: surface.surfaceId,
3421
- componentId,
3422
- accessibility
3423
- }), [
3424
- surface.key,
3425
- surface.surfaceId,
3426
- componentId,
3427
- accessibility
3428
- ]);
3429
- const problem = dataProps.ok ? void 0 : dataProps.problem;
3430
- (0, react.useEffect)(() => {
3431
- if (problem) reportErrorSafely(runtime, {
3432
- kind: "props",
3433
- surfaceId: surface.surfaceId,
3434
- componentId,
3435
- error: /* @__PURE__ */ new Error(`Invalid props: ${problem}`)
3436
- });
3437
- }, [
3438
- problem,
3439
- runtime,
3440
- surface.surfaceId,
3441
- componentId
3442
- ]);
3443
- if (!dataProps.ok) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
3444
- message: `invalid props (${problem})`,
3445
- componentId
3446
- });
3447
- const Component = definition.component;
3448
- const rendered = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Component, {
3449
- ...childRefProps,
3450
- ...eventProps,
3451
- ...slotProps,
3452
- ...setters
3453
- });
3454
- const hasEnvelope = properties.accessibility !== void 0 && definition.accessibility !== "self";
3455
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GenerativeUINodeContext.Provider, {
3456
- value: nodeContext,
3457
- children: hasEnvelope ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
3458
- "data-a2ui-accessibility": "",
3459
- style: ROOT_STYLE,
3460
- ...wrapperAria(accessibilityAttributes(accessibility)),
3461
- children: rendered
3462
- }) : rendered
3463
- });
3464
- }
3465
-
3466
- //#endregion
3467
- //#region src/generative-ui/chat.tsx
3468
- const GenerativeUIChatSlotContext = (0, react.createContext)(void 0);
3469
- function DefaultGenerativeUIChatCard({ surfaceId, isStreaming, error, children }) {
3470
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3471
- "data-generative-ui-chat-surface": surfaceId,
3472
- className: "cpk-generative-ui-chat-card",
3473
- children: [children, error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3474
- role: "alert",
3475
- className: "cpk-generative-ui-chat-card-error",
3476
- children: "Part of this UI couldn't be shown."
3477
- })]
3478
- });
3479
- }
3480
- const ContentSchema = zod.z.object({
3481
- surfaceId: zod.z.string(),
3482
- target: zod.z.string(),
3483
- catalogId: zod.z.string(),
3484
- operations: zod.z.array(zod.z.any()),
3485
- status: zod.z.enum([
3486
- "streaming",
3487
- "ready",
3488
- "error"
3489
- ]),
3490
- rejected: zod.z.array(zod.z.object({
3491
- index: zod.z.number(),
3492
- reason: zod.z.string()
3493
- })).default([])
3494
- }).passthrough();
3495
- function GenerativeUIChatActivity({ content, agent }) {
3496
- const runtime = useGenerativeUIRuntime();
3497
- const threadId = useCopilotChatConfiguration()?.threadId ?? agent?.threadId;
3498
- const Wrapper = (0, react.useContext)(GenerativeUIChatSlotContext) ?? DefaultGenerativeUIChatCard;
3499
- useManagerVersion(runtime);
3500
- (0, react.useLayoutEffect)(() => {
3501
- if (runtime && threadId) runtime.manager.ingest(threadId, agent?.agentId, content);
3502
- }, [
3503
- runtime,
3504
- threadId,
3505
- agent?.agentId,
3506
- content
3507
- ]);
3508
- if (!runtime || !threadId || content.target !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET) return null;
3509
- const surface = runtime.manager.getSurface(threadId, content.surfaceId) ?? runtime.manager.getFailedSurface(threadId, content.surfaceId);
3510
- if (!surface) return null;
3511
- const rejected = [...content.rejected ?? [], ...surface.clientRejected];
3512
- const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
3513
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Wrapper, {
3514
- surfaceId: content.surfaceId,
3515
- isStreaming: content.status === "streaming",
3516
- error,
3517
- rejected,
3518
- children: surface.failed ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceView, { surface })
3519
- });
3520
- }
3521
- function createGenerativeUIActivityRenderer() {
3522
- return {
3523
- activityType: _copilotkit_shared.GENERATIVE_UI_ACTIVITY_TYPE,
3524
- content: ContentSchema,
3525
- render: GenerativeUIChatActivity
3526
- };
3527
- }
3528
- /**
3529
- * Shows nothing in the chat for an agent-called function. The root reads the
3530
- * function-call activities from the messages and runs them. This renderer
3531
- * only keeps a wildcard ("*") activity renderer from showing them.
3532
- */
3533
- function createGenerativeUIFunctionCallActivityRenderer() {
3534
- return {
3535
- activityType: _copilotkit_shared.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,
3536
- content: zod.z.unknown(),
3537
- render: () => null
3538
- };
3539
- }
3540
- /** Hides the raw `render_ui` tool call; the surface activity owns the UX. */
3541
- function GenerativeUIToolCallRenderer() {
3542
- const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
3543
- (0, react.useEffect)(() => {
3544
- const renderer = defineToolCallRenderer({
3545
- name: _copilotkit_shared.GENERATIVE_UI_RENDER_TOOL,
3546
- args: zod.z.any(),
3547
- render: () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {})
3548
- });
3549
- const existing = copilotkit._renderToolCalls ?? [];
3550
- copilotkit.setRenderToolCalls([...existing.filter((rc) => rc.name !== _copilotkit_shared.GENERATIVE_UI_RENDER_TOOL), renderer]);
3551
- }, [copilotkit]);
3552
- return null;
3553
- }
3554
-
3555
- //#endregion
3556
- //#region src/generative-ui/markdown/ProviderMarkdown.tsx
3557
- /**
3558
- * Markdown prose inside generative UI, rendered like the chat text around
3559
- * it: the renderer set on the provider when there is one, else the built-in
3560
- * streaming renderer. Config passed here wins over provider config.
3561
- */
3562
- function ProviderMarkdown({ content, isStreaming, className, ...config }) {
3563
- const renderer = useMarkdownRenderer();
3564
- if (renderer && isReactComponentType(renderer)) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(renderer, {
3565
- content,
3566
- isStreaming,
3567
- className
3568
- });
3569
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StreamingMarkdownDefaultRenderer, {
3570
- ...renderer,
3571
- ...config,
3572
- content,
3573
- isStreaming,
3574
- className
3575
- });
3576
- }
3577
-
3578
- //#endregion
3579
- //#region src/generative-ui/markdown/MarkdownSurfaces.tsx
3580
- const FADE_STYLE_ID = "a2ui-markdown-fade";
3581
- /**
3582
- * Components fade in as they stream: each element that appears under a
3583
- * markdown surface runs the keyframes once on mount. React keeps the keys
3584
- * stable per component id, so an element that is already there never
3585
- * animates again. SVG internals are left out: a chart library re-creates
3586
- * its nodes on each render, and a fade on each of them would read as the
3587
- * chart flashing whenever a sibling arrives. The fade runs under reduced
3588
- * motion too, because it moves nothing.
3589
- */
3590
- 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");
3591
- const noEffect = () => {};
3592
- const useInjectEffect = typeof document === "undefined" ? noEffect : react.useInsertionEffect;
3593
- function useFadeStyles() {
3594
- useInjectEffect(() => {
3595
- if (document.getElementById(FADE_STYLE_ID)) return;
3596
- const style = document.createElement("style");
3597
- style.id = FADE_STYLE_ID;
3598
- style.textContent = FADE_CSS;
3599
- document.head.appendChild(style);
3600
- }, []);
3601
- }
3602
- /**
3603
- * The default wrapper of a chat surface in the markdown transport. It draws
3604
- * no box: a surface sits in the flow of the reply like a paragraph, and a
3605
- * Card draws its own box when it is interactive. Nothing shows while the
3606
- * surface streams. A rejected operation gets one line.
3607
- */
3608
- function DefaultMarkdownChatSurface({ surfaceId, error, children }) {
3609
- useFadeStyles();
3610
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3611
- "data-generative-ui-chat-surface": surfaceId,
3612
- "data-a2ui-markdown-surface": surfaceId,
3613
- className: "cpk-markdown-chat-surface",
3614
- children: [children, error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3615
- role: "alert",
3616
- className: "cpk-markdown-chat-surface-error",
3617
- children: "Part of this UI couldn't be shown."
3618
- })]
3619
- });
3620
- }
3621
- /**
3622
- * One chat surface in the chat wrapper. Nothing renders until the surface
3623
- * has its root component, so a half-streamed fence shows no empty card.
3624
- */
3625
- function ChatSurface({ runtime, threadId, surfaceId, Wrapper }) {
3626
- const surface = runtime.manager.getSurface(threadId, surfaceId) ?? runtime.manager.getFailedSurface(threadId, surfaceId);
3627
- const root = surface?.model.componentsModel.get(_copilotkit_shared.GENERATIVE_UI_ROOT_ID);
3628
- if (!surface || !root && !surface.failed) return null;
3629
- const rejected = [...surface.serverRejected, ...surface.clientRejected];
3630
- const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
3631
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Wrapper, {
3632
- surfaceId,
3633
- isStreaming: surface.status === "streaming",
3634
- error,
3635
- rejected,
3636
- children: surface.failed ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceView, { surface })
3637
- });
3638
- }
3639
- /** The blocks of one fence: lifted prose and chat surfaces, in order. */
3640
- function FenceBlocks({ blocks, runtime, threadId, isStreaming, markdownProps }) {
3641
- const Wrapper = (0, react.useContext)(GenerativeUIChatSlotContext) ?? DefaultMarkdownChatSurface;
3642
- let surfaceCount = 0;
3643
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: blocks.map((block, index) => {
3644
- if (block.kind === "markdown") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProviderMarkdown, {
3645
- ...markdownProps,
3646
- content: block.markdown,
3647
- isStreaming: isStreaming && index === blocks.length - 1
3648
- }, `md-${surfaceCount}`);
3649
- surfaceCount++;
3650
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChatSurface, {
3651
- runtime,
3652
- threadId,
3653
- surfaceId: block.surfaceId,
3654
- Wrapper
3655
- }, block.surfaceId);
3656
- }) });
3657
- }
3658
- /**
3659
- * Experimental. Renders an assistant message of the markdown transport.
3660
- * Prose renders as markdown. In place of each ```a2ui fence:
3661
- *
3662
- * - the fence that created a chat surface renders that surface (and the
3663
- * prose lifted out of it) in the chat wrapper;
3664
- * - every other fence renders nothing: a fence that updates the surface of
3665
- * an earlier fence, or a fence for a named target, which
3666
- * `<GenerativeUISurface id>` renders.
3667
- *
3668
- * Use it inside `<CopilotKitProvider generativeUI={{ ui, transport: "markdown" }}>`.
3669
- * `CopilotChatAssistantMessage` uses it there on its own.
3670
- *
3671
- * @example
3672
- * ```tsx
3673
- * <MarkdownSurfaces content={message.content} messageId={message.id} />
3674
- * ```
3675
- */
3676
- function MarkdownSurfaces({ content, messageId, isStreaming = false, ...markdownProps }) {
3677
- const runtime = useRequiredGenerativeUIRuntime();
3678
- const chatThreadId = useCopilotChatConfiguration()?.threadId;
3679
- useManagerVersion(runtime);
3680
- const segments = (0, react.useMemo)(() => (0, _copilotkit_core.splitA2UIMarkdown)(content), [content]);
3681
- const threadId = chatThreadId ?? runtime.manager.getActiveThread();
3682
- const source = getMarkdownSurfaceSource(runtime);
3683
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: segments.map((segment, index) => {
3684
- const isLast = index === segments.length - 1;
3685
- if (segment.type === "markdown") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProviderMarkdown, {
3686
- ...markdownProps,
3687
- content: segment.text,
3688
- isStreaming: isStreaming && isLast
3689
- }, `md-${index}`);
3690
- const blocks = threadId ? source.getFenceBlocks(threadId, messageId, segment.index) : void 0;
3691
- if (!threadId || !blocks) return null;
3692
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FenceBlocks, {
3693
- blocks,
3694
- runtime,
3695
- threadId,
3696
- isStreaming: isStreaming && isLast,
3697
- markdownProps
3698
- }, `a2ui-${segment.index}`);
3699
- }) });
3700
- }
3701
-
3702
- //#endregion
3703
- Object.defineProperty(exports, 'BASIC_FUNCTIONS', {
3704
- enumerable: true,
3705
- get: function () {
3706
- return BASIC_FUNCTIONS;
3707
- }
3708
- });
3709
- Object.defineProperty(exports, 'ControlledModalOpenScope', {
3710
- enumerable: true,
3711
- get: function () {
3712
- return ControlledModalOpenScope;
3713
- }
3714
- });
3715
- Object.defineProperty(exports, 'CopilotChatConfigurationProvider', {
3716
- enumerable: true,
3717
- get: function () {
3718
- return CopilotChatConfigurationProvider;
3719
- }
3720
- });
3721
- Object.defineProperty(exports, 'CopilotChatDefaultLabels', {
3722
- enumerable: true,
3723
- get: function () {
3724
- return CopilotChatDefaultLabels;
3725
- }
3726
- });
3727
- Object.defineProperty(exports, 'DARK_THEME_CSS', {
3728
- enumerable: true,
3729
- get: function () {
3730
- return DARK_THEME_CSS;
3731
- }
3732
- });
3733
- Object.defineProperty(exports, 'DefaultGenerativeUIChatCard', {
3734
- enumerable: true,
3735
- get: function () {
3736
- return DefaultGenerativeUIChatCard;
3737
- }
3738
- });
3739
- Object.defineProperty(exports, 'ExpressionError', {
3740
- enumerable: true,
3741
- get: function () {
3742
- return ExpressionError;
3743
- }
3744
- });
3745
- Object.defineProperty(exports, 'GenerativeUIChatSlotContext', {
3746
- enumerable: true,
3747
- get: function () {
3748
- return GenerativeUIChatSlotContext;
3749
- }
3750
- });
3751
- Object.defineProperty(exports, 'GenerativeUIError', {
3752
- enumerable: true,
3753
- get: function () {
3754
- return GenerativeUIError;
3755
- }
3756
- });
3757
- Object.defineProperty(exports, 'GenerativeUINodeContext', {
3758
- enumerable: true,
3759
- get: function () {
3760
- return GenerativeUINodeContext;
3761
- }
3762
- });
3763
- Object.defineProperty(exports, 'GenerativeUIRuntimeContext', {
3764
- enumerable: true,
3765
- get: function () {
3766
- return GenerativeUIRuntimeContext;
3767
- }
3768
- });
3769
- Object.defineProperty(exports, 'GenerativeUIToolCallRenderer', {
3770
- enumerable: true,
3771
- get: function () {
3772
- return GenerativeUIToolCallRenderer;
3773
- }
3774
- });
3775
- Object.defineProperty(exports, 'MarkdownRendererProvider', {
3776
- enumerable: true,
3777
- get: function () {
3778
- return MarkdownRendererProvider;
3779
- }
3780
- });
3781
- Object.defineProperty(exports, 'MarkdownSurfaces', {
3782
- enumerable: true,
3783
- get: function () {
3784
- return MarkdownSurfaces;
3785
- }
3786
- });
3787
- Object.defineProperty(exports, 'ProviderMarkdown', {
3788
- enumerable: true,
3789
- get: function () {
3790
- return ProviderMarkdown;
3791
- }
3792
- });
3793
- Object.defineProperty(exports, 'StreamingMarkdownDefaultRenderer', {
3794
- enumerable: true,
3795
- get: function () {
3796
- return StreamingMarkdownDefaultRenderer;
3797
- }
3798
- });
3799
- Object.defineProperty(exports, 'SurfaceView', {
3800
- enumerable: true,
3801
- get: function () {
3802
- return SurfaceView;
3803
- }
3804
- });
3805
- Object.defineProperty(exports, '__toESM', {
3806
- enumerable: true,
3807
- get: function () {
3808
- return __toESM;
3809
- }
3810
- });
3811
- Object.defineProperty(exports, 'catalogIdsOf', {
3812
- enumerable: true,
3813
- get: function () {
3814
- return catalogIdsOf;
3815
- }
3816
- });
3817
- Object.defineProperty(exports, 'cn', {
3818
- enumerable: true,
3819
- get: function () {
3820
- return cn;
3821
- }
3822
- });
3823
- Object.defineProperty(exports, 'componentCatalogIds', {
3824
- enumerable: true,
3825
- get: function () {
3826
- return componentCatalogIds;
3827
- }
3828
- });
3829
- Object.defineProperty(exports, 'containsDynamicValue', {
3830
- enumerable: true,
3831
- get: function () {
3832
- return containsDynamicValue;
3833
- }
3834
- });
3835
- Object.defineProperty(exports, 'controlAria', {
3836
- enumerable: true,
3837
- get: function () {
3838
- return controlAria;
3839
- }
3840
- });
3841
- Object.defineProperty(exports, 'createGenerativeUI', {
3842
- enumerable: true,
3843
- get: function () {
3844
- return createGenerativeUI;
3845
- }
3846
- });
3847
- Object.defineProperty(exports, 'createGenerativeUIActivityRenderer', {
3848
- enumerable: true,
3849
- get: function () {
3850
- return createGenerativeUIActivityRenderer;
3851
- }
3852
- });
3853
- Object.defineProperty(exports, 'createGenerativeUIFunctionCallActivityRenderer', {
3854
- enumerable: true,
3855
- get: function () {
3856
- return createGenerativeUIFunctionCallActivityRenderer;
3857
- }
3858
- });
3859
- Object.defineProperty(exports, 'defineToolCallRenderer', {
3860
- enumerable: true,
3861
- get: function () {
3862
- return defineToolCallRenderer;
3863
- }
3864
- });
3865
- Object.defineProperty(exports, 'formatIssues', {
3866
- enumerable: true,
3867
- get: function () {
3868
- return formatIssues;
3869
- }
3870
- });
3871
- Object.defineProperty(exports, 'getMarkdownSurfaceSource', {
3872
- enumerable: true,
3873
- get: function () {
3874
- return getMarkdownSurfaceSource;
3875
- }
3876
- });
3877
- Object.defineProperty(exports, 'isAsyncIssue', {
3878
- enumerable: true,
3879
- get: function () {
3880
- return isAsyncIssue;
3881
- }
3882
- });
3883
- Object.defineProperty(exports, 'isReactComponentType', {
3884
- enumerable: true,
3885
- get: function () {
3886
- return isReactComponentType;
3887
- }
3888
- });
3889
- Object.defineProperty(exports, 'isRecord', {
3890
- enumerable: true,
3891
- get: function () {
3892
- return isRecord;
3893
- }
3894
- });
3895
- Object.defineProperty(exports, 'issueKey', {
3896
- enumerable: true,
3897
- get: function () {
3898
- return issueKey;
3899
- }
3900
- });
3901
- Object.defineProperty(exports, 'namedRole', {
3902
- enumerable: true,
3903
- get: function () {
3904
- return namedRole;
3905
- }
3906
- });
3907
- Object.defineProperty(exports, 'renderSlot', {
3908
- enumerable: true,
3909
- get: function () {
3910
- return renderSlot;
3911
- }
3912
- });
3913
- Object.defineProperty(exports, 'toJsonSchema', {
3914
- enumerable: true,
3915
- get: function () {
3916
- return toJsonSchema;
3917
- }
3918
- });
3919
- Object.defineProperty(exports, 'useCopilotChatConfiguration', {
3920
- enumerable: true,
3921
- get: function () {
3922
- return useCopilotChatConfiguration;
3923
- }
3924
- });
3925
- Object.defineProperty(exports, 'useGenerativeUIAccessibility', {
3926
- enumerable: true,
3927
- get: function () {
3928
- return useGenerativeUIAccessibility;
3929
- }
3930
- });
3931
- Object.defineProperty(exports, 'useGenerativeUIFunction', {
3932
- enumerable: true,
3933
- get: function () {
3934
- return useGenerativeUIFunction;
3935
- }
3936
- });
3937
- Object.defineProperty(exports, 'useGenerativeUIRuntime', {
3938
- enumerable: true,
3939
- get: function () {
3940
- return useGenerativeUIRuntime;
3941
- }
3942
- });
3943
- Object.defineProperty(exports, 'useGenerativeUIState', {
3944
- enumerable: true,
3945
- get: function () {
3946
- return useGenerativeUIState;
3947
- }
3948
- });
3949
- Object.defineProperty(exports, 'useManagerVersion', {
3950
- enumerable: true,
3951
- get: function () {
3952
- return useManagerVersion;
3953
- }
3954
- });
3955
- Object.defineProperty(exports, 'useMarkdownRenderer', {
3956
- enumerable: true,
3957
- get: function () {
3958
- return useMarkdownRenderer;
3959
- }
3960
- });
3961
- Object.defineProperty(exports, 'useRequiredGenerativeUIRuntime', {
3962
- enumerable: true,
3963
- get: function () {
3964
- return useRequiredGenerativeUIRuntime;
3965
- }
3966
- });
3967
- Object.defineProperty(exports, 'useShallowStableRef', {
3968
- enumerable: true,
3969
- get: function () {
3970
- return useShallowStableRef;
3971
- }
3972
- });
3973
- Object.defineProperty(exports, 'validateSchemaSync', {
3974
- enumerable: true,
3975
- get: function () {
3976
- return validateSchemaSync;
3977
- }
3978
- });
3979
- Object.defineProperty(exports, 'withoutRejectedNulls', {
3980
- enumerable: true,
3981
- get: function () {
3982
- return withoutRejectedNulls;
3983
- }
3984
- });
3985
- Object.defineProperty(exports, 'wrapperAria', {
3986
- enumerable: true,
3987
- get: function () {
3988
- return wrapperAria;
3989
- }
3990
- });
3991
- //# sourceMappingURL=MarkdownSurfaces-S4wfUl3J.cjs.map