@copilotkit/react-core 2.0.0-rc.31 → 2.0.0-rc.32

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 (34) hide show
  1. package/README.md +1 -1
  2. package/dist/MarkdownRendererContext-CPfNVyde.d.mts +241 -0
  3. package/dist/MarkdownRendererContext-CPfNVyde.d.mts.map +1 -0
  4. package/dist/MarkdownRendererContext-iOl2pj9l.d.cts +241 -0
  5. package/dist/MarkdownRendererContext-iOl2pj9l.d.cts.map +1 -0
  6. package/dist/MarkdownSurfaces-BFoO6wSB.cjs +1650 -0
  7. package/dist/MarkdownSurfaces-BFoO6wSB.cjs.map +1 -0
  8. package/dist/MarkdownSurfaces-BQ1HGCzB.mjs +1442 -0
  9. package/dist/MarkdownSurfaces-BQ1HGCzB.mjs.map +1 -0
  10. package/dist/generative-ui.cjs +687 -2964
  11. package/dist/generative-ui.cjs.map +1 -1
  12. package/dist/generative-ui.d.cts +2478 -2683
  13. package/dist/generative-ui.d.cts.map +1 -1
  14. package/dist/generative-ui.d.mts +2477 -2682
  15. package/dist/generative-ui.d.mts.map +1 -1
  16. package/dist/generative-ui.mjs +299 -2585
  17. package/dist/generative-ui.mjs.map +1 -1
  18. package/dist/index.cjs +26 -1367
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +1 -1
  21. package/dist/index.d.mts +1 -1
  22. package/dist/index.mjs +11 -1352
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/index.umd.js +124 -3358
  25. package/dist/index.umd.js.map +1 -1
  26. package/package.json +9 -9
  27. package/dist/MarkdownRendererContext-BX26QLwl.d.cts +0 -937
  28. package/dist/MarkdownRendererContext-BX26QLwl.d.cts.map +0 -1
  29. package/dist/MarkdownRendererContext-DAOMewji.d.mts +0 -937
  30. package/dist/MarkdownRendererContext-DAOMewji.d.mts.map +0 -1
  31. package/dist/MarkdownSurfaces-BbrHcSHN.cjs +0 -3903
  32. package/dist/MarkdownSurfaces-BbrHcSHN.cjs.map +0 -1
  33. package/dist/MarkdownSurfaces-DQbRS91-.mjs +0 -3587
  34. package/dist/MarkdownSurfaces-DQbRS91-.mjs.map +0 -1
