@copilotkit/react-core 2.0.0-rc.6 → 2.0.0-rc.60

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