@copilotkit/react-core 1.80.0 → 1.82.0

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