@@ -0,0 +1,1442 @@
1
+ import { CopilotChatDefaultLabels, splitA2UIMarkdown, ɵChatConfigurationStore, ɵcn as cn, ɵcopilotIconSvgAttributes, ɵcopilotIcons, ɵshallowEqualRecord } from "@copilotkit/core";
2
+ import React, { Component, createContext, createElement, forwardRef, memo, useCallback, useContext, useEffect, useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
3
+ import { StreamingMarkdownRenderer } from "@copilotkit/markdown/react";
4
+ import { CHAT_MARKDOWN_NODE_CLASS_NAMES, warnUnsupportedRichSyntaxOnce } from "@copilotkit/markdown";
5
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
6
+ import { CopilotKitContext, useCopilotKit, useDefaultAgentId } from "@copilotkit/react-core/context";
7
+ import { A2UI_COMPONENT_ENVELOPE_KEYS, GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_CHAT_TARGET, GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE, GENERATIVE_UI_RENDER_TOOL, GENERATIVE_UI_ROOT_ID, isActionBinding, isPathBinding, mapAtChildRef, ɵanySchema } from "@copilotkit/shared";
8
+ import * as z from "zod";
9
+ import { accessibilityAttributes, accessibilityAttributes as accessibilityAttributes$1, controlAria, getMarkdownSurfaceSource, invokeBoundEvent, invokeMatchedEvent, joinPath, namedRole, readAccessibility, reportErrorSafely, resolvePath, tryResolveDynamicValue, wrapperAria } from "@copilotkit/core/generative-ui";
10
+ import { catalogIdsOf, createGenerativeUI, formatIssues, isAsyncIssue, issueKey, setterNameOf, themeStyleSheet, validateSchema, validateSchemaSync, withoutRejectedNulls } from "@copilotkit/shared/generative-ui";
11
+
12
+ //#region src/components/chat/StreamingMarkdownDefaultRenderer.tsx
13
+ /**
14
+ * react-core's built-in default markdown renderer — a thin adapter over
15
+ * `@copilotkit/markdown`'s streaming renderer. Maps the pluggable
16
+ * renderer contract (`{ content, isStreaming, className }`) onto the streaming
17
+ * renderer for streaming-safe incremental rendering + per-token animation.
18
+ * Still overridable via the slot/provider pluggable interface.
19
+ */
20
+ function StreamingMarkdownDefaultRenderer({ content, isStreaming, className, nodeRenderers, caret, options, onLinkClick, onCitationClick }) {
21
+ if (!content) return null;
22
+ warnUnsupportedRichSyntaxOnce(content);
23
+ return /* @__PURE__ */ jsx(StreamingMarkdownRenderer, {
24
+ className,
25
+ isComplete: !isStreaming,
26
+ caret: caret ?? !!isStreaming,
27
+ nodeRenderers,
28
+ nodeClassNames: CHAT_MARKDOWN_NODE_CLASS_NAMES,
29
+ options,
30
+ onLinkClick,
31
+ onCitationClick,
32
+ children: content
33
+ });
34
+ }
35
+ StreamingMarkdownDefaultRenderer.displayName = "StreamingMarkdownDefaultRenderer";
36
+
37
+ //#endregion
38
+ //#region src/components/icons/CopilotIcon.tsx
39
+ /** Turns SVG attribute names such as `stroke-width` into React's `strokeWidth`. */
40
+ function toReactAttributes(attributes) {
41
+ return Object.fromEntries(Object.entries(attributes).map(([key, value]) => [key.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase()), value]));
42
+ }
43
+ const svgDefaults = toReactAttributes(ɵcopilotIconSvgAttributes);
44
+ /** True when the props give the icon an accessible name or role. */
45
+ function hasAccessibleProp(props) {
46
+ return Object.keys(props).some((key) => key.startsWith("aria-") || key === "role" || key === "title");
47
+ }
48
+ /**
49
+ * Internal. Draws a Lucide icon from its node data, the way Lucide's React package
50
+ * does: Lucide's default SVG attributes, the `lucide lucide-<name>` classes,
51
+ * and `aria-hidden="true"` when no `aria-*`, `role` or `title` prop names it.
52
+ */
53
+ const IconSvg = forwardRef(function IconSvg({ lucideName, nodes, size = 24, color = "currentColor", strokeWidth = 2, className, children, ...props }, ref) {
54
+ const isDecorative = !children && !hasAccessibleProp(props);
55
+ return /* @__PURE__ */ jsxs("svg", {
56
+ ref,
57
+ ...svgDefaults,
58
+ width: size,
59
+ height: size,
60
+ stroke: color,
61
+ strokeWidth,
62
+ className: cn("lucide", `lucide-${lucideName}`, className),
63
+ "aria-hidden": isDecorative || void 0,
64
+ ...props,
65
+ children: [nodes.map((node, index) => createElement(node.tag, {
66
+ key: index,
67
+ ...node.attributes
68
+ })), children]
69
+ });
70
+ });
71
+ /**
72
+ * Draws one of the chat icons as an inline `<svg>`.
73
+ *
74
+ * The `<svg>` has the classes `lucide lucide-<icon name>`, so CSS that selects
75
+ * them (for example `svg.lucide-arrow-up`) keeps working. The icon is hidden
76
+ * from screen readers unless you give it an `aria-label`, `role` or `title`.
77
+ *
78
+ * @param props.name - The chat icon, for example `"ArrowUp"` or `"X"`.
79
+ * @param props.size - Width and height. Defaults to `24`.
80
+ * @param props.strokeWidth - Line width. Defaults to `2`.
81
+ * @param props.color - Line color. Defaults to `currentColor`.
82
+ *
83
+ * @example
84
+ * ```tsx
85
+ * <CopilotIcon name="ArrowUp" className="cpk-chat-input-send-icon" />
86
+ * <CopilotIcon name="X" aria-label="Close" />
87
+ * ```
88
+ */
89
+ const CopilotIcon = forwardRef(function CopilotIcon({ name, ...props }, ref) {
90
+ const icon = ɵcopilotIcons[name];
91
+ return /* @__PURE__ */ jsx(IconSvg, {
92
+ ref,
93
+ lucideName: icon.name,
94
+ nodes: icon.nodes,
95
+ ...props
96
+ });
97
+ });
98
+
99
+ //#endregion
100
+ //#region src/lib/shallow-stable-ref.ts
101
+ /**
102
+ * Shallow equality comparison for objects: same own keys, each holding the
103
+ * same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.
104
+ */
105
+ function shallowEqual(obj1, obj2) {
106
+ return ɵshallowEqualRecord(obj1, obj2);
107
+ }
108
+ /**
109
+ * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
110
+ * class instances, and other exotic objects that happen to have typeof "object".
111
+ */
112
+ function isPlainObject(obj) {
113
+ return obj !== null && typeof obj === "object" && Object.prototype.toString.call(obj) === "[object Object]";
114
+ }
115
+ /**
116
+ * Returns the same reference as long as the value is shallowly equal to the
117
+ * previous render's value.
118
+ *
119
+ * - Identical references bail out immediately (O(1)).
120
+ * - Plain objects ({}) are shallow-compared key-by-key.
121
+ * - Arrays, Dates, class instances, functions, and primitives are compared by
122
+ * reference only — shallowEqual is never called on non-plain objects, which
123
+ * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).
124
+ *
125
+ * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow
126
+ * equality check isn't defeated by a new object reference on every render.
127
+ */
128
+ function useShallowStableRef(value) {
129
+ const ref = useRef(value);
130
+ if (ref.current === value) return ref.current;
131
+ if (isPlainObject(ref.current) && isPlainObject(value)) {
132
+ if (shallowEqual(ref.current, value)) return ref.current;
133
+ }
134
+ ref.current = value;
135
+ return ref.current;
136
+ }
137
+
138
+ //#endregion
139
+ //#region src/providers/CopilotChatConfigurationProvider.tsx
140
+ const CopilotChatConfiguration = createContext(null);
141
+ const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
142
+ const parentConfig = useContext(CopilotChatConfiguration);
143
+ const stableLabels = useShallowStableRef(labels);
144
+ const mergedLabels = useMemo(() => ({
145
+ ...CopilotChatDefaultLabels,
146
+ ...parentConfig?.labels,
147
+ ...stableLabels
148
+ }), [stableLabels, parentConfig?.labels]);
149
+ const providerAgentId = useDefaultAgentId();
150
+ const options = {
151
+ agentId,
152
+ threadId,
153
+ hasExplicitThreadId,
154
+ isModalDefaultOpen,
155
+ providerAgentId
156
+ };
157
+ const parentStore = parentConfig?.ɵstore ?? null;
158
+ const [store] = useState(() => new ɵChatConfigurationStore(options, parentStore));
159
+ store.ɵsetOptions(options);
160
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
161
+ useEffect(() => {
162
+ store.update({
163
+ agentId,
164
+ threadId,
165
+ hasExplicitThreadId,
166
+ isModalDefaultOpen,
167
+ providerAgentId
168
+ });
169
+ }, [
170
+ store,
171
+ agentId,
172
+ threadId,
173
+ hasExplicitThreadId,
174
+ isModalDefaultOpen,
175
+ providerAgentId
176
+ ]);
177
+ const copilotkit = useContext(CopilotKitContext)?.copilotkit;
178
+ useEffect(() => {
179
+ if (copilotkit === void 0) return;
180
+ return store.bindOpenThread(copilotkit);
181
+ }, [copilotkit, store]);
182
+ const ownsModal = isModalDefaultOpen !== void 0;
183
+ const isModalOpen = ownsModal || !parentConfig ? snapshot.isModalOpen : parentConfig.isModalOpen;
184
+ const setModalOpen = ownsModal || !parentConfig ? store.setModalOpen : parentConfig.setModalOpen;
185
+ const { agentId: resolvedAgentId, threadId: resolvedThreadId, hasExplicitThreadId: resolvedHasExplicitThreadId, drawerOpen, drawerRegistered } = snapshot;
186
+ const configurationValue = useMemo(() => ({
187
+ labels: mergedLabels,
188
+ agentId: resolvedAgentId,
189
+ threadId: resolvedThreadId,
190
+ hasExplicitThreadId: resolvedHasExplicitThreadId,
191
+ isModalOpen,
192
+ setModalOpen,
193
+ drawerOpen,
194
+ setDrawerOpen: store.setDrawerOpen,
195
+ drawerRegistered,
196
+ registerDrawer: store.registerDrawer,
197
+ ɵregisterModalCloser: store.registerModalCloser,
198
+ setActiveThreadId: store.setActiveThreadId,
199
+ startNewThread: store.startNewThread,
200
+ ɵstore: store
201
+ }), [
202
+ mergedLabels,
203
+ resolvedAgentId,
204
+ resolvedThreadId,
205
+ resolvedHasExplicitThreadId,
206
+ isModalOpen,
207
+ setModalOpen,
208
+ drawerOpen,
209
+ drawerRegistered,
210
+ store
211
+ ]);
212
+ return /* @__PURE__ */ jsx(CopilotChatConfiguration.Provider, {
213
+ value: configurationValue,
214
+ children
215
+ });
216
+ };
217
+ const useCopilotChatConfiguration = () => {
218
+ return useContext(CopilotChatConfiguration);
219
+ };
220
+ /**
221
+ * Reports modal open/close requests to the host, and — when `open` is
222
+ * supplied — makes the modal state of an already-established chat
223
+ * configuration **controlled** for the subtree it wraps.
224
+ *
225
+ * This is deliberately a scope component rather than another mode inside
226
+ * {@link CopilotChatConfigurationProvider}. The provider resolves modal state
227
+ * across a nested chain (own state, parent sync, drawer mutual-exclusion, the
228
+ * modal-closer registry); a controlled branch inside that resolution would add
229
+ * a fourth interacting mode. Overriding the context for the subtree instead
230
+ * leaves every one of those paths untouched:
231
+ *
232
+ * - `isModalOpen` is replaced with the host's `open`, so the rendered surface
233
+ * follows the prop from the very first frame (no open-then-close flash).
234
+ * - `setModalOpen` still calls the underlying setter, so the existing
235
+ * parent-sync and drawer mutual-exclusion side effects continue to run, and
236
+ * *then* reports the request through `onOpenChange`.
237
+ * - The wrapped setter is registered as the modal closer, so the drawer's
238
+ * mobile mutual-exclusion reaches the host instead of silently flipping
239
+ * state that nothing displays.
240
+ *
241
+ * A host that supplies `open` and ignores `onOpenChange` gets a modal pinned
242
+ * to `open`, which is the standard controlled-component contract. A host that
243
+ * supplies only `onOpenChange` is notified while the modal keeps managing
244
+ * itself.
245
+ *
246
+ * Renders `children` unchanged when no chat configuration is in scope.
247
+ */
248
+ const ControlledModalOpenScope = ({ children, open, onOpenChange }) => {
249
+ const parentConfig = useContext(CopilotChatConfiguration);
250
+ const parentSetModalOpen = parentConfig?.setModalOpen;
251
+ const registerModalCloser = parentConfig?.ɵregisterModalCloser;
252
+ const setModalOpen = useCallback((next) => {
253
+ parentSetModalOpen?.(next);
254
+ onOpenChange?.(next);
255
+ }, [parentSetModalOpen, onOpenChange]);
256
+ useEffect(() => {
257
+ if (!registerModalCloser) return;
258
+ return registerModalCloser(setModalOpen);
259
+ }, [registerModalCloser, setModalOpen]);
260
+ const configurationValue = useMemo(() => parentConfig ? {
261
+ ...parentConfig,
262
+ isModalOpen: open ?? parentConfig.isModalOpen,
263
+ setModalOpen
264
+ } : null, [
265
+ parentConfig,
266
+ open,
267
+ setModalOpen
268
+ ]);
269
+ if (!configurationValue) return /* @__PURE__ */ jsx(Fragment$1, { children });
270
+ return /* @__PURE__ */ jsx(CopilotChatConfiguration.Provider, {
271
+ value: configurationValue,
272
+ children
273
+ });
274
+ };
275
+ ControlledModalOpenScope.displayName = "ControlledModalOpenScope";
276
+
277
+ //#endregion
278
+ //#region src/lib/slots.tsx
279
+ /**
280
+ * Check if a value is a React component type (function, class, forwardRef, memo, etc.)
281
+ */
282
+ function isReactComponentType(value) {
283
+ if (typeof value === "function") return true;
284
+ if (value && typeof value === "object" && "$$typeof" in value && !React.isValidElement(value)) return true;
285
+ return false;
286
+ }
287
+ /**
288
+ * Internal function to render a slot value as a React element (non-memoized).
289
+ */
290
+ function renderSlotElement(slot, DefaultComponent, props) {
291
+ if (typeof slot === "string") {
292
+ const existingClassName = props.className;
293
+ return React.createElement(DefaultComponent, {
294
+ ...props,
295
+ className: cn(existingClassName, slot)
296
+ });
297
+ }
298
+ if (isReactComponentType(slot)) return React.createElement(slot, props);
299
+ if (slot && typeof slot === "object" && !React.isValidElement(slot)) return React.createElement(DefaultComponent, {
300
+ ...props,
301
+ ...slot
302
+ });
303
+ return React.createElement(DefaultComponent, props);
304
+ }
305
+ /**
306
+ * Internal memoized wrapper component for renderSlot.
307
+ * Uses forwardRef to support ref forwarding.
308
+ */
309
+ const MemoizedSlotWrapper = React.memo(React.forwardRef(function MemoizedSlotWrapper(props, ref) {
310
+ const { $slot, $component, ...rest } = props;
311
+ return renderSlotElement($slot, $component, ref !== null ? {
312
+ ...rest,
313
+ ref
314
+ } : rest);
315
+ }), (prev, next) => {
316
+ if (prev.$slot !== next.$slot) return false;
317
+ if (prev.$component !== next.$component) return false;
318
+ const { $slot: _ps, $component: _pc, ...prevRest } = prev;
319
+ const { $slot: _ns, $component: _nc, ...nextRest } = next;
320
+ return shallowEqual(prevRest, nextRest);
321
+ });
322
+ /**
323
+ * Renders a slot value as a memoized React element.
324
+ * Automatically prevents unnecessary re-renders using shallow prop comparison.
325
+ * Supports ref forwarding.
326
+ *
327
+ * @example
328
+ * renderSlot(customInput, CopilotChatInput, { onSubmit: handleSubmit })
329
+ */
330
+ function renderSlot(slot, DefaultComponent, props) {
331
+ return React.createElement(MemoizedSlotWrapper, {
332
+ ...props,
333
+ $slot: slot,
334
+ $component: DefaultComponent
335
+ });
336
+ }
337
+
338
+ //#endregion
339
+ //#region src/providers/MarkdownRendererContext.tsx
340
+ const MarkdownRendererContext = createContext(void 0);
341
+ const MarkdownRendererProvider = ({ renderer, children }) => /* @__PURE__ */ jsx(MarkdownRendererContext.Provider, {
342
+ value: renderer,
343
+ children
344
+ });
345
+ /**
346
+ * The markdown renderer set at the provider level, or `undefined` when none was
347
+ * supplied. Message components fall back to the built-in
348
+ * `StreamingMarkdownDefaultRenderer` (via `CopilotChatAssistantMessage.MarkdownRenderer`)
349
+ * when this is `undefined`.
350
+ */
351
+ function useMarkdownRenderer() {
352
+ return useContext(MarkdownRendererContext);
353
+ }
354
+
355
+ //#endregion
356
+ //#region src/types/defineToolCallRenderer.ts
357
+ function defineToolCallRenderer(def) {
358
+ const argsSchema = def.name === "*" && !def.args ? ɵanySchema : def.args;
359
+ return {
360
+ name: def.name,
361
+ args: argsSchema,
362
+ render: def.render,
363
+ ...def.agentId ? { agentId: def.agentId } : {},
364
+ ...def.group ? { group: true } : {}
365
+ };
366
+ }
367
+
368
+ //#endregion
369
+ //#region src/generative-ui/catalog.ts
370
+ /**
371
+ * Experimental. Declares the components the model can render, the app state
372
+ * they read, and the functions they call.
373
+ *
374
+ * - A prop with the name of a top-level state key is bound to that state.
375
+ * - `bind: { prop: (state, props) => value }` binds a prop to a selector.
376
+ * - An event binds to the function with its name, else to the name without
377
+ * `on` (`onAddToCart` calls `addToCart`).
378
+ * - `writable: ["value"]` gives the component a `setValue` prop. See
379
+ * `GenerativeUIComponentDefinition.writable`.
380
+ *
381
+ * The model does not see bound props or matched events.
382
+ *
383
+ * @param config - `id`, then optional `extends`, `state`, `functions` and
384
+ * `overrides`, then `components`. Put `state` before `components`, so the selectors
385
+ * get typed state.
386
+ * @throws Error when a name comes from two places, an override names no
387
+ * component of the bases, `props` is not an object
388
+ * schema with a JSON Schema, a key is reserved or used
389
+ * twice on a component, an event matches two functions, an unmatched event
390
+ * has no `parameters`, a `bind` key is not a prop, a `writable` key is not
391
+ * a prop or is a bound prop, or a setter name is already a key of the
392
+ * component. Also throws when `parameterOrder` contains duplicate or unknown
393
+ * keys, or an ordered component declares integer-index keys whose JSON object
394
+ * enumeration order cannot be controlled.
395
+ *
396
+ * @example
397
+ * ```ts
398
+ * const ui = createGenerativeUI({
399
+ * id: "acme/store@1",
400
+ * state: { cart: cartSchema },
401
+ * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },
402
+ * components: {
403
+ * CartSummary: {
404
+ * component: CartSummary,
405
+ * props: z.object({ count: z.number() }),
406
+ * bind: { count: (state) => state.cart.count },
407
+ * },
408
+ * },
409
+ * });
410
+ * ```
411
+ */
412
+ function createGenerativeUI$1(config) {
413
+ return createGenerativeUI(config);
414
+ }
415
+
416
+ //#endregion
417
+ //#region src/generative-ui/runtime-context.ts
418
+ const GenerativeUIRuntimeContext = createContext(null);
419
+ function useGenerativeUIRuntime() {
420
+ return useContext(GenerativeUIRuntimeContext);
421
+ }
422
+ function useRequiredGenerativeUIRuntime() {
423
+ const runtime = useContext(GenerativeUIRuntimeContext);
424
+ if (!runtime) throw new Error("Generative UI components must be rendered inside <CopilotKitProvider generativeUI={{ ui }}>.");
425
+ return runtime;
426
+ }
427
+ const GenerativeUINodeContext = createContext(null);
428
+
429
+ //#endregion
430
+ //#region src/generative-ui/hooks.ts
431
+ const noopSubscribe$1 = () => () => {};
432
+ const zero = () => 0;
433
+ /** Re-renders on any surface-manager change. */
434
+ function useManagerVersion(runtime) {
435
+ return useSyncExternalStore(runtime?.manager.subscribe ?? noopSubscribe$1, runtime?.manager.getVersion ?? zero, zero);
436
+ }
437
+ /**
438
+ * Experimental. Gives one key of the app state declared in
439
+ * `createGenerativeUI({ state })` its value. Bound props of generated
440
+ * components read it. The model does not see it.
441
+ *
442
+ * The key is set on mount and when the value changes (compared as JSON). It
443
+ * is removed on unmount.
444
+ *
445
+ * @param ui - The object from `createGenerativeUI`. It gives the key and the
446
+ * value their types.
447
+ * @param key - A top-level key of `state`.
448
+ * @param value - The value of that key. It must fit the key's schema.
449
+ *
450
+ * @example
451
+ * ```tsx
452
+ * useGenerativeUIState(storeUI, "cart", { count, total, coupon, items });
453
+ * ```
454
+ */
455
+ function useGenerativeUIState(ui, key, value) {
456
+ const runtime = useRequiredGenerativeUIRuntime();
457
+ const serialized = JSON.stringify(value);
458
+ useEffect(() => {
459
+ const raw = JSON.parse(serialized ?? "null");
460
+ let current = true;
461
+ const apply = (parsed) => {
462
+ if (!current) return;
463
+ if (parsed.success) {
464
+ runtime.manager.setState(key, parsed.data);
465
+ return;
466
+ }
467
+ runtime.manager.removeState(key);
468
+ if (process.env.NODE_ENV !== "production") console.error(`[generativeUI] useGenerativeUIState: invalid value for "${key}": ${formatIssues(parsed.issues, "value")}`);
469
+ };
470
+ const schema = runtime.ui.state.get(key);
471
+ const parsed = schema ? validateSchema(schema, raw) : {
472
+ success: true,
473
+ data: raw
474
+ };
475
+ if (parsed instanceof Promise) parsed.then(apply);
476
+ else apply(parsed);
477
+ return () => {
478
+ current = false;
479
+ };
480
+ }, [
481
+ runtime,
482
+ key,
483
+ serialized
484
+ ]);
485
+ useEffect(() => () => runtime.manager.removeState(key), [runtime, key]);
486
+ }
487
+ /**
488
+ * Experimental. Mounts the handler of a function declared in
489
+ * `createGenerativeUI({ functions })`. Generated UI can call the function
490
+ * only while exactly one handler for it is mounted.
491
+ *
492
+ * The handler gets the parsed arguments: schema defaults are set. It can
493
+ * change on each render. The latest handler always runs, and the hook does
494
+ * not register again.
495
+ *
496
+ * @param ui - The object from `createGenerativeUI`. It gives the name and the
497
+ * handler arguments their types.
498
+ * @param name - A key of `functions`.
499
+ * @param handler - Runs when generated UI calls the function. Its return
500
+ * value goes back to the caller as `{ ok: true, result }`.
501
+ *
502
+ * @example
503
+ * ```tsx
504
+ * useGenerativeUIFunction(storeUI, "addToCart", ({ productId, quantity }) =>
505
+ * cart.addItem(productId, quantity),
506
+ * );
507
+ * ```
508
+ */
509
+ function useGenerativeUIFunction(ui, name, handler) {
510
+ const runtime = useRequiredGenerativeUIRuntime();
511
+ const latest = useRef(handler);
512
+ latest.current = handler;
513
+ useEffect(() => runtime.dispatcher.register(name, latest), [runtime, name]);
514
+ }
515
+
516
+ //#endregion
517
+ //#region src/generative-ui/boundaries.tsx
518
+ function DefaultNodeFallback({ message, componentId, retry }) {
519
+ return /* @__PURE__ */ jsxs("div", {
520
+ role: "alert",
521
+ "data-generative-ui-error": componentId,
522
+ style: {
523
+ border: "1px solid #fca5a5",
524
+ background: "#fef2f2",
525
+ color: "#991b1b",
526
+ borderRadius: 8,
527
+ padding: "8px 12px",
528
+ fontSize: 13
529
+ },
530
+ children: [
531
+ "Couldn’t display this part: ",
532
+ message,
533
+ retry && /* @__PURE__ */ jsx("button", {
534
+ type: "button",
535
+ onClick: retry,
536
+ style: {
537
+ marginLeft: 8,
538
+ textDecoration: "underline"
539
+ },
540
+ children: "Retry"
541
+ })
542
+ ]
543
+ });
544
+ }
545
+ /**
546
+ * A child that has not streamed yet renders nothing. The prose keeps
547
+ * streaming above the surface, and each component appears as soon as it is
548
+ * complete. A grey block in its place would read as a broken layout.
549
+ */
550
+ function NodePlaceholder(_props) {
551
+ return null;
552
+ }
553
+ /** Per-node boundary. Resets on retry or a new agent revision, not on data ticks. */
554
+ var NodeBoundary = class extends Component {
555
+ state = {
556
+ error: null,
557
+ revision: this.props.revision
558
+ };
559
+ static getDerivedStateFromError(error) {
560
+ return { error };
561
+ }
562
+ static getDerivedStateFromProps(props, state) {
563
+ return props.revision !== state.revision ? {
564
+ error: null,
565
+ revision: props.revision
566
+ } : null;
567
+ }
568
+ componentDidCatch(error) {
569
+ const { runtime, surfaceId, componentId } = this.props;
570
+ reportErrorSafely(runtime, {
571
+ kind: "render",
572
+ surfaceId,
573
+ componentId,
574
+ error
575
+ });
576
+ }
577
+ retry = () => this.setState({ error: null });
578
+ render() {
579
+ const { error } = this.state;
580
+ if (!error) return this.props.children;
581
+ const { runtime, surfaceId, componentId } = this.props;
582
+ const fallback = runtime.errorFallback;
583
+ return fallback ? fallback({
584
+ error,
585
+ retry: this.retry,
586
+ surfaceId,
587
+ componentId
588
+ }) : /* @__PURE__ */ jsx(DefaultNodeFallback, {
589
+ message: error.message,
590
+ componentId,
591
+ retry: this.retry
592
+ });
593
+ }
594
+ };
595
+ /** Outer boundary: a failure here must not reach the chat or the host page. */
596
+ var SurfaceBoundary = class extends Component {
597
+ state = { error: null };
598
+ static getDerivedStateFromError(error) {
599
+ return { error };
600
+ }
601
+ componentDidCatch(error) {
602
+ reportErrorSafely(this.props.runtime, {
603
+ kind: "render",
604
+ surfaceId: this.props.surfaceId,
605
+ error
606
+ });
607
+ }
608
+ render() {
609
+ if (!this.state.error) return this.props.children;
610
+ return /* @__PURE__ */ jsx(DefaultNodeFallback, {
611
+ message: "this generated UI failed to render",
612
+ componentId: "surface"
613
+ });
614
+ }
615
+ };
616
+
617
+ //#endregion
618
+ //#region src/generative-ui/accessibility.ts
619
+ /**
620
+ * Experimental. The ARIA attributes of the `accessibility` that the model
621
+ * gave the component being rendered, to spread on its root element. The
622
+ * standard components do this; a custom component does it itself:
623
+ *
624
+ * @example
625
+ * ```tsx
626
+ * function Panel({ children }: { children?: ReactNode }) {
627
+ * const aria = useGenerativeUIAccessibility();
628
+ * return <section {...aria}>{children}</section>;
629
+ * }
630
+ * ```
631
+ *
632
+ * Outside of generated UI it gives `{}`.
633
+ */
634
+ function useGenerativeUIAccessibility() {
635
+ const accessibility = useContext(GenerativeUINodeContext)?.accessibility;
636
+ return useMemo(() => accessibilityAttributes(accessibility), [accessibility]);
637
+ }
638
+
639
+ //#endregion
640
+ //#region src/generative-ui/SurfaceView.tsx
641
+ const NO_ANCESTORS = [];
642
+ const ROOT_STYLE = { display: "contents" };
643
+ const undefinedSnapshot = () => void 0;
644
+ const noopSubscribe = () => () => {};
645
+ const zeroSnapshot = () => 0;
646
+ /** A "multiple" slot value that repeats a component for each list item. */
647
+ function isTemplateChildren(value) {
648
+ return typeof value === "object" && value !== null && "componentId" in value && typeof value.componentId === "string" && "path" in value && typeof value.path === "string";
649
+ }
650
+ function SurfaceView({ surface }) {
651
+ const runtime = useRequiredGenerativeUIRuntime();
652
+ const { theme } = runtime;
653
+ const sheet = useMemo(() => themeStyleSheet(theme), [theme]);
654
+ return /* @__PURE__ */ jsxs("div", {
655
+ className: "a2ui-surface",
656
+ "data-generative-ui-root": surface.surfaceId,
657
+ "data-a2ui-theme": sheet?.id,
658
+ style: ROOT_STYLE,
659
+ children: [sheet ? /* @__PURE__ */ jsx("style", { dangerouslySetInnerHTML: { __html: sheet.css } }) : null, /* @__PURE__ */ jsx(SurfaceBoundary, {
660
+ surfaceId: surface.surfaceId,
661
+ runtime,
662
+ children: /* @__PURE__ */ jsx(NodeView, {
663
+ surface,
664
+ componentId: GENERATIVE_UI_ROOT_ID,
665
+ basePath: void 0,
666
+ ancestors: NO_ANCESTORS
667
+ })
668
+ })]
669
+ });
670
+ }
671
+ /**
672
+ * Resolves a component by id. Subscribes to the manager rather than web_core's
673
+ * `onCreated`/`onDeleted`: web_core's EventEmitter awaits each listener in turn,
674
+ * so with several subscribers (one per slotted child, or one per mount of the
675
+ * same surface) all but the first are notified a microtask late. That is only
676
+ * visible inside synchronous flushes such as `act()` / `flushSync`, where the
677
+ * old tree would still be on screen, but it makes updates order-dependent.
678
+ * The manager notifies synchronously once an ingest has been fully applied.
679
+ */
680
+ function useComponentModel(manager, model, id) {
681
+ return useSyncExternalStore(manager.subscribe, () => model.componentsModel.get(id), undefinedSnapshot);
682
+ }
683
+ /** Same reasoning as `useComponentModel`: never rely on web_core's emitters. */
684
+ function useComponentProperties(manager, component) {
685
+ return useSyncExternalStore(manager.subscribe, () => component?.properties, undefinedSnapshot);
686
+ }
687
+ /**
688
+ * The id of a node in the ancestor list. A template renders the same
689
+ * component once per item, so the item path is part of the id. A real cycle
690
+ * repeats both.
691
+ */
692
+ function scopedId(componentId, basePath) {
693
+ return `${basePath ?? ""}#${componentId}`;
694
+ }
695
+ const NodeView = memo(function NodeView({ surface, componentId, basePath, ancestors }) {
696
+ const runtime = useRequiredGenerativeUIRuntime();
697
+ const component = useComponentModel(runtime.manager, surface.model, componentId);
698
+ const properties = useComponentProperties(runtime.manager, component);
699
+ if (ancestors.includes(scopedId(componentId, basePath))) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
700
+ message: `cyclic reference to ${componentId}`,
701
+ componentId
702
+ });
703
+ if (!component || !properties) return /* @__PURE__ */ jsx(NodePlaceholder, { componentId });
704
+ const definition = runtime.ui.components.get(component.type);
705
+ if (!definition) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
706
+ message: `unknown component "${component.type}"`,
707
+ componentId
708
+ });
709
+ return /* @__PURE__ */ jsx(NodeBoundary, {
710
+ surfaceId: surface.surfaceId,
711
+ componentId,
712
+ revision: properties,
713
+ runtime,
714
+ children: /* @__PURE__ */ jsx(ResolvedNode, {
715
+ surface,
716
+ componentId,
717
+ definition,
718
+ properties,
719
+ runtime,
720
+ basePath,
721
+ ancestors
722
+ })
723
+ }, component.type);
724
+ });
725
+ /**
726
+ * Renders the component of a template once for each item of the list at the
727
+ * template path, keyed by index. Renders nothing when there is no list.
728
+ */
729
+ function TemplateChildren({ surface, template, basePath, ancestors }) {
730
+ const dataModel = surface.model.dataModel;
731
+ const listPath = resolvePath(template.path, basePath);
732
+ const subscribe = useCallback((onChange) => {
733
+ const subscription = dataModel.subscribe(listPath, onChange);
734
+ return () => subscription.unsubscribe();
735
+ }, [dataModel, listPath]);
736
+ const getCount = () => {
737
+ const list = dataModel.get(listPath);
738
+ return Array.isArray(list) ? list.length : 0;
739
+ };
740
+ const count = useSyncExternalStore(subscribe, getCount, zeroSnapshot);
741
+ return /* @__PURE__ */ jsx(Fragment$1, { children: Array.from({ length: count }, (_, index) => index).map((index) => /* @__PURE__ */ jsx(NodeView, {
742
+ surface,
743
+ componentId: template.componentId,
744
+ basePath: joinPath(listPath, String(index)),
745
+ ancestors
746
+ }, index)) });
747
+ }
748
+ /**
749
+ * The props the model sets, with their dynamic values resolved from the
750
+ * surface data model: `{"@path"}` bindings, `{"@call"}` function values and
751
+ * `{"@call":"@index"}` in a template, at any depth. A literal writable prop
752
+ * that the component set shows the local value from `overrides`. Bound
753
+ * props, events and slots are left out, and so are the keys of the A2UI
754
+ * component envelope; `accessibility` is resolved the same way and given
755
+ * on its own.
756
+ *
757
+ * A prop is resolved again only when its raw value or a data model value it
758
+ * read has changed, so the result keeps its identity otherwise. A function
759
+ * value that cannot be computed gives a problem instead of values.
760
+ */
761
+ function useModelDataProps(surface, definition, properties, basePath, overrides) {
762
+ const dataModel = surface.model.dataModel;
763
+ const units = useMemo(() => {
764
+ const list = [];
765
+ for (const key of Object.keys(properties)) {
766
+ if (definition.events?.[key] || definition.slots?.[key] || Object.hasOwn(definition.selectors, key) || A2UI_COMPONENT_ENVELOPE_KEYS.has(key)) continue;
767
+ list.push({
768
+ key,
769
+ raw: properties[key]
770
+ });
771
+ }
772
+ const a11y = properties.accessibility;
773
+ if (typeof a11y === "object" && a11y !== null && !Array.isArray(a11y)) for (const [field, raw] of Object.entries(a11y)) list.push({
774
+ key: `accessibility/${field}`,
775
+ raw,
776
+ field
777
+ });
778
+ return list;
779
+ }, [properties, definition]);
780
+ const [, rerender] = useReducer((n) => n + 1, 0);
781
+ const cache = useRef(/* @__PURE__ */ new Map());
782
+ const values = {};
783
+ const a11yValues = {};
784
+ const paths = /* @__PURE__ */ new Set();
785
+ let problem;
786
+ const next = /* @__PURE__ */ new Map();
787
+ for (const { key, raw, field } of units) {
788
+ const cached = cache.current.get(key);
789
+ const isFresh = cached !== void 0 && cached.raw === raw && cached.basePath === basePath && [...cached.reads].every(([path, value]) => Object.is(dataModel.get(path), value));
790
+ const resolve = () => {
791
+ const resolved = tryResolveDynamicValue(raw, {
792
+ data: dataModel,
793
+ basePath
794
+ }, { isChecks: key === "checks" });
795
+ const reads = /* @__PURE__ */ new Map();
796
+ for (const path of resolved.paths) reads.set(path, dataModel.get(path));
797
+ return {
798
+ raw,
799
+ basePath,
800
+ reads,
801
+ outcome: resolved.ok ? {
802
+ ok: true,
803
+ value: resolved.value
804
+ } : {
805
+ ok: false,
806
+ message: resolved.error.message
807
+ }
808
+ };
809
+ };
810
+ const entry = isFresh && cached ? cached : resolve();
811
+ next.set(key, entry);
812
+ if (field !== void 0) {
813
+ if (entry.outcome.ok) a11yValues[field] = entry.outcome.value;
814
+ } else if (entry.outcome.ok) values[key] = entry.outcome.value;
815
+ else problem ??= `${key}: ${entry.outcome.message}`;
816
+ for (const path of entry.reads.keys()) paths.add(path);
817
+ }
818
+ cache.current = next;
819
+ const accessibility = readAccessibility(a11yValues);
820
+ for (const [key, value] of Object.entries(overrides)) if (!isPathBinding(properties[key])) values[key] = value;
821
+ const rendered = useRef(next);
822
+ rendered.current = next;
823
+ const pathKey = [...paths].sort().join("\n");
824
+ useEffect(() => {
825
+ const list = pathKey === "" ? [] : pathKey.split("\n");
826
+ const onChange = () => {
827
+ cache.current = /* @__PURE__ */ new Map();
828
+ rerender();
829
+ };
830
+ const subscriptions = list.map((path) => dataModel.subscribe(path, onChange));
831
+ if ([...rendered.current.values()].some((entry) => [...entry.reads].some(([path, value]) => !Object.is(dataModel.get(path), value)))) rerender();
832
+ return () => subscriptions.forEach((s) => s.unsubscribe());
833
+ }, [dataModel, pathKey]);
834
+ const stable = useRef({
835
+ ok: true,
836
+ values: {},
837
+ accessibility: void 0
838
+ });
839
+ const result = problem === void 0 ? {
840
+ ok: true,
841
+ values,
842
+ accessibility
843
+ } : {
844
+ ok: false,
845
+ problem
846
+ };
847
+ const last = stable.current;
848
+ 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;
849
+ return stable.current;
850
+ }
851
+ const NO_SELECTION = {
852
+ ok: true,
853
+ values: {}
854
+ };
855
+ function isSameSelection(a, b) {
856
+ if (a.ok && b.ok) return shallowEqual(a.values, b.values);
857
+ if (!a.ok && !b.ok) return a.problem === b.problem;
858
+ return false;
859
+ }
860
+ /** Runs every selector of a node. A selector that throws gives a problem. */
861
+ function select(definition, state, modelProps) {
862
+ const values = {};
863
+ const selectors = Object.entries(definition.selectors);
864
+ for (const [key, selector] of selectors) try {
865
+ values[key] = selector(state, modelProps);
866
+ } catch (error) {
867
+ return {
868
+ ok: false,
869
+ problem: `${key}: selector threw: ${error instanceof Error ? error.message : String(error)}`
870
+ };
871
+ }
872
+ return {
873
+ ok: true,
874
+ values
875
+ };
876
+ }
877
+ /**
878
+ * The values of the bound props of a node, read from the app state.
879
+ *
880
+ * The selectors run again only when the state object or the parsed model
881
+ * props change. When the new values are shallow-equal to the last ones, the
882
+ * last snapshot is kept. So the node re-renders only when a selected value
883
+ * changes. A selector that returns a new array on each call cannot cause a
884
+ * render loop: with the same inputs, the cached snapshot comes back.
885
+ *
886
+ * A node without bound props does not subscribe to the state.
887
+ */
888
+ function useSelection(manager, definition, modelProps) {
889
+ const hasSelectors = Object.keys(definition.selectors).length > 0;
890
+ const cache = useRef(void 0);
891
+ const getSnapshot = () => {
892
+ if (!hasSelectors || modelProps === void 0) return NO_SELECTION;
893
+ const state = manager.getState();
894
+ const cached = cache.current;
895
+ if (cached !== void 0 && cached.state === state && cached.modelProps === modelProps) return cached.selection;
896
+ const next = select(definition, state, modelProps);
897
+ const selection = cached !== void 0 && isSameSelection(cached.selection, next) ? cached.selection : next;
898
+ cache.current = {
899
+ state,
900
+ modelProps,
901
+ selection
902
+ };
903
+ return selection;
904
+ };
905
+ return useSyncExternalStore(hasSelectors ? manager.subscribe : noopSubscribe, getSnapshot, getSnapshot);
906
+ }
907
+ /**
908
+ * Checks the model-set props with the props schema before the selectors run.
909
+ * The bound props are not set yet, so their issues do not count. Neither do
910
+ * issues with no path (a check over several props), which the full check
911
+ * after the selectors reports.
912
+ */
913
+ function checkModelProps(definition, modelData) {
914
+ if (!definition.props) return {
915
+ ok: true,
916
+ values: {}
917
+ };
918
+ let values = modelData;
919
+ let result = validateSchemaSync(definition.props, values);
920
+ if (!result.success) {
921
+ const unset = withoutRejectedNulls(values, result.issues);
922
+ if (unset) {
923
+ values = unset;
924
+ result = validateSchemaSync(definition.props, values);
925
+ }
926
+ }
927
+ if (!result.success) {
928
+ const issues = result.issues.filter((issue) => {
929
+ const key = issueKey(issue);
930
+ return key === void 0 ? isAsyncIssue(issue) : !Object.hasOwn(definition.selectors, key);
931
+ });
932
+ if (issues.length > 0) return {
933
+ ok: false,
934
+ problem: formatIssues(issues)
935
+ };
936
+ }
937
+ return {
938
+ ok: true,
939
+ values
940
+ };
941
+ }
942
+ /**
943
+ * The data props of a node, in three steps: check the model-set props with
944
+ * the props schema, run the selectors with them, then parse all props with
945
+ * the props schema. Gives the reason when a step fails.
946
+ */
947
+ function useDataProps(runtime, surface, definition, properties, basePath, overrides) {
948
+ const modelData = useModelDataProps(surface, definition, properties, basePath, overrides);
949
+ const modelCheck = useMemo(() => modelData.ok ? checkModelProps(definition, modelData.values) : modelData, [definition, modelData]);
950
+ const selection = useSelection(runtime.manager, definition, modelCheck.ok ? modelCheck.values : void 0);
951
+ const accessibility = modelData.ok ? modelData.accessibility : void 0;
952
+ return useMemo(() => {
953
+ if (!modelCheck.ok) return modelCheck;
954
+ if (!selection.ok) return selection;
955
+ if (!definition.props) return {
956
+ ok: true,
957
+ props: {},
958
+ accessibility
959
+ };
960
+ const input = {
961
+ ...modelCheck.values,
962
+ ...selection.values
963
+ };
964
+ let parsed = validateSchemaSync(definition.props, input);
965
+ if (!parsed.success) {
966
+ const unset = withoutRejectedNulls(input, parsed.issues);
967
+ if (unset) parsed = validateSchemaSync(definition.props, unset);
968
+ }
969
+ if (!parsed.success) return {
970
+ ok: false,
971
+ problem: formatIssues(parsed.issues)
972
+ };
973
+ return {
974
+ ok: true,
975
+ props: parsed.data,
976
+ accessibility
977
+ };
978
+ }, [
979
+ definition,
980
+ modelCheck,
981
+ selection,
982
+ accessibility
983
+ ]);
984
+ }
985
+ /**
986
+ * The event props of a node. A matched event (one that matches a declared
987
+ * function) is always bound. An unmatched event is bound only when the model
988
+ * bound it.
989
+ */
990
+ function useEventProps(runtime, surface, componentId, definition, properties, basePath) {
991
+ const latest = useRef(properties);
992
+ latest.current = properties;
993
+ const boundNames = Object.keys(definition.events ?? {}).filter((name) => Object.hasOwn(definition.eventFunctions, name) || isActionBinding(properties[name])).join("|");
994
+ return useMemo(() => {
995
+ const handlers = {};
996
+ const names = boundNames ? boundNames.split("|") : [];
997
+ for (const name of names) {
998
+ const call = {
999
+ runtime,
1000
+ surface,
1001
+ componentId,
1002
+ name,
1003
+ parameters: definition.events?.[name]?.parameters
1004
+ };
1005
+ const functionName = Object.hasOwn(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
1006
+ handlers[name] = functionName === void 0 ? (args) => invokeBoundEvent({
1007
+ ...call,
1008
+ binding: latest.current[name],
1009
+ basePath,
1010
+ args
1011
+ }) : (args) => invokeMatchedEvent({
1012
+ ...call,
1013
+ functionName,
1014
+ args
1015
+ });
1016
+ }
1017
+ return handlers;
1018
+ }, [
1019
+ boundNames,
1020
+ runtime,
1021
+ surface,
1022
+ componentId,
1023
+ definition,
1024
+ basePath
1025
+ ]);
1026
+ }
1027
+ /**
1028
+ * The setter props of a node: `setValue` for the writable prop `value`. For
1029
+ * a prop the model bound to `{"@path"}`, the setter writes the data model
1030
+ * and makes the path user-owned. For a literal prop, it sets `overrides`, a
1031
+ * local value of this mounted node. The setters keep their identity.
1032
+ */
1033
+ function useSetterProps(runtime, surface, componentId, definition, properties, basePath) {
1034
+ const [overrides, setOverrides] = useState({});
1035
+ const latest = useRef(properties);
1036
+ latest.current = properties;
1037
+ return {
1038
+ overrides,
1039
+ setters: useMemo(() => {
1040
+ const result = {};
1041
+ const writable = definition.writable ?? [];
1042
+ for (const key of writable) result[setterNameOf(key)] = (value) => {
1043
+ const binding = latest.current[key];
1044
+ if (!isPathBinding(binding)) {
1045
+ setOverrides((current) => ({
1046
+ ...current,
1047
+ [key]: value
1048
+ }));
1049
+ return;
1050
+ }
1051
+ try {
1052
+ runtime.manager.setOwnedValue(surface.key, resolvePath(binding["@path"], basePath), value);
1053
+ } catch (cause) {
1054
+ const message = cause instanceof Error ? cause.message : String(cause);
1055
+ reportErrorSafely(runtime, {
1056
+ kind: "props",
1057
+ surfaceId: surface.surfaceId,
1058
+ componentId,
1059
+ error: /* @__PURE__ */ new Error(`${setterNameOf(key)}: ${message}`)
1060
+ });
1061
+ }
1062
+ };
1063
+ return result;
1064
+ }, [
1065
+ runtime,
1066
+ surface,
1067
+ componentId,
1068
+ definition,
1069
+ basePath
1070
+ ])
1071
+ };
1072
+ }
1073
+ function useSlotProps(surface, definition, properties, componentId, basePath, ancestors) {
1074
+ return useMemo(() => {
1075
+ const childAncestors = [...ancestors, scopedId(componentId, basePath)];
1076
+ const slots = {};
1077
+ for (const [name, kind] of Object.entries(definition.slots ?? {})) {
1078
+ const value = properties[name];
1079
+ if (kind === "single" && typeof value === "string") slots[name] = /* @__PURE__ */ jsx(NodeView, {
1080
+ surface,
1081
+ componentId: value,
1082
+ basePath,
1083
+ ancestors: childAncestors
1084
+ });
1085
+ else if (kind === "multiple" && isTemplateChildren(value)) slots[name] = /* @__PURE__ */ jsx(TemplateChildren, {
1086
+ surface,
1087
+ template: value,
1088
+ basePath,
1089
+ ancestors: childAncestors
1090
+ });
1091
+ else if (kind === "multiple" && Array.isArray(value)) slots[name] = [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ jsx(NodeView, {
1092
+ surface,
1093
+ componentId: id,
1094
+ basePath,
1095
+ ancestors: childAncestors
1096
+ }, id));
1097
+ }
1098
+ return slots;
1099
+ }, [
1100
+ surface,
1101
+ definition,
1102
+ properties,
1103
+ componentId,
1104
+ basePath,
1105
+ ancestors
1106
+ ]);
1107
+ }
1108
+ /**
1109
+ * The parsed data props with every typed child reference (`child()`,
1110
+ * `childList()`, at any depth) replaced by the rendered component. Without
1111
+ * references, the parsed props come back as they are.
1112
+ */
1113
+ function useChildRefProps(surface, refs, props, componentId, basePath, ancestors) {
1114
+ return useMemo(() => {
1115
+ if (props === void 0 || refs.length === 0) return props;
1116
+ const childAncestors = [...ancestors, scopedId(componentId, basePath)];
1117
+ const render = (kind, value) => {
1118
+ if (kind === "single") return typeof value === "string" ? /* @__PURE__ */ jsx(NodeView, {
1119
+ surface,
1120
+ componentId: value,
1121
+ basePath,
1122
+ ancestors: childAncestors
1123
+ }) : void 0;
1124
+ if (isTemplateChildren(value)) return /* @__PURE__ */ jsx(TemplateChildren, {
1125
+ surface,
1126
+ template: value,
1127
+ basePath,
1128
+ ancestors: childAncestors
1129
+ });
1130
+ if (!Array.isArray(value)) return void 0;
1131
+ return [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ jsx(NodeView, {
1132
+ surface,
1133
+ componentId: id,
1134
+ basePath,
1135
+ ancestors: childAncestors
1136
+ }, id));
1137
+ };
1138
+ let result = props;
1139
+ for (const ref of refs) result = mapAtChildRef(result, ref.path, (found) => render(ref.kind, found));
1140
+ return result;
1141
+ }, [
1142
+ surface,
1143
+ refs,
1144
+ props,
1145
+ componentId,
1146
+ basePath,
1147
+ ancestors
1148
+ ]);
1149
+ }
1150
+ function ResolvedNode({ surface, componentId, definition, properties, runtime, basePath, ancestors }) {
1151
+ const { overrides, setters } = useSetterProps(runtime, surface, componentId, definition, properties, basePath);
1152
+ const dataProps = useDataProps(runtime, surface, definition, properties, basePath, overrides);
1153
+ const eventProps = useEventProps(runtime, surface, componentId, definition, properties, basePath);
1154
+ const slotProps = useSlotProps(surface, definition, properties, componentId, basePath, ancestors);
1155
+ const childRefProps = useChildRefProps(surface, definition.childRefs, dataProps.ok ? dataProps.props : void 0, componentId, basePath, ancestors);
1156
+ const accessibility = dataProps.ok ? dataProps.accessibility : void 0;
1157
+ const nodeContext = useMemo(() => ({
1158
+ surfaceKey: surface.key,
1159
+ surfaceId: surface.surfaceId,
1160
+ componentId,
1161
+ accessibility
1162
+ }), [
1163
+ surface.key,
1164
+ surface.surfaceId,
1165
+ componentId,
1166
+ accessibility
1167
+ ]);
1168
+ const problem = dataProps.ok ? void 0 : dataProps.problem;
1169
+ useEffect(() => {
1170
+ if (problem) reportErrorSafely(runtime, {
1171
+ kind: "props",
1172
+ surfaceId: surface.surfaceId,
1173
+ componentId,
1174
+ error: /* @__PURE__ */ new Error(`Invalid props: ${problem}`)
1175
+ });
1176
+ }, [
1177
+ problem,
1178
+ runtime,
1179
+ surface.surfaceId,
1180
+ componentId
1181
+ ]);
1182
+ if (!dataProps.ok) return /* @__PURE__ */ jsx(DefaultNodeFallback, {
1183
+ message: `invalid props (${problem})`,
1184
+ componentId
1185
+ });
1186
+ const Component = definition.component;
1187
+ const rendered = /* @__PURE__ */ jsx(Component, {
1188
+ ...childRefProps,
1189
+ ...eventProps,
1190
+ ...slotProps,
1191
+ ...setters
1192
+ });
1193
+ const hasEnvelope = properties.accessibility !== void 0 && definition.accessibility !== "self";
1194
+ return /* @__PURE__ */ jsx(GenerativeUINodeContext.Provider, {
1195
+ value: nodeContext,
1196
+ children: hasEnvelope ? /* @__PURE__ */ jsx("span", {
1197
+ "data-a2ui-accessibility": "",
1198
+ style: ROOT_STYLE,
1199
+ ...wrapperAria(accessibilityAttributes$1(accessibility)),
1200
+ children: rendered
1201
+ }) : rendered
1202
+ });
1203
+ }
1204
+
1205
+ //#endregion
1206
+ //#region src/generative-ui/chat.tsx
1207
+ const GenerativeUIChatSlotContext = createContext(void 0);
1208
+ function DefaultGenerativeUIChatCard({ surfaceId, error, children }) {
1209
+ return /* @__PURE__ */ jsxs("div", {
1210
+ "data-generative-ui-chat-surface": surfaceId,
1211
+ className: "cpk-generative-ui-chat-card",
1212
+ children: [children, error && /* @__PURE__ */ jsx("div", {
1213
+ role: "alert",
1214
+ className: "cpk-generative-ui-chat-card-error",
1215
+ children: "Part of this UI couldn't be shown."
1216
+ })]
1217
+ });
1218
+ }
1219
+ const ContentSchema = z.object({
1220
+ surfaceId: z.string(),
1221
+ target: z.string(),
1222
+ catalogId: z.string(),
1223
+ operations: z.array(z.any()),
1224
+ status: z.enum([
1225
+ "streaming",
1226
+ "ready",
1227
+ "error"
1228
+ ]),
1229
+ rejected: z.array(z.object({
1230
+ index: z.number(),
1231
+ reason: z.string()
1232
+ })).default([])
1233
+ }).loose();
1234
+ function GenerativeUIChatActivity({ content, agent }) {
1235
+ const runtime = useGenerativeUIRuntime();
1236
+ const threadId = useCopilotChatConfiguration()?.threadId ?? agent?.threadId;
1237
+ const Wrapper = useContext(GenerativeUIChatSlotContext) ?? DefaultGenerativeUIChatCard;
1238
+ useManagerVersion(runtime);
1239
+ useLayoutEffect(() => {
1240
+ if (runtime && threadId) runtime.manager.ingest(threadId, agent?.agentId, content);
1241
+ }, [
1242
+ runtime,
1243
+ threadId,
1244
+ agent?.agentId,
1245
+ content
1246
+ ]);
1247
+ if (!runtime || !threadId || content.target !== GENERATIVE_UI_CHAT_TARGET) return null;
1248
+ const surface = runtime.manager.getSurface(threadId, content.surfaceId) ?? runtime.manager.getFailedSurface(threadId, content.surfaceId);
1249
+ if (!surface) return null;
1250
+ const rejected = [...content.rejected ?? [], ...surface.clientRejected];
1251
+ const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
1252
+ return /* @__PURE__ */ jsx(Wrapper, {
1253
+ surfaceId: content.surfaceId,
1254
+ isStreaming: content.status === "streaming",
1255
+ error,
1256
+ rejected,
1257
+ children: surface.failed ? null : /* @__PURE__ */ jsx(SurfaceView, { surface })
1258
+ });
1259
+ }
1260
+ function createGenerativeUIActivityRenderer() {
1261
+ return {
1262
+ activityType: GENERATIVE_UI_ACTIVITY_TYPE,
1263
+ content: ContentSchema,
1264
+ render: GenerativeUIChatActivity
1265
+ };
1266
+ }
1267
+ /**
1268
+ * Shows nothing in the chat for an agent-called function. The root reads the
1269
+ * function-call activities from the messages and runs them. This renderer
1270
+ * only keeps a wildcard ("*") activity renderer from showing them.
1271
+ */
1272
+ function createGenerativeUIFunctionCallActivityRenderer() {
1273
+ return {
1274
+ activityType: GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,
1275
+ content: z.unknown(),
1276
+ render: () => null
1277
+ };
1278
+ }
1279
+ /** Hides the raw `render_ui` tool call; the surface activity owns the UX. */
1280
+ function GenerativeUIToolCallRenderer() {
1281
+ const { copilotkit } = useCopilotKit();
1282
+ useEffect(() => {
1283
+ const renderer = defineToolCallRenderer({
1284
+ name: GENERATIVE_UI_RENDER_TOOL,
1285
+ args: z.any(),
1286
+ render: () => /* @__PURE__ */ jsx(Fragment$1, {})
1287
+ });
1288
+ return copilotkit.ɵaddBuiltInRenderToolCall(renderer);
1289
+ }, [copilotkit]);
1290
+ return null;
1291
+ }
1292
+
1293
+ //#endregion
1294
+ //#region src/generative-ui/markdown/ProviderMarkdown.tsx
1295
+ /**
1296
+ * Markdown prose inside generative UI, rendered like the chat text around
1297
+ * it: the renderer set on the provider when there is one, else the built-in
1298
+ * streaming renderer. Config passed here wins over provider config.
1299
+ */
1300
+ function ProviderMarkdown({ content, isStreaming, className, ...config }) {
1301
+ const renderer = useMarkdownRenderer();
1302
+ if (renderer && isReactComponentType(renderer)) return /* @__PURE__ */ jsx(renderer, {
1303
+ content,
1304
+ isStreaming,
1305
+ className
1306
+ });
1307
+ return /* @__PURE__ */ jsx(StreamingMarkdownDefaultRenderer, {
1308
+ ...renderer,
1309
+ ...config,
1310
+ content,
1311
+ isStreaming,
1312
+ className
1313
+ });
1314
+ }
1315
+
1316
+ //#endregion
1317
+ //#region src/generative-ui/markdown/MarkdownSurfaces.tsx
1318
+ const FADE_STYLE_ID = "a2ui-markdown-fade";
1319
+ /**
1320
+ * Components fade in as they stream: each element that appears under a
1321
+ * markdown surface runs the keyframes once on mount. React keeps the keys
1322
+ * stable per component id, so an element that is already there never
1323
+ * animates again. SVG internals are left out: a chart library re-creates
1324
+ * its nodes on each render, and a fade on each of them would read as the
1325
+ * chart flashing whenever a sibling arrives. The fade runs under reduced
1326
+ * motion too, because it moves nothing.
1327
+ */
1328
+ 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");
1329
+ const noEffect = () => {};
1330
+ const useInjectEffect = typeof document === "undefined" ? noEffect : useInsertionEffect;
1331
+ function useFadeStyles() {
1332
+ useInjectEffect(() => {
1333
+ if (document.getElementById(FADE_STYLE_ID)) return;
1334
+ const style = document.createElement("style");
1335
+ style.id = FADE_STYLE_ID;
1336
+ style.textContent = FADE_CSS;
1337
+ document.head.appendChild(style);
1338
+ }, []);
1339
+ }
1340
+ /**
1341
+ * The default wrapper of a chat surface in the markdown transport. It draws
1342
+ * no box: a surface sits in the flow of the reply like a paragraph, and a
1343
+ * Card draws its own box when it is interactive. Nothing shows while the
1344
+ * surface streams. A rejected operation gets one line.
1345
+ */
1346
+ function DefaultMarkdownChatSurface({ surfaceId, error, children }) {
1347
+ useFadeStyles();
1348
+ return /* @__PURE__ */ jsxs("div", {
1349
+ "data-generative-ui-chat-surface": surfaceId,
1350
+ "data-a2ui-markdown-surface": surfaceId,
1351
+ className: "cpk-markdown-chat-surface",
1352
+ children: [children, error && /* @__PURE__ */ jsx("div", {
1353
+ role: "alert",
1354
+ className: "cpk-markdown-chat-surface-error",
1355
+ children: "Part of this UI couldn't be shown."
1356
+ })]
1357
+ });
1358
+ }
1359
+ /**
1360
+ * One chat surface in the chat wrapper. Nothing renders until the surface
1361
+ * has its root component, so a half-streamed fence shows no empty card.
1362
+ */
1363
+ function ChatSurface({ runtime, threadId, surfaceId, Wrapper }) {
1364
+ const surface = runtime.manager.getSurface(threadId, surfaceId) ?? runtime.manager.getFailedSurface(threadId, surfaceId);
1365
+ const root = surface?.model.componentsModel.get(GENERATIVE_UI_ROOT_ID);
1366
+ if (!surface || !root && !surface.failed) return null;
1367
+ const rejected = [...surface.serverRejected, ...surface.clientRejected];
1368
+ const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
1369
+ return /* @__PURE__ */ jsx(Wrapper, {
1370
+ surfaceId,
1371
+ isStreaming: surface.status === "streaming",
1372
+ error,
1373
+ rejected,
1374
+ children: surface.failed ? null : /* @__PURE__ */ jsx(SurfaceView, { surface })
1375
+ });
1376
+ }
1377
+ /** The blocks of one fence: lifted prose and chat surfaces, in order. */
1378
+ function FenceBlocks({ blocks, runtime, threadId, isStreaming, markdownProps }) {
1379
+ const Wrapper = useContext(GenerativeUIChatSlotContext) ?? DefaultMarkdownChatSurface;
1380
+ let surfaceCount = 0;
1381
+ return /* @__PURE__ */ jsx(Fragment$1, { children: blocks.map((block, index) => {
1382
+ if (block.kind === "markdown") return /* @__PURE__ */ jsx(ProviderMarkdown, {
1383
+ ...markdownProps,
1384
+ content: block.markdown,
1385
+ isStreaming: isStreaming && index === blocks.length - 1
1386
+ }, `md-${surfaceCount}`);
1387
+ surfaceCount++;
1388
+ return /* @__PURE__ */ jsx(ChatSurface, {
1389
+ runtime,
1390
+ threadId,
1391
+ surfaceId: block.surfaceId,
1392
+ Wrapper
1393
+ }, block.surfaceId);
1394
+ }) });
1395
+ }
1396
+ /**
1397
+ * Experimental. Renders an assistant message of the markdown transport.
1398
+ * Prose renders as markdown. In place of each ```a2ui fence:
1399
+ *
1400
+ * - the fence that created a chat surface renders that surface (and the
1401
+ * prose lifted out of it) in the chat wrapper;
1402
+ * - every other fence renders nothing: a fence that updates the surface of
1403
+ * an earlier fence, or a fence for a named target, which
1404
+ * `<GenerativeUISurface id>` renders.
1405
+ *
1406
+ * Use it inside `<CopilotKitProvider generativeUI={{ ui, transport: "markdown" }}>`.
1407
+ * `CopilotChatAssistantMessage` uses it there on its own.
1408
+ *
1409
+ * @example
1410
+ * ```tsx
1411
+ * <MarkdownSurfaces content={message.content} messageId={message.id} />
1412
+ * ```
1413
+ */
1414
+ function MarkdownSurfaces({ content, messageId, isStreaming = false, ...markdownProps }) {
1415
+ const runtime = useRequiredGenerativeUIRuntime();
1416
+ const chatThreadId = useCopilotChatConfiguration()?.threadId;
1417
+ useManagerVersion(runtime);
1418
+ const segments = useMemo(() => splitA2UIMarkdown(content), [content]);
1419
+ const threadId = chatThreadId ?? runtime.manager.getActiveThread();
1420
+ const source = getMarkdownSurfaceSource(runtime);
1421
+ return /* @__PURE__ */ jsx(Fragment$1, { children: segments.map((segment, index) => {
1422
+ const isLast = index === segments.length - 1;
1423
+ if (segment.type === "markdown") return /* @__PURE__ */ jsx(ProviderMarkdown, {
1424
+ ...markdownProps,
1425
+ content: segment.text,
1426
+ isStreaming: isStreaming && isLast
1427
+ }, `md-${index}`);
1428
+ const blocks = threadId ? source.getFenceBlocks(threadId, messageId, segment.index) : void 0;
1429
+ if (!threadId || !blocks) return null;
1430
+ return /* @__PURE__ */ jsx(FenceBlocks, {
1431
+ blocks,
1432
+ runtime,
1433
+ threadId,
1434
+ isStreaming: isStreaming && isLast,
1435
+ markdownProps
1436
+ }, `a2ui-${segment.index}`);
1437
+ }) });
1438
+ }
1439
+
1440
+ //#endregion
1441
+ export { useShallowStableRef as A, MarkdownRendererProvider as C, ControlledModalOpenScope as D, renderSlot as E, IconSvg as M, cn as N, CopilotChatConfigurationProvider as O, StreamingMarkdownDefaultRenderer as P, defineToolCallRenderer as S, isReactComponentType as T, GenerativeUIRuntimeContext as _, GenerativeUIToolCallRenderer as a, catalogIdsOf as b, SurfaceView as c, useGenerativeUIAccessibility as d, wrapperAria as f, GenerativeUINodeContext as g, useManagerVersion as h, GenerativeUIChatSlotContext as i, CopilotIcon as j, useCopilotChatConfiguration as k, controlAria as l, useGenerativeUIState as m, ProviderMarkdown as n, createGenerativeUIActivityRenderer as o, useGenerativeUIFunction as p, DefaultGenerativeUIChatCard as r, createGenerativeUIFunctionCallActivityRenderer as s, MarkdownSurfaces as t, namedRole as u, useGenerativeUIRuntime as v, useMarkdownRenderer as w, createGenerativeUI$1 as x, useRequiredGenerativeUIRuntime as y };
1442
+ //# sourceMappingURL=MarkdownSurfaces-BQ1HGCzB.mjs.map