@copilotkit/react-core 2.0.0-rc.4 → 2.0.0-rc.40

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 (80) hide show
  1. package/README.md +1 -1
  2. package/dist/MarkdownRendererContext-BL8ct_3U.d.mts +34 -0
  3. package/dist/MarkdownRendererContext-BL8ct_3U.d.mts.map +1 -0
  4. package/dist/MarkdownRendererContext-C2J_lgqF.d.cts +34 -0
  5. package/dist/MarkdownRendererContext-C2J_lgqF.d.cts.map +1 -0
  6. package/dist/MarkdownSurfaces-Byz821bg.mjs +324 -0
  7. package/dist/MarkdownSurfaces-Byz821bg.mjs.map +1 -0
  8. package/dist/MarkdownSurfaces-D2Ck-cbb.cjs +378 -0
  9. package/dist/MarkdownSurfaces-D2Ck-cbb.cjs.map +1 -0
  10. package/dist/chat-Bf0vVdo7.mjs +1600 -0
  11. package/dist/chat-Bf0vVdo7.mjs.map +1 -0
  12. package/dist/chat-D3fxo6Ah.cjs +1784 -0
  13. package/dist/chat-D3fxo6Ah.cjs.map +1 -0
  14. package/dist/chat-DgP2N7bD.d.mts +233 -0
  15. package/dist/chat-DgP2N7bD.d.mts.map +1 -0
  16. package/dist/chat-DtHs4alO.d.cts +233 -0
  17. package/dist/chat-DtHs4alO.d.cts.map +1 -0
  18. package/dist/context.cjs +75 -63
  19. package/dist/context.cjs.map +1 -1
  20. package/dist/context.d.cts +62 -107
  21. package/dist/context.d.cts.map +1 -1
  22. package/dist/context.d.mts +62 -107
  23. package/dist/context.d.mts.map +1 -1
  24. package/dist/context.mjs +76 -64
  25. package/dist/context.mjs.map +1 -1
  26. package/dist/generative-ui/native.cjs +66 -0
  27. package/dist/generative-ui/native.cjs.map +1 -0
  28. package/dist/generative-ui/native.d.cts +155 -0
  29. package/dist/generative-ui/native.d.cts.map +1 -0
  30. package/dist/generative-ui/native.d.mts +155 -0
  31. package/dist/generative-ui/native.d.mts.map +1 -0
  32. package/dist/generative-ui/native.mjs +24 -0
  33. package/dist/generative-ui/native.mjs.map +1 -0
  34. package/dist/generative-ui.cjs +757 -3056
  35. package/dist/generative-ui.cjs.map +1 -1
  36. package/dist/generative-ui.d.cts +2470 -4788
  37. package/dist/generative-ui.d.cts.map +1 -1
  38. package/dist/generative-ui.d.mts +2470 -4788
  39. package/dist/generative-ui.d.mts.map +1 -1
  40. package/dist/generative-ui.mjs +327 -2636
  41. package/dist/generative-ui.mjs.map +1 -1
  42. package/dist/headless.cjs +289 -1054
  43. package/dist/headless.cjs.map +1 -1
  44. package/dist/headless.d.cts +145 -370
  45. package/dist/headless.d.cts.map +1 -1
  46. package/dist/headless.d.mts +119 -235
  47. package/dist/headless.d.mts.map +1 -1
  48. package/dist/headless.mjs +283 -1054
  49. package/dist/headless.mjs.map +1 -1
  50. package/dist/hooks-2Ur8NQhj.d.cts +84 -0
  51. package/dist/hooks-2Ur8NQhj.d.cts.map +1 -0
  52. package/dist/hooks-BRYonCVu.d.mts +84 -0
  53. package/dist/hooks-BRYonCVu.d.mts.map +1 -0
  54. package/dist/index.cjs +6960 -11012
  55. package/dist/index.cjs.map +1 -1
  56. package/dist/index.d.cts +337 -831
  57. package/dist/index.d.cts.map +1 -1
  58. package/dist/index.d.mts +334 -828
  59. package/dist/index.d.mts.map +1 -1
  60. package/dist/index.mjs +1896 -7582
  61. package/dist/index.mjs.map +1 -1
  62. package/dist/index.umd.js +6319 -11463
  63. package/dist/index.umd.js.map +1 -1
  64. package/dist/refs-BIUfn1wb.cjs +43 -0
  65. package/dist/refs-BIUfn1wb.cjs.map +1 -0
  66. package/dist/refs-CMrRm3ta.mjs +31 -0
  67. package/dist/refs-CMrRm3ta.mjs.map +1 -0
  68. package/dist/use-generative-ui-root-C12htqbK.cjs +390 -0
  69. package/dist/use-generative-ui-root-C12htqbK.cjs.map +1 -0
  70. package/dist/use-generative-ui-root-CVgsDy1f.mjs +385 -0
  71. package/dist/use-generative-ui-root-CVgsDy1f.mjs.map +1 -0
  72. package/package.json +45 -23
  73. package/dist/MarkdownRendererContext-B4Us6mwL.d.cts +0 -954
  74. package/dist/MarkdownRendererContext-B4Us6mwL.d.cts.map +0 -1
  75. package/dist/MarkdownRendererContext-CRKFzsEB.d.mts +0 -954
  76. package/dist/MarkdownRendererContext-CRKFzsEB.d.mts.map +0 -1
  77. package/dist/MarkdownSurfaces-Bd--93O1.mjs +0 -3676
  78. package/dist/MarkdownSurfaces-Bd--93O1.mjs.map +0 -1
  79. package/dist/MarkdownSurfaces-S4wfUl3J.cjs +0 -3991
  80. package/dist/MarkdownSurfaces-S4wfUl3J.cjs.map +0 -1
