@copilotkit/core 1.84.2-canary.1793809041 → 1.84.2-canary.openbot-intel-fixes
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/a2ui-markdown-BxZr1mEU.mjs +1360 -0
- package/dist/a2ui-markdown-BxZr1mEU.mjs.map +1 -0
- package/dist/a2ui-markdown-DkMXFQih.cjs +1419 -0
- package/dist/a2ui-markdown-DkMXFQih.cjs.map +1 -0
- package/dist/generative-ui/index.cjs +3121 -0
- package/dist/generative-ui/index.cjs.map +1 -0
- package/dist/generative-ui/index.d.cts +974 -0
- package/dist/generative-ui/index.d.cts.map +1 -0
- package/dist/generative-ui/index.d.mts +974 -0
- package/dist/generative-ui/index.d.mts.map +1 -0
- package/dist/generative-ui/index.mjs +3075 -0
- package/dist/generative-ui/index.mjs.map +1 -0
- package/dist/index-BC1dzn_F.d.mts +3886 -0
- package/dist/index-BC1dzn_F.d.mts.map +1 -0
- package/dist/index-wj1XowZI.d.cts +3886 -0
- package/dist/index-wj1XowZI.d.cts.map +1 -0
- package/dist/index.cjs +56 -1444
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -3902
- package/dist/index.d.mts +2 -3902
- package/dist/index.mjs +48 -1435
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +41 -81
- package/dist/index.umd.js.map +1 -1
- package/package.json +14 -6
- package/tsdown.config.ts +5 -1
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.mts.map +0 -1
|
@@ -0,0 +1,3121 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_a2ui_markdown = require('../a2ui-markdown-DkMXFQih.cjs');
|
|
3
|
+
let _copilotkit_shared = require("@copilotkit/shared");
|
|
4
|
+
let _copilotkit_shared_generative_ui = require("@copilotkit/shared/generative-ui");
|
|
5
|
+
let _a2ui_web_core_v0_9 = require("@a2ui/web_core/v0_9");
|
|
6
|
+
let zod = require("zod");
|
|
7
|
+
|
|
8
|
+
//#region src/generative-ui/runtime.ts
|
|
9
|
+
/**
|
|
10
|
+
* Reports an error without ever throwing: `reportError` reaches host code
|
|
11
|
+
* (`onError`), and a throwing host callback must not break rendering or an
|
|
12
|
+
* event handler.
|
|
13
|
+
*/
|
|
14
|
+
function reportErrorSafely(engine, info) {
|
|
15
|
+
try {
|
|
16
|
+
engine.reportError(info);
|
|
17
|
+
} catch {}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/generative-ui/functions.ts
|
|
22
|
+
/**
|
|
23
|
+
* The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes
|
|
24
|
+
* resolved args (no bindings left in them) and gives a plain value. They
|
|
25
|
+
* run synchronously, so a prop bound to one updates in the same render as
|
|
26
|
+
* the data it reads. The signatures the model sees are in
|
|
27
|
+
* `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).
|
|
28
|
+
*/
|
|
29
|
+
/** Thrown for a bad call: an unknown function, bad args, or a bad value. */
|
|
30
|
+
var ExpressionError = class extends Error {
|
|
31
|
+
constructor(message) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "ExpressionError";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
/** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */
|
|
37
|
+
function truthOf(value) {
|
|
38
|
+
if ((0, _copilotkit_shared.isValidationResult)(value)) return value.valid;
|
|
39
|
+
return Boolean(value);
|
|
40
|
+
}
|
|
41
|
+
const valid = () => ({ valid: true });
|
|
42
|
+
/** A failed result. `code` names the failure, the same for every locale. */
|
|
43
|
+
const invalid = (message, code) => ({
|
|
44
|
+
valid: false,
|
|
45
|
+
message,
|
|
46
|
+
code
|
|
47
|
+
});
|
|
48
|
+
function text(value) {
|
|
49
|
+
if (value === void 0 || value === null) return "";
|
|
50
|
+
return typeof value === "string" ? value : String(value);
|
|
51
|
+
}
|
|
52
|
+
function numberOf$1(value) {
|
|
53
|
+
if (typeof value === "number") return value;
|
|
54
|
+
if (typeof value === "string" && value.trim() !== "") return Number(value);
|
|
55
|
+
return NaN;
|
|
56
|
+
}
|
|
57
|
+
function optionalNumber(value, name) {
|
|
58
|
+
if (value === void 0 || value === null) return void 0;
|
|
59
|
+
const parsed = numberOf$1(value);
|
|
60
|
+
if (Number.isNaN(parsed)) throw new ExpressionError(`${name} must be a number`);
|
|
61
|
+
return parsed;
|
|
62
|
+
}
|
|
63
|
+
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
64
|
+
/** The locale of the user. `undefined` lets Intl pick the default. */
|
|
65
|
+
function locale() {
|
|
66
|
+
return typeof navigator !== "undefined" ? navigator.language : void 0;
|
|
67
|
+
}
|
|
68
|
+
function numberFormat(args, options) {
|
|
69
|
+
const decimals = optionalNumber(args.decimals, "decimals");
|
|
70
|
+
return new Intl.NumberFormat(locale(), {
|
|
71
|
+
...options,
|
|
72
|
+
useGrouping: args.grouping !== false,
|
|
73
|
+
...decimals === void 0 ? {} : {
|
|
74
|
+
minimumFractionDigits: decimals,
|
|
75
|
+
maximumFractionDigits: decimals
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/** A date from an ISO string, a timestamp, or a Date. */
|
|
80
|
+
function dateOf(value) {
|
|
81
|
+
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;
|
|
82
|
+
if (date === void 0 || Number.isNaN(date.getTime())) throw new ExpressionError("value must be a date");
|
|
83
|
+
return date;
|
|
84
|
+
}
|
|
85
|
+
const pad = (value, width) => String(value).padStart(width, "0");
|
|
86
|
+
/**
|
|
87
|
+
* A TR35 field is a run of one letter ("EEE" is one abbreviated weekday,
|
|
88
|
+
* not three), and text in single quotes is literal. Letters that are not
|
|
89
|
+
* fields stay as they are.
|
|
90
|
+
*/
|
|
91
|
+
const DATE_FIELD = /([A-Za-z])\1*|'(?:[^']|'')*'/g;
|
|
92
|
+
function formatDatePattern(date, pattern) {
|
|
93
|
+
const parts = (options) => new Intl.DateTimeFormat(locale(), options).format(date);
|
|
94
|
+
const hours12 = date.getHours() % 12 || 12;
|
|
95
|
+
const numeric = (value, width) => width >= 2 ? pad(value, 2) : String(value);
|
|
96
|
+
return pattern.replace(DATE_FIELD, (token) => {
|
|
97
|
+
if (token.startsWith("'")) return token.slice(1, -1).replace(/''/g, "'");
|
|
98
|
+
const width = token.length;
|
|
99
|
+
switch (token[0]) {
|
|
100
|
+
case "y": return width === 2 ? pad(date.getFullYear() % 100, 2) : String(date.getFullYear());
|
|
101
|
+
case "M":
|
|
102
|
+
if (width >= 4) return parts({ month: "long" });
|
|
103
|
+
if (width === 3) return parts({ month: "short" });
|
|
104
|
+
return numeric(date.getMonth() + 1, width);
|
|
105
|
+
case "d": return numeric(date.getDate(), width);
|
|
106
|
+
case "E": return parts({ weekday: width >= 4 ? "long" : "short" });
|
|
107
|
+
case "H": return numeric(date.getHours(), width);
|
|
108
|
+
case "h": return numeric(hours12, width);
|
|
109
|
+
case "m": return pad(date.getMinutes(), 2);
|
|
110
|
+
case "s": return pad(date.getSeconds(), 2);
|
|
111
|
+
case "a": return date.getHours() < 12 ? "AM" : "PM";
|
|
112
|
+
default: return token;
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/** Opens an http(s) URL in a new tab. Any other scheme is refused. */
|
|
117
|
+
function openUrlSafely(url) {
|
|
118
|
+
if (typeof url !== "string" || url === "") throw new ExpressionError("url must be a string");
|
|
119
|
+
if (typeof window === "undefined") return;
|
|
120
|
+
let parsed;
|
|
121
|
+
try {
|
|
122
|
+
parsed = new URL(url, window.location.href);
|
|
123
|
+
} catch {
|
|
124
|
+
throw new ExpressionError(`"${url}" is not a URL`);
|
|
125
|
+
}
|
|
126
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new ExpressionError(`openUrl takes only http(s) URLs, not ${parsed.protocol}`);
|
|
127
|
+
window.open(parsed.href, "_blank", "noopener,noreferrer");
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* The basic functions, except `formatString`, which needs the resolver.
|
|
131
|
+
* `calc` and `series` are added by `resolve.ts`, which imports both.
|
|
132
|
+
*/
|
|
133
|
+
const BASIC_FUNCTIONS = {
|
|
134
|
+
required: ({ value }) => {
|
|
135
|
+
return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0 ? invalid("Required", "required") : valid();
|
|
136
|
+
},
|
|
137
|
+
regex: ({ value, pattern }) => {
|
|
138
|
+
if (typeof pattern !== "string") throw new ExpressionError("pattern must be a string");
|
|
139
|
+
let expression;
|
|
140
|
+
try {
|
|
141
|
+
expression = new RegExp(pattern, "u");
|
|
142
|
+
} catch {
|
|
143
|
+
throw new ExpressionError(`"${pattern}" is not a regular expression`);
|
|
144
|
+
}
|
|
145
|
+
return expression.test(text(value)) ? valid() : invalid("Invalid format", "pattern");
|
|
146
|
+
},
|
|
147
|
+
length: ({ value, min, max }) => {
|
|
148
|
+
const size = text(value).length;
|
|
149
|
+
const low = optionalNumber(min, "min");
|
|
150
|
+
const high = optionalNumber(max, "max");
|
|
151
|
+
if (low !== void 0 && size < low) return invalid(`At least ${low} characters`, "tooShort");
|
|
152
|
+
if (high !== void 0 && size > high) return invalid(`At most ${high} characters`, "tooLong");
|
|
153
|
+
return valid();
|
|
154
|
+
},
|
|
155
|
+
numeric: ({ value, min, max }) => {
|
|
156
|
+
const parsed = numberOf$1(value);
|
|
157
|
+
if (Number.isNaN(parsed)) return invalid("Must be a number", "notANumber");
|
|
158
|
+
const low = optionalNumber(min, "min");
|
|
159
|
+
const high = optionalNumber(max, "max");
|
|
160
|
+
if (low !== void 0 && parsed < low) return invalid(`At least ${low}`, "tooSmall");
|
|
161
|
+
if (high !== void 0 && parsed > high) return invalid(`At most ${high}`, "tooLarge");
|
|
162
|
+
return valid();
|
|
163
|
+
},
|
|
164
|
+
email: ({ value }) => EMAIL.test(text(value)) ? valid() : invalid("Invalid email address", "email"),
|
|
165
|
+
formatNumber: (args) => {
|
|
166
|
+
const parsed = numberOf$1(args.value);
|
|
167
|
+
if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
|
|
168
|
+
return numberFormat(args, {}).format(parsed);
|
|
169
|
+
},
|
|
170
|
+
formatCurrency: (args) => {
|
|
171
|
+
const parsed = numberOf$1(args.value);
|
|
172
|
+
if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
|
|
173
|
+
if (typeof args.currency !== "string" || args.currency === "") throw new ExpressionError("currency must be an ISO 4217 code");
|
|
174
|
+
try {
|
|
175
|
+
return numberFormat(args, {
|
|
176
|
+
style: "currency",
|
|
177
|
+
currency: args.currency
|
|
178
|
+
}).format(parsed);
|
|
179
|
+
} catch {
|
|
180
|
+
throw new ExpressionError(`"${args.currency}" is not a currency code`);
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
formatDate: ({ value, format }) => {
|
|
184
|
+
if (typeof format !== "string") throw new ExpressionError("format must be a string");
|
|
185
|
+
return formatDatePattern(dateOf(value), format);
|
|
186
|
+
},
|
|
187
|
+
pluralize: (args) => {
|
|
188
|
+
const parsed = numberOf$1(args.value);
|
|
189
|
+
if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
|
|
190
|
+
const category = new Intl.PluralRules(locale()).select(parsed);
|
|
191
|
+
return text((parsed === 0 ? args.zero : void 0) ?? args[category] ?? args.other);
|
|
192
|
+
},
|
|
193
|
+
and: ({ values }) => {
|
|
194
|
+
if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
|
|
195
|
+
return values.every(truthOf);
|
|
196
|
+
},
|
|
197
|
+
or: ({ values }) => {
|
|
198
|
+
if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
|
|
199
|
+
return values.some(truthOf);
|
|
200
|
+
},
|
|
201
|
+
not: ({ value }) => !truthOf(value),
|
|
202
|
+
openUrl: ({ url }) => {
|
|
203
|
+
openUrlSafely(url);
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
/** True when the basic function `name` must run from a user gesture. */
|
|
207
|
+
function requiresUserActivation(name) {
|
|
208
|
+
return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.requiresUserActivation === true;
|
|
209
|
+
}
|
|
210
|
+
/** True when a basic function gives a ValidationResult. */
|
|
211
|
+
function givesValidationResult(name) {
|
|
212
|
+
return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.returnType === "validationResult";
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
//#endregion
|
|
216
|
+
//#region src/generative-ui/function-calls.ts
|
|
217
|
+
/** At most this many function follow-up runs for each user turn. */
|
|
218
|
+
const MAX_FUNCTION_FOLLOW_UPS = 5;
|
|
219
|
+
/** True when `value` names a `functionCallId`. */
|
|
220
|
+
function hasFunctionCallId(value) {
|
|
221
|
+
return typeof value === "object" && value !== null && "functionCallId" in value && typeof value.functionCallId === "string" && value.functionCallId !== "";
|
|
222
|
+
}
|
|
223
|
+
/** The `functionCallId` that a developer message answers, if any. */
|
|
224
|
+
function answeredCallId(content) {
|
|
225
|
+
if (!content.includes("rendererFunctionResponse")) return void 0;
|
|
226
|
+
try {
|
|
227
|
+
const parsed = JSON.parse(content);
|
|
228
|
+
const response = typeof parsed === "object" && parsed !== null && "rendererFunctionResponse" in parsed ? parsed.rendererFunctionResponse : void 0;
|
|
229
|
+
return hasFunctionCallId(response) ? response.functionCallId : void 0;
|
|
230
|
+
} catch {
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/** The function calls that a developer message in `messages` answers. */
|
|
235
|
+
function answeredCallIds(messages) {
|
|
236
|
+
const ids = /* @__PURE__ */ new Set();
|
|
237
|
+
for (const message of messages) {
|
|
238
|
+
if (message.role !== "developer") continue;
|
|
239
|
+
const id = answeredCallId(message.content);
|
|
240
|
+
if (id !== void 0) ids.add(id);
|
|
241
|
+
}
|
|
242
|
+
return ids;
|
|
243
|
+
}
|
|
244
|
+
/** The id of the last user message. A user turn starts with it. */
|
|
245
|
+
function lastUserMessageId(messages) {
|
|
246
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
247
|
+
const message = messages[index];
|
|
248
|
+
if (message?.role === "user") return message.id;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/** The function calls of the tool transport: its function-call activities. */
|
|
252
|
+
function activityFunctionCalls(messages) {
|
|
253
|
+
const requests = [];
|
|
254
|
+
for (const message of messages) {
|
|
255
|
+
if (!(message.role === "activity" && message.activityType === _copilotkit_shared.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE) || !hasFunctionCallId(message.content)) continue;
|
|
256
|
+
requests.push({
|
|
257
|
+
functionCallId: message.content.functionCallId,
|
|
258
|
+
operation: {
|
|
259
|
+
version: _copilotkit_shared.A2UI_VERSION,
|
|
260
|
+
callRendererFunction: message.content
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
return requests;
|
|
265
|
+
}
|
|
266
|
+
/** The function calls of the markdown transport: its fence lines. */
|
|
267
|
+
function markdownFunctionCalls(calls) {
|
|
268
|
+
const requests = [];
|
|
269
|
+
for (const { operation } of calls) {
|
|
270
|
+
const payload = operation.callRendererFunction;
|
|
271
|
+
if (!hasFunctionCallId(payload)) continue;
|
|
272
|
+
requests.push({
|
|
273
|
+
functionCallId: payload.functionCallId,
|
|
274
|
+
operation
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
return requests;
|
|
278
|
+
}
|
|
279
|
+
/** The text of a `rendererFunctionResponse` developer message. */
|
|
280
|
+
function responseContent(response) {
|
|
281
|
+
return JSON.stringify({
|
|
282
|
+
version: _copilotkit_shared.A2UI_VERSION,
|
|
283
|
+
rendererFunctionResponse: response
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
function errorAnswer(functionCallId, code, message) {
|
|
287
|
+
return {
|
|
288
|
+
content: responseContent({
|
|
289
|
+
functionCallId,
|
|
290
|
+
error: {
|
|
291
|
+
code,
|
|
292
|
+
message
|
|
293
|
+
}
|
|
294
|
+
}),
|
|
295
|
+
followUp: true
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
const overCapAnswer = (functionCallId) => ({
|
|
299
|
+
content: responseContent({
|
|
300
|
+
functionCallId,
|
|
301
|
+
error: {
|
|
302
|
+
code: "follow_up_limit",
|
|
303
|
+
message: `The function did not run. A user turn can have at most ${MAX_FUNCTION_FOLLOW_UPS} function follow-up runs. Wait for the next user message.`
|
|
304
|
+
}
|
|
305
|
+
}),
|
|
306
|
+
followUp: false
|
|
307
|
+
});
|
|
308
|
+
/**
|
|
309
|
+
* Runs the functions that the agent calls with `callRendererFunction`, for
|
|
310
|
+
* both transports, and answers each call.
|
|
311
|
+
*
|
|
312
|
+
* - Each `functionCallId` runs once for each thread. A replay, a sync of
|
|
313
|
+
* the same messages again, or a call that already has an answer message
|
|
314
|
+
* does not run it again.
|
|
315
|
+
* - The answer is a hidden developer message with a `rendererFunctionResponse`.
|
|
316
|
+
* The answers go to the agent only when it is not running. Then one
|
|
317
|
+
* follow-up run starts for all of them.
|
|
318
|
+
* - A user turn has at most {@link MAX_FUNCTION_FOLLOW_UPS} follow-up runs.
|
|
319
|
+
* A call after that does not run. It gets a `follow_up_limit` error and
|
|
320
|
+
* starts no follow-up run.
|
|
321
|
+
*/
|
|
322
|
+
function createFunctionCallRunner(options) {
|
|
323
|
+
const { core, dispatcher, manifest, settle, warn } = options;
|
|
324
|
+
const threads = /* @__PURE__ */ new Map();
|
|
325
|
+
const threadState = (threadId) => {
|
|
326
|
+
let state = threads.get(threadId);
|
|
327
|
+
if (!state) {
|
|
328
|
+
state = {
|
|
329
|
+
done: /* @__PURE__ */ new Set(),
|
|
330
|
+
pending: [],
|
|
331
|
+
turn: void 0,
|
|
332
|
+
followUps: 0,
|
|
333
|
+
flushing: false
|
|
334
|
+
};
|
|
335
|
+
threads.set(threadId, state);
|
|
336
|
+
}
|
|
337
|
+
return state;
|
|
338
|
+
};
|
|
339
|
+
const answer = async (request) => {
|
|
340
|
+
const { functionCallId } = request;
|
|
341
|
+
const validation = (0, _copilotkit_shared.validateOperation)(request.operation, {
|
|
342
|
+
manifest,
|
|
343
|
+
knownSurfaces: /* @__PURE__ */ new Set()
|
|
344
|
+
});
|
|
345
|
+
if (!validation.ok) return errorAnswer(functionCallId, "invalid_arguments", validation.reason);
|
|
346
|
+
const operation = request.operation;
|
|
347
|
+
if (!("callRendererFunction" in operation)) return errorAnswer(functionCallId, "invalid_arguments", "the operation is not a callRendererFunction");
|
|
348
|
+
const { callFunction } = operation.callRendererFunction;
|
|
349
|
+
const name = callFunction["@call"];
|
|
350
|
+
const result = await dispatcher.invoke(name, callFunction.args ?? {}, { functionCallId });
|
|
351
|
+
if (!result.ok) return errorAnswer(functionCallId, result.error.code, result.error.message);
|
|
352
|
+
try {
|
|
353
|
+
return {
|
|
354
|
+
content: responseContent({
|
|
355
|
+
functionCallId,
|
|
356
|
+
value: result.result ?? null
|
|
357
|
+
}),
|
|
358
|
+
followUp: true
|
|
359
|
+
};
|
|
360
|
+
} catch (cause) {
|
|
361
|
+
return errorAnswer(functionCallId, "handler_failed", `The result of "${name}" is not JSON: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
/**
|
|
365
|
+
* Adds the pending answers of a thread to the agent, then starts one
|
|
366
|
+
* follow-up run. It waits while the agent runs: the next read of the
|
|
367
|
+
* thread, at the end of the run, flushes again.
|
|
368
|
+
*/
|
|
369
|
+
const flush = async (agent, threadId, state) => {
|
|
370
|
+
if (state.flushing) return;
|
|
371
|
+
state.flushing = true;
|
|
372
|
+
try {
|
|
373
|
+
while (state.pending.length > 0) {
|
|
374
|
+
const batch = [...state.pending];
|
|
375
|
+
const answers = await Promise.all(batch);
|
|
376
|
+
await settle();
|
|
377
|
+
if (agent.isRunning || agent.threadId !== threadId) return;
|
|
378
|
+
if (state.pending.length > batch.length) continue;
|
|
379
|
+
state.pending = [];
|
|
380
|
+
for (const { content } of answers) agent.addMessage({
|
|
381
|
+
id: (0, _copilotkit_shared.randomUUID)(),
|
|
382
|
+
role: "developer",
|
|
383
|
+
content
|
|
384
|
+
});
|
|
385
|
+
if (!answers.some((item) => item.followUp)) continue;
|
|
386
|
+
state.followUps++;
|
|
387
|
+
await core.runAgent({ agent });
|
|
388
|
+
}
|
|
389
|
+
} catch (error) {
|
|
390
|
+
warn("[generativeUI] function follow-up run failed:", error);
|
|
391
|
+
} finally {
|
|
392
|
+
state.flushing = false;
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
return { run(agent, requests, messages, running) {
|
|
396
|
+
const { threadId } = agent;
|
|
397
|
+
if (!threadId) return;
|
|
398
|
+
const state = threadState(threadId);
|
|
399
|
+
const turn = lastUserMessageId(messages);
|
|
400
|
+
if (turn !== state.turn) {
|
|
401
|
+
state.turn = turn;
|
|
402
|
+
state.followUps = 0;
|
|
403
|
+
}
|
|
404
|
+
const fresh = requests.filter((request) => !state.done.has(request.functionCallId));
|
|
405
|
+
const answered = fresh.length > 0 ? answeredCallIds(messages) : /* @__PURE__ */ new Set();
|
|
406
|
+
for (const request of fresh) {
|
|
407
|
+
const { functionCallId } = request;
|
|
408
|
+
if (state.done.has(functionCallId)) continue;
|
|
409
|
+
state.done.add(functionCallId);
|
|
410
|
+
if (answered.has(functionCallId)) continue;
|
|
411
|
+
const isOverCap = state.followUps >= MAX_FUNCTION_FOLLOW_UPS;
|
|
412
|
+
state.pending.push(isOverCap ? Promise.resolve(overCapAnswer(functionCallId)) : answer(request));
|
|
413
|
+
}
|
|
414
|
+
if (!running) flush(agent, threadId, state);
|
|
415
|
+
} };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
//#endregion
|
|
419
|
+
//#region src/generative-ui/calc.ts
|
|
420
|
+
const MAX_SERIES = 1e3;
|
|
421
|
+
const OPERATORS = [
|
|
422
|
+
"&&",
|
|
423
|
+
"||",
|
|
424
|
+
"==",
|
|
425
|
+
"!=",
|
|
426
|
+
"<=",
|
|
427
|
+
">=",
|
|
428
|
+
"<",
|
|
429
|
+
">",
|
|
430
|
+
"+",
|
|
431
|
+
"-",
|
|
432
|
+
"*",
|
|
433
|
+
"/",
|
|
434
|
+
"%",
|
|
435
|
+
"^",
|
|
436
|
+
"(",
|
|
437
|
+
")",
|
|
438
|
+
",",
|
|
439
|
+
"?",
|
|
440
|
+
":",
|
|
441
|
+
"!"
|
|
442
|
+
];
|
|
443
|
+
function tokenize(source) {
|
|
444
|
+
const tokens = [];
|
|
445
|
+
let i = 0;
|
|
446
|
+
while (i < source.length) {
|
|
447
|
+
const char = source.charAt(i);
|
|
448
|
+
if (/\s/.test(char)) {
|
|
449
|
+
i++;
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
if (/[0-9.]/.test(char)) {
|
|
453
|
+
const match = /^\d*\.?\d+(?:[eE][-+]?\d+)?|^\d+\.?/.exec(source.slice(i));
|
|
454
|
+
if (!match) throw new ExpressionError(`calc: bad number at "${source.slice(i, i + 8)}"`);
|
|
455
|
+
tokens.push({
|
|
456
|
+
kind: "number",
|
|
457
|
+
value: Number(match[0])
|
|
458
|
+
});
|
|
459
|
+
i += match[0].length;
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
if (char === "'" || char === "\"") {
|
|
463
|
+
let value = "";
|
|
464
|
+
i++;
|
|
465
|
+
while (i < source.length && source[i] !== char) {
|
|
466
|
+
if (source[i] === "\\" && i + 1 < source.length) i++;
|
|
467
|
+
value += source.charAt(i++);
|
|
468
|
+
}
|
|
469
|
+
if (i >= source.length) throw new ExpressionError("calc: unclosed string");
|
|
470
|
+
i++;
|
|
471
|
+
tokens.push({
|
|
472
|
+
kind: "string",
|
|
473
|
+
value
|
|
474
|
+
});
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
if (/[A-Za-z_]/.test(char)) {
|
|
478
|
+
const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));
|
|
479
|
+
tokens.push({
|
|
480
|
+
kind: "name",
|
|
481
|
+
value: match[0]
|
|
482
|
+
});
|
|
483
|
+
i += match[0].length;
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));
|
|
487
|
+
if (!op) throw new ExpressionError(`calc: unexpected "${char}"`);
|
|
488
|
+
tokens.push({
|
|
489
|
+
kind: "op",
|
|
490
|
+
value: op
|
|
491
|
+
});
|
|
492
|
+
i += op.length;
|
|
493
|
+
}
|
|
494
|
+
tokens.push({ kind: "end" });
|
|
495
|
+
return tokens;
|
|
496
|
+
}
|
|
497
|
+
function numberOf(value, what) {
|
|
498
|
+
if (typeof value === "number") {
|
|
499
|
+
if (!Number.isFinite(value)) throw new ExpressionError(`calc: ${what} is not finite`);
|
|
500
|
+
return value;
|
|
501
|
+
}
|
|
502
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
503
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
504
|
+
const parsed = Number(value);
|
|
505
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
506
|
+
}
|
|
507
|
+
if (value === null || value === void 0) throw new ExpressionError(`calc: ${what} has no value`);
|
|
508
|
+
throw new ExpressionError(`calc: ${what} is not a number`);
|
|
509
|
+
}
|
|
510
|
+
function describe(value) {
|
|
511
|
+
return typeof value === "string" ? `"${value}"` : String(value);
|
|
512
|
+
}
|
|
513
|
+
const MATH = {
|
|
514
|
+
min: (args) => Math.min(...args),
|
|
515
|
+
max: (args) => Math.max(...args),
|
|
516
|
+
abs: ([x = NaN]) => Math.abs(x),
|
|
517
|
+
floor: ([x = NaN]) => Math.floor(x),
|
|
518
|
+
ceil: ([x = NaN]) => Math.ceil(x),
|
|
519
|
+
round: ([x = NaN, decimals = 0]) => {
|
|
520
|
+
const factor = 10 ** Math.trunc(decimals);
|
|
521
|
+
return Math.round(x * factor) / factor;
|
|
522
|
+
},
|
|
523
|
+
pow: ([x = NaN, y = NaN]) => x ** y,
|
|
524
|
+
sqrt: ([x = NaN]) => Math.sqrt(x),
|
|
525
|
+
exp: ([x = NaN]) => Math.exp(x),
|
|
526
|
+
ln: ([x = NaN]) => Math.log(x),
|
|
527
|
+
log10: ([x = NaN]) => Math.log10(x)
|
|
528
|
+
};
|
|
529
|
+
/** How many args a function takes, at least and at most; min and max take any. */
|
|
530
|
+
const ARITY = {
|
|
531
|
+
abs: [1, 1],
|
|
532
|
+
floor: [1, 1],
|
|
533
|
+
ceil: [1, 1],
|
|
534
|
+
round: [1, 2],
|
|
535
|
+
pow: [2, 2],
|
|
536
|
+
sqrt: [1, 1],
|
|
537
|
+
exp: [1, 1],
|
|
538
|
+
ln: [1, 1],
|
|
539
|
+
log10: [1, 1]
|
|
540
|
+
};
|
|
541
|
+
/** Named constants, when no arg of the same name is passed. */
|
|
542
|
+
const CONSTANTS = {
|
|
543
|
+
pi: Math.PI,
|
|
544
|
+
e: Math.E
|
|
545
|
+
};
|
|
546
|
+
const END = { kind: "end" };
|
|
547
|
+
var CalcParser = class {
|
|
548
|
+
pos = 0;
|
|
549
|
+
constructor(tokens, scope, source) {
|
|
550
|
+
this.tokens = tokens;
|
|
551
|
+
this.scope = scope;
|
|
552
|
+
this.source = source;
|
|
553
|
+
}
|
|
554
|
+
/** The current token. The list always ends with an "end" token. */
|
|
555
|
+
peek() {
|
|
556
|
+
return this.tokens[this.pos] ?? END;
|
|
557
|
+
}
|
|
558
|
+
parse() {
|
|
559
|
+
const value = this.ternary();
|
|
560
|
+
if (this.peek().kind !== "end") this.fail(`unexpected "${this.text(this.peek())}"`);
|
|
561
|
+
return value;
|
|
562
|
+
}
|
|
563
|
+
fail(what) {
|
|
564
|
+
throw new ExpressionError(`calc: ${what} in "${this.source}"`);
|
|
565
|
+
}
|
|
566
|
+
text(token) {
|
|
567
|
+
return token.kind === "end" ? "end" : String(token.value);
|
|
568
|
+
}
|
|
569
|
+
peekOp(...ops) {
|
|
570
|
+
const token = this.peek();
|
|
571
|
+
return token.kind === "op" && ops.includes(token.value) ? token.value : void 0;
|
|
572
|
+
}
|
|
573
|
+
expectOp(op) {
|
|
574
|
+
if (this.peekOp(op) === void 0) this.fail(`expected "${op}" but found "${this.text(this.peek())}"`);
|
|
575
|
+
this.pos++;
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* Parses a part of the expression that the result does not need (the
|
|
579
|
+
* other branch of `?:`, the right side of a decided `&&` or `||`). It
|
|
580
|
+
* still has to be parsed to find where it ends, so syntax errors are
|
|
581
|
+
* reported, but no value is checked or computed: `n == 0 ? 0 : 10 / n`
|
|
582
|
+
* is a valid guard.
|
|
583
|
+
*/
|
|
584
|
+
skipped(parse) {
|
|
585
|
+
this.skipDepth++;
|
|
586
|
+
try {
|
|
587
|
+
parse();
|
|
588
|
+
} finally {
|
|
589
|
+
this.skipDepth--;
|
|
590
|
+
}
|
|
591
|
+
return null;
|
|
592
|
+
}
|
|
593
|
+
/** Above 0 while parsing a part whose value is not needed. */
|
|
594
|
+
skipDepth = 0;
|
|
595
|
+
/** The number of a value, or 0 while skipping. */
|
|
596
|
+
num(value, what) {
|
|
597
|
+
return this.skipDepth > 0 ? 0 : numberOf(value, what);
|
|
598
|
+
}
|
|
599
|
+
ternary() {
|
|
600
|
+
const condition = this.or();
|
|
601
|
+
if (this.peekOp("?") === void 0) return condition;
|
|
602
|
+
this.pos++;
|
|
603
|
+
const takesFirst = truthOf(condition);
|
|
604
|
+
const whenTrue = takesFirst ? this.ternary() : this.skipped(() => this.ternary());
|
|
605
|
+
this.expectOp(":");
|
|
606
|
+
const whenFalse = takesFirst ? this.skipped(() => this.ternary()) : this.ternary();
|
|
607
|
+
return takesFirst ? whenTrue : whenFalse;
|
|
608
|
+
}
|
|
609
|
+
or() {
|
|
610
|
+
let left = this.and();
|
|
611
|
+
while (this.peekOp("||")) {
|
|
612
|
+
this.pos++;
|
|
613
|
+
if (truthOf(left)) {
|
|
614
|
+
this.skipped(() => this.and());
|
|
615
|
+
left = true;
|
|
616
|
+
} else left = truthOf(this.and());
|
|
617
|
+
}
|
|
618
|
+
return left;
|
|
619
|
+
}
|
|
620
|
+
and() {
|
|
621
|
+
let left = this.equality();
|
|
622
|
+
while (this.peekOp("&&")) {
|
|
623
|
+
this.pos++;
|
|
624
|
+
if (!truthOf(left)) {
|
|
625
|
+
this.skipped(() => this.equality());
|
|
626
|
+
left = false;
|
|
627
|
+
} else left = truthOf(this.equality());
|
|
628
|
+
}
|
|
629
|
+
return left;
|
|
630
|
+
}
|
|
631
|
+
equality() {
|
|
632
|
+
let left = this.comparison();
|
|
633
|
+
for (let op = this.peekOp("==", "!="); op; op = this.peekOp("==", "!=")) {
|
|
634
|
+
this.pos++;
|
|
635
|
+
const right = this.comparison();
|
|
636
|
+
const isEqual = typeof left === "number" || typeof right === "number" ? this.num(left, "the left side of ==") === this.num(right, "the right side of ==") : left === right;
|
|
637
|
+
left = op === "==" ? isEqual : !isEqual;
|
|
638
|
+
}
|
|
639
|
+
return left;
|
|
640
|
+
}
|
|
641
|
+
comparison() {
|
|
642
|
+
let left = this.additive();
|
|
643
|
+
for (let op = this.peekOp("<", "<=", ">", ">="); op; op = this.peekOp("<", "<=", ">", ">=")) {
|
|
644
|
+
this.pos++;
|
|
645
|
+
const a = this.num(left, `the left side of ${op}`);
|
|
646
|
+
const b = this.num(this.additive(), `the right side of ${op}`);
|
|
647
|
+
left = op === "<" ? a < b : op === "<=" ? a <= b : op === ">" ? a > b : a >= b;
|
|
648
|
+
}
|
|
649
|
+
return left;
|
|
650
|
+
}
|
|
651
|
+
additive() {
|
|
652
|
+
let left = this.multiplicative();
|
|
653
|
+
for (let op = this.peekOp("+", "-"); op; op = this.peekOp("+", "-")) {
|
|
654
|
+
this.pos++;
|
|
655
|
+
const right = this.multiplicative();
|
|
656
|
+
if (op === "+" && (typeof left === "string" || typeof right === "string")) left = `${left ?? ""}${right ?? ""}`;
|
|
657
|
+
else {
|
|
658
|
+
const a = this.num(left, `the left side of ${op}`);
|
|
659
|
+
const b = this.num(right, `the right side of ${op}`);
|
|
660
|
+
left = op === "+" ? a + b : a - b;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
return left;
|
|
664
|
+
}
|
|
665
|
+
multiplicative() {
|
|
666
|
+
let left = this.unary();
|
|
667
|
+
for (let op = this.peekOp("*", "/", "%"); op; op = this.peekOp("*", "/", "%")) {
|
|
668
|
+
this.pos++;
|
|
669
|
+
const a = this.num(left, `the left side of ${op}`);
|
|
670
|
+
const b = this.num(this.unary(), `the right side of ${op}`);
|
|
671
|
+
if (op !== "*" && b === 0 && this.skipDepth === 0) this.fail("division by zero");
|
|
672
|
+
left = op === "*" ? a * b : op === "/" ? a / b : a % b;
|
|
673
|
+
}
|
|
674
|
+
return left;
|
|
675
|
+
}
|
|
676
|
+
unary() {
|
|
677
|
+
if (this.peekOp("-")) {
|
|
678
|
+
this.pos++;
|
|
679
|
+
return -this.num(this.unary(), "the operand of -");
|
|
680
|
+
}
|
|
681
|
+
if (this.peekOp("!")) {
|
|
682
|
+
this.pos++;
|
|
683
|
+
return !truthOf(this.unary());
|
|
684
|
+
}
|
|
685
|
+
return this.power();
|
|
686
|
+
}
|
|
687
|
+
/** `a ^ b`: binds tighter than `*` and unary minus, right to left. */
|
|
688
|
+
power() {
|
|
689
|
+
const base = this.primary();
|
|
690
|
+
if (!this.peekOp("^")) return base;
|
|
691
|
+
this.pos++;
|
|
692
|
+
const exponent = this.unary();
|
|
693
|
+
if (this.skipDepth > 0) return null;
|
|
694
|
+
return this.finite(this.num(base, "the left side of ^") ** this.num(exponent, "the right side of ^"), "^");
|
|
695
|
+
}
|
|
696
|
+
finite(value, what) {
|
|
697
|
+
if (!Number.isFinite(value)) this.fail(`${what} has no finite result`);
|
|
698
|
+
return value;
|
|
699
|
+
}
|
|
700
|
+
primary() {
|
|
701
|
+
const token = this.peek();
|
|
702
|
+
this.pos++;
|
|
703
|
+
switch (token.kind) {
|
|
704
|
+
case "number": return token.value;
|
|
705
|
+
case "string": return token.value;
|
|
706
|
+
case "name": return this.name(token.value);
|
|
707
|
+
case "op":
|
|
708
|
+
if (token.value === "(") {
|
|
709
|
+
const value = this.ternary();
|
|
710
|
+
this.expectOp(")");
|
|
711
|
+
return value;
|
|
712
|
+
}
|
|
713
|
+
return this.fail(`unexpected "${token.value}"`);
|
|
714
|
+
case "end": return this.fail("missing value");
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
name(name) {
|
|
718
|
+
if (name === "true") return true;
|
|
719
|
+
if (name === "false") return false;
|
|
720
|
+
if (name === "null") return null;
|
|
721
|
+
if (this.peekOp("(")) {
|
|
722
|
+
this.pos++;
|
|
723
|
+
const args = [];
|
|
724
|
+
if (this.peekOp(")") === void 0) for (;;) {
|
|
725
|
+
args.push(this.num(this.ternary(), `an argument of ${name}`));
|
|
726
|
+
if (this.peekOp(",") === void 0) break;
|
|
727
|
+
this.pos++;
|
|
728
|
+
}
|
|
729
|
+
this.expectOp(")");
|
|
730
|
+
if (this.skipDepth > 0) return null;
|
|
731
|
+
const fn = Object.prototype.hasOwnProperty.call(MATH, name) ? MATH[name] : void 0;
|
|
732
|
+
if (!fn) this.fail(`unknown function ${name}`);
|
|
733
|
+
if (args.length === 0) this.fail(`${name} needs an argument`);
|
|
734
|
+
const [least, most] = ARITY[name] ?? [1, Infinity];
|
|
735
|
+
if (args.length < least || args.length > most) this.fail(`${name} takes ${least === most ? least : `${least} or ${most}`} argument${most === 1 ? "" : "s"}`);
|
|
736
|
+
return this.finite(fn(args), name);
|
|
737
|
+
}
|
|
738
|
+
if (this.skipDepth > 0) return null;
|
|
739
|
+
if (!Object.prototype.hasOwnProperty.call(this.scope, name)) {
|
|
740
|
+
const constant = Object.prototype.hasOwnProperty.call(CONSTANTS, name) ? CONSTANTS[name] : void 0;
|
|
741
|
+
if (constant !== void 0) return constant;
|
|
742
|
+
this.fail(`unknown name ${name}; pass it as an arg`);
|
|
743
|
+
}
|
|
744
|
+
const value = this.scope[name];
|
|
745
|
+
if (value !== null && typeof value !== "number" && typeof value !== "string" && typeof value !== "boolean") this.fail(`${name} is not a number, text or boolean (${describe(value)})`);
|
|
746
|
+
return value;
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
/**
|
|
750
|
+
* Evaluates `expression` with the names in `scope`. Gives a number, a
|
|
751
|
+
* string, a boolean or null. Throws an {@link ExpressionError} for a bad
|
|
752
|
+
* expression or a missing name.
|
|
753
|
+
*/
|
|
754
|
+
function evaluateCalc(expression, scope) {
|
|
755
|
+
if (typeof expression !== "string" || expression.trim() === "") throw new ExpressionError("calc: expression must be a string");
|
|
756
|
+
return new CalcParser(tokenize(expression), scope, expression).parse();
|
|
757
|
+
}
|
|
758
|
+
/** The `calc` function: the expression is `args.expression`, the rest is the scope. */
|
|
759
|
+
function calc(args) {
|
|
760
|
+
const { expression, ...scope } = args;
|
|
761
|
+
return evaluateCalc(expression, scope);
|
|
762
|
+
}
|
|
763
|
+
const WHOLE_EXPRESSION = /^\$\{([^}]*)\}$/;
|
|
764
|
+
/**
|
|
765
|
+
* Fills `item` for one iteration: a string that is one `${...}` gives the
|
|
766
|
+
* typed value of the expression, a string with `${...}` inside it is
|
|
767
|
+
* interpolated as text, and objects and arrays are walked.
|
|
768
|
+
*/
|
|
769
|
+
function fillItem(item, scope) {
|
|
770
|
+
if (typeof item === "string") {
|
|
771
|
+
const whole = WHOLE_EXPRESSION.exec(item);
|
|
772
|
+
if (whole) return evaluateCalc(whole[1], scope);
|
|
773
|
+
return item.replace(/\$\{([^}]*)\}/g, (_, expression) => {
|
|
774
|
+
const value = evaluateCalc(expression, scope);
|
|
775
|
+
return value === null ? "" : String(value);
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
if (Array.isArray(item)) return item.map((entry) => fillItem(entry, scope));
|
|
779
|
+
if (typeof item === "object" && item !== null) return Object.fromEntries(Object.entries(item).map(([key, value]) => [key, fillItem(value, scope)]));
|
|
780
|
+
return item;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* The `series` function: `count` copies of `item`, with the loop variable
|
|
784
|
+
* (`variable`, default "i") counting from `start` (default 1) and the other
|
|
785
|
+
* args in scope of the `${...}` expressions of the item.
|
|
786
|
+
*/
|
|
787
|
+
function series(args) {
|
|
788
|
+
const { count, item, variable, start, ...scope } = args;
|
|
789
|
+
const length = numberOf(count, "count");
|
|
790
|
+
if (!Number.isInteger(length) || length < 0) throw new ExpressionError("series: count must be a whole number");
|
|
791
|
+
if (length > MAX_SERIES) throw new ExpressionError(`series: count is at most ${MAX_SERIES}`);
|
|
792
|
+
if (item === void 0) throw new ExpressionError("series: item is required");
|
|
793
|
+
const name = variable === void 0 ? "i" : variable;
|
|
794
|
+
if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new ExpressionError("series: variable must be a name");
|
|
795
|
+
const first = start === void 0 ? 1 : numberOf(start, "start");
|
|
796
|
+
return Array.from({ length }, (_, index) => fillItem(item, {
|
|
797
|
+
...scope,
|
|
798
|
+
[name]: first + index
|
|
799
|
+
}));
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
//#endregion
|
|
803
|
+
//#region src/generative-ui/resolve.ts
|
|
804
|
+
BASIC_FUNCTIONS.calc = calc;
|
|
805
|
+
BASIC_FUNCTIONS.series = series;
|
|
806
|
+
const NO_DATA = { get: () => void 0 };
|
|
807
|
+
BASIC_FUNCTIONS.formatString = (args) => resolveDynamicValue({
|
|
808
|
+
"@call": "formatString",
|
|
809
|
+
args
|
|
810
|
+
}, {
|
|
811
|
+
data: NO_DATA,
|
|
812
|
+
basePath: void 0
|
|
813
|
+
}).value;
|
|
814
|
+
/** Adds one segment to a JSON pointer: ("/items", "0") gives "/items/0". */
|
|
815
|
+
function joinPath(base, segment) {
|
|
816
|
+
return base === "/" ? `/${segment}` : `${base}/${segment}`;
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* The absolute data model path of a binding. A path without a leading "/"
|
|
820
|
+
* is relative to the current template item, or to the root outside of one.
|
|
821
|
+
*/
|
|
822
|
+
function resolvePath(path, basePath) {
|
|
823
|
+
if (path.startsWith("/")) return path;
|
|
824
|
+
return joinPath(basePath ?? "/", path);
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* The index of the template item at `basePath`: its last segment.
|
|
828
|
+
* `undefined` outside of a template.
|
|
829
|
+
*/
|
|
830
|
+
function templateIndex(basePath) {
|
|
831
|
+
if (basePath === void 0) return void 0;
|
|
832
|
+
const index = Number(basePath.slice(basePath.lastIndexOf("/") + 1));
|
|
833
|
+
return Number.isInteger(index) ? index : void 0;
|
|
834
|
+
}
|
|
835
|
+
/** The value of a ValidationResult where a boolean is expected. */
|
|
836
|
+
function coerce(value, keep) {
|
|
837
|
+
return !keep && (0, _copilotkit_shared.isValidationResult)(value) ? value.valid : value;
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* Resolves `value`. `keepValidation` keeps a ValidationResult as it is; by
|
|
841
|
+
* default it becomes its `valid` boolean, which is what every prop except
|
|
842
|
+
* a check condition wants.
|
|
843
|
+
*/
|
|
844
|
+
function walk(value, state, keepValidation, scope = "outside") {
|
|
845
|
+
if (Array.isArray(value)) {
|
|
846
|
+
let changed = false;
|
|
847
|
+
const itemScope = scope === "list" ? "check" : "outside";
|
|
848
|
+
const items = value.map((item) => {
|
|
849
|
+
const next = walk(item, state, keepValidation, itemScope);
|
|
850
|
+
if (next !== item) changed = true;
|
|
851
|
+
return next;
|
|
852
|
+
});
|
|
853
|
+
return changed ? items : value;
|
|
854
|
+
}
|
|
855
|
+
if (!(0, _copilotkit_shared_generative_ui.isRecord)(value)) return value;
|
|
856
|
+
if ((0, _copilotkit_shared.isPathBinding)(value)) {
|
|
857
|
+
const path = resolvePath(value["@path"], state.context.basePath);
|
|
858
|
+
state.paths.add(path);
|
|
859
|
+
return state.context.data.get(path);
|
|
860
|
+
}
|
|
861
|
+
if ((0, _copilotkit_shared.isCallBinding)(value)) return call(value, state, keepValidation);
|
|
862
|
+
if ((0, _copilotkit_shared.isActionBinding)(value)) return value;
|
|
863
|
+
let changed = false;
|
|
864
|
+
const entries = Object.entries(value).map(([key, item]) => {
|
|
865
|
+
const next = walk(item, state, keepValidation || scope === "check" && key === "condition", key === "checks" ? "list" : "outside");
|
|
866
|
+
if (next !== item) changed = true;
|
|
867
|
+
return [key, next];
|
|
868
|
+
});
|
|
869
|
+
return changed ? Object.fromEntries(entries) : value;
|
|
870
|
+
}
|
|
871
|
+
function call(binding, state, keepValidation) {
|
|
872
|
+
const name = binding["@call"];
|
|
873
|
+
const rawArgs = binding.args ?? {};
|
|
874
|
+
if (!(0, _copilotkit_shared_generative_ui.isRecord)(rawArgs)) throw new ExpressionError(`the args of "${name}" must be an object`);
|
|
875
|
+
if (name === _copilotkit_shared.A2UI_INDEX_FUNCTION) {
|
|
876
|
+
const index = templateIndex(state.context.basePath);
|
|
877
|
+
if (index === void 0) return void 0;
|
|
878
|
+
const offset = walk(rawArgs.offset, state, false);
|
|
879
|
+
return index + (typeof offset === "number" ? offset : 0);
|
|
880
|
+
}
|
|
881
|
+
if (name === "formatString") {
|
|
882
|
+
const template = walk(rawArgs.value, state, false);
|
|
883
|
+
if (typeof template !== "string") throw new ExpressionError("formatString takes a string value");
|
|
884
|
+
return formatString(template, state);
|
|
885
|
+
}
|
|
886
|
+
const fn = Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name) ? BASIC_FUNCTIONS[name] : void 0;
|
|
887
|
+
if (!fn) throw new ExpressionError(`"${name}" is not a basic function`);
|
|
888
|
+
if (requiresUserActivation(name)) throw new ExpressionError(`"${name}" is not a value; bind it as the functionCall of an event`);
|
|
889
|
+
const result = fn(walk(rawArgs, state, false));
|
|
890
|
+
return givesValidationResult(name) ? coerce(result, keepValidation) : result;
|
|
891
|
+
}
|
|
892
|
+
function resolveDynamicValue(value, context, options = {}) {
|
|
893
|
+
const result = tryResolveDynamicValue(value, context, options);
|
|
894
|
+
if (!result.ok) throw result.error;
|
|
895
|
+
return result;
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Like {@link resolveDynamicValue}, but a failure comes back as a result
|
|
899
|
+
* with the paths read so far, so the caller can keep watching them: a
|
|
900
|
+
* function that fails on an empty field works once the user fills it.
|
|
901
|
+
*/
|
|
902
|
+
function tryResolveDynamicValue(value, context, options = {}) {
|
|
903
|
+
const state = {
|
|
904
|
+
context,
|
|
905
|
+
paths: /* @__PURE__ */ new Set()
|
|
906
|
+
};
|
|
907
|
+
try {
|
|
908
|
+
return {
|
|
909
|
+
ok: true,
|
|
910
|
+
value: walk(value, state, options.keepValidation ?? false, options.isChecks ? "list" : "outside"),
|
|
911
|
+
paths: state.paths
|
|
912
|
+
};
|
|
913
|
+
} catch (error) {
|
|
914
|
+
return {
|
|
915
|
+
ok: false,
|
|
916
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
917
|
+
paths: state.paths
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
/** True when `value` holds a `{"@path"}` or `{"@call"}` at any depth. */
|
|
922
|
+
function containsDynamicValue(value) {
|
|
923
|
+
if (Array.isArray(value)) return value.some(containsDynamicValue);
|
|
924
|
+
if (!(0, _copilotkit_shared_generative_ui.isRecord)(value)) return false;
|
|
925
|
+
if ((0, _copilotkit_shared.isPathBinding)(value) || (0, _copilotkit_shared.isCallBinding)(value)) return true;
|
|
926
|
+
if ((0, _copilotkit_shared.isActionBinding)(value)) return false;
|
|
927
|
+
return Object.values(value).some(containsDynamicValue);
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* The `${...}` grammar of `formatString`:
|
|
931
|
+
*
|
|
932
|
+
* expression := path | literal | call
|
|
933
|
+
* path := "/" segments | identifier ("/" segments)*
|
|
934
|
+
* literal := 'text' | "text" | number | true | false | null
|
|
935
|
+
* call := identifier "(" [ name ":" expression ("," name ":" expression)* ] ")"
|
|
936
|
+
*
|
|
937
|
+
* A `\${` in the template is a literal `${`.
|
|
938
|
+
*/
|
|
939
|
+
function formatString(template, state) {
|
|
940
|
+
let out = "";
|
|
941
|
+
let index = 0;
|
|
942
|
+
while (index < template.length) {
|
|
943
|
+
const start = template.indexOf("${", index);
|
|
944
|
+
if (start === -1) {
|
|
945
|
+
out += template.slice(index);
|
|
946
|
+
break;
|
|
947
|
+
}
|
|
948
|
+
if (start > 0 && template[start - 1] === "\\") {
|
|
949
|
+
out += `${template.slice(index, start - 1)}\${`;
|
|
950
|
+
index = start + 2;
|
|
951
|
+
continue;
|
|
952
|
+
}
|
|
953
|
+
out += template.slice(index, start);
|
|
954
|
+
const end = matchingBrace(template, start + 2);
|
|
955
|
+
if (end === -1) throw new ExpressionError("formatString: unclosed ${");
|
|
956
|
+
const value = new ExpressionParser(template.slice(start + 2, end).trim(), state).parse();
|
|
957
|
+
out += value === void 0 || value === null ? "" : String(value);
|
|
958
|
+
index = end + 1;
|
|
959
|
+
}
|
|
960
|
+
return out;
|
|
961
|
+
}
|
|
962
|
+
/** The index of the `}` that closes the block opened at `from`, or -1. */
|
|
963
|
+
function matchingBrace(template, from) {
|
|
964
|
+
let depth = 1;
|
|
965
|
+
let quote;
|
|
966
|
+
for (let i = from; i < template.length; i++) {
|
|
967
|
+
const char = template[i];
|
|
968
|
+
if (quote) {
|
|
969
|
+
if (char === "\\") i++;
|
|
970
|
+
else if (char === quote) quote = void 0;
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
if (char === "'" || char === "\"") quote = char;
|
|
974
|
+
else if (char === "{") depth++;
|
|
975
|
+
else if (char === "}" && --depth === 0) return i;
|
|
976
|
+
}
|
|
977
|
+
return -1;
|
|
978
|
+
}
|
|
979
|
+
const IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;
|
|
980
|
+
const NUMBER = /-?\d+(?:\.\d+)?/y;
|
|
981
|
+
const PATH_SEGMENT = /[^\s,():'"]+/y;
|
|
982
|
+
var ExpressionParser = class {
|
|
983
|
+
pos = 0;
|
|
984
|
+
constructor(source, state) {
|
|
985
|
+
this.source = source;
|
|
986
|
+
this.state = state;
|
|
987
|
+
}
|
|
988
|
+
parse() {
|
|
989
|
+
const value = this.expression();
|
|
990
|
+
this.skipSpace();
|
|
991
|
+
if (this.pos < this.source.length) throw new ExpressionError(`formatString: unexpected "${this.source.slice(this.pos)}" in \${${this.source}}`);
|
|
992
|
+
return value;
|
|
993
|
+
}
|
|
994
|
+
fail(what) {
|
|
995
|
+
throw new ExpressionError(`formatString: ${what} in \${${this.source}}`);
|
|
996
|
+
}
|
|
997
|
+
skipSpace() {
|
|
998
|
+
while (this.pos < this.source.length && /\s/.test(this.source.charAt(this.pos))) this.pos++;
|
|
999
|
+
}
|
|
1000
|
+
match(pattern) {
|
|
1001
|
+
pattern.lastIndex = this.pos;
|
|
1002
|
+
const found = pattern.exec(this.source);
|
|
1003
|
+
if (!found) return void 0;
|
|
1004
|
+
this.pos = pattern.lastIndex;
|
|
1005
|
+
return found[0];
|
|
1006
|
+
}
|
|
1007
|
+
expression() {
|
|
1008
|
+
this.skipSpace();
|
|
1009
|
+
const char = this.source[this.pos];
|
|
1010
|
+
if (char === void 0) this.fail("missing expression");
|
|
1011
|
+
if (char === "'" || char === "\"") return this.quoted(char);
|
|
1012
|
+
if (char === "/") return this.path(this.match(PATH_SEGMENT) ?? "/");
|
|
1013
|
+
const number = this.match(NUMBER);
|
|
1014
|
+
if (number !== void 0) return Number(number);
|
|
1015
|
+
const name = this.match(IDENTIFIER);
|
|
1016
|
+
if (name === void 0) this.fail(`unexpected "${char}"`);
|
|
1017
|
+
if (name === "true") return true;
|
|
1018
|
+
if (name === "false") return false;
|
|
1019
|
+
if (name === "null") return null;
|
|
1020
|
+
this.skipSpace();
|
|
1021
|
+
if (this.source[this.pos] === "(") return this.call(name);
|
|
1022
|
+
if (name.startsWith("@")) return call({ "@call": name }, this.state, false);
|
|
1023
|
+
const rest = this.source[this.pos] === "/" ? this.match(PATH_SEGMENT) : "";
|
|
1024
|
+
return this.path(`${name}${rest ?? ""}`);
|
|
1025
|
+
}
|
|
1026
|
+
quoted(quote) {
|
|
1027
|
+
let value = "";
|
|
1028
|
+
this.pos++;
|
|
1029
|
+
while (this.pos < this.source.length) {
|
|
1030
|
+
const char = this.source[this.pos++];
|
|
1031
|
+
if (char === "\\" && this.pos < this.source.length) value += this.source[this.pos++];
|
|
1032
|
+
else if (char === quote) return value;
|
|
1033
|
+
else value += char;
|
|
1034
|
+
}
|
|
1035
|
+
return this.fail("unclosed string");
|
|
1036
|
+
}
|
|
1037
|
+
path(path) {
|
|
1038
|
+
const absolute = resolvePath(path, this.state.context.basePath);
|
|
1039
|
+
this.state.paths.add(absolute);
|
|
1040
|
+
return this.state.context.data.get(absolute);
|
|
1041
|
+
}
|
|
1042
|
+
call(name) {
|
|
1043
|
+
this.pos++;
|
|
1044
|
+
const args = {};
|
|
1045
|
+
this.skipSpace();
|
|
1046
|
+
if (this.source[this.pos] === ")") {
|
|
1047
|
+
this.pos++;
|
|
1048
|
+
return call({
|
|
1049
|
+
"@call": name,
|
|
1050
|
+
args
|
|
1051
|
+
}, this.state, false);
|
|
1052
|
+
}
|
|
1053
|
+
for (;;) {
|
|
1054
|
+
this.skipSpace();
|
|
1055
|
+
const key = this.match(IDENTIFIER);
|
|
1056
|
+
if (key === void 0) this.fail("expected an argument name");
|
|
1057
|
+
this.skipSpace();
|
|
1058
|
+
if (this.source[this.pos] !== ":") this.fail(`expected ":" after ${key}`);
|
|
1059
|
+
this.pos++;
|
|
1060
|
+
args[key] = this.expression();
|
|
1061
|
+
this.skipSpace();
|
|
1062
|
+
const next = this.source[this.pos++];
|
|
1063
|
+
if (next === ")") break;
|
|
1064
|
+
if (next !== ",") this.fail(`expected "," or ")" after ${key}`);
|
|
1065
|
+
}
|
|
1066
|
+
return call({
|
|
1067
|
+
"@call": name,
|
|
1068
|
+
args
|
|
1069
|
+
}, this.state, false);
|
|
1070
|
+
}
|
|
1071
|
+
};
|
|
1072
|
+
|
|
1073
|
+
//#endregion
|
|
1074
|
+
//#region src/generative-ui/surface-manager.ts
|
|
1075
|
+
function surfaceKey(threadId, surfaceId) {
|
|
1076
|
+
return `${threadId}::${surfaceId}`;
|
|
1077
|
+
}
|
|
1078
|
+
let creationCounter = 0;
|
|
1079
|
+
const FORBIDDEN_SEGMENTS = new Set([
|
|
1080
|
+
"__proto__",
|
|
1081
|
+
"constructor",
|
|
1082
|
+
"prototype"
|
|
1083
|
+
]);
|
|
1084
|
+
/** "/a/b/" to "/a/b". The root stays "/". */
|
|
1085
|
+
function normalizePath(path) {
|
|
1086
|
+
return (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path) || "/";
|
|
1087
|
+
}
|
|
1088
|
+
/** True when `path` is `ancestor` or below it. */
|
|
1089
|
+
function isAtOrBelow(path, ancestor) {
|
|
1090
|
+
if (ancestor === "/") return true;
|
|
1091
|
+
return path === ancestor || path.startsWith(`${ancestor}/`);
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Rejections as `"operation <index>: <reason>"` lines, cut to the size that
|
|
1095
|
+
* the envelope reader accepts.
|
|
1096
|
+
*/
|
|
1097
|
+
function summarizeRejections(rejections) {
|
|
1098
|
+
return rejections.slice(0, _copilotkit_shared.GENERATIVE_UI_MAX_SUMMARY_REJECTIONS).map(({ index, reason }) => `operation ${index}: ${reason}`.slice(0, _copilotkit_shared.GENERATIVE_UI_MAX_REJECTION_LENGTH));
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Framework-agnostic store of generated surfaces. One web_core SurfaceModel per
|
|
1102
|
+
* (threadId, surfaceId), shared by every mount. Applies only newly committed
|
|
1103
|
+
* operations, validates each before applying it, and owns app state and the
|
|
1104
|
+
* data model paths that the user wrote, so agent updates cannot overwrite
|
|
1105
|
+
* them. App state never goes into a surface's data model. Selectors read it
|
|
1106
|
+
* with `getState()`.
|
|
1107
|
+
*/
|
|
1108
|
+
var GenerativeUISurfaceManager = class {
|
|
1109
|
+
surfaces = /* @__PURE__ */ new Map();
|
|
1110
|
+
bookkeeping = /* @__PURE__ */ new Map();
|
|
1111
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1112
|
+
/** Mounts of each target id, in mount order. */
|
|
1113
|
+
targets = /* @__PURE__ */ new Map();
|
|
1114
|
+
state = {};
|
|
1115
|
+
/**
|
|
1116
|
+
* User-owned data model values, by surface key, then by path. Kept when a
|
|
1117
|
+
* surface is rebuilt. Cleared when the surface is deleted.
|
|
1118
|
+
*/
|
|
1119
|
+
owned = /* @__PURE__ */ new Map();
|
|
1120
|
+
/**
|
|
1121
|
+
* Keys of the surfaces that a `deleteSurface` removed. A surface id is
|
|
1122
|
+
* unique for the life of the page, so a key stays here when its surface is
|
|
1123
|
+
* built again.
|
|
1124
|
+
*/
|
|
1125
|
+
deletedKeys = /* @__PURE__ */ new Set();
|
|
1126
|
+
/**
|
|
1127
|
+
* Surfaces that share their data model, by surface key: the parts of a
|
|
1128
|
+
* chat surface that the prose lift split. A user write to one part goes
|
|
1129
|
+
* to every part, so an input in one part drives a binding in another.
|
|
1130
|
+
*/
|
|
1131
|
+
linked = /* @__PURE__ */ new Map();
|
|
1132
|
+
webCoreCatalog;
|
|
1133
|
+
activeThreadId;
|
|
1134
|
+
version = 0;
|
|
1135
|
+
constructor(ui, options = {}) {
|
|
1136
|
+
this.ui = ui;
|
|
1137
|
+
this.options = options;
|
|
1138
|
+
this.webCoreCatalog = new _a2ui_web_core_v0_9.Catalog(ui.id, [...ui.components.keys()].map((name) => ({
|
|
1139
|
+
name,
|
|
1140
|
+
schema: zod.z.any()
|
|
1141
|
+
})), []);
|
|
1142
|
+
}
|
|
1143
|
+
subscribe = (listener) => {
|
|
1144
|
+
this.listeners.add(listener);
|
|
1145
|
+
return () => {
|
|
1146
|
+
this.listeners.delete(listener);
|
|
1147
|
+
};
|
|
1148
|
+
};
|
|
1149
|
+
getVersion = () => this.version;
|
|
1150
|
+
notify() {
|
|
1151
|
+
this.version++;
|
|
1152
|
+
for (const listener of [...this.listeners]) listener();
|
|
1153
|
+
}
|
|
1154
|
+
setActiveThread(threadId) {
|
|
1155
|
+
if (threadId === this.activeThreadId) return;
|
|
1156
|
+
this.activeThreadId = threadId;
|
|
1157
|
+
this.notify();
|
|
1158
|
+
}
|
|
1159
|
+
getActiveThread() {
|
|
1160
|
+
return this.activeThreadId;
|
|
1161
|
+
}
|
|
1162
|
+
ingest(threadId, agentId, content) {
|
|
1163
|
+
const key = surfaceKey(threadId, content.surfaceId);
|
|
1164
|
+
const operations = content.operations ?? [];
|
|
1165
|
+
let surface = this.surfaces.get(key);
|
|
1166
|
+
let book = this.bookkeeping.get(key);
|
|
1167
|
+
let changed = false;
|
|
1168
|
+
if (surface && book && !this.extendsApplied(book, operations)) {
|
|
1169
|
+
this.disposeSurface(key);
|
|
1170
|
+
surface = void 0;
|
|
1171
|
+
book = void 0;
|
|
1172
|
+
}
|
|
1173
|
+
if (!surface || !book) {
|
|
1174
|
+
surface = this.createSurface(key, threadId, agentId, content);
|
|
1175
|
+
this.restoreOwnedValues(surface);
|
|
1176
|
+
book = {
|
|
1177
|
+
appliedCount: 0,
|
|
1178
|
+
lastFingerprint: void 0
|
|
1179
|
+
};
|
|
1180
|
+
this.surfaces.set(key, surface);
|
|
1181
|
+
this.bookkeeping.set(key, book);
|
|
1182
|
+
changed = true;
|
|
1183
|
+
}
|
|
1184
|
+
const serverRejected = content.rejected ?? [];
|
|
1185
|
+
if (surface.clientRejected.length > 0 && (surface.status !== "streaming" && content.status === "streaming" || serverRejected.length < surface.serverRejected.length)) {
|
|
1186
|
+
surface.clientRejected = [];
|
|
1187
|
+
changed = true;
|
|
1188
|
+
}
|
|
1189
|
+
if (operations.length > 0) {
|
|
1190
|
+
const lastFingerprint = JSON.stringify(operations[operations.length - 1]);
|
|
1191
|
+
const isReplay = operations.some((op) => (0, _copilotkit_shared.getOperationKind)(op) === "deleteSurface");
|
|
1192
|
+
for (let index = book.appliedCount; index < operations.length; index++) {
|
|
1193
|
+
this.applyOperation(surface, operations[index], {
|
|
1194
|
+
index,
|
|
1195
|
+
isReplay
|
|
1196
|
+
});
|
|
1197
|
+
changed = true;
|
|
1198
|
+
}
|
|
1199
|
+
book.appliedCount = operations.length;
|
|
1200
|
+
surface.operations = operations;
|
|
1201
|
+
book.lastFingerprint = lastFingerprint;
|
|
1202
|
+
}
|
|
1203
|
+
if (surface.status !== content.status || surface.target !== content.target || surface.serverRejected.length !== serverRejected.length) {
|
|
1204
|
+
surface.status = content.status;
|
|
1205
|
+
surface.target = content.target;
|
|
1206
|
+
surface.serverRejected = serverRejected;
|
|
1207
|
+
changed = true;
|
|
1208
|
+
}
|
|
1209
|
+
if (changed) this.notify();
|
|
1210
|
+
}
|
|
1211
|
+
/** The surface of a `key` (see `surfaceKey`), unless it is deleted. */
|
|
1212
|
+
getSurfaceByKey(key) {
|
|
1213
|
+
const surface = this.surfaces.get(key);
|
|
1214
|
+
return surface && !surface.deleted ? surface : void 0;
|
|
1215
|
+
}
|
|
1216
|
+
getSurface(threadId, surfaceId) {
|
|
1217
|
+
const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
|
|
1218
|
+
return surface && !surface.deleted ? surface : void 0;
|
|
1219
|
+
}
|
|
1220
|
+
getSurfaceForTarget(target, threadId = this.activeThreadId) {
|
|
1221
|
+
if (!threadId) return void 0;
|
|
1222
|
+
let latest;
|
|
1223
|
+
for (const surface of this.surfaces.values()) {
|
|
1224
|
+
if (surface.threadId !== threadId || surface.target !== target || surface.deleted) continue;
|
|
1225
|
+
if (!latest || surface.createdAt > latest.createdAt) latest = surface;
|
|
1226
|
+
}
|
|
1227
|
+
return latest;
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* A surface whose first createSurface was rejected, so the chat can show
|
|
1231
|
+
* the error where the surface would be. `undefined` for any other surface.
|
|
1232
|
+
*/
|
|
1233
|
+
getFailedSurface(threadId, surfaceId) {
|
|
1234
|
+
const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
|
|
1235
|
+
return surface?.failed ? surface : void 0;
|
|
1236
|
+
}
|
|
1237
|
+
/**
|
|
1238
|
+
* The surfaces of a thread, for the model. A surface with user-owned
|
|
1239
|
+
* values lists them in `dataModel`, so the model can read what the user
|
|
1240
|
+
* entered. A surface with dropped operations lists them in `rejected`, so
|
|
1241
|
+
* the model can fix them on the next run. A deleted surface, or one that
|
|
1242
|
+
* was never created, has a `status`, so the model knows that the id is
|
|
1243
|
+
* not a live surface.
|
|
1244
|
+
*/
|
|
1245
|
+
describeSurfaces(threadId) {
|
|
1246
|
+
const described = {};
|
|
1247
|
+
for (const surface of this.surfaces.values()) {
|
|
1248
|
+
if (surface.threadId !== threadId) continue;
|
|
1249
|
+
const owned = this.owned.get(surface.key);
|
|
1250
|
+
const rejections = [...surface.serverRejected, ...surface.clientRejected];
|
|
1251
|
+
const status = this.deletedKeys.has(surface.key) ? "deleted" : surface.failed ? "failed" : void 0;
|
|
1252
|
+
described[surface.surfaceId] = {
|
|
1253
|
+
target: surface.target,
|
|
1254
|
+
...owned && owned.size > 0 ? { dataModel: Object.fromEntries(owned) } : {},
|
|
1255
|
+
...rejections.length > 0 && status !== "deleted" ? { rejected: summarizeRejections(rejections) } : {},
|
|
1256
|
+
...status ? { status } : {}
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
return described;
|
|
1260
|
+
}
|
|
1261
|
+
/** Every surface that is not deleted, oldest first, for the inspector. */
|
|
1262
|
+
debugSurfaces() {
|
|
1263
|
+
return [...this.surfaces.values()].filter((surface) => !surface.deleted).sort((a, b) => a.createdAt - b.createdAt).map((surface) => ({
|
|
1264
|
+
surfaceId: surface.surfaceId,
|
|
1265
|
+
threadId: surface.threadId,
|
|
1266
|
+
agentId: surface.agentId,
|
|
1267
|
+
target: surface.target,
|
|
1268
|
+
status: surface.status,
|
|
1269
|
+
operations: surface.operations,
|
|
1270
|
+
dataModel: surface.model.dataModel.get("/"),
|
|
1271
|
+
userValues: Object.fromEntries(this.owned.get(surface.key) ?? []),
|
|
1272
|
+
rejected: [...surface.serverRejected.map((r) => ({
|
|
1273
|
+
...r,
|
|
1274
|
+
source: "runtime"
|
|
1275
|
+
})), ...surface.clientRejected.map((r) => ({
|
|
1276
|
+
...r,
|
|
1277
|
+
source: "browser"
|
|
1278
|
+
}))]
|
|
1279
|
+
}));
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Marks a target as mounted. Returns the function that unmounts it. Calling
|
|
1283
|
+
* that function more than once has no effect.
|
|
1284
|
+
*
|
|
1285
|
+
* @param id - The target id.
|
|
1286
|
+
* @param options - The description and the allowed components of this mount.
|
|
1287
|
+
*/
|
|
1288
|
+
registerTarget(id, options = {}) {
|
|
1289
|
+
const registration = { ...options };
|
|
1290
|
+
const registrations = this.targets.get(id) ?? /* @__PURE__ */ new Set();
|
|
1291
|
+
registrations.add(registration);
|
|
1292
|
+
this.targets.set(id, registrations);
|
|
1293
|
+
this.notify();
|
|
1294
|
+
let released = false;
|
|
1295
|
+
return () => {
|
|
1296
|
+
if (released) return;
|
|
1297
|
+
released = true;
|
|
1298
|
+
registrations.delete(registration);
|
|
1299
|
+
if (registrations.size === 0) this.targets.delete(id);
|
|
1300
|
+
this.notify();
|
|
1301
|
+
};
|
|
1302
|
+
}
|
|
1303
|
+
/**
|
|
1304
|
+
* The mounted targets. Each has the description and the component list of
|
|
1305
|
+
* its earliest mount that has one.
|
|
1306
|
+
*/
|
|
1307
|
+
getMountedTargets() {
|
|
1308
|
+
const mounted = [];
|
|
1309
|
+
for (const [id, registrations] of this.targets) {
|
|
1310
|
+
const description = [...registrations].find((registration) => registration.description !== void 0)?.description;
|
|
1311
|
+
const components = this.targetComponents(id);
|
|
1312
|
+
mounted.push({
|
|
1313
|
+
id,
|
|
1314
|
+
...description === void 0 ? {} : { description },
|
|
1315
|
+
...components === void 0 ? {} : { components: [...components] }
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
return mounted;
|
|
1319
|
+
}
|
|
1320
|
+
/**
|
|
1321
|
+
* The component list of the earliest mount of `id` that has one.
|
|
1322
|
+
* `undefined` when no mount of `id` limits its components.
|
|
1323
|
+
*/
|
|
1324
|
+
targetComponents(id) {
|
|
1325
|
+
return [...this.targets.get(id) ?? /* @__PURE__ */ new Set()].find((registration) => registration.components !== void 0)?.components;
|
|
1326
|
+
}
|
|
1327
|
+
/** The components that `validateOperation` allows on a surface. */
|
|
1328
|
+
allowedComponentsFor(surface) {
|
|
1329
|
+
const components = this.targetComponents(surface.target);
|
|
1330
|
+
return components === void 0 ? void 0 : {
|
|
1331
|
+
target: surface.target,
|
|
1332
|
+
names: new Set(components)
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* The app state object. It is the same object until a key changes, so it
|
|
1337
|
+
* can be a `useSyncExternalStore` snapshot.
|
|
1338
|
+
*/
|
|
1339
|
+
getState = () => this.state;
|
|
1340
|
+
/** Sets one state key. Notifies only when the value changed. */
|
|
1341
|
+
setState(key, value) {
|
|
1342
|
+
if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
|
|
1343
|
+
this.state = {
|
|
1344
|
+
...this.state,
|
|
1345
|
+
[key]: value
|
|
1346
|
+
};
|
|
1347
|
+
this.notify();
|
|
1348
|
+
}
|
|
1349
|
+
/** Removes one state key. Notifies only when the key was set. */
|
|
1350
|
+
removeState(key) {
|
|
1351
|
+
if (!Object.hasOwn(this.state, key)) return;
|
|
1352
|
+
const { [key]: _removed, ...rest } = this.state;
|
|
1353
|
+
this.state = rest;
|
|
1354
|
+
this.notify();
|
|
1355
|
+
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Makes the surfaces of `surfaceIds` share their data model: a user write
|
|
1358
|
+
* to one of them goes to all of them (see `setOwnedValue`). The markdown
|
|
1359
|
+
* transport links the parts of a chat surface that the prose lift split.
|
|
1360
|
+
* A later call for one of the surfaces replaces its group.
|
|
1361
|
+
*
|
|
1362
|
+
* @param threadId - The thread of the surfaces.
|
|
1363
|
+
* @param surfaceIds - The surface ids of the group. One id clears a link.
|
|
1364
|
+
*/
|
|
1365
|
+
linkSurfaces(threadId, surfaceIds) {
|
|
1366
|
+
const keys = new Set(surfaceIds.map((id) => surfaceKey(threadId, id)));
|
|
1367
|
+
for (const key of keys) if (keys.size > 1) this.linked.set(key, keys);
|
|
1368
|
+
else this.linked.delete(key);
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Writes a user value into the data model of a surface, and marks `path`
|
|
1372
|
+
* as user-owned. Then agent writes to that path, or below it, are ignored.
|
|
1373
|
+
* An agent write above it keeps the user value. Ownership ends when the
|
|
1374
|
+
* surface is deleted. Does nothing for an unknown or deleted surface. The
|
|
1375
|
+
* surfaces linked to it (see `linkSurfaces`) get the same write.
|
|
1376
|
+
*
|
|
1377
|
+
* @param key - The `key` of the surface.
|
|
1378
|
+
* @param path - An absolute JSON pointer, for example "/form/email".
|
|
1379
|
+
* @param value - The new value. It is copied.
|
|
1380
|
+
* @throws Error when a path segment is "__proto__", "constructor" or
|
|
1381
|
+
* "prototype", or when the path does not fit the data (for example, a
|
|
1382
|
+
* segment above it holds a string).
|
|
1383
|
+
*/
|
|
1384
|
+
setOwnedValue(key, path, value) {
|
|
1385
|
+
const normalized = normalizePath(path);
|
|
1386
|
+
const forbidden = normalized.split("/").find((segment) => FORBIDDEN_SEGMENTS.has(segment));
|
|
1387
|
+
if (forbidden !== void 0) throw new Error(`[generativeUI] path segment "${forbidden}" is not allowed in "${path}".`);
|
|
1388
|
+
for (const target of this.linked.get(key) ?? [key]) this.writeOwnedValue(target, normalized, value);
|
|
1389
|
+
}
|
|
1390
|
+
writeOwnedValue(key, path, value) {
|
|
1391
|
+
const surface = this.surfaces.get(key);
|
|
1392
|
+
if (!surface || surface.deleted) return;
|
|
1393
|
+
surface.model.dataModel.set(path, structuredClone(value));
|
|
1394
|
+
const owned = this.owned.get(key) ?? /* @__PURE__ */ new Map();
|
|
1395
|
+
owned.set(path, structuredClone(value));
|
|
1396
|
+
this.owned.set(key, owned);
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Writes the user-owned values into the new, empty data model of a rebuilt
|
|
1400
|
+
* surface. The agent operations are applied after it.
|
|
1401
|
+
*/
|
|
1402
|
+
restoreOwnedValues(surface) {
|
|
1403
|
+
const owned = this.owned.get(surface.key) ?? /* @__PURE__ */ new Map();
|
|
1404
|
+
for (const [path, value] of owned) surface.model.dataModel.set(path, structuredClone(value));
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* The value that an agent write puts at `path`, with the user-owned values
|
|
1408
|
+
* below `path` written back into it. `undefined` when `path` is user-owned
|
|
1409
|
+
* or below a user-owned path, so the agent cannot write it. Throws when a
|
|
1410
|
+
* user value does not fit the new value.
|
|
1411
|
+
*/
|
|
1412
|
+
mergeOwnedValues(key, path, value) {
|
|
1413
|
+
const merged = { value: structuredClone(value) };
|
|
1414
|
+
const owned = this.owned.get(key);
|
|
1415
|
+
if (!owned) return merged;
|
|
1416
|
+
const ownedPaths = [...owned.keys()];
|
|
1417
|
+
if (ownedPaths.some((ownedPath) => isAtOrBelow(path, ownedPath))) return void 0;
|
|
1418
|
+
const below = ownedPaths.filter((ownedPath) => isAtOrBelow(ownedPath, path));
|
|
1419
|
+
if (below.length === 0) return merged;
|
|
1420
|
+
const scratch = new _a2ui_web_core_v0_9.DataModel({ value: merged.value });
|
|
1421
|
+
const prefix = path === "/" ? "" : path;
|
|
1422
|
+
for (const ownedPath of below) {
|
|
1423
|
+
const relative = ownedPath.slice(prefix.length);
|
|
1424
|
+
scratch.set(`/value${relative}`, structuredClone(owned.get(ownedPath)));
|
|
1425
|
+
}
|
|
1426
|
+
return { value: scratch.get("/value") };
|
|
1427
|
+
}
|
|
1428
|
+
extendsApplied(book, operations) {
|
|
1429
|
+
if (operations.length < book.appliedCount) return false;
|
|
1430
|
+
if (book.appliedCount === 0) return true;
|
|
1431
|
+
return JSON.stringify(operations[book.appliedCount - 1]) === book.lastFingerprint;
|
|
1432
|
+
}
|
|
1433
|
+
createSurface(key, threadId, agentId, content) {
|
|
1434
|
+
return {
|
|
1435
|
+
key,
|
|
1436
|
+
threadId,
|
|
1437
|
+
surfaceId: content.surfaceId,
|
|
1438
|
+
agentId,
|
|
1439
|
+
model: new _a2ui_web_core_v0_9.SurfaceModel(content.surfaceId, this.webCoreCatalog),
|
|
1440
|
+
createdAt: ++creationCounter,
|
|
1441
|
+
target: content.target,
|
|
1442
|
+
status: content.status,
|
|
1443
|
+
deleted: false,
|
|
1444
|
+
failed: false,
|
|
1445
|
+
serverRejected: content.rejected ?? [],
|
|
1446
|
+
clientRejected: [],
|
|
1447
|
+
operations: []
|
|
1448
|
+
};
|
|
1449
|
+
}
|
|
1450
|
+
disposeSurface(key) {
|
|
1451
|
+
this.surfaces.get(key)?.model.dispose();
|
|
1452
|
+
this.surfaces.delete(key);
|
|
1453
|
+
this.bookkeeping.delete(key);
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* Marks a surface deleted and frees its components and data. The record
|
|
1457
|
+
* stays, so the model is still told about the id and the bookkeeping does
|
|
1458
|
+
* not rebuild the surface for content that was already applied.
|
|
1459
|
+
*/
|
|
1460
|
+
closeSurface(surface) {
|
|
1461
|
+
surface.deleted = true;
|
|
1462
|
+
surface.model.dispose();
|
|
1463
|
+
surface.model = new _a2ui_web_core_v0_9.SurfaceModel(surface.surfaceId, this.webCoreCatalog);
|
|
1464
|
+
this.owned.delete(surface.key);
|
|
1465
|
+
this.linked.delete(surface.key);
|
|
1466
|
+
}
|
|
1467
|
+
/** The surfaces of a thread that a part of `surfaceId` reads, for tests. */
|
|
1468
|
+
getLinkedSurfaceIds(threadId, surfaceId) {
|
|
1469
|
+
const keys = this.linked.get(surfaceKey(threadId, surfaceId));
|
|
1470
|
+
if (!keys) return [surfaceId];
|
|
1471
|
+
const prefix = `${threadId}::`;
|
|
1472
|
+
return [...keys].map((key) => key.slice(prefix.length));
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* Drops the node keys that the app sets: bound props and matched events.
|
|
1476
|
+
* The model does not see them, so a model value for one is ignored, not
|
|
1477
|
+
* rejected. This runs before validation, because validation rejects keys
|
|
1478
|
+
* that are not in the manifest. It never changes the given operation.
|
|
1479
|
+
*/
|
|
1480
|
+
dropAppSetKeys(op) {
|
|
1481
|
+
const kind = (0, _copilotkit_shared.getOperationKind)(op);
|
|
1482
|
+
if (kind !== "updateComponents" && kind !== "createSurface") return op;
|
|
1483
|
+
const record = op;
|
|
1484
|
+
const payload = record[kind];
|
|
1485
|
+
const nodes = payload?.components;
|
|
1486
|
+
if (!Array.isArray(nodes)) return op;
|
|
1487
|
+
return {
|
|
1488
|
+
...record,
|
|
1489
|
+
[kind]: {
|
|
1490
|
+
...payload,
|
|
1491
|
+
components: nodes.map((node) => this.dropAppSetNodeKeys(node))
|
|
1492
|
+
}
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
dropAppSetNodeKeys(node) {
|
|
1496
|
+
if (typeof node !== "object" || node === null || !("component" in node)) return node;
|
|
1497
|
+
const { component } = node;
|
|
1498
|
+
if (typeof component !== "string") return node;
|
|
1499
|
+
const definition = this.ui.components.get(component);
|
|
1500
|
+
if (!definition) return node;
|
|
1501
|
+
return Object.fromEntries(Object.entries(node).filter(([key]) => !Object.hasOwn(definition.selectors, key) && !Object.hasOwn(definition.eventFunctions, key)));
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* The surfaces that `validateOperation` gets for one operation of the
|
|
1505
|
+
* content of `surface`.
|
|
1506
|
+
*
|
|
1507
|
+
* - `knownSurfaces`: the surface, when it exists before the operation. It
|
|
1508
|
+
* does not exist before its first createSurface, or after a delete.
|
|
1509
|
+
* - `createdSurfaces`: the surface, when a createSurface at this position
|
|
1510
|
+
* uses its id again. That is the case after the first operation, and for
|
|
1511
|
+
* a surface that was deleted before, unless the content replays that
|
|
1512
|
+
* delete.
|
|
1513
|
+
*/
|
|
1514
|
+
surfacesFor(surface, kind, position) {
|
|
1515
|
+
const isFirstCreate = kind === "createSurface" && position.index === 0;
|
|
1516
|
+
const exists = !surface.deleted && !isFirstCreate;
|
|
1517
|
+
const isRecreate = this.deletedKeys.has(surface.key) && !position.isReplay;
|
|
1518
|
+
const isUsedAgain = position.index > 0 || isRecreate;
|
|
1519
|
+
return {
|
|
1520
|
+
knownSurfaces: new Set(exists ? [surface.surfaceId] : []),
|
|
1521
|
+
createdSurfaces: new Set(isUsedAgain ? [surface.surfaceId] : [])
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
applyOperation(surface, received, position) {
|
|
1525
|
+
const { index } = position;
|
|
1526
|
+
const kind = (0, _copilotkit_shared.getOperationKind)(received);
|
|
1527
|
+
if (kind === "callRendererFunction") return;
|
|
1528
|
+
const reject = (reason) => {
|
|
1529
|
+
if (kind === "createSurface" && index === 0) {
|
|
1530
|
+
this.closeSurface(surface);
|
|
1531
|
+
surface.failed = true;
|
|
1532
|
+
}
|
|
1533
|
+
surface.clientRejected.push({
|
|
1534
|
+
index,
|
|
1535
|
+
reason
|
|
1536
|
+
});
|
|
1537
|
+
this.options.onOperationRejected?.({
|
|
1538
|
+
surfaceId: surface.surfaceId,
|
|
1539
|
+
index,
|
|
1540
|
+
reason
|
|
1541
|
+
});
|
|
1542
|
+
};
|
|
1543
|
+
const targetId = (0, _copilotkit_shared.getOperationSurfaceId)(received);
|
|
1544
|
+
if (targetId !== void 0 && targetId !== surface.surfaceId) return reject(`operation is for surface "${targetId}", not "${surface.surfaceId}"`);
|
|
1545
|
+
const op = this.dropAppSetKeys(received);
|
|
1546
|
+
const validation = (0, _copilotkit_shared.validateOperation)(op, {
|
|
1547
|
+
manifest: {
|
|
1548
|
+
catalogId: this.ui.id,
|
|
1549
|
+
catalogIds: (0, _copilotkit_shared_generative_ui.catalogIdsOf)(this.ui),
|
|
1550
|
+
components: this.ui.manifestComponents
|
|
1551
|
+
},
|
|
1552
|
+
...this.surfacesFor(surface, kind, position),
|
|
1553
|
+
allowedComponents: this.allowedComponentsFor(surface)
|
|
1554
|
+
});
|
|
1555
|
+
if (!validation.ok) return reject(validation.reason);
|
|
1556
|
+
const typed = op;
|
|
1557
|
+
if ("createSurface" in typed) {
|
|
1558
|
+
const { dataModel, components = [] } = typed.createSurface;
|
|
1559
|
+
const problem = this.nodesProblem(components);
|
|
1560
|
+
if (problem) return reject(problem);
|
|
1561
|
+
if (dataModel) {
|
|
1562
|
+
const failure = this.writeAgentData(surface, "/", dataModel);
|
|
1563
|
+
if (failure) return reject(failure);
|
|
1564
|
+
}
|
|
1565
|
+
for (const node of components) this.upsertNode(surface.model, node);
|
|
1566
|
+
return;
|
|
1567
|
+
}
|
|
1568
|
+
if ("updateComponents" in typed) {
|
|
1569
|
+
const nodes = typed.updateComponents.components;
|
|
1570
|
+
const problem = this.nodesProblem(nodes);
|
|
1571
|
+
if (problem) return reject(problem);
|
|
1572
|
+
for (const node of nodes) this.upsertNode(surface.model, node);
|
|
1573
|
+
return;
|
|
1574
|
+
}
|
|
1575
|
+
if ("updateDataModel" in typed) {
|
|
1576
|
+
const { path = "/", value } = typed.updateDataModel;
|
|
1577
|
+
const written = value === null ? void 0 : value;
|
|
1578
|
+
const failure = this.writeAgentData(surface, normalizePath(path), written);
|
|
1579
|
+
if (failure) return reject(failure);
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
if ("deleteSurface" in typed) {
|
|
1583
|
+
this.closeSurface(surface);
|
|
1584
|
+
this.deletedKeys.add(surface.key);
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
/** The first node with props of the wrong type, as a reason. */
|
|
1588
|
+
nodesProblem(nodes) {
|
|
1589
|
+
for (const node of nodes) {
|
|
1590
|
+
const problem = this.checkNodeProps(node);
|
|
1591
|
+
if (problem) return `component "${node.id}": ${problem}`;
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
/**
|
|
1595
|
+
* Writes an agent value at `path` and keeps the user-owned values. A write
|
|
1596
|
+
* to a user-owned path is ignored, not rejected. Gives the reason when the
|
|
1597
|
+
* value does not fit the data, else `undefined`.
|
|
1598
|
+
*/
|
|
1599
|
+
writeAgentData(surface, path, value) {
|
|
1600
|
+
try {
|
|
1601
|
+
const merged = this.mergeOwnedValues(surface.key, path, value);
|
|
1602
|
+
if (merged) surface.model.dataModel.set(path, merged.value);
|
|
1603
|
+
return;
|
|
1604
|
+
} catch (error) {
|
|
1605
|
+
return error instanceof Error ? error.message : String(error);
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
checkNodeProps(node) {
|
|
1609
|
+
const definition = this.ui.components.get(node.component);
|
|
1610
|
+
if (!definition) return `unknown component "${node.component}"`;
|
|
1611
|
+
const { id: _id, component: _component, ...rest } = node;
|
|
1612
|
+
const dataProps = Object.fromEntries(Object.entries(rest).filter(([key]) => !definition.events?.[key] && !definition.slots?.[key] && !_copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS.has(key)));
|
|
1613
|
+
if (!definition.props) return void 0;
|
|
1614
|
+
const unknownNow = new Set(Object.keys(definition.selectors));
|
|
1615
|
+
const literals = {};
|
|
1616
|
+
for (const [key, value] of Object.entries(dataProps)) if (containsDynamicValue(value)) unknownNow.add(key);
|
|
1617
|
+
else literals[key] = value;
|
|
1618
|
+
let result = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, literals);
|
|
1619
|
+
if (!result.success) {
|
|
1620
|
+
const unset = (0, _copilotkit_shared_generative_ui.withoutRejectedNulls)(literals, result.issues);
|
|
1621
|
+
if (unset) result = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, unset);
|
|
1622
|
+
}
|
|
1623
|
+
if (result.success) return void 0;
|
|
1624
|
+
const issues = result.issues.filter((issue) => {
|
|
1625
|
+
const key = (0, _copilotkit_shared_generative_ui.issueKey)(issue);
|
|
1626
|
+
return key === void 0 ? (0, _copilotkit_shared_generative_ui.isAsyncIssue)(issue) : !unknownNow.has(key);
|
|
1627
|
+
});
|
|
1628
|
+
return issues.length > 0 ? (0, _copilotkit_shared_generative_ui.formatIssues)(issues) : void 0;
|
|
1629
|
+
}
|
|
1630
|
+
upsertNode(model, node) {
|
|
1631
|
+
const { id, component, ...rest } = node;
|
|
1632
|
+
const properties = structuredClone(rest);
|
|
1633
|
+
const existing = model.componentsModel.get(id);
|
|
1634
|
+
if (existing && existing.type === component) {
|
|
1635
|
+
existing.properties = properties;
|
|
1636
|
+
return;
|
|
1637
|
+
}
|
|
1638
|
+
if (existing) model.componentsModel.removeComponent(id);
|
|
1639
|
+
model.componentsModel.addComponent(new _a2ui_web_core_v0_9.ComponentModel(id, component, properties));
|
|
1640
|
+
}
|
|
1641
|
+
};
|
|
1642
|
+
|
|
1643
|
+
//#endregion
|
|
1644
|
+
//#region src/generative-ui/dispatcher.ts
|
|
1645
|
+
const messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
1646
|
+
/**
|
|
1647
|
+
* Creates the registry of functions that generated UI may call.
|
|
1648
|
+
*
|
|
1649
|
+
* A function is callable when it is declared in `getDeclared()` and exactly
|
|
1650
|
+
* one handler is mounted for it with `register`. Names are resolved at call
|
|
1651
|
+
* time and fail closed. Nothing is sent to the agent.
|
|
1652
|
+
* Neither `invoke` nor `listExposed` throws.
|
|
1653
|
+
*
|
|
1654
|
+
* @param options.getDeclared - Returns the declared functions.
|
|
1655
|
+
* @param options.onError - Gets each failed call.
|
|
1656
|
+
*
|
|
1657
|
+
* @example
|
|
1658
|
+
* ```ts
|
|
1659
|
+
* const dispatcher = createGenerativeUIDispatcher({
|
|
1660
|
+
* getDeclared: () => new Map(Object.entries(ui.functions)),
|
|
1661
|
+
* });
|
|
1662
|
+
* const unregister = dispatcher.register("addToCart", handlerRef);
|
|
1663
|
+
* await dispatcher.invoke("addToCart", { productId: "p1" }, origin);
|
|
1664
|
+
* unregister();
|
|
1665
|
+
* ```
|
|
1666
|
+
*/
|
|
1667
|
+
/**
|
|
1668
|
+
* True while the browser counts the current task as user-activated (a
|
|
1669
|
+
* click, a key press). Where the API is missing (older browsers, test
|
|
1670
|
+
* environments), the gesture is assumed.
|
|
1671
|
+
*/
|
|
1672
|
+
function hasUserActivation() {
|
|
1673
|
+
if (typeof navigator === "undefined") return true;
|
|
1674
|
+
const activation = navigator.userActivation;
|
|
1675
|
+
return activation === void 0 || activation.isActive;
|
|
1676
|
+
}
|
|
1677
|
+
/**
|
|
1678
|
+
* The permissions of a declared function as the manifest states them: the
|
|
1679
|
+
* callers always written out, so a reader needs no default.
|
|
1680
|
+
*/
|
|
1681
|
+
function permissionsOf(fn) {
|
|
1682
|
+
const callers = (0, _copilotkit_shared.functionCallers)(fn);
|
|
1683
|
+
return {
|
|
1684
|
+
allowedCallers: callers.renderer && callers.agent ? "rendererOrAgent" : callers.agent ? "agentOnly" : "rendererOnly",
|
|
1685
|
+
...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
|
|
1686
|
+
};
|
|
1687
|
+
}
|
|
1688
|
+
function createGenerativeUIDispatcher(options) {
|
|
1689
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
1690
|
+
const resolveUnchecked = (name) => {
|
|
1691
|
+
const declared = options.getDeclared().get(name);
|
|
1692
|
+
if (!declared) return {
|
|
1693
|
+
ok: false,
|
|
1694
|
+
error: new _copilotkit_shared_generative_ui.GenerativeUIError("function_not_found", `No generative UI function named "${name}" is declared in createGenerativeUI({ functions })`)
|
|
1695
|
+
};
|
|
1696
|
+
const mounted = [...handlers.get(name) ?? []];
|
|
1697
|
+
const [ref] = mounted;
|
|
1698
|
+
if (!ref) return {
|
|
1699
|
+
ok: false,
|
|
1700
|
+
error: new _copilotkit_shared_generative_ui.GenerativeUIError("function_not_found", `"${name}" is declared, but no useGenerativeUIFunction handler is mounted for it`)
|
|
1701
|
+
};
|
|
1702
|
+
if (mounted.length > 1) return {
|
|
1703
|
+
ok: false,
|
|
1704
|
+
error: new _copilotkit_shared_generative_ui.GenerativeUIError("function_conflict", `"${name}" has ${mounted.length} useGenerativeUIFunction handlers mounted. Mount exactly one.`)
|
|
1705
|
+
};
|
|
1706
|
+
return {
|
|
1707
|
+
ok: true,
|
|
1708
|
+
declared,
|
|
1709
|
+
ref
|
|
1710
|
+
};
|
|
1711
|
+
};
|
|
1712
|
+
const isDeclared = (name) => {
|
|
1713
|
+
try {
|
|
1714
|
+
return options.getDeclared().has(name);
|
|
1715
|
+
} catch {
|
|
1716
|
+
return false;
|
|
1717
|
+
}
|
|
1718
|
+
};
|
|
1719
|
+
const resolve = (name) => {
|
|
1720
|
+
try {
|
|
1721
|
+
return resolveUnchecked(name);
|
|
1722
|
+
} catch (error) {
|
|
1723
|
+
return {
|
|
1724
|
+
ok: false,
|
|
1725
|
+
error: new _copilotkit_shared_generative_ui.GenerativeUIError("handler_failed", `"${name}" could not be resolved: ${messageOf(error)}`)
|
|
1726
|
+
};
|
|
1727
|
+
}
|
|
1728
|
+
};
|
|
1729
|
+
const validateArgs = async (name, schema, args) => {
|
|
1730
|
+
try {
|
|
1731
|
+
const validation = await schema["~standard"].validate(args);
|
|
1732
|
+
if (!validation.issues) return {
|
|
1733
|
+
ok: true,
|
|
1734
|
+
value: validation.value
|
|
1735
|
+
};
|
|
1736
|
+
return {
|
|
1737
|
+
ok: false,
|
|
1738
|
+
error: new _copilotkit_shared_generative_ui.GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${validation.issues.map((i) => `${(i.path ?? []).map((p) => typeof p === "object" ? p.key : p).join(".") || "args"}: ${i.message}`).join("; ")}`)
|
|
1739
|
+
};
|
|
1740
|
+
} catch (error) {
|
|
1741
|
+
return {
|
|
1742
|
+
ok: false,
|
|
1743
|
+
error: new _copilotkit_shared_generative_ui.GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${messageOf(error)}`)
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
};
|
|
1747
|
+
const failWith = (name, origin, error) => {
|
|
1748
|
+
try {
|
|
1749
|
+
options.onError?.({
|
|
1750
|
+
name,
|
|
1751
|
+
origin,
|
|
1752
|
+
error
|
|
1753
|
+
});
|
|
1754
|
+
} catch {}
|
|
1755
|
+
return {
|
|
1756
|
+
ok: false,
|
|
1757
|
+
error
|
|
1758
|
+
};
|
|
1759
|
+
};
|
|
1760
|
+
/**
|
|
1761
|
+
* Why `origin` may not call a function with these permissions now, as an
|
|
1762
|
+
* error, or `undefined` when it may. The agent is refused what is for the
|
|
1763
|
+
* renderer; a component is refused what is for the agent, and a gesture
|
|
1764
|
+
* function when the browser counts no user activation.
|
|
1765
|
+
*/
|
|
1766
|
+
const callerError = (name, fn, origin) => {
|
|
1767
|
+
const isComponent = "componentId" in origin;
|
|
1768
|
+
if (!isComponent && !_copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS) return new _copilotkit_shared_generative_ui.GenerativeUIError("invalid_function_call", _copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
|
|
1769
|
+
const problem = (0, _copilotkit_shared.callerProblem)(name, fn, isComponent ? "renderer" : "agent");
|
|
1770
|
+
if (problem !== void 0) return new _copilotkit_shared_generative_ui.GenerativeUIError("invalid_function_call", problem);
|
|
1771
|
+
if (isComponent && fn.requiresUserActivation && !hasUserActivation()) return new _copilotkit_shared_generative_ui.GenerativeUIError("invalid_function_call", `function "${name}" runs only from a user gesture; this event was not one`);
|
|
1772
|
+
};
|
|
1773
|
+
/**
|
|
1774
|
+
* Runs a basic function of the A2UI catalog. They are value functions of
|
|
1775
|
+
* the renderer: the agent cannot call them, and one that needs a user
|
|
1776
|
+
* gesture runs only from an event binding.
|
|
1777
|
+
*/
|
|
1778
|
+
const invokeBasic = (name, args, origin) => {
|
|
1779
|
+
const info = _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name];
|
|
1780
|
+
const run = BASIC_FUNCTIONS[name];
|
|
1781
|
+
if (!info || !run) return failWith(name, origin, new _copilotkit_shared_generative_ui.GenerativeUIError("function_not_found", `"${name}" is not a basic function`));
|
|
1782
|
+
const refused = callerError(name, info, origin);
|
|
1783
|
+
if (refused) return failWith(name, origin, refused);
|
|
1784
|
+
if (args !== void 0 && !(typeof args === "object" && args !== null && !Array.isArray(args))) return failWith(name, origin, new _copilotkit_shared_generative_ui.GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": args must be an object`));
|
|
1785
|
+
try {
|
|
1786
|
+
return {
|
|
1787
|
+
ok: true,
|
|
1788
|
+
result: run(args ?? {})
|
|
1789
|
+
};
|
|
1790
|
+
} catch (error) {
|
|
1791
|
+
return failWith(name, origin, new _copilotkit_shared_generative_ui.GenerativeUIError(error instanceof ExpressionError ? "invalid_arguments" : "handler_failed", `"${name}" failed: ${messageOf(error)}`));
|
|
1792
|
+
}
|
|
1793
|
+
};
|
|
1794
|
+
return {
|
|
1795
|
+
async invoke(name, args, origin) {
|
|
1796
|
+
const resolved = resolve(name);
|
|
1797
|
+
if (!resolved.ok && resolved.error.code === "function_not_found" && !isDeclared(name) && Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name)) return invokeBasic(name, args, origin);
|
|
1798
|
+
if (!resolved.ok) return failWith(name, origin, resolved.error);
|
|
1799
|
+
const refused = callerError(name, resolved.declared, origin);
|
|
1800
|
+
if (refused) return failWith(name, origin, refused);
|
|
1801
|
+
const validated = await validateArgs(name, resolved.declared.parameters, args ?? {});
|
|
1802
|
+
if (!validated.ok) return failWith(name, origin, validated.error);
|
|
1803
|
+
try {
|
|
1804
|
+
return {
|
|
1805
|
+
ok: true,
|
|
1806
|
+
result: await resolved.ref.current(validated.value)
|
|
1807
|
+
};
|
|
1808
|
+
} catch (error) {
|
|
1809
|
+
return failWith(name, origin, new _copilotkit_shared_generative_ui.GenerativeUIError("handler_failed", `"${name}" failed: ${messageOf(error)}`));
|
|
1810
|
+
}
|
|
1811
|
+
},
|
|
1812
|
+
listExposed() {
|
|
1813
|
+
let names;
|
|
1814
|
+
try {
|
|
1815
|
+
names = [...options.getDeclared().keys()];
|
|
1816
|
+
} catch {
|
|
1817
|
+
return {};
|
|
1818
|
+
}
|
|
1819
|
+
const listed = {};
|
|
1820
|
+
for (const name of names) {
|
|
1821
|
+
const resolved = resolve(name);
|
|
1822
|
+
if (!resolved.ok) continue;
|
|
1823
|
+
if (!(0, _copilotkit_shared.functionCallers)(resolved.declared).renderer && !_copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS) continue;
|
|
1824
|
+
const { description, parameters, returnType } = resolved.declared;
|
|
1825
|
+
try {
|
|
1826
|
+
listed[name] = {
|
|
1827
|
+
...description ? { description } : {},
|
|
1828
|
+
parameters: (0, _copilotkit_shared_generative_ui.toJsonSchema)(parameters),
|
|
1829
|
+
...returnType ? { returnType } : {},
|
|
1830
|
+
...permissionsOf(resolved.declared)
|
|
1831
|
+
};
|
|
1832
|
+
} catch {}
|
|
1833
|
+
}
|
|
1834
|
+
return listed;
|
|
1835
|
+
},
|
|
1836
|
+
register(name, ref) {
|
|
1837
|
+
const mounted = handlers.get(name) ?? /* @__PURE__ */ new Set();
|
|
1838
|
+
mounted.add(ref);
|
|
1839
|
+
handlers.set(name, mounted);
|
|
1840
|
+
return () => {
|
|
1841
|
+
mounted.delete(ref);
|
|
1842
|
+
};
|
|
1843
|
+
},
|
|
1844
|
+
handlerCount: (name) => handlers.get(name)?.size ?? 0
|
|
1845
|
+
};
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
//#endregion
|
|
1849
|
+
//#region src/generative-ui/events.ts
|
|
1850
|
+
/**
|
|
1851
|
+
* The context of a running event binding: it reads the surface data model
|
|
1852
|
+
* and resolves relative paths against the template item of the component.
|
|
1853
|
+
* A function that needs a user gesture (openUrl) is not a value here
|
|
1854
|
+
* either; it runs through the dispatcher as the binding's functionCall.
|
|
1855
|
+
*/
|
|
1856
|
+
function eventContext(surface, basePath) {
|
|
1857
|
+
return {
|
|
1858
|
+
data: surface.model.dataModel,
|
|
1859
|
+
basePath
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* A value of an event binding with its dynamic values resolved: `{"@path"}`
|
|
1864
|
+
* bindings and function values, at any depth.
|
|
1865
|
+
*/
|
|
1866
|
+
function resolveValue(surface, basePath, value) {
|
|
1867
|
+
return resolveDynamicValue(value, eventContext(surface, basePath)).value;
|
|
1868
|
+
}
|
|
1869
|
+
/**
|
|
1870
|
+
* The entries of an args or context record, each resolved on its own. The
|
|
1871
|
+
* record is not resolved as a whole, because a record with one `event` or
|
|
1872
|
+
* `functionCall` key would look like an action binding and stay as it is.
|
|
1873
|
+
*/
|
|
1874
|
+
function resolveValues(surface, basePath, values) {
|
|
1875
|
+
return Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [key, resolveValue(surface, basePath, value)]));
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* The `userMessage` of an event binding, as text. A `{"@path"}` or a
|
|
1879
|
+
* function value is resolved. `undefined` when there is no message, or
|
|
1880
|
+
* the value is not a string.
|
|
1881
|
+
*/
|
|
1882
|
+
function resolveUserMessage(surface, basePath, userMessage) {
|
|
1883
|
+
const value = resolveValue(surface, basePath, userMessage);
|
|
1884
|
+
return typeof value === "string" ? value : void 0;
|
|
1885
|
+
}
|
|
1886
|
+
/**
|
|
1887
|
+
* Validates the component's args with the event `parameters`, then runs
|
|
1888
|
+
* `send` with them. Never throws: every failure is reported and becomes
|
|
1889
|
+
* `{ ok: false, error }`.
|
|
1890
|
+
*/
|
|
1891
|
+
async function runEvent(call, send) {
|
|
1892
|
+
const { runtime, surface, componentId, name, parameters, args } = call;
|
|
1893
|
+
const origin = {
|
|
1894
|
+
surfaceId: surface.surfaceId,
|
|
1895
|
+
componentId
|
|
1896
|
+
};
|
|
1897
|
+
try {
|
|
1898
|
+
if (!parameters) return await send(args ?? {}, origin);
|
|
1899
|
+
const result = (0, _copilotkit_shared_generative_ui.validateSchema)(parameters, args ?? {});
|
|
1900
|
+
const parsed = result instanceof Promise ? await result : result;
|
|
1901
|
+
if (!parsed.success) {
|
|
1902
|
+
const error = new _copilotkit_shared_generative_ui.GenerativeUIError("invalid_event_args", `${name}: ${(0, _copilotkit_shared_generative_ui.formatIssues)(parsed.issues, "args")}`);
|
|
1903
|
+
reportErrorSafely(runtime, {
|
|
1904
|
+
kind: "event",
|
|
1905
|
+
...origin,
|
|
1906
|
+
error
|
|
1907
|
+
});
|
|
1908
|
+
return {
|
|
1909
|
+
ok: false,
|
|
1910
|
+
error
|
|
1911
|
+
};
|
|
1912
|
+
}
|
|
1913
|
+
return await send(parsed.data ?? {}, origin);
|
|
1914
|
+
} catch (cause) {
|
|
1915
|
+
const error = new _copilotkit_shared_generative_ui.GenerativeUIError("event_forward_failed", `${name}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
1916
|
+
reportErrorSafely(runtime, {
|
|
1917
|
+
kind: "event",
|
|
1918
|
+
...origin,
|
|
1919
|
+
error
|
|
1920
|
+
});
|
|
1921
|
+
return {
|
|
1922
|
+
ok: false,
|
|
1923
|
+
error
|
|
1924
|
+
};
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
/**
|
|
1928
|
+
* Runs one call of an event that the model bound: validates the component's
|
|
1929
|
+
* args, merges them with the args from the binding (binding literals win),
|
|
1930
|
+
* then calls a declared function or forwards an agent event. Never throws.
|
|
1931
|
+
*/
|
|
1932
|
+
function invokeBoundEvent(params) {
|
|
1933
|
+
const { runtime, surface, binding, basePath } = params;
|
|
1934
|
+
return runEvent(params, (args, origin) => {
|
|
1935
|
+
const componentArgs = args;
|
|
1936
|
+
if ("functionCall" in binding) return runtime.dispatcher.invoke(binding.functionCall["@call"], {
|
|
1937
|
+
...componentArgs,
|
|
1938
|
+
...resolveValues(surface, basePath, binding.functionCall.args)
|
|
1939
|
+
}, origin);
|
|
1940
|
+
const { event } = binding;
|
|
1941
|
+
const forwarded = {
|
|
1942
|
+
name: event.name,
|
|
1943
|
+
...origin,
|
|
1944
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1945
|
+
userMessage: resolveUserMessage(surface, basePath, event.userMessage),
|
|
1946
|
+
context: {
|
|
1947
|
+
...componentArgs,
|
|
1948
|
+
...resolveValues(surface, basePath, event.context)
|
|
1949
|
+
}
|
|
1950
|
+
};
|
|
1951
|
+
return runtime.forwardEvent(forwarded, surface.agentId);
|
|
1952
|
+
});
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* Runs one call of an event that matches a declared function: validates the
|
|
1956
|
+
* component's args with the event `parameters` (if any), then calls the
|
|
1957
|
+
* function, which validates them with its own schema. Never throws.
|
|
1958
|
+
*/
|
|
1959
|
+
function invokeMatchedEvent(params) {
|
|
1960
|
+
const { runtime, functionName } = params;
|
|
1961
|
+
return runEvent(params, (componentArgs, origin) => runtime.dispatcher.invoke(functionName, componentArgs, origin));
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
//#endregion
|
|
1965
|
+
//#region src/generative-ui/manifest.ts
|
|
1966
|
+
/**
|
|
1967
|
+
* The built-in functions (the A2UI basic catalog plus calc and series) as
|
|
1968
|
+
* manifest entries. Their args are described by the short signature, not
|
|
1969
|
+
* by a full JSON Schema: the renderer checks them when they run. An app
|
|
1970
|
+
* function of the same name replaces the entry.
|
|
1971
|
+
*/
|
|
1972
|
+
function builtInFunctionManifests() {
|
|
1973
|
+
return Object.fromEntries(Object.entries(_copilotkit_shared.GENERATIVE_UI_FUNCTIONS).map(([name, fn]) => [name, {
|
|
1974
|
+
description: fn.description,
|
|
1975
|
+
parameters: {
|
|
1976
|
+
type: "object",
|
|
1977
|
+
description: fn.parameters
|
|
1978
|
+
},
|
|
1979
|
+
returnType: fn.returnType,
|
|
1980
|
+
allowedCallers: fn.allowedCallers,
|
|
1981
|
+
...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
|
|
1982
|
+
}]));
|
|
1983
|
+
}
|
|
1984
|
+
/**
|
|
1985
|
+
* The manifest of a catalog, with no React runtime: the components of `ui`,
|
|
1986
|
+
* the built-in functions (minus the names the app declares) and
|
|
1987
|
+
* `options.functions`, the chat target and `options.targets`, and
|
|
1988
|
+
* `options.surfaces`. `buildGenerativeUIManifest` builds the per-run
|
|
1989
|
+
* manifest with it; tools that run outside React use it directly.
|
|
1990
|
+
*
|
|
1991
|
+
* @example
|
|
1992
|
+
* ```ts
|
|
1993
|
+
* const manifest = buildCatalogManifest(standardUI);
|
|
1994
|
+
* manifest.targets; // [{ id: "chat", kind: "chat" }]
|
|
1995
|
+
* ```
|
|
1996
|
+
*/
|
|
1997
|
+
function buildCatalogManifest(ui, options = {}) {
|
|
1998
|
+
return {
|
|
1999
|
+
catalogId: ui.id,
|
|
2000
|
+
catalogIds: (0, _copilotkit_shared_generative_ui.catalogIdsOf)(ui),
|
|
2001
|
+
components: (0, _copilotkit_shared.applyDescriptionOverrides)({ components: ui.manifestComponents }, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().descriptions).manifest.components,
|
|
2002
|
+
functions: {
|
|
2003
|
+
...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
|
|
2004
|
+
...options.functions
|
|
2005
|
+
},
|
|
2006
|
+
targets: [{
|
|
2007
|
+
id: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
|
|
2008
|
+
kind: "chat"
|
|
2009
|
+
}, ...options.targets ?? []],
|
|
2010
|
+
surfaces: options.surfaces ?? {}
|
|
2011
|
+
};
|
|
2012
|
+
}
|
|
2013
|
+
/**
|
|
2014
|
+
* Builds the per-run manifest. Never contains handlers or renderers.
|
|
2015
|
+
*
|
|
2016
|
+
* - `functions`: the built-in functions, then the declared functions with
|
|
2017
|
+
* exactly one mounted handler.
|
|
2018
|
+
* - `targets`: the chat first, then each mounted `<GenerativeUISurface>`,
|
|
2019
|
+
* with its `description` and its `components` when it has them.
|
|
2020
|
+
*/
|
|
2021
|
+
function buildGenerativeUIManifest(runtime, threadId) {
|
|
2022
|
+
const { ui, manager, dispatcher } = runtime;
|
|
2023
|
+
const inlineTargets = manager.getMountedTargets().filter((target) => target.id !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET).map(({ id, ...rest }) => ({
|
|
2024
|
+
id,
|
|
2025
|
+
kind: "inline",
|
|
2026
|
+
...rest
|
|
2027
|
+
}));
|
|
2028
|
+
return buildCatalogManifest(ui, {
|
|
2029
|
+
functions: dispatcher.listExposed(),
|
|
2030
|
+
targets: inlineTargets,
|
|
2031
|
+
surfaces: threadId ? manager.describeSurfaces(threadId) : {}
|
|
2032
|
+
});
|
|
2033
|
+
}
|
|
2034
|
+
/** What the envelope of a run says, from the provider config. */
|
|
2035
|
+
function envelopeOptionsFor(config) {
|
|
2036
|
+
if (config.transport === "markdown") return {
|
|
2037
|
+
transport: "markdown",
|
|
2038
|
+
includeCatalog: config.includeCatalog !== false,
|
|
2039
|
+
contextSent: config.sendContext !== false
|
|
2040
|
+
};
|
|
2041
|
+
return {
|
|
2042
|
+
transport: "tool",
|
|
2043
|
+
includeCatalog: true,
|
|
2044
|
+
contextSent: false
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
/**
|
|
2048
|
+
* Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
|
|
2049
|
+
* from the per-run manifest. It has the A2UI v1.0 renderer capabilities
|
|
2050
|
+
* shape: one inline catalog with the id of the UI, and the CopilotKit data
|
|
2051
|
+
* in `metadata.extensions`.
|
|
2052
|
+
*
|
|
2053
|
+
* The inline catalog has no `components` only for the markdown transport
|
|
2054
|
+
* with `includeCatalog: false`. It has `instructions` for the markdown
|
|
2055
|
+
* transport, or when given.
|
|
2056
|
+
*
|
|
2057
|
+
* @param runtime - The generative UI runtime of the provider.
|
|
2058
|
+
* @param threadId - The thread of the run. Its surfaces go in `copilotkit_surfaces`.
|
|
2059
|
+
* @param options - The transport and what to send.
|
|
2060
|
+
*
|
|
2061
|
+
* @example
|
|
2062
|
+
* ```ts
|
|
2063
|
+
* const envelope = buildGenerativeUIEnvelope(runtime, agent.threadId, {
|
|
2064
|
+
* transport: "tool",
|
|
2065
|
+
* includeCatalog: true,
|
|
2066
|
+
* contextSent: false,
|
|
2067
|
+
* });
|
|
2068
|
+
* envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
|
|
2069
|
+
* ```
|
|
2070
|
+
*/
|
|
2071
|
+
function buildGenerativeUIEnvelope(runtime, threadId, options) {
|
|
2072
|
+
const { transport, includeCatalog, contextSent, action } = options;
|
|
2073
|
+
const manifest = buildGenerativeUIManifest(runtime, threadId);
|
|
2074
|
+
const instructions = options.instructions ?? (transport === "markdown" ? (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest)) : void 0);
|
|
2075
|
+
const omitComponents = transport === "markdown" && !includeCatalog;
|
|
2076
|
+
return {
|
|
2077
|
+
"1.0": {
|
|
2078
|
+
supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
|
|
2079
|
+
inlineCatalogs: [{
|
|
2080
|
+
catalogId: manifest.catalogId,
|
|
2081
|
+
protocolVersion: "1.0",
|
|
2082
|
+
...omitComponents ? {} : { components: manifest.components },
|
|
2083
|
+
functions: manifest.functions,
|
|
2084
|
+
...instructions === void 0 ? {} : { instructions }
|
|
2085
|
+
}]
|
|
2086
|
+
},
|
|
2087
|
+
metadata: { extensions: {
|
|
2088
|
+
copilotkit_format: _copilotkit_shared.COPILOTKIT_UI_ENVELOPE_FORMAT,
|
|
2089
|
+
copilotkit_transport: transport,
|
|
2090
|
+
copilotkit_targets: manifest.targets,
|
|
2091
|
+
copilotkit_surfaces: manifest.surfaces,
|
|
2092
|
+
copilotkit_contextSent: contextSent,
|
|
2093
|
+
...action === void 0 ? {} : { copilotkit_action: action }
|
|
2094
|
+
} }
|
|
2095
|
+
};
|
|
2096
|
+
}
|
|
2097
|
+
|
|
2098
|
+
//#endregion
|
|
2099
|
+
//#region src/generative-ui/markdown-source.ts
|
|
2100
|
+
/**
|
|
2101
|
+
* Values by key, from the latest build. A value that a build does not use
|
|
2102
|
+
* is dropped at the end of that build, so the cache does not grow.
|
|
2103
|
+
*/
|
|
2104
|
+
var BuildMemo = class {
|
|
2105
|
+
previous = /* @__PURE__ */ new Map();
|
|
2106
|
+
current = /* @__PURE__ */ new Map();
|
|
2107
|
+
/**
|
|
2108
|
+
* The value of `key`. It is computed when no earlier value is there, or
|
|
2109
|
+
* when `isFresh` says that the earlier value is out of date.
|
|
2110
|
+
*/
|
|
2111
|
+
get(key, compute, isFresh = () => true) {
|
|
2112
|
+
let value = this.current.get(key) ?? this.previous.get(key);
|
|
2113
|
+
if (value === void 0 || !isFresh(value)) value = compute();
|
|
2114
|
+
this.current.set(key, value);
|
|
2115
|
+
return value;
|
|
2116
|
+
}
|
|
2117
|
+
endBuild() {
|
|
2118
|
+
this.previous = this.current;
|
|
2119
|
+
this.current = /* @__PURE__ */ new Map();
|
|
2120
|
+
}
|
|
2121
|
+
};
|
|
2122
|
+
/** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */
|
|
2123
|
+
var MarkdownBuildCache = class {
|
|
2124
|
+
segments = new BuildMemo();
|
|
2125
|
+
fences = new BuildMemo();
|
|
2126
|
+
drafts = new BuildMemo();
|
|
2127
|
+
/** The copies of an operation for other surface ids, by operation. */
|
|
2128
|
+
readdressed = /* @__PURE__ */ new WeakMap();
|
|
2129
|
+
endBuild() {
|
|
2130
|
+
this.segments.endBuild();
|
|
2131
|
+
this.fences.endBuild();
|
|
2132
|
+
this.drafts.endBuild();
|
|
2133
|
+
}
|
|
2134
|
+
};
|
|
2135
|
+
/** True when both lists hold the same objects in the same order. */
|
|
2136
|
+
function sameItems(a, b) {
|
|
2137
|
+
return a.length === b.length && a.every((item, index) => item === b[index]);
|
|
2138
|
+
}
|
|
2139
|
+
function isString(value) {
|
|
2140
|
+
return typeof value === "string";
|
|
2141
|
+
}
|
|
2142
|
+
/** The key of one fence of one message. */
|
|
2143
|
+
function fenceKey(messageId, fenceIndex) {
|
|
2144
|
+
return `${messageId}:${fenceIndex}`;
|
|
2145
|
+
}
|
|
2146
|
+
/**
|
|
2147
|
+
* The operations of a fence body. While the fence streams, the last object
|
|
2148
|
+
* can be unfinished. Of an unfinished updateComponents or createSurface, the
|
|
2149
|
+
* components that are complete render at once (a createSurface also keeps
|
|
2150
|
+
* its data model when all of it arrived). Any other unfinished object is
|
|
2151
|
+
* left out, because a part of a data model value can still change. A final
|
|
2152
|
+
* fence keeps what can be saved from an unfinished object.
|
|
2153
|
+
*/
|
|
2154
|
+
function fenceOperations(text, isStreaming) {
|
|
2155
|
+
const parsed = require_a2ui_markdown.extractFenceOperations(text);
|
|
2156
|
+
if (!isStreaming || parsed.partialObject === null) return parsed.operations;
|
|
2157
|
+
const complete = require_a2ui_markdown.extractFenceOperations(text.slice(0, text.length - parsed.partialObject.length)).operations;
|
|
2158
|
+
const partial = parsed.operations.length > complete.length ? parsed.operations[parsed.operations.length - 1] : void 0;
|
|
2159
|
+
return partial !== void 0 && ((0, _copilotkit_shared_generative_ui.isRecord)(partial.updateComponents) || (0, _copilotkit_shared_generative_ui.isRecord)(partial.createSurface)) ? [...complete, partial] : complete;
|
|
2160
|
+
}
|
|
2161
|
+
/**
|
|
2162
|
+
* An inline createSurface becomes a createSurface with only its surfaceId
|
|
2163
|
+
* and catalog, then an updateDataModel for its data model, then an
|
|
2164
|
+
* updateComponents for its components. The prose lift and the split per
|
|
2165
|
+
* component read only updateComponents, so they then work for an inline
|
|
2166
|
+
* surface too. A createSurface with a data model or components of a wrong
|
|
2167
|
+
* shape does not change, so that validation rejects it with the reason.
|
|
2168
|
+
*/
|
|
2169
|
+
function expandInlineCreate(operations) {
|
|
2170
|
+
return operations.flatMap((op) => {
|
|
2171
|
+
const create = op.createSurface;
|
|
2172
|
+
if (!(0, _copilotkit_shared_generative_ui.isRecord)(create)) return [op];
|
|
2173
|
+
const { dataModel, components, ...rest } = create;
|
|
2174
|
+
const hasData = (0, _copilotkit_shared_generative_ui.isRecord)(dataModel);
|
|
2175
|
+
const hasComponents = Array.isArray(components) && components.length > 0;
|
|
2176
|
+
if (!((dataModel === void 0 || hasData) && (components === void 0 || hasComponents)) || !hasData && !hasComponents) return [op];
|
|
2177
|
+
const { surfaceId } = create;
|
|
2178
|
+
const expanded = [{
|
|
2179
|
+
...op,
|
|
2180
|
+
createSurface: rest
|
|
2181
|
+
}];
|
|
2182
|
+
if (hasData) expanded.push({
|
|
2183
|
+
version: op.version,
|
|
2184
|
+
updateDataModel: {
|
|
2185
|
+
surfaceId,
|
|
2186
|
+
path: "/",
|
|
2187
|
+
value: dataModel
|
|
2188
|
+
}
|
|
2189
|
+
});
|
|
2190
|
+
if (hasComponents) expanded.push({
|
|
2191
|
+
version: op.version,
|
|
2192
|
+
updateComponents: {
|
|
2193
|
+
surfaceId,
|
|
2194
|
+
components
|
|
2195
|
+
}
|
|
2196
|
+
});
|
|
2197
|
+
return expanded;
|
|
2198
|
+
});
|
|
2199
|
+
}
|
|
2200
|
+
/**
|
|
2201
|
+
* Each updateComponents becomes one operation per component, in order. The
|
|
2202
|
+
* complete components of a streaming line then give the same first
|
|
2203
|
+
* operations as the finished line, so the operation list only grows and the
|
|
2204
|
+
* manager never has to start the surface again.
|
|
2205
|
+
*/
|
|
2206
|
+
function splitComponentUpdates(operations) {
|
|
2207
|
+
return operations.flatMap((op) => {
|
|
2208
|
+
const update = op.updateComponents;
|
|
2209
|
+
if (!(0, _copilotkit_shared_generative_ui.isRecord)(update) || !Array.isArray(update.components)) return [op];
|
|
2210
|
+
if (update.components.length <= 1) return [op];
|
|
2211
|
+
return update.components.map((component) => ({
|
|
2212
|
+
...op,
|
|
2213
|
+
updateComponents: {
|
|
2214
|
+
...update,
|
|
2215
|
+
components: [component]
|
|
2216
|
+
}
|
|
2217
|
+
}));
|
|
2218
|
+
});
|
|
2219
|
+
}
|
|
2220
|
+
/** createSurface first, the other operations after it in their order. */
|
|
2221
|
+
function createSurfaceFirst(operations) {
|
|
2222
|
+
const creates = operations.filter((op) => (0, _copilotkit_shared_generative_ui.isRecord)(op.createSurface));
|
|
2223
|
+
const others = operations.filter((op) => !(0, _copilotkit_shared_generative_ui.isRecord)(op.createSurface));
|
|
2224
|
+
return [...creates, ...others];
|
|
2225
|
+
}
|
|
2226
|
+
/** True when the component of `name` has the prop `prop`. */
|
|
2227
|
+
function hasProp(ui, name, prop) {
|
|
2228
|
+
const properties = ui.manifestComponents[name]?.props.properties;
|
|
2229
|
+
return (0, _copilotkit_shared_generative_ui.isRecord)(properties) && Object.hasOwn(properties, prop);
|
|
2230
|
+
}
|
|
2231
|
+
const childRefCache = /* @__PURE__ */ new WeakMap();
|
|
2232
|
+
/** The ids in a slot value: an id, a list of ids, or a template. */
|
|
2233
|
+
function slotIds(value) {
|
|
2234
|
+
if (typeof value === "string") return [value];
|
|
2235
|
+
if (Array.isArray(value)) return value.filter(isString);
|
|
2236
|
+
return (0, _copilotkit_shared_generative_ui.isRecord)(value) && isString(value.componentId) ? [value.componentId] : [];
|
|
2237
|
+
}
|
|
2238
|
+
/**
|
|
2239
|
+
* A reader of the ids a component renders beyond `child` and `children`:
|
|
2240
|
+
* its declared slots (the `trigger` and `content` of a Modal) and its typed
|
|
2241
|
+
* child references (the `child` of each entry of `tabs`), from its catalog
|
|
2242
|
+
* entry. The prose lift follows these ids like `children`, so a panel is
|
|
2243
|
+
* never cut off from its Tabs. A reference that is bound to the data
|
|
2244
|
+
* model is "unknown": its ids exist only at render time.
|
|
2245
|
+
*/
|
|
2246
|
+
function childIdsReader(ui) {
|
|
2247
|
+
return (component) => {
|
|
2248
|
+
const name = component.component;
|
|
2249
|
+
const entry = typeof name === "string" && Object.hasOwn(ui.manifestComponents, name) ? ui.manifestComponents[name] : void 0;
|
|
2250
|
+
if (!entry) return [];
|
|
2251
|
+
const ids = [];
|
|
2252
|
+
for (const slot of Object.keys(entry.slots ?? {})) if (slot !== "child" && slot !== "children") ids.push(...slotIds(component[slot]));
|
|
2253
|
+
let refs = childRefCache.get(entry.props);
|
|
2254
|
+
if (!refs) {
|
|
2255
|
+
refs = (0, _copilotkit_shared.collectChildRefs)(entry.props);
|
|
2256
|
+
childRefCache.set(entry.props, refs);
|
|
2257
|
+
}
|
|
2258
|
+
if (refs.length === 0) return ids;
|
|
2259
|
+
if ((0, _copilotkit_shared.hasBoundChildRef)(component, refs)) return "unknown";
|
|
2260
|
+
return [...ids, ...(0, _copilotkit_shared.childIdsAtRefs)(component, refs)];
|
|
2261
|
+
};
|
|
2262
|
+
}
|
|
2263
|
+
/** Every component of the operations by id, last definition wins. */
|
|
2264
|
+
function collectComponents(operations) {
|
|
2265
|
+
const byId = /* @__PURE__ */ new Map();
|
|
2266
|
+
for (const op of operations) {
|
|
2267
|
+
const update = op.updateComponents;
|
|
2268
|
+
const list = (0, _copilotkit_shared_generative_ui.isRecord)(update) ? update.components : void 0;
|
|
2269
|
+
if (!Array.isArray(list)) continue;
|
|
2270
|
+
for (const component of list) if ((0, _copilotkit_shared_generative_ui.isRecord)(component) && isString(component.id)) byId.set(component.id, component);
|
|
2271
|
+
}
|
|
2272
|
+
return [...byId.values()];
|
|
2273
|
+
}
|
|
2274
|
+
/**
|
|
2275
|
+
* The data model must not be shared between two surfaces. A data model
|
|
2276
|
+
* keeps the object it gets, so an input in one surface would change the
|
|
2277
|
+
* data of the other one.
|
|
2278
|
+
*/
|
|
2279
|
+
function cloneData(value) {
|
|
2280
|
+
return value === void 0 ? void 0 : structuredClone(value);
|
|
2281
|
+
}
|
|
2282
|
+
/** The operation sent to `surfaceId`, with a copy of its data model value. */
|
|
2283
|
+
function readdress(op, surfaceId) {
|
|
2284
|
+
const kind = (0, _copilotkit_shared.getOperationKind)(op);
|
|
2285
|
+
const payload = kind ? op[kind] : void 0;
|
|
2286
|
+
if (!kind || !(0, _copilotkit_shared_generative_ui.isRecord)(payload)) return op;
|
|
2287
|
+
const next = {
|
|
2288
|
+
...payload,
|
|
2289
|
+
surfaceId
|
|
2290
|
+
};
|
|
2291
|
+
if (kind === "updateDataModel" && "value" in payload) next.value = cloneData(payload.value);
|
|
2292
|
+
return {
|
|
2293
|
+
...op,
|
|
2294
|
+
[kind]: next
|
|
2295
|
+
};
|
|
2296
|
+
}
|
|
2297
|
+
/**
|
|
2298
|
+
* The operations of one sub-surface. Each updateComponents keeps only the
|
|
2299
|
+
* components of the sub-surface, with its own root. The other operations
|
|
2300
|
+
* are sent to the sub-surface. The order stays the same, so a new operation
|
|
2301
|
+
* of the fence only adds operations at the end.
|
|
2302
|
+
*/
|
|
2303
|
+
function subSurfaceOperations(operations, components, surfaceId) {
|
|
2304
|
+
const root = components.find((c) => c.id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID);
|
|
2305
|
+
const ids = new Set(components.map((c) => c.id));
|
|
2306
|
+
const out = [];
|
|
2307
|
+
for (const op of operations) {
|
|
2308
|
+
const update = op.updateComponents;
|
|
2309
|
+
if (!(0, _copilotkit_shared_generative_ui.isRecord)(update) || !Array.isArray(update.components)) {
|
|
2310
|
+
out.push(readdress(op, surfaceId));
|
|
2311
|
+
continue;
|
|
2312
|
+
}
|
|
2313
|
+
const kept = update.components.filter((c) => (0, _copilotkit_shared_generative_ui.isRecord)(c) && ids.has(c.id)).map((c) => (0, _copilotkit_shared_generative_ui.isRecord)(c) && c.id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID ? root : c);
|
|
2314
|
+
if (kept.length === 0) continue;
|
|
2315
|
+
out.push({
|
|
2316
|
+
...op,
|
|
2317
|
+
updateComponents: {
|
|
2318
|
+
...update,
|
|
2319
|
+
surfaceId,
|
|
2320
|
+
components: kept
|
|
2321
|
+
}
|
|
2322
|
+
});
|
|
2323
|
+
}
|
|
2324
|
+
return out;
|
|
2325
|
+
}
|
|
2326
|
+
/**
|
|
2327
|
+
* Prose lift. Text components in the main stack of the surface (titles,
|
|
2328
|
+
* paragraphs, text lists and the dividers between them) become chat
|
|
2329
|
+
* markdown. The surface splits around them: the first surface keeps
|
|
2330
|
+
* `surfaceId`, the next ones are `<surfaceId>#1`, `<surfaceId>#2`, and so
|
|
2331
|
+
* on. A surface with no prose comes back as one part with the same
|
|
2332
|
+
* operations.
|
|
2333
|
+
*/
|
|
2334
|
+
function liftProse(operations, surfaceId, childIds) {
|
|
2335
|
+
const components = collectComponents(operations);
|
|
2336
|
+
const segments = require_a2ui_markdown.segmentSurfaceProse(components, { childIds });
|
|
2337
|
+
const [first] = segments;
|
|
2338
|
+
if (segments.length === 1 && first?.kind === "surface" && first.components === components) return [{
|
|
2339
|
+
kind: "surface",
|
|
2340
|
+
surfaceId,
|
|
2341
|
+
operations
|
|
2342
|
+
}];
|
|
2343
|
+
let surfaceIndex = 0;
|
|
2344
|
+
return segments.map((segment) => {
|
|
2345
|
+
if (segment.kind === "markdown") return segment;
|
|
2346
|
+
const id = surfaceIndex === 0 ? surfaceId : `${surfaceId}#${surfaceIndex}`;
|
|
2347
|
+
surfaceIndex++;
|
|
2348
|
+
return {
|
|
2349
|
+
kind: "surface",
|
|
2350
|
+
surfaceId: id,
|
|
2351
|
+
operations: subSurfaceOperations(operations, segment.components, id)
|
|
2352
|
+
};
|
|
2353
|
+
});
|
|
2354
|
+
}
|
|
2355
|
+
/** `validateOperation`, with the operation typed when it is valid. */
|
|
2356
|
+
function checkOperation(op, options) {
|
|
2357
|
+
const validation = (0, _copilotkit_shared.validateOperation)(op, options);
|
|
2358
|
+
if (!validation.ok) return validation;
|
|
2359
|
+
return {
|
|
2360
|
+
ok: true,
|
|
2361
|
+
operation: op
|
|
2362
|
+
};
|
|
2363
|
+
}
|
|
2364
|
+
/**
|
|
2365
|
+
* The content of one surface. Each operation is validated against the
|
|
2366
|
+
* manifest. A valid operation goes in `operations`. A rejected one goes in
|
|
2367
|
+
* `rejected`, with its position and the reason.
|
|
2368
|
+
*/
|
|
2369
|
+
function surfaceContent(surfaceId, draft, operations, options) {
|
|
2370
|
+
const { ui, functions } = options;
|
|
2371
|
+
const knownSurfaces = /* @__PURE__ */ new Set();
|
|
2372
|
+
const manifest = {
|
|
2373
|
+
catalogId: ui.id,
|
|
2374
|
+
catalogIds: (0, _copilotkit_shared_generative_ui.catalogIdsOf)(ui),
|
|
2375
|
+
components: ui.manifestComponents
|
|
2376
|
+
};
|
|
2377
|
+
const valid = [];
|
|
2378
|
+
const rejected = [];
|
|
2379
|
+
operations.forEach((op, index) => {
|
|
2380
|
+
const result = checkOperation(op, {
|
|
2381
|
+
manifest,
|
|
2382
|
+
knownSurfaces,
|
|
2383
|
+
functions
|
|
2384
|
+
});
|
|
2385
|
+
if (!result.ok) {
|
|
2386
|
+
rejected.push({
|
|
2387
|
+
index,
|
|
2388
|
+
reason: result.reason
|
|
2389
|
+
});
|
|
2390
|
+
return;
|
|
2391
|
+
}
|
|
2392
|
+
valid.push(result.operation);
|
|
2393
|
+
const kind = (0, _copilotkit_shared.getOperationKind)(result.operation);
|
|
2394
|
+
if (kind === "createSurface") knownSurfaces.add(surfaceId);
|
|
2395
|
+
if (kind === "deleteSurface") knownSurfaces.delete(surfaceId);
|
|
2396
|
+
});
|
|
2397
|
+
const create = valid.find((op) => "createSurface" in op);
|
|
2398
|
+
return {
|
|
2399
|
+
surfaceId,
|
|
2400
|
+
target: draft.target,
|
|
2401
|
+
catalogId: create?.createSurface.catalogId ?? ui.id,
|
|
2402
|
+
operations: valid,
|
|
2403
|
+
status: draft.streaming ? "streaming" : "ready",
|
|
2404
|
+
rejected
|
|
2405
|
+
};
|
|
2406
|
+
}
|
|
2407
|
+
/**
|
|
2408
|
+
* Builds the surfaces of a thread from the ```a2ui fences of its assistant
|
|
2409
|
+
* messages, in message order.
|
|
2410
|
+
*
|
|
2411
|
+
* - Operations are grouped by surfaceId across all messages. An operation
|
|
2412
|
+
* with no surfaceId goes to the first surface of its fence, else to
|
|
2413
|
+
* `<messageId>-<fenceIndex>`.
|
|
2414
|
+
* - The fence that first writes a surface creates it. The `target=<id>` of
|
|
2415
|
+
* that fence sets the target. With no target, the surface goes to the
|
|
2416
|
+
* chat.
|
|
2417
|
+
* - A later fence of the same reply for the same surfaceId updates it. A
|
|
2418
|
+
* later reply that reuses the id of a chat surface gets a surface of its
|
|
2419
|
+
* own, `<id>@<messageId>`. A page target is updated from any reply.
|
|
2420
|
+
* - The status is "streaming" while the creating fence streams, else
|
|
2421
|
+
* "ready".
|
|
2422
|
+
* - Each operation is validated with `validateOperation`. Rejected ones are
|
|
2423
|
+
* left out and listed in `rejected`.
|
|
2424
|
+
* - Chat surfaces get the prose lift: informational cards lose their box,
|
|
2425
|
+
* and prose becomes markdown that renders between sub-surfaces
|
|
2426
|
+
* (`<surfaceId>#<n>`). An inline createSurface is split into its
|
|
2427
|
+
* createSurface, updateDataModel and updateComponents first.
|
|
2428
|
+
* - A `callRendererFunction` line is not part of a surface. It goes to
|
|
2429
|
+
* `functionCalls`. A streaming line gives nothing, so a function never
|
|
2430
|
+
* runs with a part of its args.
|
|
2431
|
+
*
|
|
2432
|
+
* The function is pure. Call it again on each stream update. The manager
|
|
2433
|
+
* applies only the new operations, so unchanged surfaces do not render
|
|
2434
|
+
* again.
|
|
2435
|
+
*
|
|
2436
|
+
* @param messages - The messages of one thread.
|
|
2437
|
+
* @param options - The generative UI, its declared functions, and whether
|
|
2438
|
+
* the last message can still grow.
|
|
2439
|
+
* @returns `surfaces`, one content for each surface and sub-surface;
|
|
2440
|
+
* `fences`, the blocks that each fence renders, by `fenceKey` (a fence
|
|
2441
|
+
* that is not in `fences` renders nothing); `functionCalls`, the function
|
|
2442
|
+
* calls of the fences in order; and `parts`, the surface ids of the parts
|
|
2443
|
+
* of each surface, by surface id.
|
|
2444
|
+
*
|
|
2445
|
+
* @example
|
|
2446
|
+
* ```ts
|
|
2447
|
+
* const { surfaces } = buildMarkdownSurfaces(agent.messages, {
|
|
2448
|
+
* ui,
|
|
2449
|
+
* functions: {},
|
|
2450
|
+
* running: agent.isRunning,
|
|
2451
|
+
* });
|
|
2452
|
+
* for (const content of surfaces) manager.ingest(threadId, agentId, content);
|
|
2453
|
+
* ```
|
|
2454
|
+
*/
|
|
2455
|
+
function buildMarkdownSurfaces(messages, options) {
|
|
2456
|
+
const { ui, cache } = options;
|
|
2457
|
+
const drafts = /* @__PURE__ */ new Map();
|
|
2458
|
+
const readdressOnce = (op, surfaceId) => {
|
|
2459
|
+
if (!cache) return readdress(op, surfaceId);
|
|
2460
|
+
let copies = cache.readdressed.get(op);
|
|
2461
|
+
if (!copies) {
|
|
2462
|
+
copies = /* @__PURE__ */ new Map();
|
|
2463
|
+
cache.readdressed.set(op, copies);
|
|
2464
|
+
}
|
|
2465
|
+
let copy = copies.get(surfaceId);
|
|
2466
|
+
if (!copy) {
|
|
2467
|
+
copy = readdress(op, surfaceId);
|
|
2468
|
+
copies.set(surfaceId, copy);
|
|
2469
|
+
}
|
|
2470
|
+
return copy;
|
|
2471
|
+
};
|
|
2472
|
+
/** The surfaces that each fence created, in order. */
|
|
2473
|
+
const created = /* @__PURE__ */ new Map();
|
|
2474
|
+
const functionCalls = [];
|
|
2475
|
+
/** The message that owns each chat surface id, by the id the model wrote. */
|
|
2476
|
+
const chatOwners = /* @__PURE__ */ new Map();
|
|
2477
|
+
const lastMessage = messages[messages.length - 1];
|
|
2478
|
+
/**
|
|
2479
|
+
* A chat surface belongs to the reply that wrote it: the chat is a
|
|
2480
|
+
* transcript, so a later reply that reuses an id gets a surface of its
|
|
2481
|
+
* own (`<id>@<messageId>`) instead of changing the earlier reply. A fence
|
|
2482
|
+
* for a page target keeps its id, because a target is a place on the
|
|
2483
|
+
* page that a later reply updates on purpose.
|
|
2484
|
+
*/
|
|
2485
|
+
const scopedSurfaceId = (requested, messageId, target) => {
|
|
2486
|
+
if (target !== void 0) return requested;
|
|
2487
|
+
const owner = chatOwners.get(requested);
|
|
2488
|
+
if (owner === void 0) {
|
|
2489
|
+
chatOwners.set(requested, messageId);
|
|
2490
|
+
return requested;
|
|
2491
|
+
}
|
|
2492
|
+
return owner === messageId ? requested : `${requested}@${messageId}`;
|
|
2493
|
+
};
|
|
2494
|
+
for (const message of messages) {
|
|
2495
|
+
if (message.role !== "assistant" || !isString(message.content)) continue;
|
|
2496
|
+
const isLastMessage = message === lastMessage;
|
|
2497
|
+
const content = message.content;
|
|
2498
|
+
const segments = cache ? cache.segments.get(content, () => require_a2ui_markdown.splitA2UIMarkdown(content)) : require_a2ui_markdown.splitA2UIMarkdown(content);
|
|
2499
|
+
for (const segment of segments) {
|
|
2500
|
+
if (segment.type !== "a2ui") continue;
|
|
2501
|
+
const isStreaming = !segment.closed && isLastMessage && options.running;
|
|
2502
|
+
const parseFence = () => {
|
|
2503
|
+
const parsed = fenceOperations(segment.text, isStreaming);
|
|
2504
|
+
const { functionCalls } = require_a2ui_markdown.prepareSurfaceOperations({
|
|
2505
|
+
operations: parsed,
|
|
2506
|
+
fallbackSurfaceId: "",
|
|
2507
|
+
catalogId: ui.id
|
|
2508
|
+
});
|
|
2509
|
+
return {
|
|
2510
|
+
operations: parsed,
|
|
2511
|
+
functionCalls
|
|
2512
|
+
};
|
|
2513
|
+
};
|
|
2514
|
+
const fence = cache ? cache.fences.get(`${isStreaming}:${segment.text}`, parseFence) : parseFence();
|
|
2515
|
+
const { operations } = fence;
|
|
2516
|
+
const key = fenceKey(message.id, segment.index);
|
|
2517
|
+
const fenceSurfaceId = operations.map(require_a2ui_markdown.getMarkdownOperationSurfaceId).find(isString) ?? `${message.id}-${segment.index}`;
|
|
2518
|
+
for (const operation of fence.functionCalls) functionCalls.push({
|
|
2519
|
+
messageId: message.id,
|
|
2520
|
+
fenceIndex: segment.index,
|
|
2521
|
+
operation
|
|
2522
|
+
});
|
|
2523
|
+
const surfaceOperations = operations.filter((op) => (0, _copilotkit_shared.getOperationKind)(op) !== "callRendererFunction");
|
|
2524
|
+
for (const op of surfaceOperations) {
|
|
2525
|
+
const requested = require_a2ui_markdown.getMarkdownOperationSurfaceId(op) ?? fenceSurfaceId;
|
|
2526
|
+
const surfaceId = scopedSurfaceId(requested, message.id, segment.target);
|
|
2527
|
+
let draft = drafts.get(surfaceId);
|
|
2528
|
+
if (!draft) {
|
|
2529
|
+
draft = {
|
|
2530
|
+
surfaceId,
|
|
2531
|
+
target: segment.target ?? _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
|
|
2532
|
+
operations: [],
|
|
2533
|
+
streaming: isStreaming
|
|
2534
|
+
};
|
|
2535
|
+
drafts.set(surfaceId, draft);
|
|
2536
|
+
created.set(key, [...created.get(key) ?? [], surfaceId]);
|
|
2537
|
+
}
|
|
2538
|
+
draft.operations.push(surfaceId === requested ? op : readdressOnce(op, surfaceId));
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
const canFlattenCards = hasProp(ui, "Card", "variant");
|
|
2543
|
+
const surfaces = [];
|
|
2544
|
+
const partsBySurface = /* @__PURE__ */ new Map();
|
|
2545
|
+
const childIds = childIdsReader(ui);
|
|
2546
|
+
const buildDraft = (draft) => {
|
|
2547
|
+
const operations = splitComponentUpdates(expandInlineCreate(createSurfaceFirst(require_a2ui_markdown.prepareSurfaceOperations({
|
|
2548
|
+
operations: draft.operations,
|
|
2549
|
+
fallbackSurfaceId: draft.surfaceId,
|
|
2550
|
+
catalogId: ui.id,
|
|
2551
|
+
catalogIds: (0, _copilotkit_shared_generative_ui.catalogIdsOf)(ui)
|
|
2552
|
+
}).operations)));
|
|
2553
|
+
const parts = draft.target === _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET ? liftProse(canFlattenCards ? require_a2ui_markdown.flattenInformationalCards(operations, { childIds }) : operations, draft.surfaceId, childIds) : [{
|
|
2554
|
+
kind: "surface",
|
|
2555
|
+
surfaceId: draft.surfaceId,
|
|
2556
|
+
operations
|
|
2557
|
+
}];
|
|
2558
|
+
const contents = parts.flatMap((part) => part.kind === "surface" ? [surfaceContent(part.surfaceId, draft, part.operations, options)] : []);
|
|
2559
|
+
return {
|
|
2560
|
+
...draft,
|
|
2561
|
+
parts,
|
|
2562
|
+
contents
|
|
2563
|
+
};
|
|
2564
|
+
};
|
|
2565
|
+
for (const draft of drafts.values()) {
|
|
2566
|
+
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);
|
|
2567
|
+
partsBySurface.set(draft.surfaceId, built.parts);
|
|
2568
|
+
surfaces.push(...built.contents);
|
|
2569
|
+
}
|
|
2570
|
+
cache?.endBuild();
|
|
2571
|
+
/** The surface ids of the parts of each split surface, by surface id. */
|
|
2572
|
+
const parts = /* @__PURE__ */ new Map();
|
|
2573
|
+
for (const [surfaceId, surfaceParts] of partsBySurface) {
|
|
2574
|
+
const ids = surfaceParts.flatMap((part) => part.kind === "surface" ? [part.surfaceId] : []);
|
|
2575
|
+
parts.set(surfaceId, ids);
|
|
2576
|
+
}
|
|
2577
|
+
const fences = /* @__PURE__ */ new Map();
|
|
2578
|
+
for (const [key, surfaceIds] of created) {
|
|
2579
|
+
const blocks = [];
|
|
2580
|
+
for (const surfaceId of surfaceIds) {
|
|
2581
|
+
if (drafts.get(surfaceId)?.target !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET) continue;
|
|
2582
|
+
for (const part of partsBySurface.get(surfaceId) ?? []) blocks.push(part.kind === "markdown" ? part : {
|
|
2583
|
+
kind: "surface",
|
|
2584
|
+
surfaceId: part.surfaceId
|
|
2585
|
+
});
|
|
2586
|
+
}
|
|
2587
|
+
if (blocks.length > 0) fences.set(key, blocks);
|
|
2588
|
+
}
|
|
2589
|
+
return {
|
|
2590
|
+
surfaces,
|
|
2591
|
+
fences,
|
|
2592
|
+
functionCalls,
|
|
2593
|
+
parts
|
|
2594
|
+
};
|
|
2595
|
+
}
|
|
2596
|
+
/** The declared functions, as `validateOperation` takes them. */
|
|
2597
|
+
function declaredFunctions(ui) {
|
|
2598
|
+
const functions = {};
|
|
2599
|
+
for (const [name, fn] of ui.functions) try {
|
|
2600
|
+
functions[name] = {
|
|
2601
|
+
...fn.description ? { description: fn.description } : {},
|
|
2602
|
+
parameters: (0, _copilotkit_shared_generative_ui.toJsonSchema)(fn.parameters)
|
|
2603
|
+
};
|
|
2604
|
+
} catch {
|
|
2605
|
+
functions[name] = { parameters: {} };
|
|
2606
|
+
}
|
|
2607
|
+
return functions;
|
|
2608
|
+
}
|
|
2609
|
+
/** True when `list` starts with all the items of `prefix`. */
|
|
2610
|
+
function startsWith(list, prefix) {
|
|
2611
|
+
return list.length >= prefix.length && prefix.every((item, index) => item === list[index]);
|
|
2612
|
+
}
|
|
2613
|
+
/** A content that deletes a surface that the fences no longer write. */
|
|
2614
|
+
function removalContent(surfaceId, catalogId) {
|
|
2615
|
+
return {
|
|
2616
|
+
surfaceId,
|
|
2617
|
+
target: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
|
|
2618
|
+
catalogId,
|
|
2619
|
+
status: "ready",
|
|
2620
|
+
rejected: [],
|
|
2621
|
+
operations: [{
|
|
2622
|
+
version: _copilotkit_shared.A2UI_VERSION,
|
|
2623
|
+
createSurface: {
|
|
2624
|
+
surfaceId,
|
|
2625
|
+
catalogId
|
|
2626
|
+
}
|
|
2627
|
+
}, {
|
|
2628
|
+
version: _copilotkit_shared.A2UI_VERSION,
|
|
2629
|
+
deleteSurface: { surfaceId }
|
|
2630
|
+
}]
|
|
2631
|
+
};
|
|
2632
|
+
}
|
|
2633
|
+
/**
|
|
2634
|
+
* The markdown transport source of one surface manager. It turns the
|
|
2635
|
+
* messages of a thread into surfaces in the manager, and keeps the blocks
|
|
2636
|
+
* that each fence renders.
|
|
2637
|
+
*/
|
|
2638
|
+
var MarkdownSurfaceSource = class {
|
|
2639
|
+
functions;
|
|
2640
|
+
/** By thread: the blocks of each fence, from the latest sync. */
|
|
2641
|
+
fences = /* @__PURE__ */ new Map();
|
|
2642
|
+
/** By thread, then surface: the operations last ingested, as JSON. */
|
|
2643
|
+
ingested = /* @__PURE__ */ new Map();
|
|
2644
|
+
/** By thread, then surface: the content last ingested. */
|
|
2645
|
+
contents = /* @__PURE__ */ new Map();
|
|
2646
|
+
/** By thread: the results of the earlier builds. */
|
|
2647
|
+
caches = /* @__PURE__ */ new Map();
|
|
2648
|
+
constructor(manager, ui) {
|
|
2649
|
+
this.manager = manager;
|
|
2650
|
+
this.ui = ui;
|
|
2651
|
+
this.functions = declaredFunctions(ui);
|
|
2652
|
+
}
|
|
2653
|
+
/**
|
|
2654
|
+
* Builds the surfaces of `threadId` from `messages` and gives them to the
|
|
2655
|
+
* manager. A surface that an earlier sync of the thread made, and that the
|
|
2656
|
+
* messages no longer write, is deleted. Other threads do not change.
|
|
2657
|
+
*
|
|
2658
|
+
* @param threadId - The thread of the messages.
|
|
2659
|
+
* @param agentId - The agent that owns the thread.
|
|
2660
|
+
* @param messages - All messages of the thread.
|
|
2661
|
+
* @param options - `running`: the last message can still grow.
|
|
2662
|
+
* @returns The function calls of the fences, in order. The source does
|
|
2663
|
+
* not run them.
|
|
2664
|
+
*/
|
|
2665
|
+
sync(threadId, agentId, messages, options) {
|
|
2666
|
+
let cache = this.caches.get(threadId);
|
|
2667
|
+
if (!cache) {
|
|
2668
|
+
cache = new MarkdownBuildCache();
|
|
2669
|
+
this.caches.set(threadId, cache);
|
|
2670
|
+
}
|
|
2671
|
+
const result = buildMarkdownSurfaces(messages, {
|
|
2672
|
+
ui: this.ui,
|
|
2673
|
+
functions: this.functions,
|
|
2674
|
+
running: options.running,
|
|
2675
|
+
cache
|
|
2676
|
+
});
|
|
2677
|
+
this.fences.set(threadId, result.fences);
|
|
2678
|
+
for (const parts of result.parts.values()) this.manager.linkSurfaces(threadId, parts);
|
|
2679
|
+
const previous = this.ingested.get(threadId) ?? /* @__PURE__ */ new Map();
|
|
2680
|
+
const previousContents = this.contents.get(threadId) ?? /* @__PURE__ */ new Map();
|
|
2681
|
+
const next = /* @__PURE__ */ new Map();
|
|
2682
|
+
const nextContents = /* @__PURE__ */ new Map();
|
|
2683
|
+
for (const content of result.surfaces) {
|
|
2684
|
+
nextContents.set(content.surfaceId, content);
|
|
2685
|
+
const before = previous.get(content.surfaceId);
|
|
2686
|
+
if (before && previousContents.get(content.surfaceId) === content) {
|
|
2687
|
+
next.set(content.surfaceId, before);
|
|
2688
|
+
continue;
|
|
2689
|
+
}
|
|
2690
|
+
const fingerprints = content.operations.map((op) => JSON.stringify(op));
|
|
2691
|
+
if (before && !startsWith(fingerprints, before)) this.manager.ingest(threadId, agentId, {
|
|
2692
|
+
...content,
|
|
2693
|
+
operations: []
|
|
2694
|
+
});
|
|
2695
|
+
this.manager.ingest(threadId, agentId, content);
|
|
2696
|
+
next.set(content.surfaceId, fingerprints);
|
|
2697
|
+
}
|
|
2698
|
+
for (const surfaceId of previous.keys()) {
|
|
2699
|
+
if (next.has(surfaceId)) continue;
|
|
2700
|
+
this.manager.ingest(threadId, agentId, removalContent(surfaceId, this.ui.id));
|
|
2701
|
+
}
|
|
2702
|
+
this.ingested.set(threadId, next);
|
|
2703
|
+
this.contents.set(threadId, nextContents);
|
|
2704
|
+
return result.functionCalls;
|
|
2705
|
+
}
|
|
2706
|
+
/**
|
|
2707
|
+
* The blocks that a fence renders in the chat, from the latest sync of the
|
|
2708
|
+
* thread. `undefined` when the fence renders nothing: it updates a surface
|
|
2709
|
+
* of an earlier fence, its surface is for a named target, or it has no
|
|
2710
|
+
* complete operation yet.
|
|
2711
|
+
*/
|
|
2712
|
+
getFenceBlocks(threadId, messageId, fenceIndex) {
|
|
2713
|
+
return this.fences.get(threadId)?.get(fenceKey(messageId, fenceIndex));
|
|
2714
|
+
}
|
|
2715
|
+
};
|
|
2716
|
+
const sources = /* @__PURE__ */ new WeakMap();
|
|
2717
|
+
/**
|
|
2718
|
+
* The markdown source of a generative UI runtime. There is one source for
|
|
2719
|
+
* each surface manager. The root syncs it, and the chat messages read the
|
|
2720
|
+
* fence blocks from it.
|
|
2721
|
+
*/
|
|
2722
|
+
function getMarkdownSurfaceSource(runtime) {
|
|
2723
|
+
let source = sources.get(runtime.manager);
|
|
2724
|
+
if (!source) {
|
|
2725
|
+
source = new MarkdownSurfaceSource(runtime.manager, runtime.ui);
|
|
2726
|
+
sources.set(runtime.manager, source);
|
|
2727
|
+
}
|
|
2728
|
+
return source;
|
|
2729
|
+
}
|
|
2730
|
+
|
|
2731
|
+
//#endregion
|
|
2732
|
+
//#region src/generative-ui/action-message.ts
|
|
2733
|
+
/** Context keys that supply the message's first line, in priority order. */
|
|
2734
|
+
const TEXT_KEYS = ["message", "label"];
|
|
2735
|
+
function isNonEmptyString(value) {
|
|
2736
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
2737
|
+
}
|
|
2738
|
+
/** `choose_plan`, `choose-plan` and `choosePlan` all become "Choose plan". */
|
|
2739
|
+
function humanize(name) {
|
|
2740
|
+
const spaced = name.replace(/[_-]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").trim();
|
|
2741
|
+
return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();
|
|
2742
|
+
}
|
|
2743
|
+
function formatContextValue(value) {
|
|
2744
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
2745
|
+
}
|
|
2746
|
+
/**
|
|
2747
|
+
* Turns a user event that no function handles into the text of a visible
|
|
2748
|
+
* user message.
|
|
2749
|
+
*
|
|
2750
|
+
* The first line is, in order: `userMessage`, `context.message`,
|
|
2751
|
+
* `context.label`, the label of the source component (from `resolveLabel`),
|
|
2752
|
+
* or the event name made readable (`choose_plan` becomes "Choose plan").
|
|
2753
|
+
* Each other context field follows as one `key: value` line. Objects are
|
|
2754
|
+
* written as JSON. `null` and `undefined` fields are skipped.
|
|
2755
|
+
*
|
|
2756
|
+
* @param event - The user event, as sent by a surface.
|
|
2757
|
+
* @param resolveLabel - Finds the visible label of a component by id. Build
|
|
2758
|
+
* one with {@link createComponentLabelResolver}.
|
|
2759
|
+
*
|
|
2760
|
+
* @example
|
|
2761
|
+
* ```ts
|
|
2762
|
+
* buildActionMessageText({
|
|
2763
|
+
* name: "choose_plan",
|
|
2764
|
+
* surfaceId: "plans",
|
|
2765
|
+
* componentId: "team-button",
|
|
2766
|
+
* userMessage: "I pick the Team plan",
|
|
2767
|
+
* context: { seats: 12 },
|
|
2768
|
+
* });
|
|
2769
|
+
* // "I pick the Team plan\n\nseats: 12"
|
|
2770
|
+
* ```
|
|
2771
|
+
*/
|
|
2772
|
+
function buildActionMessageText(event, resolveLabel) {
|
|
2773
|
+
const { context, userMessage } = event;
|
|
2774
|
+
const explicit = [userMessage, ...TEXT_KEYS.map((key) => context[key])].find(isNonEmptyString);
|
|
2775
|
+
const resolved = explicit ? void 0 : resolveLabel?.(event.componentId);
|
|
2776
|
+
const head = explicit ?? (isNonEmptyString(resolved) ? resolved.trim() : humanize(event.name));
|
|
2777
|
+
const lines = Object.entries(context).filter(([key, value]) => !TEXT_KEYS.includes(key) && value !== void 0 && value !== null).map(([key, value]) => `${key}: ${formatContextValue(value)}`);
|
|
2778
|
+
return lines.length > 0 ? `${head}\n\n${lines.join("\n")}` : head;
|
|
2779
|
+
}
|
|
2780
|
+
function ownText(component) {
|
|
2781
|
+
if (!component) return void 0;
|
|
2782
|
+
if (isNonEmptyString(component.label)) return component.label;
|
|
2783
|
+
if (isNonEmptyString(component.text)) return component.text;
|
|
2784
|
+
}
|
|
2785
|
+
function childIds(component) {
|
|
2786
|
+
const { child, children } = component;
|
|
2787
|
+
const single = typeof child === "string" ? [child] : [];
|
|
2788
|
+
const multiple = Array.isArray(children) ? children.filter((id) => typeof id === "string") : [];
|
|
2789
|
+
return [...single, ...multiple];
|
|
2790
|
+
}
|
|
2791
|
+
/** The components that an operation adds, inline or in an update. */
|
|
2792
|
+
function componentsOf(operation) {
|
|
2793
|
+
if ("createSurface" in operation) return operation.createSurface.components ?? [];
|
|
2794
|
+
if ("updateComponents" in operation) return operation.updateComponents.components;
|
|
2795
|
+
return [];
|
|
2796
|
+
}
|
|
2797
|
+
/**
|
|
2798
|
+
* Builds a function that finds the visible label of a component on a surface.
|
|
2799
|
+
*
|
|
2800
|
+
* The label is the component's own string `label`, else its string `text`,
|
|
2801
|
+
* else the first `child` or `children` component that has a string `label`
|
|
2802
|
+
* or `text`. When a component id is defined more than once, the last
|
|
2803
|
+
* definition wins, as in the renderer.
|
|
2804
|
+
*
|
|
2805
|
+
* @param operations - The committed operations of the surface.
|
|
2806
|
+
*
|
|
2807
|
+
* @example
|
|
2808
|
+
* ```ts
|
|
2809
|
+
* const resolveLabel = createComponentLabelResolver(surface.operations);
|
|
2810
|
+
* buildActionMessageText(event, resolveLabel);
|
|
2811
|
+
* ```
|
|
2812
|
+
*/
|
|
2813
|
+
function createComponentLabelResolver(operations) {
|
|
2814
|
+
const byId = /* @__PURE__ */ new Map();
|
|
2815
|
+
for (const operation of operations) {
|
|
2816
|
+
const components = componentsOf(operation);
|
|
2817
|
+
for (const component of components) byId.set(component.id, component);
|
|
2818
|
+
}
|
|
2819
|
+
return (componentId) => {
|
|
2820
|
+
const component = byId.get(componentId);
|
|
2821
|
+
if (!component) return void 0;
|
|
2822
|
+
const own = ownText(component);
|
|
2823
|
+
if (own) return own;
|
|
2824
|
+
const ids = childIds(component);
|
|
2825
|
+
for (const id of ids) {
|
|
2826
|
+
const text = ownText(byId.get(id));
|
|
2827
|
+
if (text) return text;
|
|
2828
|
+
}
|
|
2829
|
+
};
|
|
2830
|
+
}
|
|
2831
|
+
/**
|
|
2832
|
+
* The label resolver of a rendered surface: the components the surface has
|
|
2833
|
+
* now, as one `updateComponents` operation, so that the label of the
|
|
2834
|
+
* component that sent an event can be found.
|
|
2835
|
+
*/
|
|
2836
|
+
function surfaceLabelResolver(surface) {
|
|
2837
|
+
const components = [...surface.model.componentsModel.entries].map(([id, model]) => ({
|
|
2838
|
+
...model.properties,
|
|
2839
|
+
id,
|
|
2840
|
+
component: model.type
|
|
2841
|
+
}));
|
|
2842
|
+
return createComponentLabelResolver([{
|
|
2843
|
+
version: _copilotkit_shared.A2UI_VERSION,
|
|
2844
|
+
updateComponents: {
|
|
2845
|
+
surfaceId: surface.surfaceId,
|
|
2846
|
+
components
|
|
2847
|
+
}
|
|
2848
|
+
}]);
|
|
2849
|
+
}
|
|
2850
|
+
|
|
2851
|
+
//#endregion
|
|
2852
|
+
//#region src/generative-ui/debug-source.ts
|
|
2853
|
+
/**
|
|
2854
|
+
* What a run of `threadId` sends: its envelope, and the text that goes into
|
|
2855
|
+
* the prompt of the model because of it.
|
|
2856
|
+
*
|
|
2857
|
+
* - Tool transport: the runtime adds the `render_ui` guide. It builds it
|
|
2858
|
+
* from the envelope with `buildGenerativeUIPrompt`, as done here.
|
|
2859
|
+
* - Markdown transport: the provider sends the guideline and the compact
|
|
2860
|
+
* schema as context entries. With `sendContext: false`, the backend builds
|
|
2861
|
+
* its own prompt, usually from the `instructions` of the envelope.
|
|
2862
|
+
*/
|
|
2863
|
+
function describeGenerativeUIRun(runtime, threadId, options) {
|
|
2864
|
+
const envelope = buildGenerativeUIEnvelope(runtime, threadId, options);
|
|
2865
|
+
if (options.transport === "tool") return {
|
|
2866
|
+
envelope,
|
|
2867
|
+
prompt: [{
|
|
2868
|
+
title: "render_ui guide",
|
|
2869
|
+
source: "runtime",
|
|
2870
|
+
text: (0, _copilotkit_shared.buildGenerativeUIPrompt)((0, _copilotkit_shared.envelopeToManifest)(envelope))
|
|
2871
|
+
}]
|
|
2872
|
+
};
|
|
2873
|
+
const manifest = buildGenerativeUIManifest(runtime, threadId);
|
|
2874
|
+
if (!options.contextSent) return {
|
|
2875
|
+
envelope,
|
|
2876
|
+
prompt: [{
|
|
2877
|
+
title: "Envelope instructions",
|
|
2878
|
+
source: "backend",
|
|
2879
|
+
text: (0, _copilotkit_shared.envelopeToManifest)(envelope).instructions ?? ""
|
|
2880
|
+
}]
|
|
2881
|
+
};
|
|
2882
|
+
const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
|
|
2883
|
+
const schema = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
|
|
2884
|
+
return {
|
|
2885
|
+
envelope,
|
|
2886
|
+
prompt: [{
|
|
2887
|
+
title: "Markdown guideline",
|
|
2888
|
+
source: "context",
|
|
2889
|
+
text: guideline
|
|
2890
|
+
}, {
|
|
2891
|
+
title: "Component schema",
|
|
2892
|
+
source: "context",
|
|
2893
|
+
text: schema
|
|
2894
|
+
}]
|
|
2895
|
+
};
|
|
2896
|
+
}
|
|
2897
|
+
/** The declared functions, with the JSON Schema of their parameters. */
|
|
2898
|
+
function debugFunctions(runtime) {
|
|
2899
|
+
const functions = {};
|
|
2900
|
+
for (const [name, declared] of runtime.ui.functions) {
|
|
2901
|
+
let parameters = {};
|
|
2902
|
+
try {
|
|
2903
|
+
parameters = (0, _copilotkit_shared_generative_ui.toJsonSchema)(declared.parameters);
|
|
2904
|
+
} catch {}
|
|
2905
|
+
functions[name] = {
|
|
2906
|
+
...declared.description ? { description: declared.description } : {},
|
|
2907
|
+
parameters,
|
|
2908
|
+
handlers: runtime.dispatcher.handlerCount(name)
|
|
2909
|
+
};
|
|
2910
|
+
}
|
|
2911
|
+
return functions;
|
|
2912
|
+
}
|
|
2913
|
+
/**
|
|
2914
|
+
* The debug source that the provider gives core for the inspector. It builds
|
|
2915
|
+
* a snapshot only when the inspector reads one.
|
|
2916
|
+
*
|
|
2917
|
+
* @param runtime - The generative UI parts of the provider.
|
|
2918
|
+
* @param getOptions - The envelope options and agent ids of the current config.
|
|
2919
|
+
* @returns The source, and `recordRun` for each run start.
|
|
2920
|
+
*/
|
|
2921
|
+
function createGenerativeUIDebugSource(runtime, getOptions) {
|
|
2922
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2923
|
+
let lastRun;
|
|
2924
|
+
const notify = () => {
|
|
2925
|
+
for (const listener of [...listeners]) listener();
|
|
2926
|
+
};
|
|
2927
|
+
return {
|
|
2928
|
+
source: {
|
|
2929
|
+
getSnapshot() {
|
|
2930
|
+
const { options, agentIds } = getOptions();
|
|
2931
|
+
const threadId = runtime.manager.getActiveThread();
|
|
2932
|
+
const manifest = buildGenerativeUIManifest(runtime, threadId);
|
|
2933
|
+
return {
|
|
2934
|
+
catalogId: runtime.ui.id,
|
|
2935
|
+
transport: options.transport,
|
|
2936
|
+
...agentIds ? { agentIds } : {},
|
|
2937
|
+
components: runtime.ui.manifestComponents,
|
|
2938
|
+
componentCatalogs: Object.fromEntries((0, _copilotkit_shared_generative_ui.componentCatalogIds)(runtime.ui)),
|
|
2939
|
+
functions: debugFunctions(runtime),
|
|
2940
|
+
state: { ...runtime.manager.getState() },
|
|
2941
|
+
targets: manifest.targets,
|
|
2942
|
+
activeThreadId: threadId,
|
|
2943
|
+
surfaces: runtime.manager.debugSurfaces(),
|
|
2944
|
+
lastRun,
|
|
2945
|
+
nextRun: {
|
|
2946
|
+
agentId: void 0,
|
|
2947
|
+
threadId,
|
|
2948
|
+
...describeGenerativeUIRun(runtime, threadId, options)
|
|
2949
|
+
}
|
|
2950
|
+
};
|
|
2951
|
+
},
|
|
2952
|
+
subscribe(listener) {
|
|
2953
|
+
listeners.add(listener);
|
|
2954
|
+
const unsubscribe = runtime.manager.subscribe(listener);
|
|
2955
|
+
return () => {
|
|
2956
|
+
listeners.delete(listener);
|
|
2957
|
+
unsubscribe();
|
|
2958
|
+
};
|
|
2959
|
+
}
|
|
2960
|
+
},
|
|
2961
|
+
recordRun(run) {
|
|
2962
|
+
lastRun = run;
|
|
2963
|
+
notify();
|
|
2964
|
+
}
|
|
2965
|
+
};
|
|
2966
|
+
}
|
|
2967
|
+
|
|
2968
|
+
//#endregion
|
|
2969
|
+
//#region src/generative-ui/accessibility.ts
|
|
2970
|
+
const LIVE = new Set([
|
|
2971
|
+
"off",
|
|
2972
|
+
"polite",
|
|
2973
|
+
"assertive"
|
|
2974
|
+
]);
|
|
2975
|
+
/**
|
|
2976
|
+
* The accessibility of a component from its resolved `accessibility`
|
|
2977
|
+
* value. Fields of the wrong type are left out: a label that is still a
|
|
2978
|
+
* binding, or a list, names nothing.
|
|
2979
|
+
*/
|
|
2980
|
+
function readAccessibility(value) {
|
|
2981
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return;
|
|
2982
|
+
const { label, description, live, hidden } = value;
|
|
2983
|
+
const result = {};
|
|
2984
|
+
if (typeof label === "string" && label !== "") result.label = label;
|
|
2985
|
+
if (typeof description === "string" && description !== "") result.description = description;
|
|
2986
|
+
if (typeof live === "string" && LIVE.has(live)) result.live = live;
|
|
2987
|
+
if (typeof hidden === "boolean") result.hidden = hidden;
|
|
2988
|
+
return Object.keys(result).length > 0 ? result : void 0;
|
|
2989
|
+
}
|
|
2990
|
+
/**
|
|
2991
|
+
* The ARIA attributes for an `accessibility`. `live: "off"` is written out:
|
|
2992
|
+
* a region inherits the live setting of its ancestors, and a `status` role
|
|
2993
|
+
* is live on its own, so only the explicit value silences it.
|
|
2994
|
+
*
|
|
2995
|
+
* @example
|
|
2996
|
+
* ```ts
|
|
2997
|
+
* accessibilityAttributes({ label: "Totals", live: "polite" });
|
|
2998
|
+
* // { "aria-label": "Totals", "aria-live": "polite" }
|
|
2999
|
+
* ```
|
|
3000
|
+
*/
|
|
3001
|
+
function accessibilityAttributes(accessibility) {
|
|
3002
|
+
if (!accessibility) return {};
|
|
3003
|
+
const { label, description, live, hidden } = accessibility;
|
|
3004
|
+
return {
|
|
3005
|
+
...label === void 0 ? {} : { "aria-label": label },
|
|
3006
|
+
...description === void 0 ? {} : { "aria-description": description },
|
|
3007
|
+
...live === void 0 ? {} : { "aria-live": live },
|
|
3008
|
+
...hidden ? { "aria-hidden": true } : {}
|
|
3009
|
+
};
|
|
3010
|
+
}
|
|
3011
|
+
/**
|
|
3012
|
+
* The role of a container that the envelope names. A generic element
|
|
3013
|
+
* cannot carry a name, so a label or a description makes it a `group`,
|
|
3014
|
+
* unless the component has a role of its own.
|
|
3015
|
+
*/
|
|
3016
|
+
function namedRole(aria, explicit) {
|
|
3017
|
+
if (explicit !== void 0) return explicit;
|
|
3018
|
+
return aria["aria-label"] !== void 0 || aria["aria-description"] !== void 0 ? "group" : void 0;
|
|
3019
|
+
}
|
|
3020
|
+
/**
|
|
3021
|
+
* The part of the attributes for the focusable control of a labelled pair:
|
|
3022
|
+
* its name and its description. ARIA names are not inherited, so the
|
|
3023
|
+
* wrapper of a control cannot name it.
|
|
3024
|
+
*/
|
|
3025
|
+
function controlAria(aria) {
|
|
3026
|
+
const { "aria-label": label, "aria-description": description } = aria;
|
|
3027
|
+
return {
|
|
3028
|
+
...label === void 0 ? {} : { "aria-label": label },
|
|
3029
|
+
...description === void 0 ? {} : { "aria-description": description }
|
|
3030
|
+
};
|
|
3031
|
+
}
|
|
3032
|
+
/**
|
|
3033
|
+
* The part of the attributes for the wrapper around a control: hidden and
|
|
3034
|
+
* live cover the label and the control together.
|
|
3035
|
+
*/
|
|
3036
|
+
function wrapperAria(aria) {
|
|
3037
|
+
const { "aria-hidden": hidden, "aria-live": live } = aria;
|
|
3038
|
+
return {
|
|
3039
|
+
...hidden === void 0 ? {} : { "aria-hidden": hidden },
|
|
3040
|
+
...live === void 0 ? {} : { "aria-live": live }
|
|
3041
|
+
};
|
|
3042
|
+
}
|
|
3043
|
+
|
|
3044
|
+
//#endregion
|
|
3045
|
+
//#region src/generative-ui/targets.ts
|
|
3046
|
+
/** Scrolls `element` into view, unless it is already fully on screen. */
|
|
3047
|
+
function scrollToSurface(element) {
|
|
3048
|
+
const { top, bottom } = element.getBoundingClientRect();
|
|
3049
|
+
if (top >= 0 && bottom <= window.innerHeight) return;
|
|
3050
|
+
const reduceMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
|
|
3051
|
+
element.scrollIntoView?.({
|
|
3052
|
+
behavior: reduceMotion ? "auto" : "smooth",
|
|
3053
|
+
block: "start"
|
|
3054
|
+
});
|
|
3055
|
+
}
|
|
3056
|
+
/**
|
|
3057
|
+
* The names of `requested` that `ui` has, without repeats, at most the
|
|
3058
|
+
* number that the envelope takes. `warning` tells what was dropped.
|
|
3059
|
+
*/
|
|
3060
|
+
function allowedComponents(requested, ui) {
|
|
3061
|
+
const unique = [...new Set(requested)];
|
|
3062
|
+
const unknown = unique.filter((name) => !ui.components.has(name));
|
|
3063
|
+
const known = unique.filter((name) => ui.components.has(name));
|
|
3064
|
+
const names = known.slice(0, _copilotkit_shared.GENERATIVE_UI_MAX_TARGET_COMPONENTS);
|
|
3065
|
+
const problems = [];
|
|
3066
|
+
if (unknown.length > 0) problems.push(`these components are not in the UI and are ignored: ${unknown.join(", ")}`);
|
|
3067
|
+
if (known.length > names.length) problems.push(`only the first ${_copilotkit_shared.GENERATIVE_UI_MAX_TARGET_COMPONENTS} components are used`);
|
|
3068
|
+
return {
|
|
3069
|
+
names,
|
|
3070
|
+
warning: problems.join("; ")
|
|
3071
|
+
};
|
|
3072
|
+
}
|
|
3073
|
+
|
|
3074
|
+
//#endregion
|
|
3075
|
+
exports.BASIC_FUNCTIONS = BASIC_FUNCTIONS;
|
|
3076
|
+
exports.ExpressionError = ExpressionError;
|
|
3077
|
+
exports.GenerativeUISurfaceManager = GenerativeUISurfaceManager;
|
|
3078
|
+
exports.MarkdownBuildCache = MarkdownBuildCache;
|
|
3079
|
+
exports.MarkdownSurfaceSource = MarkdownSurfaceSource;
|
|
3080
|
+
exports.accessibilityAttributes = accessibilityAttributes;
|
|
3081
|
+
exports.activityFunctionCalls = activityFunctionCalls;
|
|
3082
|
+
exports.allowedComponents = allowedComponents;
|
|
3083
|
+
exports.buildActionMessageText = buildActionMessageText;
|
|
3084
|
+
exports.buildCatalogManifest = buildCatalogManifest;
|
|
3085
|
+
exports.buildGenerativeUIEnvelope = buildGenerativeUIEnvelope;
|
|
3086
|
+
exports.buildGenerativeUIManifest = buildGenerativeUIManifest;
|
|
3087
|
+
exports.buildMarkdownSurfaces = buildMarkdownSurfaces;
|
|
3088
|
+
exports.builtInFunctionManifests = builtInFunctionManifests;
|
|
3089
|
+
exports.calc = calc;
|
|
3090
|
+
exports.containsDynamicValue = containsDynamicValue;
|
|
3091
|
+
exports.controlAria = controlAria;
|
|
3092
|
+
exports.createComponentLabelResolver = createComponentLabelResolver;
|
|
3093
|
+
exports.createFunctionCallRunner = createFunctionCallRunner;
|
|
3094
|
+
exports.createGenerativeUIDebugSource = createGenerativeUIDebugSource;
|
|
3095
|
+
exports.createGenerativeUIDispatcher = createGenerativeUIDispatcher;
|
|
3096
|
+
exports.describeGenerativeUIRun = describeGenerativeUIRun;
|
|
3097
|
+
exports.envelopeOptionsFor = envelopeOptionsFor;
|
|
3098
|
+
exports.evaluateCalc = evaluateCalc;
|
|
3099
|
+
exports.fenceKey = fenceKey;
|
|
3100
|
+
exports.getMarkdownSurfaceSource = getMarkdownSurfaceSource;
|
|
3101
|
+
exports.givesValidationResult = givesValidationResult;
|
|
3102
|
+
exports.invokeBoundEvent = invokeBoundEvent;
|
|
3103
|
+
exports.invokeMatchedEvent = invokeMatchedEvent;
|
|
3104
|
+
exports.joinPath = joinPath;
|
|
3105
|
+
exports.markdownFunctionCalls = markdownFunctionCalls;
|
|
3106
|
+
exports.namedRole = namedRole;
|
|
3107
|
+
exports.openUrlSafely = openUrlSafely;
|
|
3108
|
+
exports.readAccessibility = readAccessibility;
|
|
3109
|
+
exports.reportErrorSafely = reportErrorSafely;
|
|
3110
|
+
exports.requiresUserActivation = requiresUserActivation;
|
|
3111
|
+
exports.resolveDynamicValue = resolveDynamicValue;
|
|
3112
|
+
exports.resolvePath = resolvePath;
|
|
3113
|
+
exports.scrollToSurface = scrollToSurface;
|
|
3114
|
+
exports.series = series;
|
|
3115
|
+
exports.surfaceKey = surfaceKey;
|
|
3116
|
+
exports.surfaceLabelResolver = surfaceLabelResolver;
|
|
3117
|
+
exports.templateIndex = templateIndex;
|
|
3118
|
+
exports.truthOf = truthOf;
|
|
3119
|
+
exports.tryResolveDynamicValue = tryResolveDynamicValue;
|
|
3120
|
+
exports.wrapperAria = wrapperAria;
|
|
3121
|
+
//# sourceMappingURL=index.cjs.map
|