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