@@ -0,0 +1,1784 @@
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 react_jsx_runtime = require("react/jsx-runtime");
32
+ let _copilotkit_react_core_context = require("@copilotkit/react-core/context");
33
+ let _copilotkit_shared = require("@copilotkit/shared");
34
+ let zod = require("zod");
35
+ zod = __toESM(zod);
36
+ let _copilotkit_core_generative_ui = require("@copilotkit/core/generative-ui");
37
+ let _copilotkit_shared_generative_ui = require("@copilotkit/shared/generative-ui");
38
+
39
+ //#region src/lib/shallow-stable-ref.ts
40
+ /**
41
+ * Shallow equality comparison for objects: same own keys, each holding the
42
+ * same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.
43
+ */
44
+ function shallowEqual(obj1, obj2) {
45
+ return (0, _copilotkit_core.ɵshallowEqualRecord)(obj1, obj2);
46
+ }
47
+ /**
48
+ * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
49
+ * class instances, and other exotic objects that happen to have typeof "object".
50
+ */
51
+ function isPlainObject(obj) {
52
+ return obj !== null && typeof obj === "object" && Object.prototype.toString.call(obj) === "[object Object]";
53
+ }
54
+ /**
55
+ * Returns the same reference as long as the value is shallowly equal to the
56
+ * previous render's value.
57
+ *
58
+ * - Identical references bail out immediately (O(1)).
59
+ * - Plain objects ({}) are shallow-compared key-by-key.
60
+ * - Arrays, Dates, class instances, functions, and primitives are compared by
61
+ * reference only — shallowEqual is never called on non-plain objects, which
62
+ * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).
63
+ *
64
+ * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow
65
+ * equality check isn't defeated by a new object reference on every render.
66
+ */
67
+ function useShallowStableRef(value) {
68
+ const ref = (0, react.useRef)(value);
69
+ if (ref.current === value) return ref.current;
70
+ if (isPlainObject(ref.current) && isPlainObject(value)) {
71
+ if (shallowEqual(ref.current, value)) return ref.current;
72
+ }
73
+ ref.current = value;
74
+ return ref.current;
75
+ }
76
+
77
+ //#endregion
78
+ //#region src/providers/CopilotChatConfigurationProvider.tsx
79
+ const CopilotChatConfiguration = (0, react.createContext)(null);
80
+ const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
81
+ const parentConfig = (0, react.useContext)(CopilotChatConfiguration);
82
+ const stableLabels = useShallowStableRef(labels);
83
+ const mergedLabels = (0, react.useMemo)(() => ({
84
+ ..._copilotkit_core.CopilotChatDefaultLabels,
85
+ ...parentConfig?.labels,
86
+ ...stableLabels
87
+ }), [stableLabels, parentConfig?.labels]);
88
+ const providerAgentId = (0, _copilotkit_react_core_context.useDefaultAgentId)();
89
+ const options = {
90
+ agentId,
91
+ threadId,
92
+ hasExplicitThreadId,
93
+ isModalDefaultOpen,
94
+ providerAgentId
95
+ };
96
+ const parentStore = parentConfig?.ɵstore ?? null;
97
+ const [store] = (0, react.useState)(() => new _copilotkit_core.ɵChatConfigurationStore(options, parentStore));
98
+ store.ɵsetOptions(options);
99
+ const snapshot = (0, react.useSyncExternalStore)(store.subscribe, store.getSnapshot, store.getSnapshot);
100
+ (0, react.useEffect)(() => {
101
+ store.update({
102
+ agentId,
103
+ threadId,
104
+ hasExplicitThreadId,
105
+ isModalDefaultOpen,
106
+ providerAgentId
107
+ });
108
+ }, [
109
+ store,
110
+ agentId,
111
+ threadId,
112
+ hasExplicitThreadId,
113
+ isModalDefaultOpen,
114
+ providerAgentId
115
+ ]);
116
+ const copilotkit = (0, react.useContext)(_copilotkit_react_core_context.CopilotKitContext)?.copilotkit;
117
+ (0, react.useEffect)(() => {
118
+ if (copilotkit === void 0) return;
119
+ return store.bindOpenThread(copilotkit);
120
+ }, [copilotkit, store]);
121
+ const ownsModal = isModalDefaultOpen !== void 0;
122
+ const isModalOpen = ownsModal || !parentConfig ? snapshot.isModalOpen : parentConfig.isModalOpen;
123
+ const setModalOpen = ownsModal || !parentConfig ? store.setModalOpen : parentConfig.setModalOpen;
124
+ const { agentId: resolvedAgentId, threadId: resolvedThreadId, hasExplicitThreadId: resolvedHasExplicitThreadId, drawerOpen, drawerRegistered } = snapshot;
125
+ const configurationValue = (0, react.useMemo)(() => ({
126
+ labels: mergedLabels,
127
+ agentId: resolvedAgentId,
128
+ threadId: resolvedThreadId,
129
+ hasExplicitThreadId: resolvedHasExplicitThreadId,
130
+ isModalOpen,
131
+ setModalOpen,
132
+ drawerOpen,
133
+ setDrawerOpen: store.setDrawerOpen,
134
+ drawerRegistered,
135
+ registerDrawer: store.registerDrawer,
136
+ ɵregisterModalCloser: store.registerModalCloser,
137
+ setActiveThreadId: store.setActiveThreadId,
138
+ startNewThread: store.startNewThread,
139
+ ɵstore: store
140
+ }), [
141
+ mergedLabels,
142
+ resolvedAgentId,
143
+ resolvedThreadId,
144
+ resolvedHasExplicitThreadId,
145
+ isModalOpen,
146
+ setModalOpen,
147
+ drawerOpen,
148
+ drawerRegistered,
149
+ store
150
+ ]);
151
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfiguration.Provider, {
152
+ value: configurationValue,
153
+ children
154
+ });
155
+ };
156
+ const useCopilotChatConfiguration = () => {
157
+ return (0, react.useContext)(CopilotChatConfiguration);
158
+ };
159
+ /**
160
+ * Reports modal open/close requests to the host, and — when `open` is
161
+ * supplied — makes the modal state of an already-established chat
162
+ * configuration **controlled** for the subtree it wraps.
163
+ *
164
+ * This is deliberately a scope component rather than another mode inside
165
+ * {@link CopilotChatConfigurationProvider}. The provider resolves modal state
166
+ * across a nested chain (own state, parent sync, drawer mutual-exclusion, the
167
+ * modal-closer registry); a controlled branch inside that resolution would add
168
+ * a fourth interacting mode. Overriding the context for the subtree instead
169
+ * leaves every one of those paths untouched:
170
+ *
171
+ * - `isModalOpen` is replaced with the host's `open`, so the rendered surface
172
+ * follows the prop from the very first frame (no open-then-close flash).
173
+ * - `setModalOpen` still calls the underlying setter, so the existing
174
+ * parent-sync and drawer mutual-exclusion side effects continue to run, and
175
+ * *then* reports the request through `onOpenChange`.
176
+ * - The wrapped setter is registered as the modal closer, so the drawer's
177
+ * mobile mutual-exclusion reaches the host instead of silently flipping
178
+ * state that nothing displays.
179
+ *
180
+ * A host that supplies `open` and ignores `onOpenChange` gets a modal pinned
181
+ * to `open`, which is the standard controlled-component contract. A host that
182
+ * supplies only `onOpenChange` is notified while the modal keeps managing
183
+ * itself.
184
+ *
185
+ * Renders `children` unchanged when no chat configuration is in scope.
186
+ */
187
+ const ControlledModalOpenScope = ({ children, open, onOpenChange }) => {
188
+ const parentConfig = (0, react.useContext)(CopilotChatConfiguration);
189
+ const parentSetModalOpen = parentConfig?.setModalOpen;
190
+ const registerModalCloser = parentConfig?.ɵregisterModalCloser;
191
+ const setModalOpen = (0, react.useCallback)((next) => {
192
+ parentSetModalOpen?.(next);
193
+ onOpenChange?.(next);
194
+ }, [parentSetModalOpen, onOpenChange]);
195
+ (0, react.useEffect)(() => {
196
+ if (!registerModalCloser) return;
197
+ return registerModalCloser(setModalOpen);
198
+ }, [registerModalCloser, setModalOpen]);
199
+ const configurationValue = (0, react.useMemo)(() => parentConfig ? {
200
+ ...parentConfig,
201
+ isModalOpen: open ?? parentConfig.isModalOpen,
202
+ setModalOpen
203
+ } : null, [
204
+ parentConfig,
205
+ open,
206
+ setModalOpen
207
+ ]);
208
+ if (!configurationValue) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children });
209
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfiguration.Provider, {
210
+ value: configurationValue,
211
+ children
212
+ });
213
+ };
214
+ ControlledModalOpenScope.displayName = "ControlledModalOpenScope";
215
+
216
+ //#endregion
217
+ //#region src/types/defineToolCallRenderer.ts
218
+ function defineToolCallRenderer(def) {
219
+ const argsSchema = def.name === "*" && !def.args ? _copilotkit_shared.ɵanySchema : def.args;
220
+ return {
221
+ name: def.name,
222
+ args: argsSchema,
223
+ render: def.render,
224
+ ...def.agentId ? { agentId: def.agentId } : {},
225
+ ...def.group ? { group: true } : {}
226
+ };
227
+ }
228
+
229
+ //#endregion
230
+ //#region src/generative-ui/runtime-context.ts
231
+ const GenerativeUIRuntimeContext = (0, react.createContext)(null);
232
+ function useGenerativeUIRuntime() {
233
+ return (0, react.useContext)(GenerativeUIRuntimeContext);
234
+ }
235
+ function useRequiredGenerativeUIRuntime() {
236
+ const runtime = (0, react.useContext)(GenerativeUIRuntimeContext);
237
+ if (!runtime) throw new Error("Generative UI components must be rendered inside a generative UI provider: <CopilotKitProvider generativeUI={{ ui }}> on the web, or <GenerativeUIProvider> from @copilotkit/react-native/generative-ui on React Native.");
238
+ return runtime;
239
+ }
240
+ const GenerativeUINodeContext = (0, react.createContext)(null);
241
+
242
+ //#endregion
243
+ //#region src/generative-ui/hooks.ts
244
+ const noopSubscribe$1 = () => () => {};
245
+ const zero = () => 0;
246
+ /** Re-renders on any surface-manager change. */
247
+ function useManagerVersion(runtime) {
248
+ return (0, react.useSyncExternalStore)(runtime?.manager.subscribe ?? noopSubscribe$1, runtime?.manager.getVersion ?? zero, zero);
249
+ }
250
+ /**
251
+ * Experimental. Gives one key of the app state declared in
252
+ * `createGenerativeUI({ state })` its value. Bound props of generated
253
+ * components read it. The model does not see it.
254
+ *
255
+ * The key is set on mount and when the value changes (compared as JSON). It
256
+ * is removed on unmount.
257
+ *
258
+ * @param ui - The object from `createGenerativeUI`. It gives the key and the
259
+ * value their types.
260
+ * @param key - A top-level key of `state`.
261
+ * @param value - The value of that key. It must fit the key's schema.
262
+ *
263
+ * @example
264
+ * ```tsx
265
+ * useGenerativeUIState(storeUI, "cart", { count, total, coupon, items });
266
+ * ```
267
+ */
268
+ function useGenerativeUIState(ui, key, value) {
269
+ const runtime = useRequiredGenerativeUIRuntime();
270
+ const serialized = JSON.stringify(value);
271
+ (0, react.useEffect)(() => {
272
+ const raw = JSON.parse(serialized ?? "null");
273
+ let current = true;
274
+ const apply = (parsed) => {
275
+ if (!current) return;
276
+ if (parsed.success) {
277
+ runtime.manager.setState(key, parsed.data);
278
+ return;
279
+ }
280
+ runtime.manager.removeState(key);
281
+ if (process.env.NODE_ENV !== "production") console.error(`[generativeUI] useGenerativeUIState: invalid value for "${key}": ${(0, _copilotkit_shared_generative_ui.formatIssues)(parsed.issues, "value")}`);
282
+ };
283
+ const schema = runtime.ui.state.get(key);
284
+ const parsed = schema ? (0, _copilotkit_shared_generative_ui.validateSchema)(schema, raw) : {
285
+ success: true,
286
+ data: raw
287
+ };
288
+ if (parsed instanceof Promise) parsed.then(apply);
289
+ else apply(parsed);
290
+ return () => {
291
+ current = false;
292
+ };
293
+ }, [
294
+ runtime,
295
+ key,
296
+ serialized
297
+ ]);
298
+ (0, react.useEffect)(() => () => runtime.manager.removeState(key), [runtime, key]);
299
+ }
300
+ /**
301
+ * Experimental. Mounts the handler of a function declared in
302
+ * `createGenerativeUI({ functions })`. Generated UI can call the function
303
+ * only while exactly one handler for it is mounted.
304
+ *
305
+ * The handler gets the parsed arguments: schema defaults are set. It can
306
+ * change on each render. The latest handler always runs, and the hook does
307
+ * not register again.
308
+ *
309
+ * @param ui - The object from `createGenerativeUI`. It gives the name and the
310
+ * handler arguments their types.
311
+ * @param name - A key of `functions`.
312
+ * @param handler - Runs when generated UI calls the function. Its return
313
+ * value goes back to the caller as `{ ok: true, result }`.
314
+ *
315
+ * @example
316
+ * ```tsx
317
+ * useGenerativeUIFunction(storeUI, "addToCart", ({ productId, quantity }) =>
318
+ * cart.addItem(productId, quantity),
319
+ * );
320
+ * ```
321
+ */
322
+ function useGenerativeUIFunction(ui, name, handler) {
323
+ const runtime = useRequiredGenerativeUIRuntime();
324
+ const latest = (0, react.useRef)(handler);
325
+ latest.current = handler;
326
+ (0, react.useEffect)(() => runtime.dispatcher.register(name, latest), [runtime, name]);
327
+ }
328
+
329
+ //#endregion
330
+ //#region src/generative-ui/activity.ts
331
+ /**
332
+ * The rejected operations of a surface (the runtime's first, then the
333
+ * client's) and the error that goes with them, for a wrapper: a generic
334
+ * message, with the same list as its `cause`. The `cause` is not enumerable,
335
+ * so `JSON.stringify`, a spread and error reporters leave the list out.
336
+ * `clientRejected` is appended to in place by the manager, so its length is
337
+ * part of the key.
338
+ */
339
+ function useGenerativeUIRejected(serverRejected, clientRejected) {
340
+ const rejected = (0, react.useMemo)(() => [...serverRejected ?? [], ...clientRejected ?? []], [
341
+ serverRejected,
342
+ clientRejected,
343
+ clientRejected?.length ?? 0
344
+ ]);
345
+ return {
346
+ rejected,
347
+ error: (0, react.useMemo)(() => rejected.length ? (0, _copilotkit_shared_generative_ui.withCause)(/* @__PURE__ */ new Error(`${rejected.length} UI update(s) could not be shown`), rejected) : void 0, [rejected])
348
+ };
349
+ }
350
+ /**
351
+ * What a renderer of one surface activity message shows: the surface (or the
352
+ * failed surface whose `createSurface` was rejected), and its rejected
353
+ * operations with their error (see {@link useGenerativeUIRejected}). It
354
+ * ingests `content` into the manager (idempotent: the root ingests the
355
+ * agent's messages too, and this covers an agent the root has not seen yet),
356
+ * and renders again on every change of the manager.
357
+ *
358
+ * `surface` is undefined when there is no runtime, thread or content, when
359
+ * the surface's target is not `target`, or when the surface does not exist
360
+ * (the agent deleted it). Both rejected lists cover only the latest
361
+ * `render_ui` call (see the manager's ingest).
362
+ */
363
+ function useGenerativeUIActivitySurface({ runtime, threadId, agentId, content, target }) {
364
+ useManagerVersion(runtime);
365
+ (0, react.useLayoutEffect)(() => {
366
+ if (runtime && threadId && content) runtime.manager.ingest(threadId, agentId, content);
367
+ }, [
368
+ runtime,
369
+ threadId,
370
+ agentId,
371
+ content
372
+ ]);
373
+ const surface = runtime && threadId && content && content.target === target ? runtime.manager.getSurface(threadId, content.surfaceId) ?? runtime.manager.getFailedSurface(threadId, content.surfaceId) : void 0;
374
+ const { rejected, error } = useGenerativeUIRejected(content?.rejected, surface?.clientRejected);
375
+ return {
376
+ surface,
377
+ rejected,
378
+ error
379
+ };
380
+ }
381
+
382
+ //#endregion
383
+ //#region src/generative-ui/catalog.ts
384
+ /**
385
+ * Experimental. Declares the components the model can render, the app state
386
+ * they read, and the functions they call.
387
+ *
388
+ * - A prop with the name of a top-level state key is bound to that state.
389
+ * - `bind: { prop: (state, props) => value }` binds a prop to a selector.
390
+ * - An event binds to the function with its name, else to the name without
391
+ * `on` (`onAddToCart` calls `addToCart`).
392
+ * - `writable: ["value"]` gives the component a `setValue` prop. See
393
+ * `GenerativeUIComponentDefinition.writable`.
394
+ *
395
+ * The model does not see bound props or matched events.
396
+ *
397
+ * @param config - `id`, then optional `extends`, `state`, `functions` and
398
+ * `overrides`, then `components`. Put `state` before `components`, so the selectors
399
+ * get typed state.
400
+ * @throws Error when a name comes from two places, an override names no
401
+ * component of the bases, `props` is not an object
402
+ * schema with a JSON Schema, a key is reserved or used
403
+ * twice on a component, an event matches two functions, an unmatched event
404
+ * has no `parameters`, a `bind` key is not a prop, a `writable` key is not
405
+ * a prop or is a bound prop, or a setter name is already a key of the
406
+ * component. Also throws when `parameterOrder` contains duplicate or unknown
407
+ * keys, or an ordered component declares integer-index keys whose JSON object
408
+ * enumeration order cannot be controlled.
409
+ *
410
+ * @example
411
+ * ```ts
412
+ * const ui = createGenerativeUI({
413
+ * id: "acme/store@1",
414
+ * state: { cart: cartSchema },
415
+ * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },
416
+ * components: {
417
+ * CartSummary: {
418
+ * component: CartSummary,
419
+ * props: z.object({ count: z.number() }),
420
+ * bind: { count: (state) => state.cart.count },
421
+ * },
422
+ * },
423
+ * });
424
+ * ```
425
+ */
426
+ function createGenerativeUI(config) {
427
+ return (0, _copilotkit_shared_generative_ui.createGenerativeUI)(config);
428
+ }
429
+
430
+ //#endregion
431
+ //#region src/generative-ui/host.tsx
432
+ const DISPLAY_CONTENTS = { display: "contents" };
433
+ /**
434
+ * The root element is always there, so a theme change does not remount the
435
+ * surface. `display: contents` keeps it out of the layout, and the CSS
436
+ * variables still reach every component of the surface. The `a2ui-surface`
437
+ * class scopes the standard catalog's surface CSS rules. The theme is a
438
+ * stylesheet, not an inline style, so that its `dark` values can apply in
439
+ * dark mode only. The values are checked in `themeStyleSheet`, and the HTML
440
+ * is set as is, so the server render keeps the quotes of the rule.
441
+ */
442
+ function DomSurfaceRoot({ surfaceId, theme, children }) {
443
+ const sheet = react.default.useMemo(() => (0, _copilotkit_shared_generative_ui.themeStyleSheet)(theme), [theme]);
444
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
445
+ className: "a2ui-surface",
446
+ "data-generative-ui-root": surfaceId,
447
+ "data-a2ui-theme": sheet?.id,
448
+ style: DISPLAY_CONTENTS,
449
+ children: [sheet ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { dangerouslySetInnerHTML: { __html: sheet.css } }) : null, children]
450
+ });
451
+ }
452
+ function DomAccessibilityWrapper({ attributes, children }) {
453
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
454
+ "data-a2ui-accessibility": "",
455
+ style: DISPLAY_CONTENTS,
456
+ ...attributes,
457
+ children
458
+ });
459
+ }
460
+ function DefaultNodeFallback({ message, componentId, retry }) {
461
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
462
+ role: "alert",
463
+ "data-generative-ui-error": componentId,
464
+ style: {
465
+ border: "1px solid #fca5a5",
466
+ background: "#fef2f2",
467
+ color: "#991b1b",
468
+ borderRadius: 8,
469
+ padding: "8px 12px",
470
+ fontSize: 13
471
+ },
472
+ children: [
473
+ "Couldn’t display this part: ",
474
+ message,
475
+ retry && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
476
+ type: "button",
477
+ onClick: retry,
478
+ style: {
479
+ marginLeft: 8,
480
+ textDecoration: "underline"
481
+ },
482
+ children: "Retry"
483
+ })
484
+ ]
485
+ });
486
+ }
487
+ /** The DOM host: what a surface draws on the web. */
488
+ const domGenerativeUIHost = {
489
+ SurfaceRoot: DomSurfaceRoot,
490
+ AccessibilityWrapper: DomAccessibilityWrapper,
491
+ NodeFallback: DefaultNodeFallback
492
+ };
493
+ /**
494
+ * The host elements of the surfaces below. Defaults to the DOM host, so a
495
+ * web app never sets it.
496
+ */
497
+ const GenerativeUIHostContext = (0, react.createContext)(domGenerativeUIHost);
498
+ function useGenerativeUIHost() {
499
+ return (0, react.useContext)(GenerativeUIHostContext);
500
+ }
501
+
502
+ //#endregion
503
+ //#region src/generative-ui/boundaries.tsx
504
+ /**
505
+ * A child that has not streamed yet renders nothing. The prose keeps
506
+ * streaming above the surface, and each component appears as soon as it is
507
+ * complete. A grey block in its place would read as a broken layout.
508
+ */
509
+ function NodePlaceholder(_props) {
510
+ return null;
511
+ }
512
+ /**
513
+ * The error that a fallback threw, told apart from the error of the
514
+ * component it stood in for. The fallback's own error is the `cause`.
515
+ */
516
+ function fallbackError(error, componentId) {
517
+ const subject = componentId === void 0 ? "the surface" : componentId;
518
+ return (0, _copilotkit_shared_generative_ui.withCause)(/* @__PURE__ */ new Error(`The error fallback of ${subject} threw: ${error.message}`), error);
519
+ }
520
+ function createFailureLog() {
521
+ const last = /* @__PURE__ */ new Map();
522
+ const released = /* @__PURE__ */ new Set();
523
+ const releasedSinceSettle = /* @__PURE__ */ new Set();
524
+ const heldBack = /* @__PURE__ */ new Map();
525
+ return {
526
+ report(runtime, slot, info, context = "") {
527
+ released.delete(slot);
528
+ const signature = [
529
+ info.kind,
530
+ info.error.name,
531
+ info.error.message,
532
+ context
533
+ ].join("\n");
534
+ if (last.get(slot) === signature) {
535
+ if (releasedSinceSettle.has(slot)) heldBack.set(slot, {
536
+ runtime,
537
+ info,
538
+ signature
539
+ });
540
+ return;
541
+ }
542
+ heldBack.delete(slot);
543
+ last.set(slot, signature);
544
+ (0, _copilotkit_core_generative_ui.reportErrorSafely)(runtime, info);
545
+ },
546
+ clear(slot) {
547
+ released.delete(slot);
548
+ last.delete(slot);
549
+ heldBack.delete(slot);
550
+ },
551
+ retain(slot) {
552
+ released.delete(slot);
553
+ },
554
+ release(slot) {
555
+ heldBack.delete(slot);
556
+ if (!last.has(slot)) return;
557
+ released.add(slot);
558
+ releasedSinceSettle.add(slot);
559
+ },
560
+ settle(missed = false) {
561
+ for (const slot of missed ? releasedSinceSettle : released) last.delete(slot);
562
+ if (missed) for (const [slot, { runtime, info, signature }] of heldBack) {
563
+ if (!releasedSinceSettle.has(slot) || last.has(slot)) continue;
564
+ last.set(slot, signature);
565
+ (0, _copilotkit_core_generative_ui.reportErrorSafely)(runtime, info);
566
+ }
567
+ heldBack.clear();
568
+ released.clear();
569
+ releasedSinceSettle.clear();
570
+ }
571
+ };
572
+ }
573
+ /** Outside a surface, every failure is reported. */
574
+ const UNLOGGED = {
575
+ report: (runtime, _slot, info) => (0, _copilotkit_core_generative_ui.reportErrorSafely)(runtime, info),
576
+ clear: () => {},
577
+ retain: () => {},
578
+ release: () => {},
579
+ settle: () => {}
580
+ };
581
+ /** The failure log of the surface being rendered; set by `SurfaceView`. */
582
+ const GenerativeUIFailureLogContext = (0, react.createContext)(UNLOGGED);
583
+ function useFailureLog() {
584
+ return (0, react.useContext)(GenerativeUIFailureLogContext);
585
+ }
586
+ /**
587
+ * The slots of a failure log, per node place (one rendered copy of a node,
588
+ * see `placeOf` in SurfaceView) and surface boundary.
589
+ */
590
+ const failureSlots = {
591
+ node: (place) => `node ${place}`,
592
+ appFallback: (place) => `app-fallback ${place}`,
593
+ renderFallback: (place) => `render-fallback ${place}`,
594
+ fallback: (place) => `fallback ${place}`,
595
+ cycle: (place) => `cycle ${place}`,
596
+ props: (place) => `props ${place}`,
597
+ surface: (level) => `surface ${level}`,
598
+ surfaceFallback: (level) => `surface-fallback ${level}`
599
+ };
600
+ function sameKeys(a, b) {
601
+ return a.length === b.length && a.every((value, i) => Object.is(value, b[i]));
602
+ }
603
+ var FallbackGuard = class extends react.Component {
604
+ state = {
605
+ failed: false,
606
+ resetKeys: this.props.resetKeys
607
+ };
608
+ static getDerivedStateFromError(thrown) {
609
+ return {
610
+ failed: true,
611
+ error: (0, _copilotkit_shared_generative_ui.toError)(thrown)
612
+ };
613
+ }
614
+ static getDerivedStateFromProps(props, state) {
615
+ return sameKeys(props.resetKeys, state.resetKeys) ? null : {
616
+ failed: false,
617
+ error: void 0,
618
+ resetKeys: props.resetKeys
619
+ };
620
+ }
621
+ report(error) {
622
+ const { runtime, surfaceId, componentId, log, slot, context } = this.props;
623
+ log.report(runtime, slot, {
624
+ kind: "render",
625
+ surfaceId,
626
+ ...componentId === void 0 ? {} : { componentId },
627
+ error: fallbackError(error, componentId)
628
+ }, context);
629
+ }
630
+ componentDidCatch(thrown) {
631
+ this.report(this.state.error ?? (0, _copilotkit_shared_generative_ui.toError)(thrown));
632
+ }
633
+ componentDidMount() {
634
+ if (!this.state.failed) {
635
+ this.props.log.clear(this.props.slot);
636
+ return;
637
+ }
638
+ if (this.state.error) this.report(this.state.error);
639
+ }
640
+ componentDidUpdate() {
641
+ if (!this.state.failed) this.props.log.clear(this.props.slot);
642
+ }
643
+ render() {
644
+ return this.state.failed ? this.props.replacement ?? null : this.props.children;
645
+ }
646
+ };
647
+ /**
648
+ * The host's `NodeFallback`, guarded: when it throws, the node renders
649
+ * nothing and the error is reported, and the parent node keeps rendering.
650
+ * Every place that shows the host fallback goes through this.
651
+ */
652
+ function GuardedNodeFallback({ surfaceId, componentId, runtime, message, retry, slot, revision }) {
653
+ const { NodeFallback } = useGenerativeUIHost();
654
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FallbackGuard, {
655
+ surfaceId,
656
+ componentId,
657
+ runtime,
658
+ log: useFailureLog(),
659
+ slot,
660
+ context: message,
661
+ resetKeys: [message, revision],
662
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeFallback, {
663
+ message,
664
+ componentId: componentId ?? "surface",
665
+ retry
666
+ })
667
+ });
668
+ }
669
+ /**
670
+ * Calls the app's `errorBoundary.fallback` in a render of its own, so that
671
+ * the guard above it catches what it throws.
672
+ */
673
+ function AppErrorFallback({ render, ...props }) {
674
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: render(props) });
675
+ }
676
+ /**
677
+ * Per-node boundary. Resets on retry or a new agent revision, not on data
678
+ * ticks. A failure that stays the same across revisions is reported once.
679
+ */
680
+ var NodeBoundary = class extends react.Component {
681
+ state = {
682
+ error: null,
683
+ revision: this.props.revision
684
+ };
685
+ static getDerivedStateFromError(thrown) {
686
+ return { error: (0, _copilotkit_shared_generative_ui.toError)(thrown) };
687
+ }
688
+ static getDerivedStateFromProps(props, state) {
689
+ return props.revision !== state.revision ? {
690
+ error: null,
691
+ revision: props.revision
692
+ } : null;
693
+ }
694
+ componentDidCatch(thrown) {
695
+ const { runtime, surfaceId, componentId, log, place } = this.props;
696
+ log.clear(failureSlots.fallback(place));
697
+ log.report(runtime, failureSlots.node(place), {
698
+ kind: "render",
699
+ surfaceId,
700
+ componentId,
701
+ error: this.state.error ?? (0, _copilotkit_shared_generative_ui.toError)(thrown)
702
+ });
703
+ }
704
+ slots() {
705
+ const { place } = this.props;
706
+ return [
707
+ failureSlots.node(place),
708
+ failureSlots.appFallback(place),
709
+ failureSlots.renderFallback(place)
710
+ ];
711
+ }
712
+ clearSlots() {
713
+ for (const slot of this.slots()) this.props.log.clear(slot);
714
+ }
715
+ componentDidMount() {
716
+ for (const slot of this.slots()) this.props.log.retain(slot);
717
+ if (!this.state.error) {
718
+ this.clearSlots();
719
+ return;
720
+ }
721
+ const { runtime, surfaceId, componentId, log, place } = this.props;
722
+ log.report(runtime, failureSlots.node(place), {
723
+ kind: "render",
724
+ surfaceId,
725
+ componentId,
726
+ error: this.state.error
727
+ });
728
+ }
729
+ componentDidUpdate(prevProps) {
730
+ if (prevProps.place !== this.props.place) {
731
+ const { log } = this.props;
732
+ log.release(failureSlots.node(prevProps.place));
733
+ log.release(failureSlots.appFallback(prevProps.place));
734
+ log.release(failureSlots.renderFallback(prevProps.place));
735
+ for (const slot of this.slots()) log.retain(slot);
736
+ }
737
+ if (!this.state.error) this.clearSlots();
738
+ }
739
+ componentWillUnmount() {
740
+ for (const slot of this.slots()) this.props.log.release(slot);
741
+ }
742
+ retry = () => this.setState({ error: null });
743
+ render() {
744
+ const { error } = this.state;
745
+ if (!error) return this.props.children;
746
+ const { runtime, surfaceId, componentId, place, log } = this.props;
747
+ const hostFallback = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GuardedNodeFallback, {
748
+ surfaceId,
749
+ componentId,
750
+ runtime,
751
+ message: error.message,
752
+ retry: this.retry,
753
+ slot: failureSlots.renderFallback(place)
754
+ });
755
+ const fallback = runtime.errorFallback;
756
+ if (!fallback) return hostFallback;
757
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FallbackGuard, {
758
+ surfaceId,
759
+ componentId,
760
+ runtime,
761
+ log,
762
+ slot: failureSlots.appFallback(place),
763
+ context: error.message,
764
+ resetKeys: [error],
765
+ replacement: hostFallback,
766
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(AppErrorFallback, {
767
+ render: fallback,
768
+ error,
769
+ retry: this.retry,
770
+ surfaceId,
771
+ componentId
772
+ })
773
+ });
774
+ }
775
+ };
776
+ /**
777
+ * Surface boundary: a failure here must not reach the chat or the host page.
778
+ * It resets on a new revision, and on Retry when `retryable`. A failure that
779
+ * stays the same across revisions is reported once.
780
+ */
781
+ var SurfaceBoundary = class extends react.Component {
782
+ state = {
783
+ error: null,
784
+ revision: this.props.revision
785
+ };
786
+ static getDerivedStateFromError(thrown) {
787
+ return { error: (0, _copilotkit_shared_generative_ui.toError)(thrown) };
788
+ }
789
+ static getDerivedStateFromProps(props, state) {
790
+ return props.revision !== state.revision ? {
791
+ error: null,
792
+ revision: props.revision
793
+ } : null;
794
+ }
795
+ componentDidCatch(thrown) {
796
+ const { runtime, surfaceId, log, level } = this.props;
797
+ log.report(runtime, failureSlots.surface(level), {
798
+ kind: "render",
799
+ surfaceId,
800
+ error: this.state.error ?? (0, _copilotkit_shared_generative_ui.toError)(thrown)
801
+ });
802
+ }
803
+ clearSlots() {
804
+ const { log, level } = this.props;
805
+ log.clear(failureSlots.surface(level));
806
+ log.clear(failureSlots.surfaceFallback(level));
807
+ }
808
+ componentDidMount() {
809
+ if (!this.state.error) this.clearSlots();
810
+ }
811
+ componentDidUpdate() {
812
+ if (!this.state.error) this.clearSlots();
813
+ }
814
+ retry = () => this.setState({ error: null });
815
+ render() {
816
+ if (!this.state.error) return this.props.children;
817
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GuardedNodeFallback, {
818
+ surfaceId: this.props.surfaceId,
819
+ componentId: void 0,
820
+ runtime: this.props.runtime,
821
+ message: "this generated UI failed to render",
822
+ retry: this.props.retryable ? this.retry : void 0,
823
+ slot: failureSlots.surfaceFallback(this.props.level)
824
+ });
825
+ }
826
+ };
827
+
828
+ //#endregion
829
+ //#region src/generative-ui/accessibility.ts
830
+ /**
831
+ * Experimental. The ARIA attributes of the `accessibility` that the model
832
+ * gave the component being rendered, to spread on its root element. The
833
+ * standard components do this; a custom component does it itself:
834
+ *
835
+ * @example
836
+ * ```tsx
837
+ * function Panel({ children }: { children?: ReactNode }) {
838
+ * const aria = useGenerativeUIAccessibility();
839
+ * return <section {...aria}>{children}</section>;
840
+ * }
841
+ * ```
842
+ *
843
+ * Outside of generated UI it gives `{}`.
844
+ */
845
+ function useGenerativeUIAccessibility() {
846
+ const accessibility = (0, react.useContext)(GenerativeUINodeContext)?.accessibility;
847
+ return (0, react.useMemo)(() => (0, _copilotkit_core_generative_ui.accessibilityAttributes)(accessibility), [accessibility]);
848
+ }
849
+
850
+ //#endregion
851
+ //#region src/generative-ui/SurfaceView.tsx
852
+ const NO_ANCESTORS = [];
853
+ const undefinedSnapshot = () => void 0;
854
+ const noopSubscribe = () => () => {};
855
+ const zeroSnapshot = () => 0;
856
+ /** A "multiple" slot value that repeats a component for each list item. */
857
+ function isTemplateChildren(value) {
858
+ return typeof value === "object" && value !== null && "componentId" in value && typeof value.componentId === "string" && "path" in value && typeof value.path === "string";
859
+ }
860
+ function SurfaceView({ surface }) {
861
+ const runtime = useRequiredGenerativeUIRuntime();
862
+ const { SurfaceRoot } = useGenerativeUIHost();
863
+ const appliedCount = (0, react.useSyncExternalStore)(runtime.manager.subscribe, () => surface.operations.length, undefinedSnapshot);
864
+ const revision = (0, react.useMemo)(() => ({
865
+ surface,
866
+ appliedCount
867
+ }), [surface, appliedCount]);
868
+ const [scopedLog, setScopedLog] = (0, react.useState)(() => ({
869
+ key: surface.key,
870
+ log: createFailureLog()
871
+ }));
872
+ let failureLog = scopedLog.log;
873
+ if (scopedLog.key !== surface.key) {
874
+ const next = {
875
+ key: surface.key,
876
+ log: createFailureLog()
877
+ };
878
+ setScopedLog(next);
879
+ failureLog = next.log;
880
+ }
881
+ const { threadId, surfaceId } = surface;
882
+ const { manager } = runtime;
883
+ const seen = (0, react.useRef)(void 0);
884
+ (0, react.useLayoutEffect)(() => {
885
+ const contentOf = () => {
886
+ const current = manager.getSurface(threadId, surfaceId);
887
+ return {
888
+ log: failureLog,
889
+ current,
890
+ applied: current?.operations.length
891
+ };
892
+ };
893
+ const observe = (missed) => {
894
+ const last = seen.current;
895
+ const next = contentOf();
896
+ seen.current = next;
897
+ if (last?.log === failureLog && (next.current !== last.current || next.applied !== last.applied)) failureLog.settle(missed);
898
+ };
899
+ observe(true);
900
+ return manager.subscribe(() => observe(false));
901
+ }, [
902
+ manager,
903
+ threadId,
904
+ surfaceId,
905
+ failureLog
906
+ ]);
907
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GenerativeUIFailureLogContext.Provider, {
908
+ value: failureLog,
909
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceBoundary, {
910
+ surfaceId: surface.surfaceId,
911
+ runtime,
912
+ log: failureLog,
913
+ level: "outer",
914
+ revision,
915
+ retryable: true,
916
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceRoot, {
917
+ surfaceId: surface.surfaceId,
918
+ theme: runtime.theme,
919
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceBoundary, {
920
+ surfaceId: surface.surfaceId,
921
+ runtime,
922
+ log: failureLog,
923
+ level: "inner",
924
+ revision,
925
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
926
+ surface,
927
+ componentId: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
928
+ basePath: void 0,
929
+ ancestors: NO_ANCESTORS,
930
+ parentPlace: "",
931
+ via: ""
932
+ })
933
+ })
934
+ })
935
+ })
936
+ });
937
+ }
938
+ /**
939
+ * Resolves a component by id. Subscribes to the manager rather than web_core's
940
+ * `onCreated`/`onDeleted`: web_core's EventEmitter awaits each listener in turn,
941
+ * so with several subscribers (one per slotted child, or one per mount of the
942
+ * same surface) all but the first are notified a microtask late. That is only
943
+ * visible inside synchronous flushes such as `act()` / `flushSync`, where the
944
+ * old tree would still be on screen, but it makes updates order-dependent.
945
+ * The manager notifies synchronously once an ingest has been fully applied.
946
+ */
947
+ function useComponentModel(manager, model, id) {
948
+ return (0, react.useSyncExternalStore)(manager.subscribe, () => model.componentsModel.get(id), undefinedSnapshot);
949
+ }
950
+ /** Same reasoning as `useComponentModel`: never rely on web_core's emitters. */
951
+ function useComponentProperties(manager, component) {
952
+ return (0, react.useSyncExternalStore)(manager.subscribe, () => component?.properties, undefinedSnapshot);
953
+ }
954
+ /**
955
+ * The id of a node in the ancestor list. A template renders the same
956
+ * component once per item, so the item path is part of the id. A real cycle
957
+ * repeats both.
958
+ */
959
+ function scopedId(componentId, basePath) {
960
+ return `${basePath === void 0 ? "" : JSON.stringify(basePath)}#${JSON.stringify(componentId)}`;
961
+ }
962
+ /**
963
+ * Where one rendered copy of a node is: the place of its parent, the slot
964
+ * or child reference of the parent it renders in, and its scoped id. Names
965
+ * the node's failure-log slots. A scoped id alone is not enough: the same
966
+ * id can render under two parents, and a cyclic reference repeats the
967
+ * scoped id of an ancestor. Each copy keeps its own memory of what it
968
+ * reported, so one copy that renders, goes away or remounts does not clear
969
+ * the memory of another that still fails.
970
+ */
971
+ function placeOf(parentPlace, via, position) {
972
+ return `${parentPlace}/${via === "" ? "" : JSON.stringify(via)}${position}`;
973
+ }
974
+ const NodeView = (0, react.memo)(function NodeView({ surface, componentId, basePath, ancestors, parentPlace, via }) {
975
+ const runtime = useRequiredGenerativeUIRuntime();
976
+ const log = useFailureLog();
977
+ const component = useComponentModel(runtime.manager, surface.model, componentId);
978
+ const properties = useComponentProperties(runtime.manager, component);
979
+ const position = scopedId(componentId, basePath);
980
+ const place = placeOf(parentPlace, via, position);
981
+ (0, react.useEffect)(() => {
982
+ const slots = [
983
+ failureSlots.fallback(place),
984
+ failureSlots.cycle(place),
985
+ failureSlots.props(place)
986
+ ];
987
+ for (const slot of slots) log.retain(slot);
988
+ return () => {
989
+ for (const slot of slots) log.release(slot);
990
+ };
991
+ }, [log, place]);
992
+ if (ancestors.includes(position)) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GuardedNodeFallback, {
993
+ surfaceId: surface.surfaceId,
994
+ componentId,
995
+ runtime,
996
+ message: `cyclic reference to ${componentId}`,
997
+ slot: failureSlots.cycle(place),
998
+ revision: properties
999
+ });
1000
+ if (!component || !properties) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodePlaceholder, { componentId });
1001
+ const definition = runtime.ui.components.get(component.type);
1002
+ if (!definition) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GuardedNodeFallback, {
1003
+ surfaceId: surface.surfaceId,
1004
+ componentId,
1005
+ runtime,
1006
+ message: `unknown component "${component.type}"`,
1007
+ slot: failureSlots.fallback(place),
1008
+ revision: properties
1009
+ });
1010
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeBoundary, {
1011
+ surfaceId: surface.surfaceId,
1012
+ componentId,
1013
+ place,
1014
+ revision: properties,
1015
+ runtime,
1016
+ log,
1017
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ResolvedNode, {
1018
+ surface,
1019
+ componentId,
1020
+ definition,
1021
+ properties,
1022
+ runtime,
1023
+ basePath,
1024
+ ancestors,
1025
+ place
1026
+ })
1027
+ }, component.type);
1028
+ });
1029
+ /**
1030
+ * Renders the component of a template once for each item of the list at the
1031
+ * template path, keyed by index. Renders nothing when there is no list.
1032
+ */
1033
+ function TemplateChildren({ surface, template, basePath, ancestors, parentPlace, via }) {
1034
+ const dataModel = surface.model.dataModel;
1035
+ const listPath = (0, _copilotkit_core_generative_ui.resolvePath)(template.path, basePath);
1036
+ const subscribe = (0, react.useCallback)((onChange) => {
1037
+ const subscription = dataModel.subscribe(listPath, onChange);
1038
+ return () => subscription.unsubscribe();
1039
+ }, [dataModel, listPath]);
1040
+ const getCount = () => {
1041
+ const list = dataModel.get(listPath);
1042
+ return Array.isArray(list) ? list.length : 0;
1043
+ };
1044
+ const count = (0, react.useSyncExternalStore)(subscribe, getCount, zeroSnapshot);
1045
+ 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, {
1046
+ surface,
1047
+ componentId: template.componentId,
1048
+ basePath: (0, _copilotkit_core_generative_ui.joinPath)(listPath, String(index)),
1049
+ ancestors,
1050
+ parentPlace,
1051
+ via
1052
+ }, index)) });
1053
+ }
1054
+ /**
1055
+ * The props the model sets, with their dynamic values resolved from the
1056
+ * surface data model: `{"@path"}` bindings, `{"@call"}` function values and
1057
+ * `{"@call":"@index"}` in a template, at any depth. Bound props, events and
1058
+ * slots are left out, and so are the keys of the A2UI component envelope;
1059
+ * `accessibility` is resolved the same way and given on its own.
1060
+ *
1061
+ * A writable prop that is not bound to a path and that the component set
1062
+ * shows the local value from `overrides`, also when the model never set the
1063
+ * prop. That is intended: the user's edit wins over the model's literal
1064
+ * value, also over a newer literal the agent sends later, until the node
1065
+ * remounts. A literal is not data the agent and the user share; a prop
1066
+ * that both must write is bound to a path, and the setter writes the data
1067
+ * model.
1068
+ *
1069
+ * A prop is resolved again only when its raw value or a data model value it
1070
+ * read has changed, so the result keeps its identity otherwise. A function
1071
+ * value that cannot be computed gives a problem instead of values.
1072
+ */
1073
+ function useModelDataProps(surface, definition, properties, basePath, overrides) {
1074
+ const dataModel = surface.model.dataModel;
1075
+ const units = (0, react.useMemo)(() => {
1076
+ const list = [];
1077
+ for (const key of Object.keys(properties)) {
1078
+ if (definition.events?.[key] || definition.slots?.[key] || (0, _copilotkit_shared_generative_ui.hasOwnKey)(definition.selectors, key) || _copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS.has(key)) continue;
1079
+ list.push({
1080
+ key,
1081
+ raw: properties[key]
1082
+ });
1083
+ }
1084
+ const a11y = properties.accessibility;
1085
+ if (typeof a11y === "object" && a11y !== null && !Array.isArray(a11y)) for (const [field, raw] of Object.entries(a11y)) list.push({
1086
+ key: `accessibility/${field}`,
1087
+ raw,
1088
+ field
1089
+ });
1090
+ return list;
1091
+ }, [properties, definition]);
1092
+ const [, rerender] = (0, react.useReducer)((n) => n + 1, 0);
1093
+ const cache = (0, react.useRef)(/* @__PURE__ */ new Map());
1094
+ const values = {};
1095
+ const a11yValues = {};
1096
+ const paths = /* @__PURE__ */ new Set();
1097
+ let problem;
1098
+ const next = /* @__PURE__ */ new Map();
1099
+ for (const { key, raw, field } of units) {
1100
+ const cached = cache.current.get(key);
1101
+ const isFresh = cached !== void 0 && cached.raw === raw && cached.basePath === basePath && [...cached.reads].every(([path, value]) => Object.is(dataModel.get(path), value));
1102
+ const resolve = () => {
1103
+ const resolved = (0, _copilotkit_core_generative_ui.tryResolveDynamicValue)(raw, {
1104
+ data: dataModel,
1105
+ basePath
1106
+ }, { isChecks: key === "checks" });
1107
+ const reads = /* @__PURE__ */ new Map();
1108
+ for (const path of resolved.paths) reads.set(path, dataModel.get(path));
1109
+ return {
1110
+ raw,
1111
+ basePath,
1112
+ reads,
1113
+ outcome: resolved.ok ? {
1114
+ ok: true,
1115
+ value: resolved.value
1116
+ } : {
1117
+ ok: false,
1118
+ message: resolved.error.message
1119
+ }
1120
+ };
1121
+ };
1122
+ const entry = isFresh && cached ? cached : resolve();
1123
+ next.set(key, entry);
1124
+ if (field !== void 0) {
1125
+ if (entry.outcome.ok) a11yValues[field] = entry.outcome.value;
1126
+ } else if (entry.outcome.ok) values[key] = entry.outcome.value;
1127
+ else problem ??= `${key}: ${entry.outcome.message}`;
1128
+ for (const path of entry.reads.keys()) paths.add(path);
1129
+ }
1130
+ cache.current = next;
1131
+ const accessibility = (0, _copilotkit_core_generative_ui.readAccessibility)(a11yValues);
1132
+ for (const [key, value] of Object.entries(overrides)) if (!(0, _copilotkit_shared.isPathBinding)(properties[key])) values[key] = value;
1133
+ const rendered = (0, react.useRef)(next);
1134
+ rendered.current = next;
1135
+ const pathKey = [...paths].sort().join("\n");
1136
+ (0, react.useEffect)(() => {
1137
+ const list = pathKey === "" ? [] : pathKey.split("\n");
1138
+ const onChange = () => {
1139
+ cache.current = /* @__PURE__ */ new Map();
1140
+ rerender();
1141
+ };
1142
+ const subscriptions = list.map((path) => dataModel.subscribe(path, onChange));
1143
+ if ([...rendered.current.values()].some((entry) => [...entry.reads].some(([path, value]) => !Object.is(dataModel.get(path), value)))) rerender();
1144
+ return () => subscriptions.forEach((s) => s.unsubscribe());
1145
+ }, [dataModel, pathKey]);
1146
+ const stable = (0, react.useRef)({
1147
+ ok: true,
1148
+ values: {},
1149
+ accessibility: void 0
1150
+ });
1151
+ const result = problem === void 0 ? {
1152
+ ok: true,
1153
+ values,
1154
+ accessibility
1155
+ } : {
1156
+ ok: false,
1157
+ problem
1158
+ };
1159
+ const last = stable.current;
1160
+ 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;
1161
+ return stable.current;
1162
+ }
1163
+ const NO_SELECTION = {
1164
+ ok: true,
1165
+ values: {}
1166
+ };
1167
+ function isSameSelection(a, b) {
1168
+ if (a.ok && b.ok) return shallowEqual(a.values, b.values);
1169
+ if (!a.ok && !b.ok) return a.problem === b.problem;
1170
+ return false;
1171
+ }
1172
+ /** Runs every selector of a node. A selector that throws gives a problem. */
1173
+ function select(definition, state, modelProps) {
1174
+ const values = {};
1175
+ const selectors = Object.entries(definition.selectors);
1176
+ for (const [key, selector] of selectors) try {
1177
+ values[key] = selector(state, modelProps);
1178
+ } catch (error) {
1179
+ const { message } = (0, _copilotkit_shared_generative_ui.toError)(error);
1180
+ return {
1181
+ ok: false,
1182
+ problem: `${key}: selector threw: ${message}`
1183
+ };
1184
+ }
1185
+ return {
1186
+ ok: true,
1187
+ values
1188
+ };
1189
+ }
1190
+ /**
1191
+ * The values of the bound props of a node, read from the app state.
1192
+ *
1193
+ * The selectors get the checked model props: the resolved values that
1194
+ * passed the props schema (without the nulls it rejected), not the
1195
+ * schema's parsed output, so its defaults and transforms are not applied
1196
+ * yet. They run again only when the state object or those props change. When the new values are shallow-equal to the last ones, the
1197
+ * last snapshot is kept. So the node re-renders only when a selected value
1198
+ * changes. A selector that returns a new array on each call cannot cause a
1199
+ * render loop: with the same inputs, the cached snapshot comes back.
1200
+ *
1201
+ * A node without bound props does not subscribe to the state.
1202
+ */
1203
+ function useSelection(manager, definition, modelProps) {
1204
+ const hasSelectors = Object.keys(definition.selectors).length > 0;
1205
+ const cache = (0, react.useRef)(void 0);
1206
+ const getSnapshot = () => {
1207
+ if (!hasSelectors || modelProps === void 0) return NO_SELECTION;
1208
+ const state = manager.getState();
1209
+ const cached = cache.current;
1210
+ if (cached !== void 0 && cached.state === state && cached.modelProps === modelProps) return cached.selection;
1211
+ const next = select(definition, state, modelProps);
1212
+ const selection = cached !== void 0 && isSameSelection(cached.selection, next) ? cached.selection : next;
1213
+ cache.current = {
1214
+ state,
1215
+ modelProps,
1216
+ selection
1217
+ };
1218
+ return selection;
1219
+ };
1220
+ return (0, react.useSyncExternalStore)(hasSelectors ? manager.subscribe : noopSubscribe, getSnapshot, getSnapshot);
1221
+ }
1222
+ /**
1223
+ * Checks the model-set props with the props schema before the selectors run.
1224
+ * The bound props are not set yet, so their issues do not count. Neither do
1225
+ * issues with no path (a check over several props), which the full check
1226
+ * after the selectors reports. The exception is the issue that an async
1227
+ * props schema gives (`isAsyncIssue`): the render checks props
1228
+ * synchronously only, so the full check would fail the same way, and it is
1229
+ * reported here.
1230
+ */
1231
+ function checkModelProps(definition, modelData) {
1232
+ if (!definition.props) return {
1233
+ ok: true,
1234
+ values: {}
1235
+ };
1236
+ let values = modelData;
1237
+ let result = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, values);
1238
+ if (!result.success) {
1239
+ const unset = (0, _copilotkit_shared_generative_ui.withoutRejectedNulls)(values, result.issues);
1240
+ if (unset) {
1241
+ values = unset;
1242
+ result = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, values);
1243
+ }
1244
+ }
1245
+ if (!result.success) {
1246
+ const issues = result.issues.filter((issue) => {
1247
+ const key = (0, _copilotkit_shared_generative_ui.issueKey)(issue);
1248
+ return key === void 0 ? (0, _copilotkit_shared_generative_ui.isAsyncIssue)(issue) : !(0, _copilotkit_shared_generative_ui.hasOwnKey)(definition.selectors, key);
1249
+ });
1250
+ if (issues.length > 0) return {
1251
+ ok: false,
1252
+ problem: (0, _copilotkit_shared_generative_ui.formatIssues)(issues)
1253
+ };
1254
+ }
1255
+ return {
1256
+ ok: true,
1257
+ values
1258
+ };
1259
+ }
1260
+ /**
1261
+ * The data props of a node, in three steps: check the model-set props with
1262
+ * the props schema, run the selectors with them, then parse all props with
1263
+ * the props schema. Gives the reason when a step fails.
1264
+ */
1265
+ function useDataProps(runtime, surface, definition, properties, basePath, overrides) {
1266
+ const modelData = useModelDataProps(surface, definition, properties, basePath, overrides);
1267
+ const modelCheck = (0, react.useMemo)(() => modelData.ok ? checkModelProps(definition, modelData.values) : modelData, [definition, modelData]);
1268
+ const selection = useSelection(runtime.manager, definition, modelCheck.ok ? modelCheck.values : void 0);
1269
+ const accessibility = modelData.ok ? modelData.accessibility : void 0;
1270
+ return (0, react.useMemo)(() => {
1271
+ if (!modelCheck.ok) return modelCheck;
1272
+ if (!selection.ok) return selection;
1273
+ if (!definition.props) return {
1274
+ ok: true,
1275
+ props: {},
1276
+ accessibility
1277
+ };
1278
+ const input = {
1279
+ ...modelCheck.values,
1280
+ ...selection.values
1281
+ };
1282
+ let parsed = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, input);
1283
+ if (!parsed.success) {
1284
+ const unset = (0, _copilotkit_shared_generative_ui.withoutRejectedNulls)(input, parsed.issues);
1285
+ if (unset) parsed = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, unset);
1286
+ }
1287
+ if (!parsed.success) return {
1288
+ ok: false,
1289
+ problem: (0, _copilotkit_shared_generative_ui.formatIssues)(parsed.issues)
1290
+ };
1291
+ return {
1292
+ ok: true,
1293
+ props: parsed.data,
1294
+ accessibility
1295
+ };
1296
+ }, [
1297
+ definition,
1298
+ modelCheck,
1299
+ selection,
1300
+ accessibility
1301
+ ]);
1302
+ }
1303
+ /**
1304
+ * The event props of a node. A matched event (one that matches a declared
1305
+ * function) is always bound. An unmatched event is bound only when the model
1306
+ * bound it.
1307
+ */
1308
+ function useEventProps(runtime, surface, componentId, definition, properties, basePath) {
1309
+ const latest = (0, react.useRef)(properties);
1310
+ latest.current = properties;
1311
+ const boundNames = Object.keys(definition.events ?? {}).filter((name) => (0, _copilotkit_shared_generative_ui.hasOwnKey)(definition.eventFunctions, name) || (0, _copilotkit_shared.isActionBinding)(properties[name])).join("|");
1312
+ return (0, react.useMemo)(() => {
1313
+ const handlers = {};
1314
+ const names = boundNames ? boundNames.split("|") : [];
1315
+ for (const name of names) {
1316
+ const call = {
1317
+ runtime,
1318
+ surface,
1319
+ componentId,
1320
+ name,
1321
+ parameters: definition.events?.[name]?.parameters
1322
+ };
1323
+ const functionName = (0, _copilotkit_shared_generative_ui.hasOwnKey)(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
1324
+ handlers[name] = functionName === void 0 ? (args) => (0, _copilotkit_core_generative_ui.invokeBoundEvent)({
1325
+ ...call,
1326
+ binding: latest.current[name],
1327
+ basePath,
1328
+ args
1329
+ }) : (args) => (0, _copilotkit_core_generative_ui.invokeMatchedEvent)({
1330
+ ...call,
1331
+ functionName,
1332
+ args
1333
+ });
1334
+ }
1335
+ return handlers;
1336
+ }, [
1337
+ boundNames,
1338
+ runtime,
1339
+ surface,
1340
+ componentId,
1341
+ definition,
1342
+ basePath
1343
+ ]);
1344
+ }
1345
+ /**
1346
+ * The setter props of a node: `setValue` for the writable prop `value`. For
1347
+ * a prop the model bound to `{"@path"}`, the setter writes the data model
1348
+ * and makes the path user-owned. For a literal prop, it sets `overrides`, a
1349
+ * local value of this mounted node that wins over the model's value until
1350
+ * the node remounts (see `useModelDataProps`). The setters keep their
1351
+ * identity.
1352
+ */
1353
+ function useSetterProps(runtime, surface, componentId, definition, properties, basePath) {
1354
+ const [overrides, setOverrides] = (0, react.useState)({});
1355
+ const latest = (0, react.useRef)(properties);
1356
+ latest.current = properties;
1357
+ return {
1358
+ overrides,
1359
+ setters: (0, react.useMemo)(() => {
1360
+ const result = {};
1361
+ const writable = definition.writable ?? [];
1362
+ for (const key of writable) result[(0, _copilotkit_shared_generative_ui.setterNameOf)(key)] = (value) => {
1363
+ const binding = latest.current[key];
1364
+ if (!(0, _copilotkit_shared.isPathBinding)(binding)) {
1365
+ setOverrides((current) => ({
1366
+ ...current,
1367
+ [key]: value
1368
+ }));
1369
+ return;
1370
+ }
1371
+ try {
1372
+ runtime.manager.setOwnedValue(surface.key, (0, _copilotkit_core_generative_ui.resolvePath)(binding["@path"], basePath), value);
1373
+ } catch (cause) {
1374
+ const { message } = (0, _copilotkit_shared_generative_ui.toError)(cause);
1375
+ (0, _copilotkit_core_generative_ui.reportErrorSafely)(runtime, {
1376
+ kind: "props",
1377
+ surfaceId: surface.surfaceId,
1378
+ componentId,
1379
+ error: /* @__PURE__ */ new Error(`${(0, _copilotkit_shared_generative_ui.setterNameOf)(key)}: ${message}`)
1380
+ });
1381
+ }
1382
+ };
1383
+ return result;
1384
+ }, [
1385
+ runtime,
1386
+ surface,
1387
+ componentId,
1388
+ definition,
1389
+ basePath
1390
+ ])
1391
+ };
1392
+ }
1393
+ function useSlotProps(surface, definition, properties, componentId, basePath, ancestors, place) {
1394
+ return (0, react.useMemo)(() => {
1395
+ const childAncestors = [...ancestors, scopedId(componentId, basePath)];
1396
+ const slots = {};
1397
+ for (const [name, kind] of Object.entries(definition.slots ?? {})) {
1398
+ const value = properties[name];
1399
+ const via = `${name}:`;
1400
+ if (kind === "single" && typeof value === "string") slots[name] = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
1401
+ surface,
1402
+ componentId: value,
1403
+ basePath,
1404
+ ancestors: childAncestors,
1405
+ parentPlace: place,
1406
+ via
1407
+ });
1408
+ else if (kind === "multiple" && isTemplateChildren(value)) slots[name] = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TemplateChildren, {
1409
+ surface,
1410
+ template: value,
1411
+ basePath,
1412
+ ancestors: childAncestors,
1413
+ parentPlace: place,
1414
+ via
1415
+ });
1416
+ 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, {
1417
+ surface,
1418
+ componentId: id,
1419
+ basePath,
1420
+ ancestors: childAncestors,
1421
+ parentPlace: place,
1422
+ via
1423
+ }, id));
1424
+ }
1425
+ return slots;
1426
+ }, [
1427
+ surface,
1428
+ definition,
1429
+ properties,
1430
+ componentId,
1431
+ basePath,
1432
+ ancestors,
1433
+ place
1434
+ ]);
1435
+ }
1436
+ /**
1437
+ * The parsed data props with every typed child reference (`child()`,
1438
+ * `childList()`, at any depth) replaced by the rendered component. Without
1439
+ * references, the parsed props come back as they are.
1440
+ */
1441
+ function useChildRefProps(surface, refs, props, componentId, basePath, ancestors, place) {
1442
+ return (0, react.useMemo)(() => {
1443
+ if (props === void 0 || refs.length === 0) return props;
1444
+ const childAncestors = [...ancestors, scopedId(componentId, basePath)];
1445
+ const render = (kind, value, via) => {
1446
+ if (kind === "single") return typeof value === "string" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
1447
+ surface,
1448
+ componentId: value,
1449
+ basePath,
1450
+ ancestors: childAncestors,
1451
+ parentPlace: place,
1452
+ via
1453
+ }) : void 0;
1454
+ if (isTemplateChildren(value)) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TemplateChildren, {
1455
+ surface,
1456
+ template: value,
1457
+ basePath,
1458
+ ancestors: childAncestors,
1459
+ parentPlace: place,
1460
+ via
1461
+ });
1462
+ if (!Array.isArray(value)) return void 0;
1463
+ return [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
1464
+ surface,
1465
+ componentId: id,
1466
+ basePath,
1467
+ ancestors: childAncestors,
1468
+ parentPlace: place,
1469
+ via
1470
+ }, id));
1471
+ };
1472
+ let result = props;
1473
+ for (const ref of refs) {
1474
+ let found = 0;
1475
+ const path = ref.path.join(".");
1476
+ result = (0, _copilotkit_shared.mapAtChildRef)(result, ref.path, (value) => render(ref.kind, value, `${path}[${found++}]:`));
1477
+ }
1478
+ return result;
1479
+ }, [
1480
+ surface,
1481
+ refs,
1482
+ props,
1483
+ componentId,
1484
+ basePath,
1485
+ ancestors,
1486
+ place
1487
+ ]);
1488
+ }
1489
+ function ResolvedNode({ surface, componentId, definition, properties, runtime, basePath, ancestors, place }) {
1490
+ const { AccessibilityWrapper } = useGenerativeUIHost();
1491
+ const { overrides, setters } = useSetterProps(runtime, surface, componentId, definition, properties, basePath);
1492
+ const dataProps = useDataProps(runtime, surface, definition, properties, basePath, overrides);
1493
+ const eventProps = useEventProps(runtime, surface, componentId, definition, properties, basePath);
1494
+ const slotProps = useSlotProps(surface, definition, properties, componentId, basePath, ancestors, place);
1495
+ const childRefProps = useChildRefProps(surface, definition.childRefs, dataProps.ok ? dataProps.props : void 0, componentId, basePath, ancestors, place);
1496
+ const accessibility = dataProps.ok ? dataProps.accessibility : void 0;
1497
+ const nodeContext = (0, react.useMemo)(() => ({
1498
+ surfaceKey: surface.key,
1499
+ surfaceId: surface.surfaceId,
1500
+ componentId,
1501
+ accessibility
1502
+ }), [
1503
+ surface.key,
1504
+ surface.surfaceId,
1505
+ componentId,
1506
+ accessibility
1507
+ ]);
1508
+ const problem = dataProps.ok ? void 0 : dataProps.problem;
1509
+ const log = useFailureLog();
1510
+ (0, react.useEffect)(() => {
1511
+ if (!problem) {
1512
+ log.clear(failureSlots.fallback(place));
1513
+ log.clear(failureSlots.props(place));
1514
+ }
1515
+ }, [
1516
+ problem,
1517
+ log,
1518
+ place
1519
+ ]);
1520
+ (0, react.useEffect)(() => {
1521
+ if (problem) log.report(runtime, failureSlots.props(place), {
1522
+ kind: "props",
1523
+ surfaceId: surface.surfaceId,
1524
+ componentId,
1525
+ error: /* @__PURE__ */ new Error(`Invalid props: ${problem}`)
1526
+ });
1527
+ }, [
1528
+ problem,
1529
+ log,
1530
+ place,
1531
+ runtime,
1532
+ surface.surfaceId,
1533
+ componentId
1534
+ ]);
1535
+ if (!dataProps.ok) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GuardedNodeFallback, {
1536
+ surfaceId: surface.surfaceId,
1537
+ componentId,
1538
+ runtime,
1539
+ message: `invalid props (${problem})`,
1540
+ slot: failureSlots.fallback(place),
1541
+ revision: properties
1542
+ });
1543
+ const Component = definition.component;
1544
+ const rendered = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Component, {
1545
+ ...childRefProps,
1546
+ ...eventProps,
1547
+ ...slotProps,
1548
+ ...setters
1549
+ });
1550
+ const hasEnvelope = properties.accessibility !== void 0 && definition.accessibility !== "self";
1551
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GenerativeUINodeContext.Provider, {
1552
+ value: nodeContext,
1553
+ children: hasEnvelope ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(AccessibilityWrapper, {
1554
+ attributes: (0, _copilotkit_core_generative_ui.wrapperAria)((0, _copilotkit_core_generative_ui.accessibilityAttributes)(accessibility)),
1555
+ children: rendered
1556
+ }) : rendered
1557
+ });
1558
+ }
1559
+
1560
+ //#endregion
1561
+ //#region src/generative-ui/chat.tsx
1562
+ const GenerativeUIChatSlotContext = (0, react.createContext)(void 0);
1563
+ function DefaultGenerativeUIChatCard({ surfaceId, error, children }) {
1564
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1565
+ "data-generative-ui-chat-surface": surfaceId,
1566
+ className: "cpk-generative-ui-chat-card",
1567
+ children: [children, error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1568
+ role: "alert",
1569
+ className: "cpk-generative-ui-chat-card-error",
1570
+ children: "Part of this UI couldn't be shown."
1571
+ })]
1572
+ });
1573
+ }
1574
+ function GenerativeUIChatActivity({ content, agent }) {
1575
+ const runtime = useGenerativeUIRuntime();
1576
+ const threadId = useCopilotChatConfiguration()?.threadId ?? agent?.threadId;
1577
+ const Wrapper = (0, react.useContext)(GenerativeUIChatSlotContext) ?? DefaultGenerativeUIChatCard;
1578
+ const { surface, rejected, error } = useGenerativeUIActivitySurface({
1579
+ runtime,
1580
+ threadId,
1581
+ agentId: agent?.agentId,
1582
+ content,
1583
+ target: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET
1584
+ });
1585
+ if (!surface) return null;
1586
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Wrapper, {
1587
+ surfaceId: content.surfaceId,
1588
+ isStreaming: content.status === "streaming",
1589
+ error,
1590
+ rejected,
1591
+ children: surface.failed ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceView, { surface })
1592
+ });
1593
+ }
1594
+ function createGenerativeUIActivityRenderer() {
1595
+ return {
1596
+ activityType: _copilotkit_shared.GENERATIVE_UI_ACTIVITY_TYPE,
1597
+ content: _copilotkit_core_generative_ui.GenerativeUISurfaceContentSchema,
1598
+ render: GenerativeUIChatActivity
1599
+ };
1600
+ }
1601
+ /**
1602
+ * Shows nothing in the chat for an agent-called function. The root reads the
1603
+ * function-call activities from the messages and runs them. This renderer
1604
+ * only keeps a wildcard ("*") activity renderer from showing them.
1605
+ */
1606
+ function createGenerativeUIFunctionCallActivityRenderer() {
1607
+ return {
1608
+ activityType: _copilotkit_shared.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,
1609
+ content: zod.unknown(),
1610
+ render: () => null
1611
+ };
1612
+ }
1613
+ /** Hides the raw `render_ui` tool call; the surface activity owns the UX. */
1614
+ function GenerativeUIToolCallRenderer() {
1615
+ const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
1616
+ (0, react.useEffect)(() => {
1617
+ const renderer = defineToolCallRenderer({
1618
+ name: _copilotkit_shared.GENERATIVE_UI_RENDER_TOOL,
1619
+ args: zod.any(),
1620
+ render: () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {})
1621
+ });
1622
+ return copilotkit.ɵaddBuiltInRenderToolCall(renderer);
1623
+ }, [copilotkit]);
1624
+ return null;
1625
+ }
1626
+
1627
+ //#endregion
1628
+ Object.defineProperty(exports, 'ControlledModalOpenScope', {
1629
+ enumerable: true,
1630
+ get: function () {
1631
+ return ControlledModalOpenScope;
1632
+ }
1633
+ });
1634
+ Object.defineProperty(exports, 'CopilotChatConfigurationProvider', {
1635
+ enumerable: true,
1636
+ get: function () {
1637
+ return CopilotChatConfigurationProvider;
1638
+ }
1639
+ });
1640
+ Object.defineProperty(exports, 'DefaultGenerativeUIChatCard', {
1641
+ enumerable: true,
1642
+ get: function () {
1643
+ return DefaultGenerativeUIChatCard;
1644
+ }
1645
+ });
1646
+ Object.defineProperty(exports, 'GenerativeUIChatSlotContext', {
1647
+ enumerable: true,
1648
+ get: function () {
1649
+ return GenerativeUIChatSlotContext;
1650
+ }
1651
+ });
1652
+ Object.defineProperty(exports, 'GenerativeUIHostContext', {
1653
+ enumerable: true,
1654
+ get: function () {
1655
+ return GenerativeUIHostContext;
1656
+ }
1657
+ });
1658
+ Object.defineProperty(exports, 'GenerativeUINodeContext', {
1659
+ enumerable: true,
1660
+ get: function () {
1661
+ return GenerativeUINodeContext;
1662
+ }
1663
+ });
1664
+ Object.defineProperty(exports, 'GenerativeUIRuntimeContext', {
1665
+ enumerable: true,
1666
+ get: function () {
1667
+ return GenerativeUIRuntimeContext;
1668
+ }
1669
+ });
1670
+ Object.defineProperty(exports, 'GenerativeUIToolCallRenderer', {
1671
+ enumerable: true,
1672
+ get: function () {
1673
+ return GenerativeUIToolCallRenderer;
1674
+ }
1675
+ });
1676
+ Object.defineProperty(exports, 'SurfaceView', {
1677
+ enumerable: true,
1678
+ get: function () {
1679
+ return SurfaceView;
1680
+ }
1681
+ });
1682
+ Object.defineProperty(exports, '__toESM', {
1683
+ enumerable: true,
1684
+ get: function () {
1685
+ return __toESM;
1686
+ }
1687
+ });
1688
+ Object.defineProperty(exports, 'createGenerativeUI', {
1689
+ enumerable: true,
1690
+ get: function () {
1691
+ return createGenerativeUI;
1692
+ }
1693
+ });
1694
+ Object.defineProperty(exports, 'createGenerativeUIActivityRenderer', {
1695
+ enumerable: true,
1696
+ get: function () {
1697
+ return createGenerativeUIActivityRenderer;
1698
+ }
1699
+ });
1700
+ Object.defineProperty(exports, 'createGenerativeUIFunctionCallActivityRenderer', {
1701
+ enumerable: true,
1702
+ get: function () {
1703
+ return createGenerativeUIFunctionCallActivityRenderer;
1704
+ }
1705
+ });
1706
+ Object.defineProperty(exports, 'defineToolCallRenderer', {
1707
+ enumerable: true,
1708
+ get: function () {
1709
+ return defineToolCallRenderer;
1710
+ }
1711
+ });
1712
+ Object.defineProperty(exports, 'shallowEqual', {
1713
+ enumerable: true,
1714
+ get: function () {
1715
+ return shallowEqual;
1716
+ }
1717
+ });
1718
+ Object.defineProperty(exports, 'useCopilotChatConfiguration', {
1719
+ enumerable: true,
1720
+ get: function () {
1721
+ return useCopilotChatConfiguration;
1722
+ }
1723
+ });
1724
+ Object.defineProperty(exports, 'useGenerativeUIAccessibility', {
1725
+ enumerable: true,
1726
+ get: function () {
1727
+ return useGenerativeUIAccessibility;
1728
+ }
1729
+ });
1730
+ Object.defineProperty(exports, 'useGenerativeUIActivitySurface', {
1731
+ enumerable: true,
1732
+ get: function () {
1733
+ return useGenerativeUIActivitySurface;
1734
+ }
1735
+ });
1736
+ Object.defineProperty(exports, 'useGenerativeUIFunction', {
1737
+ enumerable: true,
1738
+ get: function () {
1739
+ return useGenerativeUIFunction;
1740
+ }
1741
+ });
1742
+ Object.defineProperty(exports, 'useGenerativeUIHost', {
1743
+ enumerable: true,
1744
+ get: function () {
1745
+ return useGenerativeUIHost;
1746
+ }
1747
+ });
1748
+ Object.defineProperty(exports, 'useGenerativeUIRejected', {
1749
+ enumerable: true,
1750
+ get: function () {
1751
+ return useGenerativeUIRejected;
1752
+ }
1753
+ });
1754
+ Object.defineProperty(exports, 'useGenerativeUIRuntime', {
1755
+ enumerable: true,
1756
+ get: function () {
1757
+ return useGenerativeUIRuntime;
1758
+ }
1759
+ });
1760
+ Object.defineProperty(exports, 'useGenerativeUIState', {
1761
+ enumerable: true,
1762
+ get: function () {
1763
+ return useGenerativeUIState;
1764
+ }
1765
+ });
1766
+ Object.defineProperty(exports, 'useManagerVersion', {
1767
+ enumerable: true,
1768
+ get: function () {
1769
+ return useManagerVersion;
1770
+ }
1771
+ });
1772
+ Object.defineProperty(exports, 'useRequiredGenerativeUIRuntime', {
1773
+ enumerable: true,
1774
+ get: function () {
1775
+ return useRequiredGenerativeUIRuntime;
1776
+ }
1777
+ });
1778
+ Object.defineProperty(exports, 'useShallowStableRef', {
1779
+ enumerable: true,
1780
+ get: function () {
1781
+ return useShallowStableRef;
1782
+ }
1783
+ });
1784
+ //# sourceMappingURL=chat-D3fxo6Ah.cjs.map