@copilotkit/react-core 1.84.2-canary.1793809041 → 1.84.2-canary.openbot-intel-fixes

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