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

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