@copilotkit/core 2.0.0-rc.38 → 2.0.0-rc.39

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.
@@ -2,7 +2,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_a2ui_markdown = require('../a2ui-markdown-DkMXFQih.cjs');
3
3
  let _copilotkit_shared = require("@copilotkit/shared");
4
4
  let _copilotkit_shared_generative_ui = require("@copilotkit/shared/generative-ui");
5
- let _a2ui_web_core_v0_9 = require("@a2ui/web_core/v0_9");
5
+ let _a2ui_web_core_catalog = require("@a2ui/web_core/catalog");
6
+ let _a2ui_web_core_state = require("@a2ui/web_core/state");
6
7
  let zod = require("zod");
7
8
 
8
9
  //#region src/generative-ui/runtime.ts
@@ -19,13 +20,6 @@ function reportErrorSafely(engine, info) {
19
20
 
20
21
  //#endregion
21
22
  //#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
23
  /** Thrown for a bad call: an unknown function, bad args, or a bad value. */
30
24
  var ExpressionError = class extends Error {
31
25
  constructor(message) {
@@ -33,6 +27,18 @@ var ExpressionError = class extends Error {
33
27
  this.name = "ExpressionError";
34
28
  }
35
29
  };
30
+ /**
31
+ * Thrown when the platform lacks what a function needs: `window.open`, or
32
+ * an `Intl` constructor on a Hermes build. The call itself was fine, so it
33
+ * is not an ExpressionError: the dispatcher reports it as `handler_failed`,
34
+ * not `invalid_arguments`, and the model is not told to change its args.
35
+ */
36
+ var PlatformError = class extends Error {
37
+ constructor(message) {
38
+ super(message);
39
+ this.name = "PlatformError";
40
+ }
41
+ };
36
42
  /** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */
37
43
  function truthOf(value) {
38
44
  if ((0, _copilotkit_shared.isValidationResult)(value)) return value.valid;
@@ -65,9 +71,25 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
65
71
  function locale() {
66
72
  return typeof navigator !== "undefined" ? navigator.language : void 0;
67
73
  }
68
- function numberFormat(args, options) {
74
+ /**
75
+ * The `Intl` constructor `name`, or `undefined` when the platform lacks it.
76
+ * Read as an optional member: Hermes has no PluralRules, and a Hermes build
77
+ * without Intl has no `Intl` at all.
78
+ */
79
+ function intlConstructor(name) {
80
+ const value = (typeof Intl === "undefined" ? void 0 : Intl)?.[name];
81
+ return typeof value === "function" ? value : void 0;
82
+ }
83
+ /** The `Intl` constructor `name`, or a PlatformError that says so. */
84
+ function requireIntl(name, caller) {
85
+ const constructor = intlConstructor(name);
86
+ if (constructor === void 0) throw new PlatformError(`${caller} needs Intl.${name}, which this platform does not have`);
87
+ return constructor;
88
+ }
89
+ function numberFormat(caller, args, options) {
90
+ const NumberFormat = requireIntl("NumberFormat", caller);
69
91
  const decimals = optionalNumber(args.decimals, "decimals");
70
- return new Intl.NumberFormat(locale(), {
92
+ return new NumberFormat(locale(), {
71
93
  ...options,
72
94
  useGrouping: args.grouping !== false,
73
95
  ...decimals === void 0 ? {} : {
@@ -90,7 +112,9 @@ const pad = (value, width) => String(value).padStart(width, "0");
90
112
  */
91
113
  const DATE_FIELD = /([A-Za-z])\1*|'(?:[^']|'')*'/g;
92
114
  function formatDatePattern(date, pattern) {
93
- const parts = (options) => new Intl.DateTimeFormat(locale(), options).format(date);
115
+ const parts = (options) => {
116
+ return new (requireIntl("DateTimeFormat", "formatDate"))(locale(), options).format(date);
117
+ };
94
118
  const hours12 = date.getHours() % 12 || 12;
95
119
  const numeric = (value, width) => width >= 2 ? pad(value, 2) : String(value);
96
120
  return pattern.replace(DATE_FIELD, (token) => {
@@ -113,22 +137,208 @@ function formatDatePattern(date, pattern) {
113
137
  }
114
138
  });
115
139
  }
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;
140
+ /**
141
+ * The plural category of `value`. Hermes has no `Intl.PluralRules`, so
142
+ * there the English rule decides: "one" for 1 and -1, else "other".
143
+ */
144
+ function pluralCategory(value) {
145
+ const PluralRules = intlConstructor("PluralRules");
146
+ if (PluralRules !== void 0) return new PluralRules(locale()).select(value);
147
+ return value === 1 || value === -1 ? "one" : "other";
148
+ }
149
+ const SCHEME = /^([A-Za-z][A-Za-z\d+\-.]*):/;
150
+ /** True for a C0 control or DEL (`spaces` also counts a space as one). */
151
+ function isControl(code, spaces = false) {
152
+ return code < 32 || code === 127 || spaces && code === 32;
153
+ }
154
+ /** WHATWG URL ignores leading and trailing C0 controls and spaces. */
155
+ function trimControls(input) {
156
+ let start = 0;
157
+ let end = input.length;
158
+ while (start < end && isControl(input.charCodeAt(start), true)) start += 1;
159
+ while (end > start && isControl(input.charCodeAt(end - 1), true)) end -= 1;
160
+ return input.slice(start, end);
161
+ }
162
+ function hasControl(input) {
163
+ for (let index = 0; index < input.length; index += 1) if (isControl(input.charCodeAt(index))) return true;
164
+ return false;
165
+ }
166
+ /** A host name: no empty label, no forbidden host code point. */
167
+ const HOSTNAME = /^[^\s#%/:<>?@[\\\]^|.]+(?:\.[^\s#%/:<>?@[\\\]^|.]+)*\.?$/;
168
+ /** A dotted-decimal IPv4 address inside an IPv6 literal, as WHATWG takes it. */
169
+ const EMBEDDED_IPV4 = /^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
170
+ const IPV6_PIECE = /^[\da-f]{1,4}$/i;
171
+ /** The colon-separated pieces of one side of an IPv6 `::`. */
172
+ function ipv6Pieces(half) {
173
+ return half === "" ? [] : half.split(":");
174
+ }
175
+ /**
176
+ * Is `literal` (the inside of `[...]`) an IPv6 address? Eight pieces of one
177
+ * to four hex digits, or fewer with one `::` that stands for at least one
178
+ * zero piece; the last two pieces may be a dotted IPv4 address. No zone.
179
+ */
180
+ function isIpv6(literal) {
181
+ const halves = literal.split("::");
182
+ if (halves.length > 2) return false;
183
+ const head = ipv6Pieces(halves[0]);
184
+ const tail = halves.length === 2 ? ipv6Pieces(halves[1]) : [];
185
+ const pieces = [...head, ...tail];
186
+ const lastCanBeIpv4 = halves.length === 1 || tail.length > 0;
187
+ let count = 0;
188
+ for (let index = 0; index < pieces.length; index += 1) {
189
+ const piece = pieces[index];
190
+ if (IPV6_PIECE.test(piece)) count += 1;
191
+ else if (lastCanBeIpv4 && index === pieces.length - 1 && EMBEDDED_IPV4.test(piece)) count += 2;
192
+ else return false;
193
+ }
194
+ return halves.length === 2 ? count < 8 : count === 8;
195
+ }
196
+ /** A WHATWG IPv4 number: decimal, `0x` hex or `0` octal, or undefined. */
197
+ function ipv4Number(part) {
198
+ if (/^0x[\da-f]*$/i.test(part)) return part.length === 2 ? 0 : parseInt(part.slice(2), 16);
199
+ if (/^0[0-7]+$/.test(part)) return parseInt(part.slice(1), 8);
200
+ if (/^(?:0|[1-9]\d*)$/.test(part)) return Number(part);
201
+ }
202
+ /**
203
+ * A host name whose last label is a number is an IPv4 address to WHATWG
204
+ * URL: up to four parts, each decimal, hex or octal, every part but the last
205
+ * at most 255 and the last filling the rest of the 32 bits. Returns the
206
+ * host in dotted decimal, the host itself when it does not end in a number,
207
+ * or undefined when it is not a valid address.
208
+ */
209
+ function ipv4Host(hostname) {
210
+ const parts = hostname.split(".");
211
+ if (parts[parts.length - 1] === "" && parts.length > 1) parts.pop();
212
+ const last = parts[parts.length - 1];
213
+ if (!/^\d+$/.test(last) && ipv4Number(last) === void 0) return hostname;
214
+ if (parts.length > 4) return void 0;
215
+ const numbers = parts.map(ipv4Number);
216
+ if (numbers.some((number) => number === void 0)) return void 0;
217
+ const values = numbers;
218
+ const lastValue = values.pop();
219
+ if (values.some((value) => value > 255)) return void 0;
220
+ if (lastValue >= 256 ** (4 - values.length)) return void 0;
221
+ let address = lastValue;
222
+ values.forEach((value, index) => {
223
+ address += value * 256 ** (3 - index);
224
+ });
225
+ return [
226
+ 24,
227
+ 16,
228
+ 8,
229
+ 0
230
+ ].map((shift) => Math.floor(address / 2 ** shift) % 256).join(".");
231
+ }
232
+ /** The host of an http(s) URL, normalized, or undefined when invalid. */
233
+ function checkHost(hostname) {
234
+ if (hostname.startsWith("[")) return hostname.endsWith("]") && isIpv6(hostname.slice(1, -1)) ? hostname : void 0;
235
+ return HOSTNAME.test(hostname) ? ipv4Host(hostname) : void 0;
236
+ }
237
+ /**
238
+ * Parses an absolute http(s) URL with no help from the `URL` global. React
239
+ * Native has its own URL class (Libraries/Blob/URL.js): its constructor
240
+ * never throws without a base, its `protocol` keeps the case of the input,
241
+ * and before 0.80 its getters throw "not implemented". The scheme is
242
+ * matched in any case, and an http(s) URL needs "//" and a host.
243
+ */
244
+ function parseUrl(input) {
245
+ const url = trimControls(input);
246
+ const scheme = SCHEME.exec(url);
247
+ if (scheme === null) return { kind: "relative" };
248
+ const protocol = `${scheme[1].toLowerCase()}:`;
249
+ if (protocol !== "http:" && protocol !== "https:") return {
250
+ kind: "other",
251
+ protocol
252
+ };
253
+ const rest = url.slice(scheme[0].length);
254
+ if (!rest.startsWith("//") || hasControl(rest)) return { kind: "invalid" };
255
+ const authorityEnd = rest.slice(2).search(/[/?#\\]/);
256
+ const authority = authorityEnd < 0 ? rest.slice(2) : rest.slice(2, authorityEnd + 2);
257
+ const tail = authorityEnd < 0 ? "" : rest.slice(authorityEnd + 2);
258
+ if (/^[^?#]*\\/.test(tail)) return { kind: "invalid" };
259
+ const at = authority.lastIndexOf("@");
260
+ const userinfo = at < 0 ? "" : authority.slice(0, at + 1);
261
+ const hostAndPort = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(authority.slice(at + 1));
262
+ if (hostAndPort === null) return { kind: "invalid" };
263
+ const hostname = checkHost(hostAndPort[1].toLowerCase());
264
+ const port = hostAndPort[2] ?? "";
265
+ if (hostname === void 0 || /\s/.test(userinfo) || Number(port) > 65535) return { kind: "invalid" };
266
+ const path = tail.startsWith("/") ? tail : `/${tail}`;
267
+ return {
268
+ kind: "web",
269
+ hostname,
270
+ href: `${protocol}//${userinfo}${hostname}${port ? `:${port}` : ""}${path.replace(/ /g, "%20")}`
271
+ };
272
+ }
273
+ /** The host of a URL with an authority, lowercase, or "" without one. */
274
+ const PAGE_HOST = /^[A-Za-z][A-Za-z\d+\-.]*:\/\/(?:[^/?#@]*@)?(\[[^\]]*\]|[^/?#:]*)/;
275
+ /**
276
+ * The URL of the page, to resolve a relative URL against. `undefined` when
277
+ * there is no real page: on React Native (`navigator.product`), where any
278
+ * `location` is a polyfill, such as "http://react-native.invalid" or the
279
+ * Metro address; or a location whose host is reserved (`.invalid` is never
280
+ * a real host, with or without the trailing dot). Any other location is a
281
+ * browser page, whatever its scheme: WHATWG URL resolves against it, as it
282
+ * did before React Native was supported.
283
+ */
284
+ function pageBase(host) {
285
+ if (typeof navigator !== "undefined") {
286
+ if (navigator.product === "ReactNative") return void 0;
287
+ }
288
+ const href = host.location?.href;
289
+ if (typeof href !== "string") return void 0;
290
+ const hostname = (PAGE_HOST.exec(href.trim())?.[1] ?? "").toLowerCase().replace(/\.$/, "");
291
+ return hostname === "invalid" || hostname.endsWith(".invalid") ? void 0 : href;
292
+ }
293
+ /**
294
+ * openUrl on a browser page, exactly as before React Native was supported:
295
+ * WHATWG URL resolves `url` against the page, and any http(s) URL it
296
+ * accepts opens, in its serialization.
297
+ */
298
+ function openOnPage(host, open, url, base) {
120
299
  let parsed;
121
300
  try {
122
- parsed = new URL(url, window.location.href);
301
+ parsed = new URL(url, base);
123
302
  } catch {
124
303
  throw new ExpressionError(`"${url}" is not a URL`);
125
304
  }
126
305
  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");
306
+ open.call(host, parsed.href, "_blank", "noopener,noreferrer");
307
+ }
308
+ /**
309
+ * Opens an http(s) URL in a new tab. Any other scheme is refused.
310
+ *
311
+ * Without a `window` (server rendering) it does nothing. A platform that has
312
+ * a `window` but no `window.open` (React Native, where `window` is the global
313
+ * object) gets a PlatformError, not a misleading URL-parsing one. On a
314
+ * browser page WHATWG URL decides, as it always did. Without a real page
315
+ * origin (React Native, also with the location polyfill) only absolute
316
+ * URLs are taken: a relative one has nothing to resolve against. There the
317
+ * URL is checked by the stricter `parseUrl`, not by React Native's URL
318
+ * class, which accepts almost anything.
319
+ */
320
+ function openUrlSafely(url) {
321
+ if (typeof url !== "string" || url === "") throw new ExpressionError("url must be a string");
322
+ if (typeof window === "undefined") return;
323
+ const host = window;
324
+ const open = host.open;
325
+ if (typeof open !== "function") throw new PlatformError("openUrl is not available on this platform");
326
+ const base = pageBase(host);
327
+ if (base !== void 0) {
328
+ openOnPage(host, open, url, base);
329
+ return;
330
+ }
331
+ const parsed = parseUrl(url);
332
+ if (parsed.kind === "relative") throw new ExpressionError(`"${url}" is not an absolute URL`);
333
+ if (parsed.kind === "other") throw new ExpressionError(`openUrl takes only http(s) URLs, not ${parsed.protocol}`);
334
+ if (parsed.kind === "invalid") throw new ExpressionError(`"${url}" is not a URL`);
335
+ open.call(host, parsed.href, "_blank", "noopener,noreferrer");
128
336
  }
129
337
  /**
130
- * The basic functions, except `formatString`, which needs the resolver.
131
- * `calc` and `series` are added by `resolve.ts`, which imports both.
338
+ * The basic functions, except `formatString`, `calc` and `series`:
339
+ * `resolve.ts` adds those three when it loads (`formatString` needs the
340
+ * resolver, and `calc.ts` uses this module). Import `resolve.ts` before
341
+ * looking a function up here.
132
342
  */
133
343
  const BASIC_FUNCTIONS = {
134
344
  required: ({ value }) => {
@@ -165,14 +375,15 @@ const BASIC_FUNCTIONS = {
165
375
  formatNumber: (args) => {
166
376
  const parsed = numberOf$1(args.value);
167
377
  if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
168
- return numberFormat(args, {}).format(parsed);
378
+ return numberFormat("formatNumber", args, {}).format(parsed);
169
379
  },
170
380
  formatCurrency: (args) => {
171
381
  const parsed = numberOf$1(args.value);
172
382
  if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
173
383
  if (typeof args.currency !== "string" || args.currency === "") throw new ExpressionError("currency must be an ISO 4217 code");
384
+ requireIntl("NumberFormat", "formatCurrency");
174
385
  try {
175
- return numberFormat(args, {
386
+ return numberFormat("formatCurrency", args, {
176
387
  style: "currency",
177
388
  currency: args.currency
178
389
  }).format(parsed);
@@ -187,7 +398,7 @@ const BASIC_FUNCTIONS = {
187
398
  pluralize: (args) => {
188
399
  const parsed = numberOf$1(args.value);
189
400
  if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
190
- const category = new Intl.PluralRules(locale()).select(parsed);
401
+ const category = pluralCategory(parsed);
191
402
  return text((parsed === 0 ? args.zero : void 0) ?? args[category] ?? args.other);
192
403
  },
193
404
  and: ({ values }) => {
@@ -1085,6 +1296,57 @@ const FORBIDDEN_SEGMENTS = new Set([
1085
1296
  function normalizePath(path) {
1086
1297
  return (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path) || "/";
1087
1298
  }
1299
+ /**
1300
+ * What the agent is told about a user value: what `JSON.stringify` makes
1301
+ * of it, as before generative UI ran on React Native. `NaN` and `Infinity`
1302
+ * become `null`, a valid `Date` its ISO string (an invalid one `null`), a
1303
+ * `Map` or a `Set` `{}`, and an `undefined` member is dropped. A value JSON refuses (a bigint or a cycle)
1304
+ * would make building the request throw, so it is left out of the
1305
+ * description instead, with a `console.warn`. It stays in the data model.
1306
+ */
1307
+ /** The JSON of an operation, or undefined when JSON refuses it. */
1308
+ function fingerprint(operation) {
1309
+ try {
1310
+ return JSON.stringify(operation);
1311
+ } catch {
1312
+ return;
1313
+ }
1314
+ }
1315
+ /** Whether two rejection lists hold the same entries in the same order. */
1316
+ function sameRejected(a, b) {
1317
+ return a.length === b.length && a.every((entry, i) => entry.index === b[i].index && entry.reason === b[i].reason);
1318
+ }
1319
+ function agentJson(value, path) {
1320
+ try {
1321
+ return JSON.stringify(value) ?? "null";
1322
+ } catch (cause) {
1323
+ const reason = cause instanceof Error ? cause.message : String(cause);
1324
+ console.warn(`[generativeUI] the value written to "${path}" is kept in the data model, but the agent is not told it, because JSON cannot hold it (${reason}). Write strings, numbers, booleans, null, arrays, plain objects or dates.`);
1325
+ return;
1326
+ }
1327
+ }
1328
+ /**
1329
+ * Defines `key` on `target` as a copy of what `read` gives, made the first
1330
+ * time it is read and then kept, so a value nobody reads is never copied.
1331
+ * The property is enumerable, and assigning it replaces the copy.
1332
+ */
1333
+ function defineCopyOnRead(target, key, read) {
1334
+ const settle = (value) => {
1335
+ Object.defineProperty(target, key, {
1336
+ value,
1337
+ enumerable: true,
1338
+ configurable: true,
1339
+ writable: true
1340
+ });
1341
+ return value;
1342
+ };
1343
+ Object.defineProperty(target, key, {
1344
+ enumerable: true,
1345
+ configurable: true,
1346
+ get: () => settle((0, _copilotkit_shared.cloneValue)(read())),
1347
+ set: settle
1348
+ });
1349
+ }
1088
1350
  /** True when `path` is `ancestor` or below it. */
1089
1351
  function isAtOrBelow(path, ancestor) {
1090
1352
  if (ancestor === "/") return true;
@@ -1135,7 +1397,7 @@ var GenerativeUISurfaceManager = class {
1135
1397
  constructor(ui, options = {}) {
1136
1398
  this.ui = ui;
1137
1399
  this.options = options;
1138
- this.webCoreCatalog = new _a2ui_web_core_v0_9.Catalog(ui.id, [...ui.components.keys()].map((name) => ({
1400
+ this.webCoreCatalog = new _a2ui_web_core_catalog.Catalog(ui.id, [...ui.components.keys()].map((name) => ({
1139
1401
  name,
1140
1402
  schema: zod.z.any()
1141
1403
  })), []);
@@ -1165,7 +1427,12 @@ var GenerativeUISurfaceManager = class {
1165
1427
  let surface = this.surfaces.get(key);
1166
1428
  let book = this.bookkeeping.get(key);
1167
1429
  let changed = false;
1168
- if (surface && book && !this.extendsApplied(book, operations)) {
1430
+ const extendsApplied = !!surface && !!book && this.extendsApplied(book, operations);
1431
+ const start = extendsApplied ? book.appliedCount : 0;
1432
+ for (let index = start; index < operations.length - 1; index++) if (fingerprint(operations[index]) === void 0) return;
1433
+ const lastFingerprint = operations.length > 0 ? fingerprint(operations[operations.length - 1]) : void 0;
1434
+ if (operations.length > 0 && lastFingerprint === void 0) return;
1435
+ if (surface && book && !extendsApplied) {
1169
1436
  this.disposeSurface(key);
1170
1437
  surface = void 0;
1171
1438
  book = void 0;
@@ -1187,7 +1454,6 @@ var GenerativeUISurfaceManager = class {
1187
1454
  changed = true;
1188
1455
  }
1189
1456
  if (operations.length > 0) {
1190
- const lastFingerprint = JSON.stringify(operations[operations.length - 1]);
1191
1457
  const isReplay = operations.some((op) => (0, _copilotkit_shared.getOperationKind)(op) === "deleteSurface");
1192
1458
  for (let index = book.appliedCount; index < operations.length; index++) {
1193
1459
  this.applyOperation(surface, operations[index], {
@@ -1200,7 +1466,7 @@ var GenerativeUISurfaceManager = class {
1200
1466
  surface.operations = operations;
1201
1467
  book.lastFingerprint = lastFingerprint;
1202
1468
  }
1203
- if (surface.status !== content.status || surface.target !== content.target || surface.serverRejected.length !== serverRejected.length) {
1469
+ if (surface.status !== content.status || surface.target !== content.target || !sameRejected(surface.serverRejected, serverRejected)) {
1204
1470
  surface.status = content.status;
1205
1471
  surface.target = content.target;
1206
1472
  surface.serverRejected = serverRejected;
@@ -1249,34 +1515,49 @@ var GenerativeUISurfaceManager = class {
1249
1515
  const owned = this.owned.get(surface.key);
1250
1516
  const rejections = [...surface.serverRejected, ...surface.clientRejected];
1251
1517
  const status = this.deletedKeys.has(surface.key) ? "deleted" : surface.failed ? "failed" : void 0;
1518
+ const dataModel = {};
1519
+ for (const [path, { json }] of owned ?? []) if (json !== void 0) dataModel[path] = JSON.parse(json);
1252
1520
  described[surface.surfaceId] = {
1253
1521
  target: surface.target,
1254
- ...owned && owned.size > 0 ? { dataModel: Object.fromEntries(owned) } : {},
1522
+ ...Object.keys(dataModel).length > 0 ? { dataModel } : {},
1255
1523
  ...rejections.length > 0 && status !== "deleted" ? { rejected: summarizeRejections(rejections) } : {},
1256
1524
  ...status ? { status } : {}
1257
1525
  };
1258
1526
  }
1259
1527
  return described;
1260
1528
  }
1261
- /** Every surface that is not deleted, oldest first, for the inspector. */
1529
+ /**
1530
+ * Every surface that is not deleted, oldest first, for the inspector. The
1531
+ * data model and the user values are copies, so the inspector cannot
1532
+ * change the surface through them. The inspector asks for this on every
1533
+ * change of the manager, so each copy is made only the first time it is
1534
+ * read (then kept): a snapshot that nobody opens copies nothing. The user
1535
+ * values are those of the call; the data model is the one of the first
1536
+ * read, which the inspector does while it renders the snapshot.
1537
+ */
1262
1538
  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
- }));
1539
+ return [...this.surfaces.values()].filter((surface) => !surface.deleted).sort((a, b) => a.createdAt - b.createdAt).map((surface) => {
1540
+ const { model } = surface;
1541
+ const owned = [...this.owned.get(surface.key) ?? []];
1542
+ const entry = {
1543
+ surfaceId: surface.surfaceId,
1544
+ threadId: surface.threadId,
1545
+ agentId: surface.agentId,
1546
+ target: surface.target,
1547
+ status: surface.status,
1548
+ operations: surface.operations,
1549
+ rejected: [...surface.serverRejected.map((r) => ({
1550
+ ...r,
1551
+ source: "runtime"
1552
+ })), ...surface.clientRejected.map((r) => ({
1553
+ ...r,
1554
+ source: "browser"
1555
+ }))]
1556
+ };
1557
+ defineCopyOnRead(entry, "dataModel", () => model.dataModel.get("/"));
1558
+ defineCopyOnRead(entry, "userValues", () => Object.fromEntries(owned.map(([path, { value }]) => [path, value])));
1559
+ return entry;
1560
+ });
1280
1561
  }
1281
1562
  /**
1282
1563
  * Marks a target as mounted. Returns the function that unmounts it. Calling
@@ -1339,7 +1620,7 @@ var GenerativeUISurfaceManager = class {
1339
1620
  getState = () => this.state;
1340
1621
  /** Sets one state key. Notifies only when the value changed. */
1341
1622
  setState(key, value) {
1342
- if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
1623
+ if ((0, _copilotkit_shared_generative_ui.hasOwnKey)(this.state, key) && Object.is(this.state[key], value)) return;
1343
1624
  this.state = {
1344
1625
  ...this.state,
1345
1626
  [key]: value
@@ -1348,7 +1629,7 @@ var GenerativeUISurfaceManager = class {
1348
1629
  }
1349
1630
  /** Removes one state key. Notifies only when the key was set. */
1350
1631
  removeState(key) {
1351
- if (!Object.hasOwn(this.state, key)) return;
1632
+ if (!(0, _copilotkit_shared_generative_ui.hasOwnKey)(this.state, key)) return;
1352
1633
  const { [key]: _removed, ...rest } = this.state;
1353
1634
  this.state = rest;
1354
1635
  this.notify();
@@ -1371,12 +1652,27 @@ var GenerativeUISurfaceManager = class {
1371
1652
  * Writes a user value into the data model of a surface, and marks `path`
1372
1653
  * as user-owned. Then agent writes to that path, or below it, are ignored.
1373
1654
  * 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
1655
+ * surface is deleted. Does nothing for an unknown or deleted surface with
1656
+ * no live linked surface, and then does not check `value` either. The
1375
1657
  * surfaces linked to it (see `linkSurfaces`) get the same write.
1376
1658
  *
1377
1659
  * @param key - The `key` of the surface.
1378
1660
  * @param path - An absolute JSON pointer, for example "/form/email".
1379
- * @param value - The new value. It is copied.
1661
+ * @param value - The new value. It is copied with structuredClone
1662
+ * semantics, so the data model never shares an object with it, and it
1663
+ * keeps what structuredClone keeps: `NaN`, `Infinity`, `-0`, a `Date`,
1664
+ * a `Map`, a `Set`; a class instance becomes a plain object. The agent
1665
+ * reads it from the JSON request of the next run, so it is told what
1666
+ * `JSON.stringify` makes of it (`NaN` becomes `null`, a valid `Date`
1667
+ * its ISO string, an invalid one `null`, a `Map` `{}`). A value JSON refuses (a bigint, a cycle) is
1668
+ * written, but left out of what the agent is told, with a
1669
+ * `console.warn`. `null` or `undefined` removes the key, as an agent
1670
+ * `null` does; the path stays user-owned, and the agent is told `null`
1671
+ * for it, which the protocol reads as "removed".
1672
+ * @throws An error named "DataCloneError" when structuredClone refuses
1673
+ * `value`: a function, a symbol, a `WeakMap`, a `Promise`... It is
1674
+ * checked before any surface is written, so nothing is written. The
1675
+ * framework setters report it with `reportError`.
1380
1676
  * @throws Error when a path segment is "__proto__", "constructor" or
1381
1677
  * "prototype", or when the path does not fit the data (for example, a
1382
1678
  * segment above it holds a string).
@@ -1385,15 +1681,26 @@ var GenerativeUISurfaceManager = class {
1385
1681
  const normalized = normalizePath(path);
1386
1682
  const forbidden = normalized.split("/").find((segment) => FORBIDDEN_SEGMENTS.has(segment));
1387
1683
  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);
1684
+ const targets = [...this.linked.get(key) ?? [key]].filter((target) => {
1685
+ const surface = this.surfaces.get(target);
1686
+ return surface !== void 0 && !surface.deleted;
1687
+ });
1688
+ if (targets.length === 0) return;
1689
+ const owned = value === void 0 ? null : (0, _copilotkit_shared.cloneValue)(value);
1690
+ const json = agentJson(owned, normalized);
1691
+ for (const target of targets) this.writeOwnedValue(target, normalized, {
1692
+ value: owned,
1693
+ json
1694
+ });
1389
1695
  }
1390
- writeOwnedValue(key, path, value) {
1696
+ /** Writes `owned`, which `setOwnedValue` made, as a user-owned value. */
1697
+ writeOwnedValue(key, path, owned) {
1391
1698
  const surface = this.surfaces.get(key);
1392
1699
  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);
1700
+ surface.model.dataModel.set(path, (0, _copilotkit_shared.cloneValue)(owned.value));
1701
+ const values = this.owned.get(key) ?? /* @__PURE__ */ new Map();
1702
+ values.set(path, owned);
1703
+ this.owned.set(key, values);
1397
1704
  }
1398
1705
  /**
1399
1706
  * Writes the user-owned values into the new, empty data model of a rebuilt
@@ -1401,7 +1708,7 @@ var GenerativeUISurfaceManager = class {
1401
1708
  */
1402
1709
  restoreOwnedValues(surface) {
1403
1710
  const owned = this.owned.get(surface.key) ?? /* @__PURE__ */ new Map();
1404
- for (const [path, value] of owned) surface.model.dataModel.set(path, structuredClone(value));
1711
+ for (const [path, { value }] of owned) surface.model.dataModel.set(path, (0, _copilotkit_shared.cloneValue)(value));
1405
1712
  }
1406
1713
  /**
1407
1714
  * The value that an agent write puts at `path`, with the user-owned values
@@ -1410,25 +1717,25 @@ var GenerativeUISurfaceManager = class {
1410
1717
  * user value does not fit the new value.
1411
1718
  */
1412
1719
  mergeOwnedValues(key, path, value) {
1413
- const merged = { value: structuredClone(value) };
1720
+ const merged = { value: (0, _copilotkit_shared.cloneValue)(value) };
1414
1721
  const owned = this.owned.get(key);
1415
1722
  if (!owned) return merged;
1416
1723
  const ownedPaths = [...owned.keys()];
1417
1724
  if (ownedPaths.some((ownedPath) => isAtOrBelow(path, ownedPath))) return void 0;
1418
1725
  const below = ownedPaths.filter((ownedPath) => isAtOrBelow(ownedPath, path));
1419
1726
  if (below.length === 0) return merged;
1420
- const scratch = new _a2ui_web_core_v0_9.DataModel({ value: merged.value });
1727
+ const scratch = new _a2ui_web_core_state.DataModel({ value: merged.value });
1421
1728
  const prefix = path === "/" ? "" : path;
1422
1729
  for (const ownedPath of below) {
1423
1730
  const relative = ownedPath.slice(prefix.length);
1424
- scratch.set(`/value${relative}`, structuredClone(owned.get(ownedPath)));
1731
+ scratch.set(`/value${relative}`, (0, _copilotkit_shared.cloneValue)(owned.get(ownedPath).value));
1425
1732
  }
1426
1733
  return { value: scratch.get("/value") };
1427
1734
  }
1428
1735
  extendsApplied(book, operations) {
1429
1736
  if (operations.length < book.appliedCount) return false;
1430
1737
  if (book.appliedCount === 0) return true;
1431
- return JSON.stringify(operations[book.appliedCount - 1]) === book.lastFingerprint;
1738
+ return fingerprint(operations[book.appliedCount - 1]) === book.lastFingerprint;
1432
1739
  }
1433
1740
  createSurface(key, threadId, agentId, content) {
1434
1741
  return {
@@ -1436,7 +1743,7 @@ var GenerativeUISurfaceManager = class {
1436
1743
  threadId,
1437
1744
  surfaceId: content.surfaceId,
1438
1745
  agentId,
1439
- model: new _a2ui_web_core_v0_9.SurfaceModel(content.surfaceId, this.webCoreCatalog),
1746
+ model: new _a2ui_web_core_state.SurfaceModel(content.surfaceId, this.webCoreCatalog),
1440
1747
  createdAt: ++creationCounter,
1441
1748
  target: content.target,
1442
1749
  status: content.status,
@@ -1460,7 +1767,7 @@ var GenerativeUISurfaceManager = class {
1460
1767
  closeSurface(surface) {
1461
1768
  surface.deleted = true;
1462
1769
  surface.model.dispose();
1463
- surface.model = new _a2ui_web_core_v0_9.SurfaceModel(surface.surfaceId, this.webCoreCatalog);
1770
+ surface.model = new _a2ui_web_core_state.SurfaceModel(surface.surfaceId, this.webCoreCatalog);
1464
1771
  this.owned.delete(surface.key);
1465
1772
  this.linked.delete(surface.key);
1466
1773
  }
@@ -1498,7 +1805,7 @@ var GenerativeUISurfaceManager = class {
1498
1805
  if (typeof component !== "string") return node;
1499
1806
  const definition = this.ui.components.get(component);
1500
1807
  if (!definition) return node;
1501
- return Object.fromEntries(Object.entries(node).filter(([key]) => !Object.hasOwn(definition.selectors, key) && !Object.hasOwn(definition.eventFunctions, key)));
1808
+ return Object.fromEntries(Object.entries(node).filter(([key]) => !(0, _copilotkit_shared_generative_ui.hasOwnKey)(definition.selectors, key) && !(0, _copilotkit_shared_generative_ui.hasOwnKey)(definition.eventFunctions, key)));
1502
1809
  }
1503
1810
  /**
1504
1811
  * The surfaces that `validateOperation` gets for one operation of the
@@ -1629,14 +1936,14 @@ var GenerativeUISurfaceManager = class {
1629
1936
  }
1630
1937
  upsertNode(model, node) {
1631
1938
  const { id, component, ...rest } = node;
1632
- const properties = structuredClone(rest);
1939
+ const properties = (0, _copilotkit_shared.cloneValue)(rest);
1633
1940
  const existing = model.componentsModel.get(id);
1634
1941
  if (existing && existing.type === component) {
1635
1942
  existing.properties = properties;
1636
1943
  return;
1637
1944
  }
1638
1945
  if (existing) model.componentsModel.removeComponent(id);
1639
- model.componentsModel.addComponent(new _a2ui_web_core_v0_9.ComponentModel(id, component, properties));
1946
+ model.componentsModel.addComponent(new _a2ui_web_core_state.ComponentModel(id, component, properties));
1640
1947
  }
1641
1948
  };
1642
1949
 
@@ -2226,7 +2533,7 @@ function createSurfaceFirst(operations) {
2226
2533
  /** True when the component of `name` has the prop `prop`. */
2227
2534
  function hasProp(ui, name, prop) {
2228
2535
  const properties = ui.manifestComponents[name]?.props.properties;
2229
- return (0, _copilotkit_shared_generative_ui.isRecord)(properties) && Object.hasOwn(properties, prop);
2536
+ return (0, _copilotkit_shared_generative_ui.isRecord)(properties) && (0, _copilotkit_shared_generative_ui.hasOwnKey)(properties, prop);
2230
2537
  }
2231
2538
  const childRefCache = /* @__PURE__ */ new WeakMap();
2232
2539
  /** The ids in a slot value: an id, a list of ids, or a template. */
@@ -2246,7 +2553,7 @@ function slotIds(value) {
2246
2553
  function childIdsReader(ui) {
2247
2554
  return (component) => {
2248
2555
  const name = component.component;
2249
- const entry = typeof name === "string" && Object.hasOwn(ui.manifestComponents, name) ? ui.manifestComponents[name] : void 0;
2556
+ const entry = typeof name === "string" && (0, _copilotkit_shared_generative_ui.hasOwnKey)(ui.manifestComponents, name) ? ui.manifestComponents[name] : void 0;
2250
2557
  if (!entry) return [];
2251
2558
  const ids = [];
2252
2559
  for (const slot of Object.keys(entry.slots ?? {})) if (slot !== "child" && slot !== "children") ids.push(...slotIds(component[slot]));
@@ -2277,7 +2584,7 @@ function collectComponents(operations) {
2277
2584
  * data of the other one.
2278
2585
  */
2279
2586
  function cloneData(value) {
2280
- return value === void 0 ? void 0 : structuredClone(value);
2587
+ return (0, _copilotkit_shared.cloneValue)(value);
2281
2588
  }
2282
2589
  /** The operation sent to `surfaceId`, with a copy of its data model value. */
2283
2590
  function readdress(op, surfaceId) {
@@ -3071,12 +3378,57 @@ function allowedComponents(requested, ui) {
3071
3378
  };
3072
3379
  }
3073
3380
 
3381
+ //#endregion
3382
+ //#region src/generative-ui/activity-content.ts
3383
+ /**
3384
+ * The content of a generative UI surface activity message. A missing
3385
+ * `rejected` reads as []. Extra keys of the content are kept.
3386
+ */
3387
+ const GenerativeUISurfaceContentSchema = zod.z.object({
3388
+ surfaceId: zod.z.string(),
3389
+ target: zod.z.string(),
3390
+ catalogId: zod.z.string(),
3391
+ operations: zod.z.array(zod.z.any()),
3392
+ status: zod.z.enum([
3393
+ "streaming",
3394
+ "ready",
3395
+ "error"
3396
+ ]),
3397
+ rejected: zod.z.array(zod.z.object({
3398
+ index: zod.z.number(),
3399
+ reason: zod.z.string()
3400
+ })).default([])
3401
+ }).passthrough();
3402
+ /** A zod issue path as `rejected[0].index`; the content itself is "content". */
3403
+ function formatPath(path) {
3404
+ let out = "";
3405
+ for (const segment of path) out += typeof segment === "number" ? `[${segment}]` : `${out ? "." : ""}${String(segment)}`;
3406
+ return out || "content";
3407
+ }
3408
+ /**
3409
+ * Reads the content of a surface activity message with
3410
+ * {@link GenerativeUISurfaceContentSchema}, or lists its issues (as
3411
+ * `path: message`) when it is malformed. Never throws.
3412
+ */
3413
+ function parseGenerativeUISurfaceContent(content) {
3414
+ let result;
3415
+ try {
3416
+ result = GenerativeUISurfaceContentSchema.safeParse(content);
3417
+ } catch {
3418
+ return { issues: ["content: could not be read"] };
3419
+ }
3420
+ if (result.success) return { content: result.data };
3421
+ return { issues: result.error.issues.map((issue) => `${formatPath(issue.path)}: ${issue.message}`) };
3422
+ }
3423
+
3074
3424
  //#endregion
3075
3425
  exports.BASIC_FUNCTIONS = BASIC_FUNCTIONS;
3076
3426
  exports.ExpressionError = ExpressionError;
3427
+ exports.GenerativeUISurfaceContentSchema = GenerativeUISurfaceContentSchema;
3077
3428
  exports.GenerativeUISurfaceManager = GenerativeUISurfaceManager;
3078
3429
  exports.MarkdownBuildCache = MarkdownBuildCache;
3079
3430
  exports.MarkdownSurfaceSource = MarkdownSurfaceSource;
3431
+ exports.PlatformError = PlatformError;
3080
3432
  exports.accessibilityAttributes = accessibilityAttributes;
3081
3433
  exports.activityFunctionCalls = activityFunctionCalls;
3082
3434
  exports.allowedComponents = allowedComponents;
@@ -3105,6 +3457,7 @@ exports.joinPath = joinPath;
3105
3457
  exports.markdownFunctionCalls = markdownFunctionCalls;
3106
3458
  exports.namedRole = namedRole;
3107
3459
  exports.openUrlSafely = openUrlSafely;
3460
+ exports.parseGenerativeUISurfaceContent = parseGenerativeUISurfaceContent;
3108
3461
  exports.readAccessibility = readAccessibility;
3109
3462
  exports.reportErrorSafely = reportErrorSafely;
3110
3463
  exports.requiresUserActivation = requiresUserActivation;