@copilotkit/core 1.85.0 → 1.86.0

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