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