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