@copilotkit/react-core 1.80.0 → 1.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/MarkdownSurfaces-D-OkjUpU.cjs +3807 -0
  2. package/dist/MarkdownSurfaces-D-OkjUpU.cjs.map +1 -0
  3. package/dist/MarkdownSurfaces-L67964_B.mjs +3522 -0
  4. package/dist/MarkdownSurfaces-L67964_B.mjs.map +1 -0
  5. package/dist/{copilotkit-CWOSXhRO.d.mts → copilotkit-BEcaM4L4.d.mts} +25 -34
  6. package/dist/copilotkit-BEcaM4L4.d.mts.map +1 -0
  7. package/dist/{copilotkit-DKICi3nC.cjs → copilotkit-BjllYYjw.cjs} +2022 -600
  8. package/dist/copilotkit-BjllYYjw.cjs.map +1 -0
  9. package/dist/{copilotkit-Dfw9HzO9.d.cts → copilotkit-D9jIImy9.d.cts} +25 -34
  10. package/dist/copilotkit-D9jIImy9.d.cts.map +1 -0
  11. package/dist/{copilotkit-BNLtgOyD.mjs → copilotkit-fKrKqoiP.mjs} +1966 -493
  12. package/dist/copilotkit-fKrKqoiP.mjs.map +1 -0
  13. package/dist/index.cjs +8 -7
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +2 -1
  16. package/dist/index.d.cts.map +1 -1
  17. package/dist/index.d.mts +2 -1
  18. package/dist/index.d.mts.map +1 -1
  19. package/dist/index.mjs +2 -1
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/index.umd.js +4463 -9
  22. package/dist/index.umd.js.map +1 -1
  23. package/dist/runtime-context-CrHq-iTf.d.mts +924 -0
  24. package/dist/runtime-context-CrHq-iTf.d.mts.map +1 -0
  25. package/dist/runtime-context-D3NcP9oE.d.cts +924 -0
  26. package/dist/runtime-context-D3NcP9oE.d.cts.map +1 -0
  27. package/dist/v2/generative-ui.cjs +8154 -0
  28. package/dist/v2/generative-ui.cjs.map +1 -0
  29. package/dist/v2/generative-ui.d.cts +4950 -0
  30. package/dist/v2/generative-ui.d.cts.map +1 -0
  31. package/dist/v2/generative-ui.d.mts +4950 -0
  32. package/dist/v2/generative-ui.d.mts.map +1 -0
  33. package/dist/v2/generative-ui.mjs +8140 -0
  34. package/dist/v2/generative-ui.mjs.map +1 -0
  35. package/dist/v2/index.cjs +65 -4
  36. package/dist/v2/index.css +1 -1
  37. package/dist/v2/index.d.cts +3 -2
  38. package/dist/v2/index.d.mts +3 -2
  39. package/dist/v2/index.mjs +3 -2
  40. package/dist/v2/index.umd.js +4832 -180
  41. package/dist/v2/index.umd.js.map +1 -1
  42. package/package.json +21 -8
  43. package/dist/copilotkit-BNLtgOyD.mjs.map +0 -1
  44. package/dist/copilotkit-CWOSXhRO.d.mts.map +0 -1
  45. package/dist/copilotkit-DKICi3nC.cjs.map +0 -1
  46. package/dist/copilotkit-Dfw9HzO9.d.cts.map +0 -1
package/dist/index.umd.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use client";
2
2
 
3
3
  (function(global, factory) {
4
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('@copilotkit/core'), require('@ag-ui/client'), require('@copilotkit/shared'), require('react/jsx-runtime'), require('@ag-ui/core'), require('zod'), require('@copilotkit/mcp-apps-renderer/activity'), require('@copilotkit/a2ui-renderer'), require('zod-to-json-schema'), require('react-dom'), require('react-markdown'), require('@copilotkit/runtime-client-gql')) :
5
- typeof define === 'function' && define.amd ? define(['exports', 'react', '@copilotkit/core', '@ag-ui/client', '@copilotkit/shared', 'react/jsx-runtime', '@ag-ui/core', 'zod', '@copilotkit/mcp-apps-renderer/activity', '@copilotkit/a2ui-renderer', 'zod-to-json-schema', 'react-dom', 'react-markdown', '@copilotkit/runtime-client-gql'], factory) :
6
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitReactCore = {}), global.React,global.CopilotKitCore,global.AgUIClient,global.CopilotKitShared,global.ReactJsxRuntime,global._ag_ui_core,global.Zod,global.CopilotKitMcpAppsRendererActivity,global.CopilotKitA2UIRenderer,global.zod_to_json_schema,global.ReactDOM,global.ReactMarkdown,global.CopilotKitRuntimeClientGQL));
7
- })(this, function(exports, react, _copilotkit_core, _ag_ui_client, _copilotkit_shared, react_jsx_runtime, _ag_ui_core, zod, _copilotkit_mcp_apps_renderer_activity, _copilotkit_a2ui_renderer, zod_to_json_schema, react_dom, react_markdown, _copilotkit_runtime_client_gql) {
4
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('@copilotkit/core'), require('@ag-ui/client'), require('@copilotkit/shared'), require('react/jsx-runtime'), require('@ag-ui/core'), require('zod'), require('@copilotkit/mcp-apps-renderer/activity'), require('@copilotkit/a2ui-renderer'), require('zod-to-json-schema'), require('@a2ui/web_core/v0_9'), require('react-dom'), require('react-markdown'), require('@copilotkit/runtime-client-gql')) :
5
+ typeof define === 'function' && define.amd ? define(['exports', 'react', '@copilotkit/core', '@ag-ui/client', '@copilotkit/shared', 'react/jsx-runtime', '@ag-ui/core', 'zod', '@copilotkit/mcp-apps-renderer/activity', '@copilotkit/a2ui-renderer', 'zod-to-json-schema', '@a2ui/web_core/v0_9', 'react-dom', 'react-markdown', '@copilotkit/runtime-client-gql'], factory) :
6
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitReactCore = {}), global.React,global.CopilotKitCore,global.AgUIClient,global.CopilotKitShared,global.ReactJsxRuntime,global._ag_ui_core,global.Zod,global.CopilotKitMcpAppsRendererActivity,global.CopilotKitA2UIRenderer,global.zod_to_json_schema,global._a2ui_web_core_v0_9,global.ReactDOM,global.ReactMarkdown,global.CopilotKitRuntimeClientGQL));
7
+ })(this, function(exports, react, _copilotkit_core, _ag_ui_client, _copilotkit_shared, react_jsx_runtime, _ag_ui_core, zod, _copilotkit_mcp_apps_renderer_activity, _copilotkit_a2ui_renderer, zod_to_json_schema, _a2ui_web_core_v0_9, react_dom, react_markdown, _copilotkit_runtime_client_gql) {
8
8
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
9
9
  //#region \0rolldown/runtime.js
10
10
  var __create = Object.create;
@@ -615,7 +615,7 @@ react_markdown = __toESM(react_markdown);
615
615
 
616
616
  //#endregion
617
617
  //#region package.json
618
- var version = "1.80.0";
618
+ var version = "1.81.0";
619
619
 
620
620
  //#endregion
621
621
  //#region src/v2/components/CopilotKitInspector.tsx
@@ -1888,7 +1888,7 @@ react_markdown = __toESM(react_markdown);
1888
1888
  const groupedOperations = (0, react.useMemo)(() => {
1889
1889
  const groups = /* @__PURE__ */ new Map();
1890
1890
  for (const operation of operations) {
1891
- const surfaceId = getOperationSurfaceId(operation) ?? _copilotkit_a2ui_renderer.DEFAULT_SURFACE_ID;
1891
+ const surfaceId = getOperationSurfaceId$1(operation) ?? _copilotkit_a2ui_renderer.DEFAULT_SURFACE_ID;
1892
1892
  if (!groups.has(surfaceId)) groups.set(surfaceId, []);
1893
1893
  groups.get(surfaceId).push(operation);
1894
1894
  }
@@ -2110,7 +2110,7 @@ react_markdown = __toESM(react_markdown);
2110
2110
  * @param operation - One A2UI operation, of any shape.
2111
2111
  * @returns The surface id, or null when the operation names none.
2112
2112
  */
2113
- function getOperationSurfaceId(operation) {
2113
+ function getOperationSurfaceId$1(operation) {
2114
2114
  if (!operation || typeof operation !== "object") return null;
2115
2115
  const nested = operation?.createSurface?.surfaceId ?? operation?.updateComponents?.surfaceId ?? operation?.updateDataModel?.surfaceId ?? operation?.deleteSurface?.surfaceId;
2116
2116
  if (typeof nested === "string") return nested;
@@ -2223,6 +2223,4452 @@ react_markdown = __toESM(react_markdown);
2223
2223
  return null;
2224
2224
  }
2225
2225
 
2226
+ //#endregion
2227
+ //#region src/v2/generative-ui/action-message.ts
2228
+ /** Context keys that supply the message's first line, in priority order. */
2229
+ const TEXT_KEYS = ["message", "label"];
2230
+ function isNonEmptyString(value) {
2231
+ return typeof value === "string" && value.trim().length > 0;
2232
+ }
2233
+ /** `choose_plan`, `choose-plan` and `choosePlan` all become "Choose plan". */
2234
+ function humanize(name) {
2235
+ const spaced = name.replace(/[_-]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").trim();
2236
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();
2237
+ }
2238
+ function formatContextValue(value) {
2239
+ return typeof value === "object" ? JSON.stringify(value) : String(value);
2240
+ }
2241
+ /**
2242
+ * Turns a user event that no function handles into the text of a visible
2243
+ * user message.
2244
+ *
2245
+ * The first line is, in order: `userMessage`, `context.message`,
2246
+ * `context.label`, the label of the source component (from `resolveLabel`),
2247
+ * or the event name made readable (`choose_plan` becomes "Choose plan").
2248
+ * Each other context field follows as one `key: value` line. Objects are
2249
+ * written as JSON. `null` and `undefined` fields are skipped.
2250
+ *
2251
+ * @param event - The user event, as sent by a surface.
2252
+ * @param resolveLabel - Finds the visible label of a component by id. Build
2253
+ * one with {@link createComponentLabelResolver}.
2254
+ *
2255
+ * @example
2256
+ * ```ts
2257
+ * buildActionMessageText({
2258
+ * name: "choose_plan",
2259
+ * surfaceId: "plans",
2260
+ * componentId: "team-button",
2261
+ * userMessage: "I pick the Team plan",
2262
+ * context: { seats: 12 },
2263
+ * });
2264
+ * // "I pick the Team plan\n\nseats: 12"
2265
+ * ```
2266
+ */
2267
+ function buildActionMessageText(event, resolveLabel) {
2268
+ const { context, userMessage } = event;
2269
+ const explicit = [userMessage, ...TEXT_KEYS.map((key) => context[key])].find(isNonEmptyString);
2270
+ const resolved = explicit ? void 0 : resolveLabel?.(event.componentId);
2271
+ const head = explicit ?? (isNonEmptyString(resolved) ? resolved.trim() : humanize(event.name));
2272
+ const lines = Object.entries(context).filter(([key, value]) => !TEXT_KEYS.includes(key) && value !== void 0 && value !== null).map(([key, value]) => `${key}: ${formatContextValue(value)}`);
2273
+ return lines.length > 0 ? `${head}\n\n${lines.join("\n")}` : head;
2274
+ }
2275
+ function ownText(component) {
2276
+ if (!component) return void 0;
2277
+ if (isNonEmptyString(component.label)) return component.label;
2278
+ if (isNonEmptyString(component.text)) return component.text;
2279
+ }
2280
+ function childIds(component) {
2281
+ const { child, children } = component;
2282
+ const single = typeof child === "string" ? [child] : [];
2283
+ const multiple = Array.isArray(children) ? children.filter((id) => typeof id === "string") : [];
2284
+ return [...single, ...multiple];
2285
+ }
2286
+ /** The components that an operation adds, inline or in an update. */
2287
+ function componentsOf(operation) {
2288
+ if ("createSurface" in operation) return operation.createSurface.components ?? [];
2289
+ if ("updateComponents" in operation) return operation.updateComponents.components;
2290
+ return [];
2291
+ }
2292
+ /**
2293
+ * Builds a function that finds the visible label of a component on a surface.
2294
+ *
2295
+ * The label is the component's own string `label`, else its string `text`,
2296
+ * else the first `child` or `children` component that has a string `label`
2297
+ * or `text`. When a component id is defined more than once, the last
2298
+ * definition wins, as in the renderer.
2299
+ *
2300
+ * @param operations - The committed operations of the surface.
2301
+ *
2302
+ * @example
2303
+ * ```ts
2304
+ * const resolveLabel = createComponentLabelResolver(surface.operations);
2305
+ * buildActionMessageText(event, resolveLabel);
2306
+ * ```
2307
+ */
2308
+ function createComponentLabelResolver(operations) {
2309
+ const byId = /* @__PURE__ */ new Map();
2310
+ for (const operation of operations) {
2311
+ const components = componentsOf(operation);
2312
+ for (const component of components) byId.set(component.id, component);
2313
+ }
2314
+ return (componentId) => {
2315
+ const component = byId.get(componentId);
2316
+ if (!component) return void 0;
2317
+ const own = ownText(component);
2318
+ if (own) return own;
2319
+ const ids = childIds(component);
2320
+ for (const id of ids) {
2321
+ const text = ownText(byId.get(id));
2322
+ if (text) return text;
2323
+ }
2324
+ };
2325
+ }
2326
+
2327
+ //#endregion
2328
+ //#region src/v2/generative-ui/json-schema.ts
2329
+ /**
2330
+ * JSON Schema for a Standard Schema (zod v3 via zod-to-json-schema),
2331
+ * inlined, no `$schema`. A prop marked by `child()` or `childList()`
2332
+ * becomes an A2UI `$ref` to `ComponentId` or `ChildList`.
2333
+ */
2334
+ function toJsonSchema(schema) {
2335
+ const { $schema: _omit, ...rest } = (0, _copilotkit_shared.schemaToJsonSchema)(schema, { zodToJsonSchema: (s) => (0, zod_to_json_schema.zodToJsonSchema)(s, { $refStrategy: "none" }) });
2336
+ return (0, _copilotkit_shared.applyChildRefMarks)(rest);
2337
+ }
2338
+
2339
+ //#endregion
2340
+ //#region src/v2/generative-ui/catalog.ts
2341
+ /** The A2UI component envelope: `id`, `component`, `catalogId`, `accessibility`, `metadata`. */
2342
+ const RESERVED_KEYS = new Set([
2343
+ "id",
2344
+ "component",
2345
+ ..._copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS
2346
+ ]);
2347
+ /** The id of the catalog that declared each component, for the inspector. */
2348
+ const componentCatalogs = /* @__PURE__ */ new WeakMap();
2349
+ /**
2350
+ * The id of the catalog that declared each component of `ui`. A component
2351
+ * from `extends` keeps the id of its base. Not exported from the package.
2352
+ */
2353
+ function componentCatalogIds(ui) {
2354
+ return componentCatalogs.get(ui) ?? /* @__PURE__ */ new Map();
2355
+ }
2356
+ /**
2357
+ * The catalogs that an operation can name: the id of `ui`, then the ids of
2358
+ * the catalogs in its `extends` that declared a component. Not exported
2359
+ * from the package.
2360
+ */
2361
+ function catalogIdsOf(ui) {
2362
+ const declared = componentCatalogs.get(ui)?.values() ?? [];
2363
+ return [...new Set([ui.id, ...declared])];
2364
+ }
2365
+ /** The setter prop of a writable prop: `value` gives `setValue`. */
2366
+ function setterNameOf(key) {
2367
+ return `set${key.charAt(0).toUpperCase()}${key.slice(1)}`;
2368
+ }
2369
+
2370
+ //#endregion
2371
+ //#region src/v2/generative-ui/manifest.ts
2372
+ /**
2373
+ * The built-in functions (the A2UI basic catalog plus calc and series) as
2374
+ * manifest entries. Their args are described by the short signature, not
2375
+ * by a full JSON Schema: the renderer checks them when they run. An app
2376
+ * function of the same name replaces the entry.
2377
+ */
2378
+ function builtInFunctionManifests() {
2379
+ return Object.fromEntries(Object.entries(_copilotkit_shared.GENERATIVE_UI_FUNCTIONS).map(([name, fn]) => [name, {
2380
+ description: fn.description,
2381
+ parameters: {
2382
+ type: "object",
2383
+ description: fn.parameters
2384
+ },
2385
+ returnType: fn.returnType,
2386
+ allowedCallers: fn.allowedCallers,
2387
+ ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
2388
+ }]));
2389
+ }
2390
+ /**
2391
+ * Builds the per-run manifest. Never contains handlers or renderers.
2392
+ *
2393
+ * - `functions`: the built-in functions, then the declared functions with
2394
+ * exactly one mounted handler.
2395
+ * - `targets`: the chat first, then each mounted `<GenerativeUISurface>`,
2396
+ * with its `description` and its `components` when it has them.
2397
+ */
2398
+ function buildGenerativeUIManifest(runtime, threadId) {
2399
+ const { ui, manager, dispatcher } = runtime;
2400
+ const inlineTargets = manager.getMountedTargets().filter((target) => target.id !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET).map(({ id, ...rest }) => ({
2401
+ id,
2402
+ kind: "inline",
2403
+ ...rest
2404
+ }));
2405
+ return {
2406
+ catalogId: ui.id,
2407
+ catalogIds: catalogIdsOf(ui),
2408
+ components: ui.manifestComponents,
2409
+ functions: {
2410
+ ...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
2411
+ ...dispatcher.listExposed()
2412
+ },
2413
+ targets: [{
2414
+ id: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
2415
+ kind: "chat"
2416
+ }, ...inlineTargets],
2417
+ surfaces: threadId ? manager.describeSurfaces(threadId) : {}
2418
+ };
2419
+ }
2420
+ /**
2421
+ * Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
2422
+ * from the per-run manifest. It has the A2UI v1.0 renderer capabilities
2423
+ * shape: one inline catalog with the id of the UI, and the CopilotKit data
2424
+ * in `metadata.extensions`.
2425
+ *
2426
+ * The inline catalog has no `components` only for the markdown transport
2427
+ * with `includeCatalog: false`. It has `instructions` for the markdown
2428
+ * transport, or when given.
2429
+ *
2430
+ * @param runtime - The generative UI runtime of the provider.
2431
+ * @param threadId - The thread of the run. Its surfaces go in `copilotkit_surfaces`.
2432
+ * @param options - The transport and what to send.
2433
+ *
2434
+ * @example
2435
+ * ```ts
2436
+ * const envelope = buildGenerativeUIEnvelope(runtime, agent.threadId, {
2437
+ * transport: "tool",
2438
+ * includeCatalog: true,
2439
+ * contextSent: false,
2440
+ * });
2441
+ * envelope["v1.0"].supportedCatalogIds; // [runtime.ui.id]
2442
+ * ```
2443
+ */
2444
+ function buildGenerativeUIEnvelope(runtime, threadId, options) {
2445
+ const { transport, includeCatalog, contextSent, action } = options;
2446
+ const manifest = buildGenerativeUIManifest(runtime, threadId);
2447
+ const instructions = options.instructions ?? (transport === "markdown" ? (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest)) : void 0);
2448
+ const omitComponents = transport === "markdown" && !includeCatalog;
2449
+ return {
2450
+ "v1.0": {
2451
+ supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
2452
+ inlineCatalogs: [{
2453
+ catalogId: manifest.catalogId,
2454
+ protocolVersion: "1.0",
2455
+ ...omitComponents ? {} : { components: manifest.components },
2456
+ functions: manifest.functions,
2457
+ ...instructions === void 0 ? {} : { instructions }
2458
+ }]
2459
+ },
2460
+ metadata: { extensions: {
2461
+ copilotkit_format: _copilotkit_shared.COPILOTKIT_UI_ENVELOPE_FORMAT,
2462
+ copilotkit_transport: transport,
2463
+ copilotkit_targets: manifest.targets,
2464
+ copilotkit_surfaces: manifest.surfaces,
2465
+ copilotkit_contextSent: contextSent,
2466
+ ...action === void 0 ? {} : { copilotkit_action: action }
2467
+ } }
2468
+ };
2469
+ }
2470
+
2471
+ //#endregion
2472
+ //#region src/v2/generative-ui/is-record.ts
2473
+ /** True for a plain object: not null, not an array. Internal, not exported. */
2474
+ function isRecord(value) {
2475
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2476
+ }
2477
+
2478
+ //#endregion
2479
+ //#region src/v2/generative-ui/markdown/context.ts
2480
+ /** Objects nested deeper than this show as `object`. */
2481
+ const MAX_OBJECT_DEPTH = 2;
2482
+ /** A prop must appear verbatim in at least this many components to be hoisted. */
2483
+ const COMMON_PROP_MIN_COMPONENTS = 8;
2484
+ /** A JSON Schema of a list of schemas (`anyOf`, `oneOf`), else an empty list. */
2485
+ function schemaList(value) {
2486
+ return Array.isArray(value) ? value.filter(isRecord) : [];
2487
+ }
2488
+ /**
2489
+ * Puts a top-level union in parentheses, so that `[]` applies to all of
2490
+ * it. A union inside braces needs none.
2491
+ */
2492
+ function asArrayItem(type) {
2493
+ let outside = type;
2494
+ for (let inner = outside.replace(/\{[^{}]*\}/g, ""); inner !== outside;) {
2495
+ outside = inner;
2496
+ inner = outside.replace(/\{[^{}]*\}/g, "");
2497
+ }
2498
+ return outside.includes(" | ") ? `(${type})[]` : `${type}[]`;
2499
+ }
2500
+ /**
2501
+ * A JSON Schema as a short TypeScript-like type, for example
2502
+ * `{ label: string; size?: "sm" | "md" }`.
2503
+ */
2504
+ function compactType(schema, depth) {
2505
+ const ref = (0, _copilotkit_shared.childRefKind)(schema);
2506
+ if (ref === "single") return "componentId";
2507
+ if (ref === "multiple") return "componentId[] | { componentId: string; path: string }";
2508
+ if ("const" in schema) return JSON.stringify(schema.const);
2509
+ if (Array.isArray(schema.enum)) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
2510
+ const variants = [...schemaList(schema.anyOf), ...schemaList(schema.oneOf)];
2511
+ if (variants.length > 0) return variants.map((variant) => compactType(variant, depth)).join(" | ");
2512
+ return (Array.isArray(schema.type) ? schema.type : [schema.type]).map((type) => {
2513
+ switch (type) {
2514
+ case "string":
2515
+ case "boolean":
2516
+ case "null": return type;
2517
+ case "number":
2518
+ case "integer": return "number";
2519
+ case "array": return isRecord(schema.items) ? asArrayItem(compactType(schema.items, depth)) : "unknown[]";
2520
+ case "object": return compactObject(schema, depth);
2521
+ default: return "unknown";
2522
+ }
2523
+ }).join(" | ");
2524
+ }
2525
+ /** An object schema as `{ key: type; other?: type }`. */
2526
+ function compactObject(schema, depth) {
2527
+ const properties = isRecord(schema.properties) ? schema.properties : {};
2528
+ const entries = Object.entries(properties);
2529
+ if (entries.length === 0) return isRecord(schema.additionalProperties) ? `Record<string, ${compactType(schema.additionalProperties, depth + 1)}>` : "object";
2530
+ if (depth >= MAX_OBJECT_DEPTH) return "object";
2531
+ const required = Array.isArray(schema.required) ? schema.required : [];
2532
+ return `{ ${entries.map(([key, value]) => {
2533
+ const type = isRecord(value) ? compactType(value, depth + 1) : "unknown";
2534
+ return `${key}${required.includes(key) ? "" : "?"}: ${type}`;
2535
+ }).join("; ")} }`;
2536
+ }
2537
+ /** A schema as its type, with its description after `//`. */
2538
+ function describedType(schema, depth) {
2539
+ const type = compactType(schema, depth);
2540
+ return typeof schema.description === "string" ? `${type} // ${schema.description}` : type;
2541
+ }
2542
+ /** The props of a component: `{ "label": "string", "size?": "..." }`. */
2543
+ function compactProps(schema) {
2544
+ const properties = isRecord(schema.properties) ? schema.properties : {};
2545
+ const required = Array.isArray(schema.required) ? schema.required : [];
2546
+ const props = {};
2547
+ for (const [key, value] of Object.entries(properties)) {
2548
+ if (!isRecord(value)) continue;
2549
+ const name = required.includes(key) ? key : `${key}?`;
2550
+ props[name] = describedType(value, 1);
2551
+ }
2552
+ return props;
2553
+ }
2554
+ /**
2555
+ * The prop set worth listing once. Candidates are (key, type) pairs that at
2556
+ * least {@link COMMON_PROP_MIN_COMPONENTS} components carry verbatim. The
2557
+ * candidate subset of each component is a possible common set, scored by
2558
+ * the characters it saves (set size times the components that contain all
2559
+ * of it). `undefined` when no set is shared by enough components.
2560
+ */
2561
+ function findCommonProps(propsList) {
2562
+ const pairKey = (key, type) => `${key}\u0000${type}`;
2563
+ const counts = /* @__PURE__ */ new Map();
2564
+ for (const props of propsList) for (const [key, type] of Object.entries(props)) {
2565
+ const id = pairKey(key, type);
2566
+ counts.set(id, (counts.get(id) ?? 0) + 1);
2567
+ }
2568
+ let best;
2569
+ let bestScore = 0;
2570
+ const seen = /* @__PURE__ */ new Set();
2571
+ for (const props of propsList) {
2572
+ const subset = Object.entries(props).filter(([key, type]) => (counts.get(pairKey(key, type)) ?? 0) >= COMMON_PROP_MIN_COMPONENTS);
2573
+ if (subset.length < 2) continue;
2574
+ const signature = subset.map(([key, type]) => pairKey(key, type)).join("\n");
2575
+ if (seen.has(signature)) continue;
2576
+ seen.add(signature);
2577
+ const members = propsList.filter((other) => subset.every(([key, type]) => other[key] === type)).length;
2578
+ if (members < COMMON_PROP_MIN_COMPONENTS) continue;
2579
+ const score = subset.reduce((total, [key, type]) => total + key.length + type.length, 0) * (members - 1);
2580
+ if (score > bestScore) {
2581
+ bestScore = score;
2582
+ best = Object.fromEntries(subset);
2583
+ }
2584
+ }
2585
+ return best;
2586
+ }
2587
+ /**
2588
+ * The component schema of the markdown transport, from the per-run
2589
+ * manifest. It is smaller than the manifest: each prop is one short type,
2590
+ * and the props that many components share verbatim (the layout props of
2591
+ * the containers) are listed once in `commonProps`; a component that takes
2592
+ * them is flagged `includesCommonProps`.
2593
+ * It has the catalog id, the targets with their descriptions and their
2594
+ * component lists, the functions with their parameters, the components
2595
+ * with their props, events and slots, and the surfaces of the thread. A surface lists the
2596
+ * values that the user set and the operations that the client dropped.
2597
+ *
2598
+ * @param manifest - The manifest from `buildGenerativeUIManifest`.
2599
+ * @returns A JSON-ready object.
2600
+ *
2601
+ * @example
2602
+ * ```ts
2603
+ * const value = JSON.stringify(
2604
+ * buildCompactGenerativeUISchema(buildGenerativeUIManifest(runtime, threadId)),
2605
+ * );
2606
+ * ```
2607
+ */
2608
+ function buildCompactGenerativeUISchema(manifest) {
2609
+ const components = {};
2610
+ for (const [name, component] of Object.entries(manifest.components)) {
2611
+ const events = Object.entries(component.events ?? {}).map(([event, definition]) => [event, definition.description ?? compactType(definition.parameters, 0)]);
2612
+ components[name] = {
2613
+ ...component.description ? { description: component.description } : {},
2614
+ props: compactProps(component.props),
2615
+ ...events.length > 0 ? { events: Object.fromEntries(events) } : {},
2616
+ ...component.slots ? { slots: component.slots } : {}
2617
+ };
2618
+ }
2619
+ const common = findCommonProps(Object.values(components).map((component) => component.props));
2620
+ if (common) {
2621
+ const commonKeys = Object.keys(common);
2622
+ for (const component of Object.values(components)) {
2623
+ if (!commonKeys.every((key) => component.props[key] === common[key])) continue;
2624
+ component.includesCommonProps = true;
2625
+ component.props = Object.fromEntries(Object.entries(component.props).filter(([key]) => !(key in common)));
2626
+ }
2627
+ }
2628
+ const functions = Object.fromEntries(Object.entries(manifest.functions).map(([name, fn]) => {
2629
+ const signature = fn.parameters.description;
2630
+ const hasSignature = typeof signature === "string" && signature.startsWith("{") && Object.keys(fn.parameters).length === 2;
2631
+ const callers = (0, _copilotkit_shared.functionCallers)(fn);
2632
+ return [name, {
2633
+ ...fn.description ? { description: fn.description } : {},
2634
+ parameters: hasSignature ? signature : compactType(fn.parameters, 0),
2635
+ ...callers.agent && _copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS ? { callers: callers.renderer ? "UI or agent" : "agent only" } : {}
2636
+ }];
2637
+ }));
2638
+ return {
2639
+ catalogId: manifest.catalogId,
2640
+ targets: manifest.targets,
2641
+ functions,
2642
+ ...common ? { commonProps: common } : {},
2643
+ components,
2644
+ surfaces: manifest.surfaces
2645
+ };
2646
+ }
2647
+ /**
2648
+ * Registers the two context entries of the markdown transport: the compact
2649
+ * component schema and the fence guideline. Both go only to `agentIds`.
2650
+ *
2651
+ * The schema is built again at each run start and when a
2652
+ * `<GenerativeUISurface>` mounts, unmounts, or changes its description or
2653
+ * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
2654
+ *
2655
+ * @param copilotkit - The CopilotKit core of the provider.
2656
+ * @param runtime - The generative UI runtime parts, or null without one.
2657
+ * @param options - `enabled` and `agentIds`.
2658
+ *
2659
+ * @example
2660
+ * ```ts
2661
+ * useGenerativeUIMarkdownContext(copilotkit, core, {
2662
+ * enabled: config?.transport === "markdown" && config.sendContext !== false,
2663
+ * agentIds: config?.agentIds,
2664
+ * });
2665
+ * ```
2666
+ */
2667
+ function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
2668
+ const { enabled, agentIds } = options;
2669
+ const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
2670
+ (0, react.useEffect)(() => {
2671
+ if (!runtime || !enabled) return;
2672
+ const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
2673
+ const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
2674
+ let guidelineId;
2675
+ let guidelineValue;
2676
+ let schemaId;
2677
+ let schemaValue;
2678
+ const refreshSchema = (threadId) => {
2679
+ const manifest = buildGenerativeUIManifest(runtime, threadId);
2680
+ const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
2681
+ if (guideline !== guidelineValue) {
2682
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
2683
+ guidelineValue = guideline;
2684
+ guidelineId = copilotkit.addContext({
2685
+ description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
2686
+ value: guideline,
2687
+ ...scope
2688
+ });
2689
+ }
2690
+ const value = JSON.stringify(buildCompactGenerativeUISchema(manifest));
2691
+ if (value === schemaValue) return;
2692
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
2693
+ schemaValue = value;
2694
+ schemaId = copilotkit.addContext({
2695
+ description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
2696
+ value,
2697
+ ...scope
2698
+ });
2699
+ };
2700
+ refreshSchema(runtime.manager.getActiveThread());
2701
+ let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
2702
+ const unsubscribeManager = runtime.manager.subscribe(() => {
2703
+ const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
2704
+ if (nextKey === targetsKey) return;
2705
+ targetsKey = nextKey;
2706
+ refreshSchema(runtime.manager.getActiveThread());
2707
+ });
2708
+ const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
2709
+ return () => {
2710
+ subscription.unsubscribe();
2711
+ unsubscribeManager();
2712
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
2713
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
2714
+ };
2715
+ }, [
2716
+ copilotkit,
2717
+ runtime,
2718
+ enabled,
2719
+ agentIdsKey
2720
+ ]);
2721
+ }
2722
+
2723
+ //#endregion
2724
+ //#region src/v2/generative-ui/debug-source.ts
2725
+ /**
2726
+ * What a run of `threadId` sends: its envelope, and the text that goes into
2727
+ * the prompt of the model because of it.
2728
+ *
2729
+ * - Tool transport: the runtime adds the `render_ui` guide. It builds it
2730
+ * from the envelope with `buildGenerativeUIPrompt`, as done here.
2731
+ * - Markdown transport: the provider sends the guideline and the compact
2732
+ * schema as context entries. With `sendContext: false`, the backend builds
2733
+ * its own prompt, usually from the `instructions` of the envelope.
2734
+ */
2735
+ function describeGenerativeUIRun(runtime, threadId, options) {
2736
+ const envelope = buildGenerativeUIEnvelope(runtime, threadId, options);
2737
+ if (options.transport === "tool") return {
2738
+ envelope,
2739
+ prompt: [{
2740
+ title: "render_ui guide",
2741
+ source: "runtime",
2742
+ text: (0, _copilotkit_shared.buildGenerativeUIPrompt)((0, _copilotkit_shared.envelopeToManifest)(envelope))
2743
+ }]
2744
+ };
2745
+ const manifest = buildGenerativeUIManifest(runtime, threadId);
2746
+ if (!options.contextSent) return {
2747
+ envelope,
2748
+ prompt: [{
2749
+ title: "Envelope instructions",
2750
+ source: "backend",
2751
+ text: (0, _copilotkit_shared.envelopeToManifest)(envelope).instructions ?? ""
2752
+ }]
2753
+ };
2754
+ const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
2755
+ const schema = JSON.stringify(buildCompactGenerativeUISchema(manifest));
2756
+ return {
2757
+ envelope,
2758
+ prompt: [{
2759
+ title: "Markdown guideline",
2760
+ source: "context",
2761
+ text: guideline
2762
+ }, {
2763
+ title: "Component schema",
2764
+ source: "context",
2765
+ text: schema
2766
+ }]
2767
+ };
2768
+ }
2769
+ /** The declared functions, with the JSON Schema of their parameters. */
2770
+ function debugFunctions(runtime) {
2771
+ const functions = {};
2772
+ for (const [name, declared] of runtime.ui.functions) {
2773
+ let parameters = {};
2774
+ try {
2775
+ parameters = toJsonSchema(declared.parameters);
2776
+ } catch {}
2777
+ functions[name] = {
2778
+ ...declared.description ? { description: declared.description } : {},
2779
+ parameters,
2780
+ handlers: runtime.dispatcher.handlerCount(name)
2781
+ };
2782
+ }
2783
+ return functions;
2784
+ }
2785
+ /**
2786
+ * The debug source that the provider gives core for the inspector. It builds
2787
+ * a snapshot only when the inspector reads one.
2788
+ *
2789
+ * @param runtime - The generative UI parts of the provider.
2790
+ * @param getOptions - The envelope options and agent ids of the current config.
2791
+ * @returns The source, and `recordRun` for each run start.
2792
+ */
2793
+ function createGenerativeUIDebugSource(runtime, getOptions) {
2794
+ const listeners = /* @__PURE__ */ new Set();
2795
+ let lastRun;
2796
+ const notify = () => {
2797
+ for (const listener of [...listeners]) listener();
2798
+ };
2799
+ return {
2800
+ source: {
2801
+ getSnapshot() {
2802
+ const { options, agentIds } = getOptions();
2803
+ const threadId = runtime.manager.getActiveThread();
2804
+ const manifest = buildGenerativeUIManifest(runtime, threadId);
2805
+ return {
2806
+ catalogId: runtime.ui.id,
2807
+ transport: options.transport,
2808
+ ...agentIds ? { agentIds } : {},
2809
+ components: runtime.ui.manifestComponents,
2810
+ componentCatalogs: Object.fromEntries(componentCatalogIds(runtime.ui)),
2811
+ functions: debugFunctions(runtime),
2812
+ state: { ...runtime.manager.getState() },
2813
+ targets: manifest.targets,
2814
+ activeThreadId: threadId,
2815
+ surfaces: runtime.manager.debugSurfaces(),
2816
+ lastRun,
2817
+ nextRun: {
2818
+ agentId: void 0,
2819
+ threadId,
2820
+ ...describeGenerativeUIRun(runtime, threadId, options)
2821
+ }
2822
+ };
2823
+ },
2824
+ subscribe(listener) {
2825
+ listeners.add(listener);
2826
+ const unsubscribe = runtime.manager.subscribe(listener);
2827
+ return () => {
2828
+ listeners.delete(listener);
2829
+ unsubscribe();
2830
+ };
2831
+ }
2832
+ },
2833
+ recordRun(run) {
2834
+ lastRun = run;
2835
+ notify();
2836
+ }
2837
+ };
2838
+ }
2839
+
2840
+ //#endregion
2841
+ //#region src/v2/generative-ui/errors.ts
2842
+ var GenerativeUIError = class extends Error {
2843
+ constructor(code, message) {
2844
+ super(message);
2845
+ this.name = "GenerativeUIError";
2846
+ this.code = code;
2847
+ }
2848
+ };
2849
+
2850
+ //#endregion
2851
+ //#region src/v2/generative-ui/functions.ts
2852
+ /**
2853
+ * The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes
2854
+ * resolved args (no bindings left in them) and gives a plain value. They
2855
+ * run synchronously, so a prop bound to one updates in the same render as
2856
+ * the data it reads. The signatures the model sees are in
2857
+ * `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).
2858
+ */
2859
+ /** Thrown for a bad call: an unknown function, bad args, or a bad value. */
2860
+ var ExpressionError = class extends Error {
2861
+ constructor(message) {
2862
+ super(message);
2863
+ this.name = "ExpressionError";
2864
+ }
2865
+ };
2866
+ /** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */
2867
+ function truthOf(value) {
2868
+ if ((0, _copilotkit_shared.isValidationResult)(value)) return value.valid;
2869
+ return Boolean(value);
2870
+ }
2871
+ const valid = () => ({ valid: true });
2872
+ /** A failed result. `code` names the failure, the same for every locale. */
2873
+ const invalid = (message, code) => ({
2874
+ valid: false,
2875
+ message,
2876
+ code
2877
+ });
2878
+ function text(value) {
2879
+ if (value === void 0 || value === null) return "";
2880
+ return typeof value === "string" ? value : String(value);
2881
+ }
2882
+ function numberOf$1(value) {
2883
+ if (typeof value === "number") return value;
2884
+ if (typeof value === "string" && value.trim() !== "") return Number(value);
2885
+ return NaN;
2886
+ }
2887
+ function optionalNumber(value, name) {
2888
+ if (value === void 0 || value === null) return void 0;
2889
+ const parsed = numberOf$1(value);
2890
+ if (Number.isNaN(parsed)) throw new ExpressionError(`${name} must be a number`);
2891
+ return parsed;
2892
+ }
2893
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
2894
+ /** The locale of the user. `undefined` lets Intl pick the default. */
2895
+ function locale() {
2896
+ return typeof navigator !== "undefined" ? navigator.language : void 0;
2897
+ }
2898
+ function numberFormat(args, options) {
2899
+ const decimals = optionalNumber(args.decimals, "decimals");
2900
+ return new Intl.NumberFormat(locale(), {
2901
+ ...options,
2902
+ useGrouping: args.grouping !== false,
2903
+ ...decimals === void 0 ? {} : {
2904
+ minimumFractionDigits: decimals,
2905
+ maximumFractionDigits: decimals
2906
+ }
2907
+ });
2908
+ }
2909
+ /** A date from an ISO string, a timestamp, or a Date. */
2910
+ function dateOf(value) {
2911
+ 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;
2912
+ if (date === void 0 || Number.isNaN(date.getTime())) throw new ExpressionError("value must be a date");
2913
+ return date;
2914
+ }
2915
+ const pad = (value, width) => String(value).padStart(width, "0");
2916
+ /**
2917
+ * A TR35 field is a run of one letter ("EEE" is one abbreviated weekday,
2918
+ * not three), and text in single quotes is literal. Letters that are not
2919
+ * fields stay as they are.
2920
+ */
2921
+ const DATE_FIELD = /([A-Za-z])\1*|'(?:[^']|'')*'/g;
2922
+ function formatDatePattern(date, pattern) {
2923
+ const parts = (options) => new Intl.DateTimeFormat(locale(), options).format(date);
2924
+ const hours12 = date.getHours() % 12 || 12;
2925
+ const numeric = (value, width) => width >= 2 ? pad(value, 2) : String(value);
2926
+ return pattern.replace(DATE_FIELD, (token) => {
2927
+ if (token.startsWith("'")) return token.slice(1, -1).replace(/''/g, "'");
2928
+ const width = token.length;
2929
+ switch (token[0]) {
2930
+ case "y": return width === 2 ? pad(date.getFullYear() % 100, 2) : String(date.getFullYear());
2931
+ case "M":
2932
+ if (width >= 4) return parts({ month: "long" });
2933
+ if (width === 3) return parts({ month: "short" });
2934
+ return numeric(date.getMonth() + 1, width);
2935
+ case "d": return numeric(date.getDate(), width);
2936
+ case "E": return parts({ weekday: width >= 4 ? "long" : "short" });
2937
+ case "H": return numeric(date.getHours(), width);
2938
+ case "h": return numeric(hours12, width);
2939
+ case "m": return pad(date.getMinutes(), 2);
2940
+ case "s": return pad(date.getSeconds(), 2);
2941
+ case "a": return date.getHours() < 12 ? "AM" : "PM";
2942
+ default: return token;
2943
+ }
2944
+ });
2945
+ }
2946
+ /** Opens an http(s) URL in a new tab. Any other scheme is refused. */
2947
+ function openUrlSafely(url) {
2948
+ if (typeof url !== "string" || url === "") throw new ExpressionError("url must be a string");
2949
+ if (typeof window === "undefined") return;
2950
+ let parsed;
2951
+ try {
2952
+ parsed = new URL(url, window.location.href);
2953
+ } catch {
2954
+ throw new ExpressionError(`"${url}" is not a URL`);
2955
+ }
2956
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new ExpressionError(`openUrl takes only http(s) URLs, not ${parsed.protocol}`);
2957
+ window.open(parsed.href, "_blank", "noopener,noreferrer");
2958
+ }
2959
+ /**
2960
+ * The basic functions, except `formatString`, which needs the resolver.
2961
+ * `calc` and `series` are added by `resolve.ts`, which imports both.
2962
+ */
2963
+ const BASIC_FUNCTIONS = {
2964
+ required: ({ value }) => {
2965
+ return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0 ? invalid("Required", "required") : valid();
2966
+ },
2967
+ regex: ({ value, pattern }) => {
2968
+ if (typeof pattern !== "string") throw new ExpressionError("pattern must be a string");
2969
+ let expression;
2970
+ try {
2971
+ expression = new RegExp(pattern, "u");
2972
+ } catch {
2973
+ throw new ExpressionError(`"${pattern}" is not a regular expression`);
2974
+ }
2975
+ return expression.test(text(value)) ? valid() : invalid("Invalid format", "pattern");
2976
+ },
2977
+ length: ({ value, min, max }) => {
2978
+ const size = text(value).length;
2979
+ const low = optionalNumber(min, "min");
2980
+ const high = optionalNumber(max, "max");
2981
+ if (low !== void 0 && size < low) return invalid(`At least ${low} characters`, "tooShort");
2982
+ if (high !== void 0 && size > high) return invalid(`At most ${high} characters`, "tooLong");
2983
+ return valid();
2984
+ },
2985
+ numeric: ({ value, min, max }) => {
2986
+ const parsed = numberOf$1(value);
2987
+ if (Number.isNaN(parsed)) return invalid("Must be a number", "notANumber");
2988
+ const low = optionalNumber(min, "min");
2989
+ const high = optionalNumber(max, "max");
2990
+ if (low !== void 0 && parsed < low) return invalid(`At least ${low}`, "tooSmall");
2991
+ if (high !== void 0 && parsed > high) return invalid(`At most ${high}`, "tooLarge");
2992
+ return valid();
2993
+ },
2994
+ email: ({ value }) => EMAIL.test(text(value)) ? valid() : invalid("Invalid email address", "email"),
2995
+ formatNumber: (args) => {
2996
+ const parsed = numberOf$1(args.value);
2997
+ if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
2998
+ return numberFormat(args, {}).format(parsed);
2999
+ },
3000
+ formatCurrency: (args) => {
3001
+ const parsed = numberOf$1(args.value);
3002
+ if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
3003
+ if (typeof args.currency !== "string" || args.currency === "") throw new ExpressionError("currency must be an ISO 4217 code");
3004
+ try {
3005
+ return numberFormat(args, {
3006
+ style: "currency",
3007
+ currency: args.currency
3008
+ }).format(parsed);
3009
+ } catch {
3010
+ throw new ExpressionError(`"${args.currency}" is not a currency code`);
3011
+ }
3012
+ },
3013
+ formatDate: ({ value, format }) => {
3014
+ if (typeof format !== "string") throw new ExpressionError("format must be a string");
3015
+ return formatDatePattern(dateOf(value), format);
3016
+ },
3017
+ pluralize: (args) => {
3018
+ const parsed = numberOf$1(args.value);
3019
+ if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
3020
+ const category = new Intl.PluralRules(locale()).select(parsed);
3021
+ return text((parsed === 0 ? args.zero : void 0) ?? args[category] ?? args.other);
3022
+ },
3023
+ and: ({ values }) => {
3024
+ if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
3025
+ return values.every(truthOf);
3026
+ },
3027
+ or: ({ values }) => {
3028
+ if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
3029
+ return values.some(truthOf);
3030
+ },
3031
+ not: ({ value }) => !truthOf(value),
3032
+ openUrl: ({ url }) => {
3033
+ openUrlSafely(url);
3034
+ }
3035
+ };
3036
+ /** True when the basic function `name` must run from a user gesture. */
3037
+ function requiresUserActivation(name) {
3038
+ return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.requiresUserActivation === true;
3039
+ }
3040
+ /** True when a basic function gives a ValidationResult. */
3041
+ function givesValidationResult(name) {
3042
+ return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.returnType === "validationResult";
3043
+ }
3044
+
3045
+ //#endregion
3046
+ //#region src/v2/generative-ui/dispatcher.ts
3047
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
3048
+ /**
3049
+ * Creates the registry of functions that generated UI may call.
3050
+ *
3051
+ * A function is callable when it is declared in `getDeclared()` and exactly
3052
+ * one handler is mounted for it with `register`. Names are resolved at call
3053
+ * time and fail closed. Nothing is sent to the agent.
3054
+ * Neither `invoke` nor `listExposed` throws.
3055
+ *
3056
+ * @param options.getDeclared - Returns the declared functions.
3057
+ * @param options.onError - Gets each failed call.
3058
+ *
3059
+ * @example
3060
+ * ```ts
3061
+ * const dispatcher = createGenerativeUIDispatcher({
3062
+ * getDeclared: () => new Map(Object.entries(ui.functions)),
3063
+ * });
3064
+ * const unregister = dispatcher.register("addToCart", handlerRef);
3065
+ * await dispatcher.invoke("addToCart", { productId: "p1" }, origin);
3066
+ * unregister();
3067
+ * ```
3068
+ */
3069
+ /**
3070
+ * True while the browser counts the current task as user-activated (a
3071
+ * click, a key press). Where the API is missing (older browsers, test
3072
+ * environments), the gesture is assumed.
3073
+ */
3074
+ function hasUserActivation() {
3075
+ if (typeof navigator === "undefined") return true;
3076
+ const activation = navigator.userActivation;
3077
+ return activation === void 0 || activation.isActive;
3078
+ }
3079
+ /**
3080
+ * The permissions of a declared function as the manifest states them: the
3081
+ * callers always written out, so a reader needs no default.
3082
+ */
3083
+ function permissionsOf(fn) {
3084
+ const callers = (0, _copilotkit_shared.functionCallers)(fn);
3085
+ return {
3086
+ allowedCallers: callers.renderer && callers.agent ? "rendererOrAgent" : callers.agent ? "agentOnly" : "rendererOnly",
3087
+ ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
3088
+ };
3089
+ }
3090
+ function createGenerativeUIDispatcher(options) {
3091
+ const handlers = /* @__PURE__ */ new Map();
3092
+ const resolveUnchecked = (name) => {
3093
+ const declared = options.getDeclared().get(name);
3094
+ if (!declared) return {
3095
+ ok: false,
3096
+ error: new GenerativeUIError("function_not_found", `No generative UI function named "${name}" is declared in createGenerativeUI({ functions })`)
3097
+ };
3098
+ const mounted = [...handlers.get(name) ?? []];
3099
+ const [ref] = mounted;
3100
+ if (!ref) return {
3101
+ ok: false,
3102
+ error: new GenerativeUIError("function_not_found", `"${name}" is declared, but no useGenerativeUIFunction handler is mounted for it`)
3103
+ };
3104
+ if (mounted.length > 1) return {
3105
+ ok: false,
3106
+ error: new GenerativeUIError("function_conflict", `"${name}" has ${mounted.length} useGenerativeUIFunction handlers mounted. Mount exactly one.`)
3107
+ };
3108
+ return {
3109
+ ok: true,
3110
+ declared,
3111
+ ref
3112
+ };
3113
+ };
3114
+ const isDeclared = (name) => {
3115
+ try {
3116
+ return options.getDeclared().has(name);
3117
+ } catch {
3118
+ return false;
3119
+ }
3120
+ };
3121
+ const resolve = (name) => {
3122
+ try {
3123
+ return resolveUnchecked(name);
3124
+ } catch (error) {
3125
+ return {
3126
+ ok: false,
3127
+ error: new GenerativeUIError("handler_failed", `"${name}" could not be resolved: ${messageOf(error)}`)
3128
+ };
3129
+ }
3130
+ };
3131
+ const validateArgs = async (name, schema, args) => {
3132
+ try {
3133
+ const validation = await schema["~standard"].validate(args);
3134
+ if (!validation.issues) return {
3135
+ ok: true,
3136
+ value: validation.value
3137
+ };
3138
+ return {
3139
+ ok: false,
3140
+ error: new 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("; ")}`)
3141
+ };
3142
+ } catch (error) {
3143
+ return {
3144
+ ok: false,
3145
+ error: new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${messageOf(error)}`)
3146
+ };
3147
+ }
3148
+ };
3149
+ const failWith = (name, origin, error) => {
3150
+ try {
3151
+ options.onError?.({
3152
+ name,
3153
+ origin,
3154
+ error
3155
+ });
3156
+ } catch {}
3157
+ return {
3158
+ ok: false,
3159
+ error
3160
+ };
3161
+ };
3162
+ /**
3163
+ * Why `origin` may not call a function with these permissions now, as an
3164
+ * error, or `undefined` when it may. The agent is refused what is for the
3165
+ * renderer; a component is refused what is for the agent, and a gesture
3166
+ * function when the browser counts no user activation.
3167
+ */
3168
+ const callerError = (name, fn, origin) => {
3169
+ const isComponent = "componentId" in origin;
3170
+ if (!isComponent && !_copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS) return new GenerativeUIError("invalid_function_call", _copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
3171
+ const problem = (0, _copilotkit_shared.callerProblem)(name, fn, isComponent ? "renderer" : "agent");
3172
+ if (problem !== void 0) return new GenerativeUIError("invalid_function_call", problem);
3173
+ if (isComponent && fn.requiresUserActivation && !hasUserActivation()) return new GenerativeUIError("invalid_function_call", `function "${name}" runs only from a user gesture; this event was not one`);
3174
+ };
3175
+ /**
3176
+ * Runs a basic function of the A2UI catalog. They are value functions of
3177
+ * the renderer: the agent cannot call them, and one that needs a user
3178
+ * gesture runs only from an event binding.
3179
+ */
3180
+ const invokeBasic = (name, args, origin) => {
3181
+ const refused = callerError(name, _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name], origin);
3182
+ if (refused) return failWith(name, origin, refused);
3183
+ if (args !== void 0 && !(typeof args === "object" && args !== null && !Array.isArray(args))) return failWith(name, origin, new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": args must be an object`));
3184
+ try {
3185
+ return {
3186
+ ok: true,
3187
+ result: BASIC_FUNCTIONS[name](args ?? {})
3188
+ };
3189
+ } catch (error) {
3190
+ return failWith(name, origin, new GenerativeUIError(error instanceof ExpressionError ? "invalid_arguments" : "handler_failed", `"${name}" failed: ${messageOf(error)}`));
3191
+ }
3192
+ };
3193
+ return {
3194
+ async invoke(name, args, origin) {
3195
+ const resolved = resolve(name);
3196
+ if (!resolved.ok && resolved.error.code === "function_not_found" && !isDeclared(name) && Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name)) return invokeBasic(name, args, origin);
3197
+ if (!resolved.ok) return failWith(name, origin, resolved.error);
3198
+ const refused = callerError(name, resolved.declared, origin);
3199
+ if (refused) return failWith(name, origin, refused);
3200
+ const validated = await validateArgs(name, resolved.declared.parameters, args ?? {});
3201
+ if (!validated.ok) return failWith(name, origin, validated.error);
3202
+ try {
3203
+ return {
3204
+ ok: true,
3205
+ result: await resolved.ref.current(validated.value)
3206
+ };
3207
+ } catch (error) {
3208
+ return failWith(name, origin, new GenerativeUIError("handler_failed", `"${name}" failed: ${messageOf(error)}`));
3209
+ }
3210
+ },
3211
+ listExposed() {
3212
+ let names;
3213
+ try {
3214
+ names = [...options.getDeclared().keys()];
3215
+ } catch {
3216
+ return {};
3217
+ }
3218
+ const listed = {};
3219
+ for (const name of names) {
3220
+ const resolved = resolve(name);
3221
+ if (!resolved.ok) continue;
3222
+ if (!(0, _copilotkit_shared.functionCallers)(resolved.declared).renderer && !_copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS) continue;
3223
+ const { description, parameters, returnType } = resolved.declared;
3224
+ try {
3225
+ listed[name] = {
3226
+ ...description ? { description } : {},
3227
+ parameters: toJsonSchema(parameters),
3228
+ ...returnType ? { returnType } : {},
3229
+ ...permissionsOf(resolved.declared)
3230
+ };
3231
+ } catch {}
3232
+ }
3233
+ return listed;
3234
+ },
3235
+ register(name, ref) {
3236
+ const mounted = handlers.get(name) ?? /* @__PURE__ */ new Set();
3237
+ mounted.add(ref);
3238
+ handlers.set(name, mounted);
3239
+ return () => {
3240
+ mounted.delete(ref);
3241
+ };
3242
+ },
3243
+ handlerCount: (name) => handlers.get(name)?.size ?? 0
3244
+ };
3245
+ }
3246
+
3247
+ //#endregion
3248
+ //#region src/v2/generative-ui/markdown/source.ts
3249
+ /**
3250
+ * Values by key, from the latest build. A value that a build does not use
3251
+ * is dropped at the end of that build, so the cache does not grow.
3252
+ */
3253
+ var BuildMemo = class {
3254
+ constructor() {
3255
+ this.previous = /* @__PURE__ */ new Map();
3256
+ this.current = /* @__PURE__ */ new Map();
3257
+ }
3258
+ /**
3259
+ * The value of `key`. It is computed when no earlier value is there, or
3260
+ * when `isFresh` says that the earlier value is out of date.
3261
+ */
3262
+ get(key, compute, isFresh = () => true) {
3263
+ let value = this.current.get(key) ?? this.previous.get(key);
3264
+ if (value === void 0 || !isFresh(value)) value = compute();
3265
+ this.current.set(key, value);
3266
+ return value;
3267
+ }
3268
+ endBuild() {
3269
+ this.previous = this.current;
3270
+ this.current = /* @__PURE__ */ new Map();
3271
+ }
3272
+ };
3273
+ /** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */
3274
+ var MarkdownBuildCache = class {
3275
+ constructor() {
3276
+ this.segments = new BuildMemo();
3277
+ this.fences = new BuildMemo();
3278
+ this.drafts = new BuildMemo();
3279
+ this.readdressed = /* @__PURE__ */ new WeakMap();
3280
+ }
3281
+ endBuild() {
3282
+ this.segments.endBuild();
3283
+ this.fences.endBuild();
3284
+ this.drafts.endBuild();
3285
+ }
3286
+ };
3287
+ /** True when both lists hold the same objects in the same order. */
3288
+ function sameItems(a, b) {
3289
+ return a.length === b.length && a.every((item, index) => item === b[index]);
3290
+ }
3291
+ function isString(value) {
3292
+ return typeof value === "string";
3293
+ }
3294
+ /** The key of one fence of one message. */
3295
+ function fenceKey(messageId, fenceIndex) {
3296
+ return `${messageId}:${fenceIndex}`;
3297
+ }
3298
+ /**
3299
+ * The operations of a fence body. While the fence streams, the last object
3300
+ * can be unfinished. Of an unfinished updateComponents or createSurface, the
3301
+ * components that are complete render at once (a createSurface also keeps
3302
+ * its data model when all of it arrived). Any other unfinished object is
3303
+ * left out, because a part of a data model value can still change. A final
3304
+ * fence keeps what can be saved from an unfinished object.
3305
+ */
3306
+ function fenceOperations(text, isStreaming) {
3307
+ const parsed = (0, _copilotkit_core.extractFenceOperations)(text);
3308
+ if (!isStreaming || parsed.partialObject === null) return parsed.operations;
3309
+ const complete = (0, _copilotkit_core.extractFenceOperations)(text.slice(0, text.length - parsed.partialObject.length)).operations;
3310
+ const partial = parsed.operations.length > complete.length ? parsed.operations[parsed.operations.length - 1] : void 0;
3311
+ return partial !== void 0 && (isRecord(partial.updateComponents) || isRecord(partial.createSurface)) ? [...complete, partial] : complete;
3312
+ }
3313
+ /**
3314
+ * An inline createSurface becomes a createSurface with only its surfaceId
3315
+ * and catalog, then an updateDataModel for its data model, then an
3316
+ * updateComponents for its components. The prose lift and the split per
3317
+ * component read only updateComponents, so they then work for an inline
3318
+ * surface too. A createSurface with a data model or components of a wrong
3319
+ * shape does not change, so that validation rejects it with the reason.
3320
+ */
3321
+ function expandInlineCreate(operations) {
3322
+ return operations.flatMap((op) => {
3323
+ const create = op.createSurface;
3324
+ if (!isRecord(create)) return [op];
3325
+ const { dataModel, components, ...rest } = create;
3326
+ const hasData = isRecord(dataModel);
3327
+ const hasComponents = Array.isArray(components) && components.length > 0;
3328
+ if (!((dataModel === void 0 || hasData) && (components === void 0 || hasComponents)) || !hasData && !hasComponents) return [op];
3329
+ const { surfaceId } = create;
3330
+ const expanded = [{
3331
+ ...op,
3332
+ createSurface: rest
3333
+ }];
3334
+ if (hasData) expanded.push({
3335
+ version: op.version,
3336
+ updateDataModel: {
3337
+ surfaceId,
3338
+ path: "/",
3339
+ value: dataModel
3340
+ }
3341
+ });
3342
+ if (hasComponents) expanded.push({
3343
+ version: op.version,
3344
+ updateComponents: {
3345
+ surfaceId,
3346
+ components
3347
+ }
3348
+ });
3349
+ return expanded;
3350
+ });
3351
+ }
3352
+ /**
3353
+ * Each updateComponents becomes one operation per component, in order. The
3354
+ * complete components of a streaming line then give the same first
3355
+ * operations as the finished line, so the operation list only grows and the
3356
+ * manager never has to start the surface again.
3357
+ */
3358
+ function splitComponentUpdates(operations) {
3359
+ return operations.flatMap((op) => {
3360
+ const update = op.updateComponents;
3361
+ if (!isRecord(update) || !Array.isArray(update.components)) return [op];
3362
+ if (update.components.length <= 1) return [op];
3363
+ return update.components.map((component) => ({
3364
+ ...op,
3365
+ updateComponents: {
3366
+ ...update,
3367
+ components: [component]
3368
+ }
3369
+ }));
3370
+ });
3371
+ }
3372
+ /** createSurface first, the other operations after it in their order. */
3373
+ function createSurfaceFirst(operations) {
3374
+ const creates = operations.filter((op) => isRecord(op.createSurface));
3375
+ const others = operations.filter((op) => !isRecord(op.createSurface));
3376
+ return [...creates, ...others];
3377
+ }
3378
+ /** True when the component of `name` has the prop `prop`. */
3379
+ function hasProp(ui, name, prop) {
3380
+ const properties = ui.manifestComponents[name]?.props.properties;
3381
+ return isRecord(properties) && Object.hasOwn(properties, prop);
3382
+ }
3383
+ const childRefCache = /* @__PURE__ */ new WeakMap();
3384
+ /** The ids in a slot value: an id, a list of ids, or a template. */
3385
+ function slotIds(value) {
3386
+ if (typeof value === "string") return [value];
3387
+ if (Array.isArray(value)) return value.filter(isString);
3388
+ return isRecord(value) && isString(value.componentId) ? [value.componentId] : [];
3389
+ }
3390
+ /**
3391
+ * A reader of the ids a component renders beyond `child` and `children`:
3392
+ * its declared slots (the `trigger` and `content` of a Modal) and its typed
3393
+ * child references (the `child` of each entry of `tabs`), from its catalog
3394
+ * entry. The prose lift follows these ids like `children`, so a panel is
3395
+ * never cut off from its Tabs. A reference that is bound to the data
3396
+ * model is "unknown": its ids exist only at render time.
3397
+ */
3398
+ function childIdsReader(ui) {
3399
+ return (component) => {
3400
+ const name = component.component;
3401
+ const entry = typeof name === "string" && Object.hasOwn(ui.manifestComponents, name) ? ui.manifestComponents[name] : void 0;
3402
+ if (!entry) return [];
3403
+ const ids = [];
3404
+ for (const slot of Object.keys(entry.slots ?? {})) if (slot !== "child" && slot !== "children") ids.push(...slotIds(component[slot]));
3405
+ let refs = childRefCache.get(entry.props);
3406
+ if (!refs) {
3407
+ refs = (0, _copilotkit_shared.collectChildRefs)(entry.props);
3408
+ childRefCache.set(entry.props, refs);
3409
+ }
3410
+ if (refs.length === 0) return ids;
3411
+ if ((0, _copilotkit_shared.hasBoundChildRef)(component, refs)) return "unknown";
3412
+ return [...ids, ...(0, _copilotkit_shared.childIdsAtRefs)(component, refs)];
3413
+ };
3414
+ }
3415
+ /** Every component of the operations by id, last definition wins. */
3416
+ function collectComponents(operations) {
3417
+ const byId = /* @__PURE__ */ new Map();
3418
+ for (const op of operations) {
3419
+ const update = op.updateComponents;
3420
+ const list = isRecord(update) ? update.components : void 0;
3421
+ if (!Array.isArray(list)) continue;
3422
+ for (const component of list) if (isRecord(component) && isString(component.id)) byId.set(component.id, component);
3423
+ }
3424
+ return [...byId.values()];
3425
+ }
3426
+ /**
3427
+ * The data model must not be shared between two surfaces. A data model
3428
+ * keeps the object it gets, so an input in one surface would change the
3429
+ * data of the other one.
3430
+ */
3431
+ function cloneData(value) {
3432
+ return value === void 0 ? void 0 : structuredClone(value);
3433
+ }
3434
+ /** The operation sent to `surfaceId`, with a copy of its data model value. */
3435
+ function readdress(op, surfaceId) {
3436
+ const kind = (0, _copilotkit_shared.getOperationKind)(op);
3437
+ const payload = kind ? op[kind] : void 0;
3438
+ if (!kind || !isRecord(payload)) return op;
3439
+ const next = {
3440
+ ...payload,
3441
+ surfaceId
3442
+ };
3443
+ if (kind === "updateDataModel" && "value" in payload) next.value = cloneData(payload.value);
3444
+ return {
3445
+ ...op,
3446
+ [kind]: next
3447
+ };
3448
+ }
3449
+ /**
3450
+ * The operations of one sub-surface. Each updateComponents keeps only the
3451
+ * components of the sub-surface, with its own root. The other operations
3452
+ * are sent to the sub-surface. The order stays the same, so a new operation
3453
+ * of the fence only adds operations at the end.
3454
+ */
3455
+ function subSurfaceOperations(operations, components, surfaceId) {
3456
+ const root = components.find((c) => c.id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID);
3457
+ const ids = new Set(components.map((c) => c.id));
3458
+ const out = [];
3459
+ for (const op of operations) {
3460
+ const update = op.updateComponents;
3461
+ if (!isRecord(update) || !Array.isArray(update.components)) {
3462
+ out.push(readdress(op, surfaceId));
3463
+ continue;
3464
+ }
3465
+ const kept = update.components.filter((c) => isRecord(c) && ids.has(c.id)).map((c) => isRecord(c) && c.id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID ? root : c);
3466
+ if (kept.length === 0) continue;
3467
+ out.push({
3468
+ ...op,
3469
+ updateComponents: {
3470
+ ...update,
3471
+ surfaceId,
3472
+ components: kept
3473
+ }
3474
+ });
3475
+ }
3476
+ return out;
3477
+ }
3478
+ /**
3479
+ * Prose lift. Text components in the main stack of the surface (titles,
3480
+ * paragraphs, text lists and the dividers between them) become chat
3481
+ * markdown. The surface splits around them: the first surface keeps
3482
+ * `surfaceId`, the next ones are `<surfaceId>#1`, `<surfaceId>#2`, and so
3483
+ * on. A surface with no prose comes back as one part with the same
3484
+ * operations.
3485
+ */
3486
+ function liftProse(operations, surfaceId, childIds) {
3487
+ const components = collectComponents(operations);
3488
+ const segments = (0, _copilotkit_core.segmentSurfaceProse)(components, { childIds });
3489
+ const [first] = segments;
3490
+ if (segments.length === 1 && first?.kind === "surface" && first.components === components) return [{
3491
+ kind: "surface",
3492
+ surfaceId,
3493
+ operations
3494
+ }];
3495
+ let surfaceIndex = 0;
3496
+ return segments.map((segment) => {
3497
+ if (segment.kind === "markdown") return segment;
3498
+ const id = surfaceIndex === 0 ? surfaceId : `${surfaceId}#${surfaceIndex}`;
3499
+ surfaceIndex++;
3500
+ return {
3501
+ kind: "surface",
3502
+ surfaceId: id,
3503
+ operations: subSurfaceOperations(operations, segment.components, id)
3504
+ };
3505
+ });
3506
+ }
3507
+ /** `validateOperation`, with the operation typed when it is valid. */
3508
+ function checkOperation(op, options) {
3509
+ const validation = (0, _copilotkit_shared.validateOperation)(op, options);
3510
+ if (!validation.ok) return validation;
3511
+ return {
3512
+ ok: true,
3513
+ operation: op
3514
+ };
3515
+ }
3516
+ /**
3517
+ * The content of one surface. Each operation is validated against the
3518
+ * manifest. A valid operation goes in `operations`. A rejected one goes in
3519
+ * `rejected`, with its position and the reason.
3520
+ */
3521
+ function surfaceContent(surfaceId, draft, operations, options) {
3522
+ const { ui, functions } = options;
3523
+ const knownSurfaces = /* @__PURE__ */ new Set();
3524
+ const manifest = {
3525
+ catalogId: ui.id,
3526
+ catalogIds: catalogIdsOf(ui),
3527
+ components: ui.manifestComponents
3528
+ };
3529
+ const valid = [];
3530
+ const rejected = [];
3531
+ operations.forEach((op, index) => {
3532
+ const result = checkOperation(op, {
3533
+ manifest,
3534
+ knownSurfaces,
3535
+ functions
3536
+ });
3537
+ if (!result.ok) {
3538
+ rejected.push({
3539
+ index,
3540
+ reason: result.reason
3541
+ });
3542
+ return;
3543
+ }
3544
+ valid.push(result.operation);
3545
+ const kind = (0, _copilotkit_shared.getOperationKind)(result.operation);
3546
+ if (kind === "createSurface") knownSurfaces.add(surfaceId);
3547
+ if (kind === "deleteSurface") knownSurfaces.delete(surfaceId);
3548
+ });
3549
+ const create = valid.find((op) => "createSurface" in op);
3550
+ return {
3551
+ surfaceId,
3552
+ target: draft.target,
3553
+ catalogId: create?.createSurface.catalogId ?? ui.id,
3554
+ operations: valid,
3555
+ status: draft.streaming ? "streaming" : "ready",
3556
+ rejected
3557
+ };
3558
+ }
3559
+ /**
3560
+ * Builds the surfaces of a thread from the ```a2ui fences of its assistant
3561
+ * messages, in message order.
3562
+ *
3563
+ * - Operations are grouped by surfaceId across all messages. An operation
3564
+ * with no surfaceId goes to the first surface of its fence, else to
3565
+ * `<messageId>-<fenceIndex>`.
3566
+ * - The fence that first writes a surface creates it. The `target=<id>` of
3567
+ * that fence sets the target. With no target, the surface goes to the
3568
+ * chat.
3569
+ * - A later fence of the same reply for the same surfaceId updates it. A
3570
+ * later reply that reuses the id of a chat surface gets a surface of its
3571
+ * own, `<id>@<messageId>`. A page target is updated from any reply.
3572
+ * - The status is "streaming" while the creating fence streams, else
3573
+ * "ready".
3574
+ * - Each operation is validated with `validateOperation`. Rejected ones are
3575
+ * left out and listed in `rejected`.
3576
+ * - Chat surfaces get the prose lift: informational cards lose their box,
3577
+ * and prose becomes markdown that renders between sub-surfaces
3578
+ * (`<surfaceId>#<n>`). An inline createSurface is split into its
3579
+ * createSurface, updateDataModel and updateComponents first.
3580
+ * - A `callRendererFunction` line is not part of a surface. It goes to
3581
+ * `functionCalls`. A streaming line gives nothing, so a function never
3582
+ * runs with a part of its args.
3583
+ *
3584
+ * The function is pure. Call it again on each stream update. The manager
3585
+ * applies only the new operations, so unchanged surfaces do not render
3586
+ * again.
3587
+ *
3588
+ * @param messages - The messages of one thread.
3589
+ * @param options - The generative UI, its declared functions, and whether
3590
+ * the last message can still grow.
3591
+ * @returns `surfaces`, one content for each surface and sub-surface;
3592
+ * `fences`, the blocks that each fence renders, by `fenceKey` (a fence
3593
+ * that is not in `fences` renders nothing); `functionCalls`, the function
3594
+ * calls of the fences in order; and `parts`, the surface ids of the parts
3595
+ * of each surface, by surface id.
3596
+ *
3597
+ * @example
3598
+ * ```ts
3599
+ * const { surfaces } = buildMarkdownSurfaces(agent.messages, {
3600
+ * ui,
3601
+ * functions: {},
3602
+ * running: agent.isRunning,
3603
+ * });
3604
+ * for (const content of surfaces) manager.ingest(threadId, agentId, content);
3605
+ * ```
3606
+ */
3607
+ function buildMarkdownSurfaces(messages, options) {
3608
+ const { ui, cache } = options;
3609
+ const drafts = /* @__PURE__ */ new Map();
3610
+ const readdressOnce = (op, surfaceId) => {
3611
+ if (!cache) return readdress(op, surfaceId);
3612
+ let copies = cache.readdressed.get(op);
3613
+ if (!copies) {
3614
+ copies = /* @__PURE__ */ new Map();
3615
+ cache.readdressed.set(op, copies);
3616
+ }
3617
+ let copy = copies.get(surfaceId);
3618
+ if (!copy) {
3619
+ copy = readdress(op, surfaceId);
3620
+ copies.set(surfaceId, copy);
3621
+ }
3622
+ return copy;
3623
+ };
3624
+ /** The surfaces that each fence created, in order. */
3625
+ const created = /* @__PURE__ */ new Map();
3626
+ const functionCalls = [];
3627
+ /** The message that owns each chat surface id, by the id the model wrote. */
3628
+ const chatOwners = /* @__PURE__ */ new Map();
3629
+ const lastMessage = messages[messages.length - 1];
3630
+ /**
3631
+ * A chat surface belongs to the reply that wrote it: the chat is a
3632
+ * transcript, so a later reply that reuses an id gets a surface of its
3633
+ * own (`<id>@<messageId>`) instead of changing the earlier reply. A fence
3634
+ * for a page target keeps its id, because a target is a place on the
3635
+ * page that a later reply updates on purpose.
3636
+ */
3637
+ const scopedSurfaceId = (requested, messageId, target) => {
3638
+ if (target !== void 0) return requested;
3639
+ const owner = chatOwners.get(requested);
3640
+ if (owner === void 0) {
3641
+ chatOwners.set(requested, messageId);
3642
+ return requested;
3643
+ }
3644
+ return owner === messageId ? requested : `${requested}@${messageId}`;
3645
+ };
3646
+ for (const message of messages) {
3647
+ if (message.role !== "assistant" || !isString(message.content)) continue;
3648
+ const isLastMessage = message === lastMessage;
3649
+ const content = message.content;
3650
+ const segments = cache ? cache.segments.get(content, () => (0, _copilotkit_core.splitA2UIMarkdown)(content)) : (0, _copilotkit_core.splitA2UIMarkdown)(content);
3651
+ for (const segment of segments) {
3652
+ if (segment.type !== "a2ui") continue;
3653
+ const isStreaming = !segment.closed && isLastMessage && options.running;
3654
+ const parseFence = () => {
3655
+ const parsed = fenceOperations(segment.text, isStreaming);
3656
+ const { functionCalls } = (0, _copilotkit_core.prepareSurfaceOperations)({
3657
+ operations: parsed,
3658
+ fallbackSurfaceId: "",
3659
+ catalogId: ui.id
3660
+ });
3661
+ return {
3662
+ operations: parsed,
3663
+ functionCalls
3664
+ };
3665
+ };
3666
+ const fence = cache ? cache.fences.get(`${isStreaming}:${segment.text}`, parseFence) : parseFence();
3667
+ const { operations } = fence;
3668
+ const key = fenceKey(message.id, segment.index);
3669
+ const fenceSurfaceId = operations.map(_copilotkit_core.getMarkdownOperationSurfaceId).find(isString) ?? `${message.id}-${segment.index}`;
3670
+ for (const operation of fence.functionCalls) functionCalls.push({
3671
+ messageId: message.id,
3672
+ fenceIndex: segment.index,
3673
+ operation
3674
+ });
3675
+ const surfaceOperations = operations.filter((op) => (0, _copilotkit_shared.getOperationKind)(op) !== "callRendererFunction");
3676
+ for (const op of surfaceOperations) {
3677
+ const requested = (0, _copilotkit_core.getMarkdownOperationSurfaceId)(op) ?? fenceSurfaceId;
3678
+ const surfaceId = scopedSurfaceId(requested, message.id, segment.target);
3679
+ let draft = drafts.get(surfaceId);
3680
+ if (!draft) {
3681
+ draft = {
3682
+ surfaceId,
3683
+ target: segment.target ?? _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
3684
+ operations: [],
3685
+ streaming: isStreaming
3686
+ };
3687
+ drafts.set(surfaceId, draft);
3688
+ created.set(key, [...created.get(key) ?? [], surfaceId]);
3689
+ }
3690
+ draft.operations.push(surfaceId === requested ? op : readdressOnce(op, surfaceId));
3691
+ }
3692
+ }
3693
+ }
3694
+ const canFlattenCards = hasProp(ui, "Card", "variant");
3695
+ const surfaces = [];
3696
+ const partsBySurface = /* @__PURE__ */ new Map();
3697
+ const childIds = childIdsReader(ui);
3698
+ const buildDraft = (draft) => {
3699
+ const operations = splitComponentUpdates(expandInlineCreate(createSurfaceFirst((0, _copilotkit_core.prepareSurfaceOperations)({
3700
+ operations: draft.operations,
3701
+ fallbackSurfaceId: draft.surfaceId,
3702
+ catalogId: ui.id,
3703
+ catalogIds: catalogIdsOf(ui)
3704
+ }).operations)));
3705
+ const parts = draft.target === _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET ? liftProse(canFlattenCards ? (0, _copilotkit_core.flattenInformationalCards)(operations, { childIds }) : operations, draft.surfaceId, childIds) : [{
3706
+ kind: "surface",
3707
+ surfaceId: draft.surfaceId,
3708
+ operations
3709
+ }];
3710
+ const contents = parts.flatMap((part) => part.kind === "surface" ? [surfaceContent(part.surfaceId, draft, part.operations, options)] : []);
3711
+ return {
3712
+ ...draft,
3713
+ parts,
3714
+ contents
3715
+ };
3716
+ };
3717
+ for (const draft of drafts.values()) {
3718
+ 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);
3719
+ partsBySurface.set(draft.surfaceId, built.parts);
3720
+ surfaces.push(...built.contents);
3721
+ }
3722
+ cache?.endBuild();
3723
+ /** The surface ids of the parts of each split surface, by surface id. */
3724
+ const parts = /* @__PURE__ */ new Map();
3725
+ for (const [surfaceId, surfaceParts] of partsBySurface) {
3726
+ const ids = surfaceParts.flatMap((part) => part.kind === "surface" ? [part.surfaceId] : []);
3727
+ parts.set(surfaceId, ids);
3728
+ }
3729
+ const fences = /* @__PURE__ */ new Map();
3730
+ for (const [key, surfaceIds] of created) {
3731
+ const blocks = [];
3732
+ for (const surfaceId of surfaceIds) {
3733
+ if (drafts.get(surfaceId)?.target !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET) continue;
3734
+ for (const part of partsBySurface.get(surfaceId) ?? []) blocks.push(part.kind === "markdown" ? part : {
3735
+ kind: "surface",
3736
+ surfaceId: part.surfaceId
3737
+ });
3738
+ }
3739
+ if (blocks.length > 0) fences.set(key, blocks);
3740
+ }
3741
+ return {
3742
+ surfaces,
3743
+ fences,
3744
+ functionCalls,
3745
+ parts
3746
+ };
3747
+ }
3748
+ /** The declared functions, as `validateOperation` takes them. */
3749
+ function declaredFunctions(ui) {
3750
+ const functions = {};
3751
+ for (const [name, fn] of ui.functions) try {
3752
+ functions[name] = {
3753
+ ...fn.description ? { description: fn.description } : {},
3754
+ parameters: toJsonSchema(fn.parameters)
3755
+ };
3756
+ } catch {
3757
+ functions[name] = { parameters: {} };
3758
+ }
3759
+ return functions;
3760
+ }
3761
+ /** True when `list` starts with all the items of `prefix`. */
3762
+ function startsWith(list, prefix) {
3763
+ return list.length >= prefix.length && prefix.every((item, index) => item === list[index]);
3764
+ }
3765
+ /** A content that deletes a surface that the fences no longer write. */
3766
+ function removalContent(surfaceId, catalogId) {
3767
+ return {
3768
+ surfaceId,
3769
+ target: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
3770
+ catalogId,
3771
+ status: "ready",
3772
+ rejected: [],
3773
+ operations: [{
3774
+ version: _copilotkit_shared.A2UI_VERSION,
3775
+ createSurface: {
3776
+ surfaceId,
3777
+ catalogId
3778
+ }
3779
+ }, {
3780
+ version: _copilotkit_shared.A2UI_VERSION,
3781
+ deleteSurface: { surfaceId }
3782
+ }]
3783
+ };
3784
+ }
3785
+ /**
3786
+ * The markdown transport source of one surface manager. It turns the
3787
+ * messages of a thread into surfaces in the manager, and keeps the blocks
3788
+ * that each fence renders.
3789
+ */
3790
+ var MarkdownSurfaceSource = class {
3791
+ constructor(manager, ui) {
3792
+ this.manager = manager;
3793
+ this.ui = ui;
3794
+ this.fences = /* @__PURE__ */ new Map();
3795
+ this.ingested = /* @__PURE__ */ new Map();
3796
+ this.contents = /* @__PURE__ */ new Map();
3797
+ this.caches = /* @__PURE__ */ new Map();
3798
+ this.functions = declaredFunctions(ui);
3799
+ }
3800
+ /**
3801
+ * Builds the surfaces of `threadId` from `messages` and gives them to the
3802
+ * manager. A surface that an earlier sync of the thread made, and that the
3803
+ * messages no longer write, is deleted. Other threads do not change.
3804
+ *
3805
+ * @param threadId - The thread of the messages.
3806
+ * @param agentId - The agent that owns the thread.
3807
+ * @param messages - All messages of the thread.
3808
+ * @param options - `running`: the last message can still grow.
3809
+ * @returns The function calls of the fences, in order. The source does
3810
+ * not run them.
3811
+ */
3812
+ sync(threadId, agentId, messages, options) {
3813
+ let cache = this.caches.get(threadId);
3814
+ if (!cache) {
3815
+ cache = new MarkdownBuildCache();
3816
+ this.caches.set(threadId, cache);
3817
+ }
3818
+ const result = buildMarkdownSurfaces(messages, {
3819
+ ui: this.ui,
3820
+ functions: this.functions,
3821
+ running: options.running,
3822
+ cache
3823
+ });
3824
+ this.fences.set(threadId, result.fences);
3825
+ for (const parts of result.parts.values()) this.manager.linkSurfaces(threadId, parts);
3826
+ const previous = this.ingested.get(threadId) ?? /* @__PURE__ */ new Map();
3827
+ const previousContents = this.contents.get(threadId) ?? /* @__PURE__ */ new Map();
3828
+ const next = /* @__PURE__ */ new Map();
3829
+ const nextContents = /* @__PURE__ */ new Map();
3830
+ for (const content of result.surfaces) {
3831
+ nextContents.set(content.surfaceId, content);
3832
+ const before = previous.get(content.surfaceId);
3833
+ if (before && previousContents.get(content.surfaceId) === content) {
3834
+ next.set(content.surfaceId, before);
3835
+ continue;
3836
+ }
3837
+ const fingerprints = content.operations.map((op) => JSON.stringify(op));
3838
+ if (before && !startsWith(fingerprints, before)) this.manager.ingest(threadId, agentId, {
3839
+ ...content,
3840
+ operations: []
3841
+ });
3842
+ this.manager.ingest(threadId, agentId, content);
3843
+ next.set(content.surfaceId, fingerprints);
3844
+ }
3845
+ for (const surfaceId of previous.keys()) {
3846
+ if (next.has(surfaceId)) continue;
3847
+ this.manager.ingest(threadId, agentId, removalContent(surfaceId, this.ui.id));
3848
+ }
3849
+ this.ingested.set(threadId, next);
3850
+ this.contents.set(threadId, nextContents);
3851
+ return result.functionCalls;
3852
+ }
3853
+ /**
3854
+ * The blocks that a fence renders in the chat, from the latest sync of the
3855
+ * thread. `undefined` when the fence renders nothing: it updates a surface
3856
+ * of an earlier fence, its surface is for a named target, or it has no
3857
+ * complete operation yet.
3858
+ */
3859
+ getFenceBlocks(threadId, messageId, fenceIndex) {
3860
+ return this.fences.get(threadId)?.get(fenceKey(messageId, fenceIndex));
3861
+ }
3862
+ };
3863
+ const sources = /* @__PURE__ */ new WeakMap();
3864
+ /**
3865
+ * The markdown source of a generative UI runtime. There is one source for
3866
+ * each surface manager. The root syncs it, and the chat messages read the
3867
+ * fence blocks from it.
3868
+ */
3869
+ function getMarkdownSurfaceSource(runtime) {
3870
+ let source = sources.get(runtime.manager);
3871
+ if (!source) {
3872
+ source = new MarkdownSurfaceSource(runtime.manager, runtime.ui);
3873
+ sources.set(runtime.manager, source);
3874
+ }
3875
+ return source;
3876
+ }
3877
+
3878
+ //#endregion
3879
+ //#region src/v2/generative-ui/calc.ts
3880
+ const MAX_SERIES = 1e3;
3881
+ const OPERATORS = [
3882
+ "&&",
3883
+ "||",
3884
+ "==",
3885
+ "!=",
3886
+ "<=",
3887
+ ">=",
3888
+ "<",
3889
+ ">",
3890
+ "+",
3891
+ "-",
3892
+ "*",
3893
+ "/",
3894
+ "%",
3895
+ "(",
3896
+ ")",
3897
+ ",",
3898
+ "?",
3899
+ ":",
3900
+ "!"
3901
+ ];
3902
+ function tokenize(source) {
3903
+ const tokens = [];
3904
+ let i = 0;
3905
+ while (i < source.length) {
3906
+ const char = source[i];
3907
+ if (/\s/.test(char)) {
3908
+ i++;
3909
+ continue;
3910
+ }
3911
+ if (/[0-9.]/.test(char)) {
3912
+ const match = /^\d*\.?\d+(?:[eE][-+]?\d+)?|^\d+\.?/.exec(source.slice(i));
3913
+ if (!match) throw new ExpressionError(`calc: bad number at "${source.slice(i, i + 8)}"`);
3914
+ tokens.push({
3915
+ kind: "number",
3916
+ value: Number(match[0])
3917
+ });
3918
+ i += match[0].length;
3919
+ continue;
3920
+ }
3921
+ if (char === "'" || char === "\"") {
3922
+ let value = "";
3923
+ i++;
3924
+ while (i < source.length && source[i] !== char) {
3925
+ if (source[i] === "\\" && i + 1 < source.length) i++;
3926
+ value += source[i++];
3927
+ }
3928
+ if (i >= source.length) throw new ExpressionError("calc: unclosed string");
3929
+ i++;
3930
+ tokens.push({
3931
+ kind: "string",
3932
+ value
3933
+ });
3934
+ continue;
3935
+ }
3936
+ if (/[A-Za-z_]/.test(char)) {
3937
+ const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));
3938
+ tokens.push({
3939
+ kind: "name",
3940
+ value: match[0]
3941
+ });
3942
+ i += match[0].length;
3943
+ continue;
3944
+ }
3945
+ const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));
3946
+ if (!op) throw new ExpressionError(`calc: unexpected "${char}"`);
3947
+ tokens.push({
3948
+ kind: "op",
3949
+ value: op
3950
+ });
3951
+ i += op.length;
3952
+ }
3953
+ tokens.push({ kind: "end" });
3954
+ return tokens;
3955
+ }
3956
+ function numberOf(value, what) {
3957
+ if (typeof value === "number") {
3958
+ if (!Number.isFinite(value)) throw new ExpressionError(`calc: ${what} is not finite`);
3959
+ return value;
3960
+ }
3961
+ if (typeof value === "boolean") return value ? 1 : 0;
3962
+ if (typeof value === "string" && value.trim() !== "") {
3963
+ const parsed = Number(value);
3964
+ if (Number.isFinite(parsed)) return parsed;
3965
+ }
3966
+ if (value === null || value === void 0) throw new ExpressionError(`calc: ${what} has no value`);
3967
+ throw new ExpressionError(`calc: ${what} is not a number`);
3968
+ }
3969
+ function describe(value) {
3970
+ return typeof value === "string" ? `"${value}"` : String(value);
3971
+ }
3972
+ const MATH = {
3973
+ min: (args) => Math.min(...args),
3974
+ max: (args) => Math.max(...args),
3975
+ abs: ([x]) => Math.abs(x),
3976
+ floor: ([x]) => Math.floor(x),
3977
+ ceil: ([x]) => Math.ceil(x),
3978
+ round: ([x, decimals = 0]) => {
3979
+ const factor = 10 ** Math.trunc(decimals);
3980
+ return Math.round(x * factor) / factor;
3981
+ }
3982
+ };
3983
+ var CalcParser = class {
3984
+ constructor(tokens, scope, source) {
3985
+ this.tokens = tokens;
3986
+ this.scope = scope;
3987
+ this.source = source;
3988
+ this.pos = 0;
3989
+ this.skipDepth = 0;
3990
+ }
3991
+ parse() {
3992
+ const value = this.ternary();
3993
+ if (this.tokens[this.pos].kind !== "end") this.fail(`unexpected "${this.text(this.tokens[this.pos])}"`);
3994
+ return value;
3995
+ }
3996
+ fail(what) {
3997
+ throw new ExpressionError(`calc: ${what} in "${this.source}"`);
3998
+ }
3999
+ text(token) {
4000
+ return token.kind === "end" ? "end" : String(token.value);
4001
+ }
4002
+ peekOp(...ops) {
4003
+ const token = this.tokens[this.pos];
4004
+ return token.kind === "op" && ops.includes(token.value) ? token.value : void 0;
4005
+ }
4006
+ expectOp(op) {
4007
+ if (this.peekOp(op) === void 0) this.fail(`expected "${op}" but found "${this.text(this.tokens[this.pos])}"`);
4008
+ this.pos++;
4009
+ }
4010
+ /**
4011
+ * Parses a part of the expression that the result does not need (the
4012
+ * other branch of `?:`, the right side of a decided `&&` or `||`). It
4013
+ * still has to be parsed to find where it ends, so syntax errors are
4014
+ * reported, but no value is checked or computed: `n == 0 ? 0 : 10 / n`
4015
+ * is a valid guard.
4016
+ */
4017
+ skipped(parse) {
4018
+ this.skipDepth++;
4019
+ try {
4020
+ parse();
4021
+ } finally {
4022
+ this.skipDepth--;
4023
+ }
4024
+ return null;
4025
+ }
4026
+ /** The number of a value, or 0 while skipping. */
4027
+ num(value, what) {
4028
+ return this.skipDepth > 0 ? 0 : numberOf(value, what);
4029
+ }
4030
+ ternary() {
4031
+ const condition = this.or();
4032
+ if (this.peekOp("?") === void 0) return condition;
4033
+ this.pos++;
4034
+ const takesFirst = truthOf(condition);
4035
+ const whenTrue = takesFirst ? this.ternary() : this.skipped(() => this.ternary());
4036
+ this.expectOp(":");
4037
+ const whenFalse = takesFirst ? this.skipped(() => this.ternary()) : this.ternary();
4038
+ return takesFirst ? whenTrue : whenFalse;
4039
+ }
4040
+ or() {
4041
+ let left = this.and();
4042
+ while (this.peekOp("||")) {
4043
+ this.pos++;
4044
+ if (truthOf(left)) {
4045
+ this.skipped(() => this.and());
4046
+ left = true;
4047
+ } else left = truthOf(this.and());
4048
+ }
4049
+ return left;
4050
+ }
4051
+ and() {
4052
+ let left = this.equality();
4053
+ while (this.peekOp("&&")) {
4054
+ this.pos++;
4055
+ if (!truthOf(left)) {
4056
+ this.skipped(() => this.equality());
4057
+ left = false;
4058
+ } else left = truthOf(this.equality());
4059
+ }
4060
+ return left;
4061
+ }
4062
+ equality() {
4063
+ let left = this.comparison();
4064
+ for (let op = this.peekOp("==", "!="); op; op = this.peekOp("==", "!=")) {
4065
+ this.pos++;
4066
+ const right = this.comparison();
4067
+ const isEqual = typeof left === "number" || typeof right === "number" ? this.num(left, "the left side of ==") === this.num(right, "the right side of ==") : left === right;
4068
+ left = op === "==" ? isEqual : !isEqual;
4069
+ }
4070
+ return left;
4071
+ }
4072
+ comparison() {
4073
+ let left = this.additive();
4074
+ for (let op = this.peekOp("<", "<=", ">", ">="); op; op = this.peekOp("<", "<=", ">", ">=")) {
4075
+ this.pos++;
4076
+ const a = this.num(left, `the left side of ${op}`);
4077
+ const b = this.num(this.additive(), `the right side of ${op}`);
4078
+ left = op === "<" ? a < b : op === "<=" ? a <= b : op === ">" ? a > b : a >= b;
4079
+ }
4080
+ return left;
4081
+ }
4082
+ additive() {
4083
+ let left = this.multiplicative();
4084
+ for (let op = this.peekOp("+", "-"); op; op = this.peekOp("+", "-")) {
4085
+ this.pos++;
4086
+ const right = this.multiplicative();
4087
+ if (op === "+" && (typeof left === "string" || typeof right === "string")) left = `${left ?? ""}${right ?? ""}`;
4088
+ else {
4089
+ const a = this.num(left, `the left side of ${op}`);
4090
+ const b = this.num(right, `the right side of ${op}`);
4091
+ left = op === "+" ? a + b : a - b;
4092
+ }
4093
+ }
4094
+ return left;
4095
+ }
4096
+ multiplicative() {
4097
+ let left = this.unary();
4098
+ for (let op = this.peekOp("*", "/", "%"); op; op = this.peekOp("*", "/", "%")) {
4099
+ this.pos++;
4100
+ const a = this.num(left, `the left side of ${op}`);
4101
+ const b = this.num(this.unary(), `the right side of ${op}`);
4102
+ if (op !== "*" && b === 0 && this.skipDepth === 0) this.fail("division by zero");
4103
+ left = op === "*" ? a * b : op === "/" ? a / b : a % b;
4104
+ }
4105
+ return left;
4106
+ }
4107
+ unary() {
4108
+ if (this.peekOp("-")) {
4109
+ this.pos++;
4110
+ return -this.num(this.unary(), "the operand of -");
4111
+ }
4112
+ if (this.peekOp("!")) {
4113
+ this.pos++;
4114
+ return !truthOf(this.unary());
4115
+ }
4116
+ return this.primary();
4117
+ }
4118
+ primary() {
4119
+ const token = this.tokens[this.pos++];
4120
+ switch (token.kind) {
4121
+ case "number": return token.value;
4122
+ case "string": return token.value;
4123
+ case "name": return this.name(token.value);
4124
+ case "op":
4125
+ if (token.value === "(") {
4126
+ const value = this.ternary();
4127
+ this.expectOp(")");
4128
+ return value;
4129
+ }
4130
+ return this.fail(`unexpected "${token.value}"`);
4131
+ case "end": return this.fail("missing value");
4132
+ }
4133
+ }
4134
+ name(name) {
4135
+ if (name === "true") return true;
4136
+ if (name === "false") return false;
4137
+ if (name === "null") return null;
4138
+ if (this.peekOp("(")) {
4139
+ this.pos++;
4140
+ const args = [];
4141
+ if (this.peekOp(")") === void 0) for (;;) {
4142
+ args.push(this.num(this.ternary(), `an argument of ${name}`));
4143
+ if (this.peekOp(",") === void 0) break;
4144
+ this.pos++;
4145
+ }
4146
+ this.expectOp(")");
4147
+ if (this.skipDepth > 0) return null;
4148
+ const fn = Object.prototype.hasOwnProperty.call(MATH, name) ? MATH[name] : void 0;
4149
+ if (!fn) this.fail(`unknown function ${name}`);
4150
+ if (args.length === 0) this.fail(`${name} needs an argument`);
4151
+ return fn(args);
4152
+ }
4153
+ if (this.skipDepth > 0) return null;
4154
+ if (!Object.prototype.hasOwnProperty.call(this.scope, name)) this.fail(`unknown name ${name}; pass it as an arg`);
4155
+ const value = this.scope[name];
4156
+ if (value !== null && typeof value !== "number" && typeof value !== "string" && typeof value !== "boolean") this.fail(`${name} is not a number, text or boolean (${describe(value)})`);
4157
+ return value;
4158
+ }
4159
+ };
4160
+ /**
4161
+ * Evaluates `expression` with the names in `scope`. Gives a number, a
4162
+ * string, a boolean or null. Throws an {@link ExpressionError} for a bad
4163
+ * expression or a missing name.
4164
+ */
4165
+ function evaluateCalc(expression, scope) {
4166
+ if (typeof expression !== "string" || expression.trim() === "") throw new ExpressionError("calc: expression must be a string");
4167
+ return new CalcParser(tokenize(expression), scope, expression).parse();
4168
+ }
4169
+ /** The `calc` function: the expression is `args.expression`, the rest is the scope. */
4170
+ function calc(args) {
4171
+ const { expression, ...scope } = args;
4172
+ return evaluateCalc(expression, scope);
4173
+ }
4174
+ const WHOLE_EXPRESSION = /^\$\{([^}]*)\}$/;
4175
+ /**
4176
+ * Fills `item` for one iteration: a string that is one `${...}` gives the
4177
+ * typed value of the expression, a string with `${...}` inside it is
4178
+ * interpolated as text, and objects and arrays are walked.
4179
+ */
4180
+ function fillItem(item, scope) {
4181
+ if (typeof item === "string") {
4182
+ const whole = WHOLE_EXPRESSION.exec(item);
4183
+ if (whole) return evaluateCalc(whole[1], scope);
4184
+ return item.replace(/\$\{([^}]*)\}/g, (_, expression) => {
4185
+ const value = evaluateCalc(expression, scope);
4186
+ return value === null ? "" : String(value);
4187
+ });
4188
+ }
4189
+ if (Array.isArray(item)) return item.map((entry) => fillItem(entry, scope));
4190
+ if (typeof item === "object" && item !== null) return Object.fromEntries(Object.entries(item).map(([key, value]) => [key, fillItem(value, scope)]));
4191
+ return item;
4192
+ }
4193
+ /**
4194
+ * The `series` function: `count` copies of `item`, with the loop variable
4195
+ * (`variable`, default "i") counting from `start` (default 1) and the other
4196
+ * args in scope of the `${...}` expressions of the item.
4197
+ */
4198
+ function series(args) {
4199
+ const { count, item, variable, start, ...scope } = args;
4200
+ const length = numberOf(count, "count");
4201
+ if (!Number.isInteger(length) || length < 0) throw new ExpressionError("series: count must be a whole number");
4202
+ if (length > MAX_SERIES) throw new ExpressionError(`series: count is at most ${MAX_SERIES}`);
4203
+ if (item === void 0) throw new ExpressionError("series: item is required");
4204
+ const name = variable === void 0 ? "i" : variable;
4205
+ if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new ExpressionError("series: variable must be a name");
4206
+ const first = start === void 0 ? 1 : numberOf(start, "start");
4207
+ return Array.from({ length }, (_, index) => fillItem(item, {
4208
+ ...scope,
4209
+ [name]: first + index
4210
+ }));
4211
+ }
4212
+
4213
+ //#endregion
4214
+ //#region src/v2/generative-ui/resolve.ts
4215
+ BASIC_FUNCTIONS.calc = calc;
4216
+ BASIC_FUNCTIONS.series = series;
4217
+ const NO_DATA = { get: () => void 0 };
4218
+ BASIC_FUNCTIONS.formatString = (args) => resolveDynamicValue({
4219
+ "@call": "formatString",
4220
+ args
4221
+ }, {
4222
+ data: NO_DATA,
4223
+ basePath: void 0
4224
+ }).value;
4225
+ /** Adds one segment to a JSON pointer: ("/items", "0") gives "/items/0". */
4226
+ function joinPath(base, segment) {
4227
+ return base === "/" ? `/${segment}` : `${base}/${segment}`;
4228
+ }
4229
+ /**
4230
+ * The absolute data model path of a binding. A path without a leading "/"
4231
+ * is relative to the current template item, or to the root outside of one.
4232
+ */
4233
+ function resolvePath(path, basePath) {
4234
+ if (path.startsWith("/")) return path;
4235
+ return joinPath(basePath ?? "/", path);
4236
+ }
4237
+ /**
4238
+ * The index of the template item at `basePath`: its last segment.
4239
+ * `undefined` outside of a template.
4240
+ */
4241
+ function templateIndex(basePath) {
4242
+ if (basePath === void 0) return void 0;
4243
+ const index = Number(basePath.slice(basePath.lastIndexOf("/") + 1));
4244
+ return Number.isInteger(index) ? index : void 0;
4245
+ }
4246
+ /** The value of a ValidationResult where a boolean is expected. */
4247
+ function coerce(value, keep) {
4248
+ return !keep && (0, _copilotkit_shared.isValidationResult)(value) ? value.valid : value;
4249
+ }
4250
+ /**
4251
+ * Resolves `value`. `keepValidation` keeps a ValidationResult as it is; by
4252
+ * default it becomes its `valid` boolean, which is what every prop except
4253
+ * a check condition wants.
4254
+ */
4255
+ function walk(value, state, keepValidation, scope = "outside") {
4256
+ if (Array.isArray(value)) {
4257
+ let changed = false;
4258
+ const itemScope = scope === "list" ? "check" : "outside";
4259
+ const items = value.map((item) => {
4260
+ const next = walk(item, state, keepValidation, itemScope);
4261
+ if (next !== item) changed = true;
4262
+ return next;
4263
+ });
4264
+ return changed ? items : value;
4265
+ }
4266
+ if (!isRecord(value)) return value;
4267
+ if ((0, _copilotkit_shared.isPathBinding)(value)) {
4268
+ const path = resolvePath(value["@path"], state.context.basePath);
4269
+ state.paths.add(path);
4270
+ return state.context.data.get(path);
4271
+ }
4272
+ if ((0, _copilotkit_shared.isCallBinding)(value)) return call(value, state, keepValidation);
4273
+ if ((0, _copilotkit_shared.isActionBinding)(value)) return value;
4274
+ let changed = false;
4275
+ const entries = Object.entries(value).map(([key, item]) => {
4276
+ const next = walk(item, state, keepValidation || scope === "check" && key === "condition", key === "checks" ? "list" : "outside");
4277
+ if (next !== item) changed = true;
4278
+ return [key, next];
4279
+ });
4280
+ return changed ? Object.fromEntries(entries) : value;
4281
+ }
4282
+ function call(binding, state, keepValidation) {
4283
+ const name = binding["@call"];
4284
+ const rawArgs = binding.args ?? {};
4285
+ if (!isRecord(rawArgs)) throw new ExpressionError(`the args of "${name}" must be an object`);
4286
+ if (name === _copilotkit_shared.A2UI_INDEX_FUNCTION) {
4287
+ const index = templateIndex(state.context.basePath);
4288
+ if (index === void 0) return void 0;
4289
+ const offset = walk(rawArgs.offset, state, false);
4290
+ return index + (typeof offset === "number" ? offset : 0);
4291
+ }
4292
+ if (name === "formatString") {
4293
+ const template = walk(rawArgs.value, state, false);
4294
+ if (typeof template !== "string") throw new ExpressionError("formatString takes a string value");
4295
+ return formatString(template, state);
4296
+ }
4297
+ const fn = Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name) ? BASIC_FUNCTIONS[name] : void 0;
4298
+ if (!fn) throw new ExpressionError(`"${name}" is not a basic function`);
4299
+ if (requiresUserActivation(name)) throw new ExpressionError(`"${name}" is not a value; bind it as the functionCall of an event`);
4300
+ const result = fn(walk(rawArgs, state, false));
4301
+ return givesValidationResult(name) ? coerce(result, keepValidation) : result;
4302
+ }
4303
+ function resolveDynamicValue(value, context, options = {}) {
4304
+ const result = tryResolveDynamicValue(value, context, options);
4305
+ if (!result.ok) throw result.error;
4306
+ return result;
4307
+ }
4308
+ /**
4309
+ * Like {@link resolveDynamicValue}, but a failure comes back as a result
4310
+ * with the paths read so far, so the caller can keep watching them: a
4311
+ * function that fails on an empty field works once the user fills it.
4312
+ */
4313
+ function tryResolveDynamicValue(value, context, options = {}) {
4314
+ const state = {
4315
+ context,
4316
+ paths: /* @__PURE__ */ new Set()
4317
+ };
4318
+ try {
4319
+ return {
4320
+ ok: true,
4321
+ value: walk(value, state, options.keepValidation ?? false, options.isChecks ? "list" : "outside"),
4322
+ paths: state.paths
4323
+ };
4324
+ } catch (error) {
4325
+ return {
4326
+ ok: false,
4327
+ error: error instanceof Error ? error : new Error(String(error)),
4328
+ paths: state.paths
4329
+ };
4330
+ }
4331
+ }
4332
+ /** True when `value` holds a `{"@path"}` or `{"@call"}` at any depth. */
4333
+ function containsDynamicValue(value) {
4334
+ if (Array.isArray(value)) return value.some(containsDynamicValue);
4335
+ if (!isRecord(value)) return false;
4336
+ if ((0, _copilotkit_shared.isPathBinding)(value) || (0, _copilotkit_shared.isCallBinding)(value)) return true;
4337
+ if ((0, _copilotkit_shared.isActionBinding)(value)) return false;
4338
+ return Object.values(value).some(containsDynamicValue);
4339
+ }
4340
+ /**
4341
+ * The `${...}` grammar of `formatString`:
4342
+ *
4343
+ * expression := path | literal | call
4344
+ * path := "/" segments | identifier ("/" segments)*
4345
+ * literal := 'text' | "text" | number | true | false | null
4346
+ * call := identifier "(" [ name ":" expression ("," name ":" expression)* ] ")"
4347
+ *
4348
+ * A `\${` in the template is a literal `${`.
4349
+ */
4350
+ function formatString(template, state) {
4351
+ let out = "";
4352
+ let index = 0;
4353
+ while (index < template.length) {
4354
+ const start = template.indexOf("${", index);
4355
+ if (start === -1) {
4356
+ out += template.slice(index);
4357
+ break;
4358
+ }
4359
+ if (start > 0 && template[start - 1] === "\\") {
4360
+ out += `${template.slice(index, start - 1)}\${`;
4361
+ index = start + 2;
4362
+ continue;
4363
+ }
4364
+ out += template.slice(index, start);
4365
+ const end = matchingBrace(template, start + 2);
4366
+ if (end === -1) throw new ExpressionError("formatString: unclosed ${");
4367
+ const value = new ExpressionParser(template.slice(start + 2, end).trim(), state).parse();
4368
+ out += value === void 0 || value === null ? "" : String(value);
4369
+ index = end + 1;
4370
+ }
4371
+ return out;
4372
+ }
4373
+ /** The index of the `}` that closes the block opened at `from`, or -1. */
4374
+ function matchingBrace(template, from) {
4375
+ let depth = 1;
4376
+ let quote;
4377
+ for (let i = from; i < template.length; i++) {
4378
+ const char = template[i];
4379
+ if (quote) {
4380
+ if (char === "\\") i++;
4381
+ else if (char === quote) quote = void 0;
4382
+ continue;
4383
+ }
4384
+ if (char === "'" || char === "\"") quote = char;
4385
+ else if (char === "{") depth++;
4386
+ else if (char === "}" && --depth === 0) return i;
4387
+ }
4388
+ return -1;
4389
+ }
4390
+ const IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;
4391
+ const NUMBER = /-?\d+(?:\.\d+)?/y;
4392
+ const PATH_SEGMENT = /[^\s,():'"]+/y;
4393
+ var ExpressionParser = class {
4394
+ constructor(source, state) {
4395
+ this.source = source;
4396
+ this.state = state;
4397
+ this.pos = 0;
4398
+ }
4399
+ parse() {
4400
+ const value = this.expression();
4401
+ this.skipSpace();
4402
+ if (this.pos < this.source.length) throw new ExpressionError(`formatString: unexpected "${this.source.slice(this.pos)}" in \${${this.source}}`);
4403
+ return value;
4404
+ }
4405
+ fail(what) {
4406
+ throw new ExpressionError(`formatString: ${what} in \${${this.source}}`);
4407
+ }
4408
+ skipSpace() {
4409
+ while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) this.pos++;
4410
+ }
4411
+ match(pattern) {
4412
+ pattern.lastIndex = this.pos;
4413
+ const found = pattern.exec(this.source);
4414
+ if (!found) return void 0;
4415
+ this.pos = pattern.lastIndex;
4416
+ return found[0];
4417
+ }
4418
+ expression() {
4419
+ this.skipSpace();
4420
+ const char = this.source[this.pos];
4421
+ if (char === void 0) this.fail("missing expression");
4422
+ if (char === "'" || char === "\"") return this.quoted(char);
4423
+ if (char === "/") return this.path(this.match(PATH_SEGMENT) ?? "/");
4424
+ const number = this.match(NUMBER);
4425
+ if (number !== void 0) return Number(number);
4426
+ const name = this.match(IDENTIFIER);
4427
+ if (name === void 0) this.fail(`unexpected "${char}"`);
4428
+ if (name === "true") return true;
4429
+ if (name === "false") return false;
4430
+ if (name === "null") return null;
4431
+ this.skipSpace();
4432
+ if (this.source[this.pos] === "(") return this.call(name);
4433
+ if (name.startsWith("@")) return call({ "@call": name }, this.state, false);
4434
+ const rest = this.source[this.pos] === "/" ? this.match(PATH_SEGMENT) : "";
4435
+ return this.path(`${name}${rest ?? ""}`);
4436
+ }
4437
+ quoted(quote) {
4438
+ let value = "";
4439
+ this.pos++;
4440
+ while (this.pos < this.source.length) {
4441
+ const char = this.source[this.pos++];
4442
+ if (char === "\\" && this.pos < this.source.length) value += this.source[this.pos++];
4443
+ else if (char === quote) return value;
4444
+ else value += char;
4445
+ }
4446
+ return this.fail("unclosed string");
4447
+ }
4448
+ path(path) {
4449
+ const absolute = resolvePath(path, this.state.context.basePath);
4450
+ this.state.paths.add(absolute);
4451
+ return this.state.context.data.get(absolute);
4452
+ }
4453
+ call(name) {
4454
+ this.pos++;
4455
+ const args = {};
4456
+ this.skipSpace();
4457
+ if (this.source[this.pos] === ")") {
4458
+ this.pos++;
4459
+ return call({
4460
+ "@call": name,
4461
+ args
4462
+ }, this.state, false);
4463
+ }
4464
+ for (;;) {
4465
+ this.skipSpace();
4466
+ const key = this.match(IDENTIFIER);
4467
+ if (key === void 0) this.fail("expected an argument name");
4468
+ this.skipSpace();
4469
+ if (this.source[this.pos] !== ":") this.fail(`expected ":" after ${key}`);
4470
+ this.pos++;
4471
+ args[key] = this.expression();
4472
+ this.skipSpace();
4473
+ const next = this.source[this.pos++];
4474
+ if (next === ")") break;
4475
+ if (next !== ",") this.fail(`expected "," or ")" after ${key}`);
4476
+ }
4477
+ return call({
4478
+ "@call": name,
4479
+ args
4480
+ }, this.state, false);
4481
+ }
4482
+ };
4483
+
4484
+ //#endregion
4485
+ //#region src/v2/generative-ui/schema.ts
4486
+ const ASYNC_ISSUE = { message: "the schema validates asynchronously; component props and state need a schema that validates synchronously" };
4487
+ function toResult(result) {
4488
+ return result.issues ? {
4489
+ success: false,
4490
+ issues: result.issues
4491
+ } : {
4492
+ success: true,
4493
+ data: result.value
4494
+ };
4495
+ }
4496
+ /**
4497
+ * Validates `value` with `schema`. The result comes back at once when the
4498
+ * schema validates synchronously, else as a promise.
4499
+ */
4500
+ function validateSchema(schema, value) {
4501
+ const result = schema["~standard"].validate(value);
4502
+ return result instanceof Promise ? result.then(toResult) : toResult(result);
4503
+ }
4504
+ /**
4505
+ * Validates `value` synchronously, for code that runs during render. A
4506
+ * schema that validates asynchronously fails with an issue that says so.
4507
+ */
4508
+ function validateSchemaSync(schema, value) {
4509
+ const result = validateSchema(schema, value);
4510
+ if (!(result instanceof Promise)) return result;
4511
+ result.catch(() => {});
4512
+ return {
4513
+ success: false,
4514
+ issues: [ASYNC_ISSUE]
4515
+ };
4516
+ }
4517
+ /** True for the issue that `validateSchemaSync` gives for an async schema. */
4518
+ function isAsyncIssue(issue) {
4519
+ return issue === ASYNC_ISSUE;
4520
+ }
4521
+ /** The first key of an issue path: the prop the issue is about. */
4522
+ function issueKey(issue) {
4523
+ const first = issue.path?.[0];
4524
+ const key = typeof first === "object" ? first.key : first;
4525
+ return key === void 0 ? void 0 : String(key);
4526
+ }
4527
+ /**
4528
+ * `props` without the top-level props whose `null` the schema rejected, or
4529
+ * `undefined` when there are none. A model writes `null` for "not set" (an
4530
+ * empty selection, a value it has not filled yet), and A2UI deletes a data
4531
+ * model key that is set to `null`, so a rejected `null` is read as an unset
4532
+ * prop. A prop whose schema accepts `null` keeps it.
4533
+ */
4534
+ function withoutRejectedNulls(props, issues) {
4535
+ const rejected = /* @__PURE__ */ new Set();
4536
+ for (const issue of issues) {
4537
+ const key = issueKey(issue);
4538
+ if (key !== void 0 && issue.path?.length === 1 && props[key] === null) rejected.add(key);
4539
+ }
4540
+ if (rejected.size === 0) return void 0;
4541
+ return Object.fromEntries(Object.entries(props).filter(([key]) => !rejected.has(key)));
4542
+ }
4543
+ /** `"a.b: message; c: message"`. A path-less issue gets `fallback`. */
4544
+ function formatIssues(issues, fallback = "props") {
4545
+ return issues.map((issue) => {
4546
+ return `${(issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".") || fallback}: ${issue.message}`;
4547
+ }).join("; ");
4548
+ }
4549
+
4550
+ //#endregion
4551
+ //#region src/v2/generative-ui/surface-manager.ts
4552
+ function surfaceKey(threadId, surfaceId) {
4553
+ return `${threadId}::${surfaceId}`;
4554
+ }
4555
+ let creationCounter = 0;
4556
+ const FORBIDDEN_SEGMENTS = new Set([
4557
+ "__proto__",
4558
+ "constructor",
4559
+ "prototype"
4560
+ ]);
4561
+ /** "/a/b/" to "/a/b". The root stays "/". */
4562
+ function normalizePath(path) {
4563
+ return (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path) || "/";
4564
+ }
4565
+ /** True when `path` is `ancestor` or below it. */
4566
+ function isAtOrBelow(path, ancestor) {
4567
+ if (ancestor === "/") return true;
4568
+ return path === ancestor || path.startsWith(`${ancestor}/`);
4569
+ }
4570
+ /**
4571
+ * Rejections as `"operation <index>: <reason>"` lines, cut to the size that
4572
+ * the envelope reader accepts.
4573
+ */
4574
+ function summarizeRejections(rejections) {
4575
+ 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));
4576
+ }
4577
+ /**
4578
+ * Framework-agnostic store of generated surfaces. One web_core SurfaceModel per
4579
+ * (threadId, surfaceId), shared by every mount. Applies only newly committed
4580
+ * operations, validates each before applying it, and owns app state and the
4581
+ * data model paths that the user wrote, so agent updates cannot overwrite
4582
+ * them. App state never goes into a surface's data model. Selectors read it
4583
+ * with `getState()`.
4584
+ */
4585
+ var GenerativeUISurfaceManager = class {
4586
+ constructor(ui, options = {}) {
4587
+ this.ui = ui;
4588
+ this.options = options;
4589
+ this.surfaces = /* @__PURE__ */ new Map();
4590
+ this.bookkeeping = /* @__PURE__ */ new Map();
4591
+ this.listeners = /* @__PURE__ */ new Set();
4592
+ this.targets = /* @__PURE__ */ new Map();
4593
+ this.state = {};
4594
+ this.owned = /* @__PURE__ */ new Map();
4595
+ this.deletedKeys = /* @__PURE__ */ new Set();
4596
+ this.linked = /* @__PURE__ */ new Map();
4597
+ this.version = 0;
4598
+ this.subscribe = (listener) => {
4599
+ this.listeners.add(listener);
4600
+ return () => {
4601
+ this.listeners.delete(listener);
4602
+ };
4603
+ };
4604
+ this.getVersion = () => this.version;
4605
+ this.getState = () => this.state;
4606
+ this.webCoreCatalog = new _a2ui_web_core_v0_9.Catalog(ui.id, [...ui.components.keys()].map((name) => ({
4607
+ name,
4608
+ schema: zod.z.any()
4609
+ })), []);
4610
+ }
4611
+ notify() {
4612
+ this.version++;
4613
+ for (const listener of [...this.listeners]) listener();
4614
+ }
4615
+ setActiveThread(threadId) {
4616
+ if (threadId === this.activeThreadId) return;
4617
+ this.activeThreadId = threadId;
4618
+ this.notify();
4619
+ }
4620
+ getActiveThread() {
4621
+ return this.activeThreadId;
4622
+ }
4623
+ ingest(threadId, agentId, content) {
4624
+ const key = surfaceKey(threadId, content.surfaceId);
4625
+ const operations = content.operations ?? [];
4626
+ let surface = this.surfaces.get(key);
4627
+ let book = this.bookkeeping.get(key);
4628
+ let changed = false;
4629
+ if (surface && book && !this.extendsApplied(book, operations)) {
4630
+ this.disposeSurface(key);
4631
+ surface = void 0;
4632
+ book = void 0;
4633
+ }
4634
+ if (!surface || !book) {
4635
+ surface = this.createSurface(key, threadId, agentId, content);
4636
+ this.restoreOwnedValues(surface);
4637
+ book = {
4638
+ appliedCount: 0,
4639
+ lastFingerprint: void 0
4640
+ };
4641
+ this.surfaces.set(key, surface);
4642
+ this.bookkeeping.set(key, book);
4643
+ changed = true;
4644
+ }
4645
+ const serverRejected = content.rejected ?? [];
4646
+ if (surface.clientRejected.length > 0 && (surface.status !== "streaming" && content.status === "streaming" || serverRejected.length < surface.serverRejected.length)) {
4647
+ surface.clientRejected = [];
4648
+ changed = true;
4649
+ }
4650
+ if (operations.length > 0) {
4651
+ const lastFingerprint = JSON.stringify(operations[operations.length - 1]);
4652
+ const isReplay = operations.some((op) => (0, _copilotkit_shared.getOperationKind)(op) === "deleteSurface");
4653
+ for (let index = book.appliedCount; index < operations.length; index++) {
4654
+ this.applyOperation(surface, operations[index], {
4655
+ index,
4656
+ isReplay
4657
+ });
4658
+ changed = true;
4659
+ }
4660
+ book.appliedCount = operations.length;
4661
+ surface.operations = operations;
4662
+ book.lastFingerprint = lastFingerprint;
4663
+ }
4664
+ if (surface.status !== content.status || surface.target !== content.target || surface.serverRejected.length !== serverRejected.length) {
4665
+ surface.status = content.status;
4666
+ surface.target = content.target;
4667
+ surface.serverRejected = serverRejected;
4668
+ changed = true;
4669
+ }
4670
+ if (changed) this.notify();
4671
+ }
4672
+ /** The surface of a `key` (see `surfaceKey`), unless it is deleted. */
4673
+ getSurfaceByKey(key) {
4674
+ const surface = this.surfaces.get(key);
4675
+ return surface && !surface.deleted ? surface : void 0;
4676
+ }
4677
+ getSurface(threadId, surfaceId) {
4678
+ const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
4679
+ return surface && !surface.deleted ? surface : void 0;
4680
+ }
4681
+ getSurfaceForTarget(target, threadId = this.activeThreadId) {
4682
+ if (!threadId) return void 0;
4683
+ let latest;
4684
+ for (const surface of this.surfaces.values()) {
4685
+ if (surface.threadId !== threadId || surface.target !== target || surface.deleted) continue;
4686
+ if (!latest || surface.createdAt > latest.createdAt) latest = surface;
4687
+ }
4688
+ return latest;
4689
+ }
4690
+ /**
4691
+ * A surface whose first createSurface was rejected, so the chat can show
4692
+ * the error where the surface would be. `undefined` for any other surface.
4693
+ */
4694
+ getFailedSurface(threadId, surfaceId) {
4695
+ const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
4696
+ return surface?.failed ? surface : void 0;
4697
+ }
4698
+ /**
4699
+ * The surfaces of a thread, for the model. A surface with user-owned
4700
+ * values lists them in `dataModel`, so the model can read what the user
4701
+ * entered. A surface with dropped operations lists them in `rejected`, so
4702
+ * the model can fix them on the next run. A deleted surface, or one that
4703
+ * was never created, has a `status`, so the model knows that the id is
4704
+ * not a live surface.
4705
+ */
4706
+ describeSurfaces(threadId) {
4707
+ const described = {};
4708
+ for (const surface of this.surfaces.values()) {
4709
+ if (surface.threadId !== threadId) continue;
4710
+ const owned = this.owned.get(surface.key);
4711
+ const rejections = [...surface.serverRejected, ...surface.clientRejected];
4712
+ const status = this.deletedKeys.has(surface.key) ? "deleted" : surface.failed ? "failed" : void 0;
4713
+ described[surface.surfaceId] = {
4714
+ target: surface.target,
4715
+ ...owned && owned.size > 0 ? { dataModel: Object.fromEntries(owned) } : {},
4716
+ ...rejections.length > 0 && status !== "deleted" ? { rejected: summarizeRejections(rejections) } : {},
4717
+ ...status ? { status } : {}
4718
+ };
4719
+ }
4720
+ return described;
4721
+ }
4722
+ /** Every surface that is not deleted, oldest first, for the inspector. */
4723
+ debugSurfaces() {
4724
+ return [...this.surfaces.values()].filter((surface) => !surface.deleted).sort((a, b) => a.createdAt - b.createdAt).map((surface) => ({
4725
+ surfaceId: surface.surfaceId,
4726
+ threadId: surface.threadId,
4727
+ agentId: surface.agentId,
4728
+ target: surface.target,
4729
+ status: surface.status,
4730
+ operations: surface.operations,
4731
+ dataModel: surface.model.dataModel.get("/"),
4732
+ userValues: Object.fromEntries(this.owned.get(surface.key) ?? []),
4733
+ rejected: [...surface.serverRejected.map((r) => ({
4734
+ ...r,
4735
+ source: "runtime"
4736
+ })), ...surface.clientRejected.map((r) => ({
4737
+ ...r,
4738
+ source: "browser"
4739
+ }))]
4740
+ }));
4741
+ }
4742
+ /**
4743
+ * Marks a target as mounted. Returns the function that unmounts it. Calling
4744
+ * that function more than once has no effect.
4745
+ *
4746
+ * @param id - The target id.
4747
+ * @param options - The description and the allowed components of this mount.
4748
+ */
4749
+ registerTarget(id, options = {}) {
4750
+ const registration = { ...options };
4751
+ const registrations = this.targets.get(id) ?? /* @__PURE__ */ new Set();
4752
+ registrations.add(registration);
4753
+ this.targets.set(id, registrations);
4754
+ this.notify();
4755
+ let released = false;
4756
+ return () => {
4757
+ if (released) return;
4758
+ released = true;
4759
+ registrations.delete(registration);
4760
+ if (registrations.size === 0) this.targets.delete(id);
4761
+ this.notify();
4762
+ };
4763
+ }
4764
+ /**
4765
+ * The mounted targets. Each has the description and the component list of
4766
+ * its earliest mount that has one.
4767
+ */
4768
+ getMountedTargets() {
4769
+ const mounted = [];
4770
+ for (const [id, registrations] of this.targets) {
4771
+ const description = [...registrations].find((registration) => registration.description !== void 0)?.description;
4772
+ const components = this.targetComponents(id);
4773
+ mounted.push({
4774
+ id,
4775
+ ...description === void 0 ? {} : { description },
4776
+ ...components === void 0 ? {} : { components: [...components] }
4777
+ });
4778
+ }
4779
+ return mounted;
4780
+ }
4781
+ /**
4782
+ * The component list of the earliest mount of `id` that has one.
4783
+ * `undefined` when no mount of `id` limits its components.
4784
+ */
4785
+ targetComponents(id) {
4786
+ return [...this.targets.get(id) ?? /* @__PURE__ */ new Set()].find((registration) => registration.components !== void 0)?.components;
4787
+ }
4788
+ /** The components that `validateOperation` allows on a surface. */
4789
+ allowedComponentsFor(surface) {
4790
+ const components = this.targetComponents(surface.target);
4791
+ return components === void 0 ? void 0 : {
4792
+ target: surface.target,
4793
+ names: new Set(components)
4794
+ };
4795
+ }
4796
+ /** Sets one state key. Notifies only when the value changed. */
4797
+ setState(key, value) {
4798
+ if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
4799
+ this.state = {
4800
+ ...this.state,
4801
+ [key]: value
4802
+ };
4803
+ this.notify();
4804
+ }
4805
+ /** Removes one state key. Notifies only when the key was set. */
4806
+ removeState(key) {
4807
+ if (!Object.hasOwn(this.state, key)) return;
4808
+ const { [key]: _removed, ...rest } = this.state;
4809
+ this.state = rest;
4810
+ this.notify();
4811
+ }
4812
+ /**
4813
+ * Makes the surfaces of `surfaceIds` share their data model: a user write
4814
+ * to one of them goes to all of them (see `setOwnedValue`). The markdown
4815
+ * transport links the parts of a chat surface that the prose lift split.
4816
+ * A later call for one of the surfaces replaces its group.
4817
+ *
4818
+ * @param threadId - The thread of the surfaces.
4819
+ * @param surfaceIds - The surface ids of the group. One id clears a link.
4820
+ */
4821
+ linkSurfaces(threadId, surfaceIds) {
4822
+ const keys = new Set(surfaceIds.map((id) => surfaceKey(threadId, id)));
4823
+ for (const key of keys) if (keys.size > 1) this.linked.set(key, keys);
4824
+ else this.linked.delete(key);
4825
+ }
4826
+ /**
4827
+ * Writes a user value into the data model of a surface, and marks `path`
4828
+ * as user-owned. Then agent writes to that path, or below it, are ignored.
4829
+ * An agent write above it keeps the user value. Ownership ends when the
4830
+ * surface is deleted. Does nothing for an unknown or deleted surface. The
4831
+ * surfaces linked to it (see `linkSurfaces`) get the same write.
4832
+ *
4833
+ * @param key - The `key` of the surface.
4834
+ * @param path - An absolute JSON pointer, for example "/form/email".
4835
+ * @param value - The new value. It is copied.
4836
+ * @throws Error when a path segment is "__proto__", "constructor" or
4837
+ * "prototype", or when the path does not fit the data (for example, a
4838
+ * segment above it holds a string).
4839
+ */
4840
+ setOwnedValue(key, path, value) {
4841
+ const normalized = normalizePath(path);
4842
+ const forbidden = normalized.split("/").find((segment) => FORBIDDEN_SEGMENTS.has(segment));
4843
+ if (forbidden !== void 0) throw new Error(`[generativeUI] path segment "${forbidden}" is not allowed in "${path}".`);
4844
+ for (const target of this.linked.get(key) ?? [key]) this.writeOwnedValue(target, normalized, value);
4845
+ }
4846
+ writeOwnedValue(key, path, value) {
4847
+ const surface = this.surfaces.get(key);
4848
+ if (!surface || surface.deleted) return;
4849
+ surface.model.dataModel.set(path, structuredClone(value));
4850
+ const owned = this.owned.get(key) ?? /* @__PURE__ */ new Map();
4851
+ owned.set(path, structuredClone(value));
4852
+ this.owned.set(key, owned);
4853
+ }
4854
+ /**
4855
+ * Writes the user-owned values into the new, empty data model of a rebuilt
4856
+ * surface. The agent operations are applied after it.
4857
+ */
4858
+ restoreOwnedValues(surface) {
4859
+ const owned = this.owned.get(surface.key) ?? /* @__PURE__ */ new Map();
4860
+ for (const [path, value] of owned) surface.model.dataModel.set(path, structuredClone(value));
4861
+ }
4862
+ /**
4863
+ * The value that an agent write puts at `path`, with the user-owned values
4864
+ * below `path` written back into it. `undefined` when `path` is user-owned
4865
+ * or below a user-owned path, so the agent cannot write it. Throws when a
4866
+ * user value does not fit the new value.
4867
+ */
4868
+ mergeOwnedValues(key, path, value) {
4869
+ const merged = { value: structuredClone(value) };
4870
+ const owned = this.owned.get(key);
4871
+ if (!owned) return merged;
4872
+ const ownedPaths = [...owned.keys()];
4873
+ if (ownedPaths.some((ownedPath) => isAtOrBelow(path, ownedPath))) return void 0;
4874
+ const below = ownedPaths.filter((ownedPath) => isAtOrBelow(ownedPath, path));
4875
+ if (below.length === 0) return merged;
4876
+ const scratch = new _a2ui_web_core_v0_9.DataModel({ value: merged.value });
4877
+ const prefix = path === "/" ? "" : path;
4878
+ for (const ownedPath of below) {
4879
+ const relative = ownedPath.slice(prefix.length);
4880
+ scratch.set(`/value${relative}`, structuredClone(owned.get(ownedPath)));
4881
+ }
4882
+ return { value: scratch.get("/value") };
4883
+ }
4884
+ extendsApplied(book, operations) {
4885
+ if (operations.length < book.appliedCount) return false;
4886
+ if (book.appliedCount === 0) return true;
4887
+ return JSON.stringify(operations[book.appliedCount - 1]) === book.lastFingerprint;
4888
+ }
4889
+ createSurface(key, threadId, agentId, content) {
4890
+ return {
4891
+ key,
4892
+ threadId,
4893
+ surfaceId: content.surfaceId,
4894
+ agentId,
4895
+ model: new _a2ui_web_core_v0_9.SurfaceModel(content.surfaceId, this.webCoreCatalog),
4896
+ createdAt: ++creationCounter,
4897
+ target: content.target,
4898
+ status: content.status,
4899
+ deleted: false,
4900
+ failed: false,
4901
+ serverRejected: content.rejected ?? [],
4902
+ clientRejected: [],
4903
+ operations: []
4904
+ };
4905
+ }
4906
+ disposeSurface(key) {
4907
+ this.surfaces.get(key)?.model.dispose();
4908
+ this.surfaces.delete(key);
4909
+ this.bookkeeping.delete(key);
4910
+ }
4911
+ /**
4912
+ * Marks a surface deleted and frees its components and data. The record
4913
+ * stays, so the model is still told about the id and the bookkeeping does
4914
+ * not rebuild the surface for content that was already applied.
4915
+ */
4916
+ closeSurface(surface) {
4917
+ surface.deleted = true;
4918
+ surface.model.dispose();
4919
+ surface.model = new _a2ui_web_core_v0_9.SurfaceModel(surface.surfaceId, this.webCoreCatalog);
4920
+ this.owned.delete(surface.key);
4921
+ this.linked.delete(surface.key);
4922
+ }
4923
+ /** The surfaces of a thread that a part of `surfaceId` reads, for tests. */
4924
+ getLinkedSurfaceIds(threadId, surfaceId) {
4925
+ const keys = this.linked.get(surfaceKey(threadId, surfaceId));
4926
+ if (!keys) return [surfaceId];
4927
+ const prefix = `${threadId}::`;
4928
+ return [...keys].map((key) => key.slice(prefix.length));
4929
+ }
4930
+ /**
4931
+ * Drops the node keys that the app sets: bound props and matched events.
4932
+ * The model does not see them, so a model value for one is ignored, not
4933
+ * rejected. This runs before validation, because validation rejects keys
4934
+ * that are not in the manifest. It never changes the given operation.
4935
+ */
4936
+ dropAppSetKeys(op) {
4937
+ const kind = (0, _copilotkit_shared.getOperationKind)(op);
4938
+ if (kind !== "updateComponents" && kind !== "createSurface") return op;
4939
+ const record = op;
4940
+ const payload = record[kind];
4941
+ const nodes = payload?.components;
4942
+ if (!Array.isArray(nodes)) return op;
4943
+ return {
4944
+ ...record,
4945
+ [kind]: {
4946
+ ...payload,
4947
+ components: nodes.map((node) => this.dropAppSetNodeKeys(node))
4948
+ }
4949
+ };
4950
+ }
4951
+ dropAppSetNodeKeys(node) {
4952
+ if (typeof node !== "object" || node === null || !("component" in node)) return node;
4953
+ const { component } = node;
4954
+ if (typeof component !== "string") return node;
4955
+ const definition = this.ui.components.get(component);
4956
+ if (!definition) return node;
4957
+ return Object.fromEntries(Object.entries(node).filter(([key]) => !Object.hasOwn(definition.selectors, key) && !Object.hasOwn(definition.eventFunctions, key)));
4958
+ }
4959
+ /**
4960
+ * The surfaces that `validateOperation` gets for one operation of the
4961
+ * content of `surface`.
4962
+ *
4963
+ * - `knownSurfaces`: the surface, when it exists before the operation. It
4964
+ * does not exist before its first createSurface, or after a delete.
4965
+ * - `createdSurfaces`: the surface, when a createSurface at this position
4966
+ * uses its id again. That is the case after the first operation, and for
4967
+ * a surface that was deleted before, unless the content replays that
4968
+ * delete.
4969
+ */
4970
+ surfacesFor(surface, kind, position) {
4971
+ const isFirstCreate = kind === "createSurface" && position.index === 0;
4972
+ const exists = !surface.deleted && !isFirstCreate;
4973
+ const isRecreate = this.deletedKeys.has(surface.key) && !position.isReplay;
4974
+ const isUsedAgain = position.index > 0 || isRecreate;
4975
+ return {
4976
+ knownSurfaces: new Set(exists ? [surface.surfaceId] : []),
4977
+ createdSurfaces: new Set(isUsedAgain ? [surface.surfaceId] : [])
4978
+ };
4979
+ }
4980
+ applyOperation(surface, received, position) {
4981
+ const { index } = position;
4982
+ const kind = (0, _copilotkit_shared.getOperationKind)(received);
4983
+ if (kind === "callRendererFunction") return;
4984
+ const reject = (reason) => {
4985
+ if (kind === "createSurface" && index === 0) {
4986
+ this.closeSurface(surface);
4987
+ surface.failed = true;
4988
+ }
4989
+ surface.clientRejected.push({
4990
+ index,
4991
+ reason
4992
+ });
4993
+ this.options.onOperationRejected?.({
4994
+ surfaceId: surface.surfaceId,
4995
+ index,
4996
+ reason
4997
+ });
4998
+ };
4999
+ const targetId = (0, _copilotkit_shared.getOperationSurfaceId)(received);
5000
+ if (targetId !== void 0 && targetId !== surface.surfaceId) return reject(`operation is for surface "${targetId}", not "${surface.surfaceId}"`);
5001
+ const op = this.dropAppSetKeys(received);
5002
+ const validation = (0, _copilotkit_shared.validateOperation)(op, {
5003
+ manifest: {
5004
+ catalogId: this.ui.id,
5005
+ catalogIds: catalogIdsOf(this.ui),
5006
+ components: this.ui.manifestComponents
5007
+ },
5008
+ ...this.surfacesFor(surface, kind, position),
5009
+ allowedComponents: this.allowedComponentsFor(surface)
5010
+ });
5011
+ if (!validation.ok) return reject(validation.reason);
5012
+ const typed = op;
5013
+ if ("createSurface" in typed) {
5014
+ const { dataModel, components = [] } = typed.createSurface;
5015
+ const problem = this.nodesProblem(components);
5016
+ if (problem) return reject(problem);
5017
+ if (dataModel) {
5018
+ const failure = this.writeAgentData(surface, "/", dataModel);
5019
+ if (failure) return reject(failure);
5020
+ }
5021
+ for (const node of components) this.upsertNode(surface.model, node);
5022
+ return;
5023
+ }
5024
+ if ("updateComponents" in typed) {
5025
+ const nodes = typed.updateComponents.components;
5026
+ const problem = this.nodesProblem(nodes);
5027
+ if (problem) return reject(problem);
5028
+ for (const node of nodes) this.upsertNode(surface.model, node);
5029
+ return;
5030
+ }
5031
+ if ("updateDataModel" in typed) {
5032
+ const { path = "/", value } = typed.updateDataModel;
5033
+ const written = value === null ? void 0 : value;
5034
+ const failure = this.writeAgentData(surface, normalizePath(path), written);
5035
+ if (failure) return reject(failure);
5036
+ return;
5037
+ }
5038
+ if ("deleteSurface" in typed) {
5039
+ this.closeSurface(surface);
5040
+ this.deletedKeys.add(surface.key);
5041
+ }
5042
+ }
5043
+ /** The first node with props of the wrong type, as a reason. */
5044
+ nodesProblem(nodes) {
5045
+ for (const node of nodes) {
5046
+ const problem = this.checkNodeProps(node);
5047
+ if (problem) return `component "${node.id}": ${problem}`;
5048
+ }
5049
+ }
5050
+ /**
5051
+ * Writes an agent value at `path` and keeps the user-owned values. A write
5052
+ * to a user-owned path is ignored, not rejected. Gives the reason when the
5053
+ * value does not fit the data, else `undefined`.
5054
+ */
5055
+ writeAgentData(surface, path, value) {
5056
+ try {
5057
+ const merged = this.mergeOwnedValues(surface.key, path, value);
5058
+ if (merged) surface.model.dataModel.set(path, merged.value);
5059
+ return;
5060
+ } catch (error) {
5061
+ return error instanceof Error ? error.message : String(error);
5062
+ }
5063
+ }
5064
+ checkNodeProps(node) {
5065
+ const definition = this.ui.components.get(node.component);
5066
+ if (!definition) return `unknown component "${node.component}"`;
5067
+ const { id: _id, component: _component, ...rest } = node;
5068
+ const dataProps = Object.fromEntries(Object.entries(rest).filter(([key]) => !definition.events?.[key] && !definition.slots?.[key] && !_copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS.has(key)));
5069
+ if (!definition.props) return void 0;
5070
+ const unknownNow = new Set(Object.keys(definition.selectors));
5071
+ const literals = {};
5072
+ for (const [key, value] of Object.entries(dataProps)) if (containsDynamicValue(value)) unknownNow.add(key);
5073
+ else literals[key] = value;
5074
+ let result = validateSchemaSync(definition.props, literals);
5075
+ if (!result.success) {
5076
+ const unset = withoutRejectedNulls(literals, result.issues);
5077
+ if (unset) result = validateSchemaSync(definition.props, unset);
5078
+ }
5079
+ if (result.success) return void 0;
5080
+ const issues = result.issues.filter((issue) => {
5081
+ const key = issueKey(issue);
5082
+ return key === void 0 ? isAsyncIssue(issue) : !unknownNow.has(key);
5083
+ });
5084
+ return issues.length > 0 ? formatIssues(issues) : void 0;
5085
+ }
5086
+ upsertNode(model, node) {
5087
+ const { id, component, ...rest } = node;
5088
+ const properties = structuredClone(rest);
5089
+ const existing = model.componentsModel.get(id);
5090
+ if (existing && existing.type === component) {
5091
+ existing.properties = properties;
5092
+ return;
5093
+ }
5094
+ if (existing) model.componentsModel.removeComponent(id);
5095
+ model.componentsModel.addComponent(new _a2ui_web_core_v0_9.ComponentModel(id, component, properties));
5096
+ }
5097
+ };
5098
+
5099
+ //#endregion
5100
+ //#region src/v2/generative-ui/use-generative-ui-root.ts
5101
+ const isDevelopment = () => process.env.NODE_ENV !== "production";
5102
+ /** At most this many function follow-up runs for each user turn. */
5103
+ const MAX_FUNCTION_FOLLOW_UPS = 5;
5104
+ function ingestMessages(manager, agent, messages) {
5105
+ if (!agent.threadId) return;
5106
+ for (const message of messages) if (message.role === "activity" && message.activityType === _copilotkit_shared.GENERATIVE_UI_ACTIVITY_TYPE) manager.ingest(agent.threadId, agent.agentId, message.content);
5107
+ }
5108
+ /** What the envelope of a run says, from the provider config. */
5109
+ function envelopeOptionsFor(config) {
5110
+ if (config.transport === "markdown") return {
5111
+ transport: "markdown",
5112
+ includeCatalog: config.includeCatalog !== false,
5113
+ contextSent: config.sendContext !== false
5114
+ };
5115
+ return {
5116
+ transport: "tool",
5117
+ includeCatalog: true,
5118
+ contextSent: false
5119
+ };
5120
+ }
5121
+ /**
5122
+ * The components of a surface as one `updateComponents` operation, so that
5123
+ * the label of the component that sent an event can be found.
5124
+ */
5125
+ function surfaceComponents(surface) {
5126
+ const components = [...surface.model.componentsModel.entries].map(([id, model]) => ({
5127
+ ...model.properties,
5128
+ id,
5129
+ component: model.type
5130
+ }));
5131
+ return [{
5132
+ version: _copilotkit_shared.A2UI_VERSION,
5133
+ updateComponents: {
5134
+ surfaceId: surface.surfaceId,
5135
+ components
5136
+ }
5137
+ }];
5138
+ }
5139
+ /** True when `value` names a `functionCallId`. */
5140
+ function hasFunctionCallId(value) {
5141
+ return typeof value === "object" && value !== null && "functionCallId" in value && typeof value.functionCallId === "string" && value.functionCallId !== "";
5142
+ }
5143
+ /** The `functionCallId` that a developer message answers, if any. */
5144
+ function answeredCallId(content) {
5145
+ if (!content.includes("rendererFunctionResponse")) return void 0;
5146
+ try {
5147
+ const parsed = JSON.parse(content);
5148
+ const response = typeof parsed === "object" && parsed !== null && "rendererFunctionResponse" in parsed ? parsed.rendererFunctionResponse : void 0;
5149
+ return hasFunctionCallId(response) ? response.functionCallId : void 0;
5150
+ } catch {
5151
+ return;
5152
+ }
5153
+ }
5154
+ /** The function calls that a developer message in `messages` answers. */
5155
+ function answeredCallIds(messages) {
5156
+ const ids = /* @__PURE__ */ new Set();
5157
+ for (const message of messages) {
5158
+ if (message.role !== "developer") continue;
5159
+ const id = answeredCallId(message.content);
5160
+ if (id !== void 0) ids.add(id);
5161
+ }
5162
+ return ids;
5163
+ }
5164
+ /** The id of the last user message. A user turn starts with it. */
5165
+ function lastUserMessageId(messages) {
5166
+ for (let index = messages.length - 1; index >= 0; index--) {
5167
+ const message = messages[index];
5168
+ if (message?.role === "user") return message.id;
5169
+ }
5170
+ }
5171
+ /** The function calls of the tool transport: its function-call activities. */
5172
+ function activityFunctionCalls(messages) {
5173
+ const requests = [];
5174
+ for (const message of messages) {
5175
+ if (!(message.role === "activity" && message.activityType === _copilotkit_shared.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE) || !hasFunctionCallId(message.content)) continue;
5176
+ requests.push({
5177
+ functionCallId: message.content.functionCallId,
5178
+ operation: {
5179
+ version: _copilotkit_shared.A2UI_VERSION,
5180
+ callRendererFunction: message.content
5181
+ }
5182
+ });
5183
+ }
5184
+ return requests;
5185
+ }
5186
+ /** The function calls of the markdown transport: its fence lines. */
5187
+ function markdownFunctionCalls(calls) {
5188
+ const requests = [];
5189
+ for (const { operation } of calls) {
5190
+ const payload = operation.callRendererFunction;
5191
+ if (!hasFunctionCallId(payload)) continue;
5192
+ requests.push({
5193
+ functionCallId: payload.functionCallId,
5194
+ operation
5195
+ });
5196
+ }
5197
+ return requests;
5198
+ }
5199
+ /** The text of a `rendererFunctionResponse` developer message. */
5200
+ function responseContent(response) {
5201
+ return JSON.stringify({
5202
+ version: _copilotkit_shared.A2UI_VERSION,
5203
+ rendererFunctionResponse: response
5204
+ });
5205
+ }
5206
+ function errorAnswer(functionCallId, code, message) {
5207
+ return {
5208
+ content: responseContent({
5209
+ functionCallId,
5210
+ error: {
5211
+ code,
5212
+ message
5213
+ }
5214
+ }),
5215
+ followUp: true
5216
+ };
5217
+ }
5218
+ const overCapAnswer = (functionCallId) => ({
5219
+ content: responseContent({
5220
+ functionCallId,
5221
+ error: {
5222
+ code: "follow_up_limit",
5223
+ 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.`
5224
+ }
5225
+ }),
5226
+ followUp: false
5227
+ });
5228
+ /**
5229
+ * Runs the functions that the agent calls with `callRendererFunction`, for
5230
+ * both transports, and answers each call.
5231
+ *
5232
+ * - Each `functionCallId` runs once for each thread. A replay, a sync of
5233
+ * the same messages again, or a call that already has an answer message
5234
+ * does not run it again.
5235
+ * - The answer is a hidden developer message with a `rendererFunctionResponse`.
5236
+ * The answers go to the agent only when it is not running. Then one
5237
+ * follow-up run starts for all of them.
5238
+ * - A user turn has at most {@link MAX_FUNCTION_FOLLOW_UPS} follow-up runs.
5239
+ * A call after that does not run. It gets a `follow_up_limit` error and
5240
+ * starts no follow-up run.
5241
+ */
5242
+ function createFunctionCallRunner(options) {
5243
+ const { copilotkit, dispatcher, manifest } = options;
5244
+ const threads = /* @__PURE__ */ new Map();
5245
+ const threadState = (threadId) => {
5246
+ let state = threads.get(threadId);
5247
+ if (!state) {
5248
+ state = {
5249
+ done: /* @__PURE__ */ new Set(),
5250
+ pending: [],
5251
+ turn: void 0,
5252
+ followUps: 0,
5253
+ flushing: false
5254
+ };
5255
+ threads.set(threadId, state);
5256
+ }
5257
+ return state;
5258
+ };
5259
+ const answer = async (request) => {
5260
+ const { functionCallId } = request;
5261
+ const validation = (0, _copilotkit_shared.validateOperation)(request.operation, {
5262
+ manifest,
5263
+ knownSurfaces: /* @__PURE__ */ new Set()
5264
+ });
5265
+ if (!validation.ok) return errorAnswer(functionCallId, "invalid_arguments", validation.reason);
5266
+ const operation = request.operation;
5267
+ if (!("callRendererFunction" in operation)) return errorAnswer(functionCallId, "invalid_arguments", "the operation is not a callRendererFunction");
5268
+ const { callFunction } = operation.callRendererFunction;
5269
+ const name = callFunction["@call"];
5270
+ const result = await dispatcher.invoke(name, callFunction.args ?? {}, { functionCallId });
5271
+ if (!result.ok) return errorAnswer(functionCallId, result.error.code, result.error.message);
5272
+ try {
5273
+ return {
5274
+ content: responseContent({
5275
+ functionCallId,
5276
+ value: result.result ?? null
5277
+ }),
5278
+ followUp: true
5279
+ };
5280
+ } catch (cause) {
5281
+ return errorAnswer(functionCallId, "handler_failed", `The result of "${name}" is not JSON: ${cause instanceof Error ? cause.message : String(cause)}`);
5282
+ }
5283
+ };
5284
+ /**
5285
+ * Adds the pending answers of a thread to the agent, then starts one
5286
+ * follow-up run. It waits while the agent runs: the next read of the
5287
+ * thread, at the end of the run, flushes again.
5288
+ */
5289
+ const flush = async (agent, threadId, state) => {
5290
+ if (state.flushing) return;
5291
+ state.flushing = true;
5292
+ try {
5293
+ while (state.pending.length > 0) {
5294
+ const batch = [...state.pending];
5295
+ const answers = await Promise.all(batch);
5296
+ await copilotkit.waitForPendingFrameworkUpdates();
5297
+ if (agent.isRunning || agent.threadId !== threadId) return;
5298
+ if (state.pending.length > batch.length) continue;
5299
+ state.pending = [];
5300
+ for (const { content } of answers) agent.addMessage({
5301
+ id: (0, _copilotkit_shared.randomUUID)(),
5302
+ role: "developer",
5303
+ content
5304
+ });
5305
+ if (!answers.some((item) => item.followUp)) continue;
5306
+ state.followUps++;
5307
+ await copilotkit.runAgent({ agent });
5308
+ }
5309
+ } catch (error) {
5310
+ if (isDevelopment()) console.warn("[generativeUI] function follow-up run failed:", error);
5311
+ } finally {
5312
+ state.flushing = false;
5313
+ }
5314
+ };
5315
+ return { run(agent, requests, messages, running) {
5316
+ const { threadId } = agent;
5317
+ if (!threadId) return;
5318
+ const state = threadState(threadId);
5319
+ const turn = lastUserMessageId(messages);
5320
+ if (turn !== state.turn) {
5321
+ state.turn = turn;
5322
+ state.followUps = 0;
5323
+ }
5324
+ const isNew = (request) => !state.done.has(request.functionCallId);
5325
+ const fresh = requests.filter(isNew);
5326
+ const answered = fresh.length > 0 ? answeredCallIds(messages) : /* @__PURE__ */ new Set();
5327
+ for (const request of fresh) {
5328
+ const { functionCallId } = request;
5329
+ if (state.done.has(functionCallId)) continue;
5330
+ state.done.add(functionCallId);
5331
+ if (answered.has(functionCallId)) continue;
5332
+ const isOverCap = state.followUps >= MAX_FUNCTION_FOLLOW_UPS;
5333
+ state.pending.push(isOverCap ? Promise.resolve(overCapAnswer(functionCallId)) : answer(request));
5334
+ }
5335
+ if (!running) flush(agent, threadId, state);
5336
+ } };
5337
+ }
5338
+ /** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */
5339
+ function useGenerativeUIRoot(copilotkit, config) {
5340
+ const configRef = (0, react.useRef)(config);
5341
+ configRef.current = config;
5342
+ const ui = config?.ui;
5343
+ const transport = config?.transport ?? "tool";
5344
+ const theme = useShallowStableRef(config?.theme);
5345
+ const core = (0, react.useMemo)(() => {
5346
+ if (!ui) return null;
5347
+ const reportError = (info) => {
5348
+ try {
5349
+ configRef.current?.errorBoundary?.onError?.(info);
5350
+ } catch (hostError) {
5351
+ if (isDevelopment()) console.error("[generativeUI] errorBoundary.onError threw:", hostError);
5352
+ }
5353
+ if (isDevelopment()) console.warn(`[generativeUI] ${info.kind} error in ${info.surfaceId}${info.componentId ? `/${info.componentId}` : ""}: ${info.error?.message}`);
5354
+ };
5355
+ const manager = new GenerativeUISurfaceManager(ui, { onOperationRejected: ({ surfaceId, index, reason }) => reportError({
5356
+ kind: "operation",
5357
+ surfaceId,
5358
+ error: /* @__PURE__ */ new Error(`operation ${index} rejected: ${reason}`)
5359
+ }) });
5360
+ const dispatcher = createGenerativeUIDispatcher({
5361
+ getDeclared: () => ui.functions,
5362
+ onError: ({ name, origin, error }) => {
5363
+ if ("functionCallId" in origin) {
5364
+ if (isDevelopment()) console.warn(`[generativeUI] function call ${origin.functionCallId} to "${name}" failed: ${error.message}`);
5365
+ return;
5366
+ }
5367
+ reportError({
5368
+ kind: "function",
5369
+ ...origin,
5370
+ error
5371
+ });
5372
+ }
5373
+ });
5374
+ const functionCalls = createFunctionCallRunner({
5375
+ copilotkit,
5376
+ dispatcher,
5377
+ manifest: {
5378
+ catalogId: ui.id,
5379
+ catalogIds: catalogIdsOf(ui),
5380
+ components: ui.manifestComponents
5381
+ }
5382
+ });
5383
+ const forwardingAgents = /* @__PURE__ */ new Set();
5384
+ /**
5385
+ * The action of a user event, as an envelope entry scoped to the agent
5386
+ * the user acted on, for the run that the event starts: the structured
5387
+ * form of the user message. It is set before the run starts and dropped
5388
+ * when the run is over, so a suggestion request or a follow-up run
5389
+ * (both read the properties with no run start) does not carry the same
5390
+ * action again, and another agent never gets a click meant for this one.
5391
+ * The entry comes after the shared envelope, so it wins for its agent;
5392
+ * `refreshActions` keeps it last when the shared envelope is set again.
5393
+ */
5394
+ const actions = /* @__PURE__ */ new Map();
5395
+ const dropAction = (agent) => {
5396
+ const entry = actions.get(agent);
5397
+ if (!entry) return;
5398
+ entry.subscription.unsubscribe();
5399
+ copilotkit.removeScopedProperties(entry.id);
5400
+ actions.delete(agent);
5401
+ };
5402
+ const setAction = (agent, action) => {
5403
+ const previous = actions.get(agent);
5404
+ previous?.subscription.unsubscribe();
5405
+ if (previous) copilotkit.removeScopedProperties(previous.id);
5406
+ actions.delete(agent);
5407
+ const latest = configRef.current;
5408
+ if (!latest) return;
5409
+ const envelope = buildGenerativeUIEnvelope({
5410
+ ui,
5411
+ manager,
5412
+ dispatcher
5413
+ }, agent.threadId, {
5414
+ ...envelopeOptionsFor(latest),
5415
+ action
5416
+ });
5417
+ const id = copilotkit.addScopedProperties({
5418
+ properties: { [_copilotkit_shared.COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: envelope } },
5419
+ agentIds: agent.agentId === void 0 ? latest.agentIds : [agent.agentId]
5420
+ });
5421
+ const subscription = agent.subscribe({
5422
+ onRunFinalized: () => dropAction(agent),
5423
+ onRunFailed: () => dropAction(agent)
5424
+ });
5425
+ actions.set(agent, {
5426
+ id,
5427
+ action,
5428
+ subscription
5429
+ });
5430
+ };
5431
+ const refreshActions = () => {
5432
+ for (const [agent, { action }] of [...actions]) setAction(agent, action);
5433
+ };
5434
+ const dropAllActions = () => {
5435
+ for (const agent of [...actions.keys()]) dropAction(agent);
5436
+ };
5437
+ const forwardEvent = async (event, agentId) => {
5438
+ const fail = (message) => {
5439
+ const error = new GenerativeUIError("event_forward_failed", message);
5440
+ reportError({
5441
+ kind: "event",
5442
+ surfaceId: event.surfaceId,
5443
+ componentId: event.componentId,
5444
+ error
5445
+ });
5446
+ return {
5447
+ ok: false,
5448
+ error
5449
+ };
5450
+ };
5451
+ const agent = copilotkit.getAgent(agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID);
5452
+ if (!agent) return fail(`No agent "${agentId}" to receive "${event.name}"`);
5453
+ if (agent.isRunning || forwardingAgents.has(agent)) return {
5454
+ ok: false,
5455
+ error: new GenerativeUIError("agent_busy", `"${event.name}" was not sent: the agent is running`)
5456
+ };
5457
+ forwardingAgents.add(agent);
5458
+ try {
5459
+ const surface = agent.threadId ? manager.getSurface(agent.threadId, event.surfaceId) : void 0;
5460
+ const resolveLabel = surface ? createComponentLabelResolver(surfaceComponents(surface)) : void 0;
5461
+ agent.addMessage({
5462
+ id: (0, _copilotkit_shared.randomUUID)(),
5463
+ role: "user",
5464
+ content: buildActionMessageText(event, resolveLabel)
5465
+ });
5466
+ setAction(agent, (0, _copilotkit_shared.toA2UIActionMessage)(event));
5467
+ await copilotkit.runAgent({ agent });
5468
+ return {
5469
+ ok: true,
5470
+ result: void 0
5471
+ };
5472
+ } catch (cause) {
5473
+ return fail(`Forwarding "${event.name}" failed: ${cause instanceof Error ? cause.message : String(cause)}`);
5474
+ } finally {
5475
+ forwardingAgents.delete(agent);
5476
+ dropAction(agent);
5477
+ }
5478
+ };
5479
+ return {
5480
+ manager,
5481
+ dispatcher,
5482
+ ui,
5483
+ forwardEvent,
5484
+ reportError,
5485
+ functionCalls,
5486
+ refreshActions,
5487
+ dropAllActions
5488
+ };
5489
+ }, [ui, copilotkit]);
5490
+ const runtime = (0, react.useMemo)(() => {
5491
+ if (!core) return null;
5492
+ const { manager, dispatcher, forwardEvent, reportError } = core;
5493
+ return {
5494
+ manager,
5495
+ dispatcher,
5496
+ ui: core.ui,
5497
+ forwardEvent,
5498
+ reportError,
5499
+ transport,
5500
+ theme,
5501
+ get config() {
5502
+ return configRef.current ?? { ui: core.ui };
5503
+ },
5504
+ get errorFallback() {
5505
+ return configRef.current?.errorBoundary?.fallback;
5506
+ }
5507
+ };
5508
+ }, [
5509
+ core,
5510
+ transport,
5511
+ theme
5512
+ ]);
5513
+ (0, react.useEffect)(() => {
5514
+ if (!core) return;
5515
+ const watched = /* @__PURE__ */ new WeakSet();
5516
+ const agentSubscriptions = [];
5517
+ let envelopeId;
5518
+ const debug = createGenerativeUIDebugSource(core, () => {
5519
+ const latest = configRef.current ?? { ui: core.ui };
5520
+ return {
5521
+ options: envelopeOptionsFor(latest),
5522
+ agentIds: latest.agentIds
5523
+ };
5524
+ });
5525
+ copilotkit.ɵsetGenerativeUIDebugSource(debug.source);
5526
+ const removeEnvelope = () => {
5527
+ if (envelopeId === void 0) return;
5528
+ copilotkit.removeScopedProperties(envelopeId);
5529
+ envelopeId = void 0;
5530
+ };
5531
+ /**
5532
+ * Sets the shared envelope of the run. The action entries of the agents
5533
+ * with a user event under way (see `forwardEvent`) are set again after
5534
+ * it, so they stay the last entries and win for their agents.
5535
+ */
5536
+ const setEnvelope = (agent, latest) => {
5537
+ removeEnvelope();
5538
+ const run = describeGenerativeUIRun(core, agent.threadId, envelopeOptionsFor(latest));
5539
+ envelopeId = copilotkit.addScopedProperties({
5540
+ properties: { [_copilotkit_shared.COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: run.envelope } },
5541
+ agentIds: latest.agentIds
5542
+ });
5543
+ core.refreshActions();
5544
+ if (!latest.agentIds || latest.agentIds.includes(agent.agentId ?? "")) debug.recordRun({
5545
+ ...run,
5546
+ agentId: agent.agentId,
5547
+ threadId: agent.threadId,
5548
+ startedAt: Date.now()
5549
+ });
5550
+ };
5551
+ /**
5552
+ * The tool transport reads the surface activity messages. The markdown
5553
+ * transport reads the ```a2ui fences of the assistant messages, and
5554
+ * builds the surfaces of the thread from them again on each change.
5555
+ * Both give their function calls to the one runner.
5556
+ */
5557
+ const readMessages = (agent, messages, running) => {
5558
+ const requests = activityFunctionCalls(messages);
5559
+ const { threadId } = agent;
5560
+ if (configRef.current?.transport !== "markdown") ingestMessages(core.manager, agent, messages);
5561
+ else if (threadId) {
5562
+ core.manager.setActiveThread(threadId);
5563
+ const calls = getMarkdownSurfaceSource(core).sync(threadId, agent.agentId, messages, { running });
5564
+ requests.push(...markdownFunctionCalls(calls));
5565
+ }
5566
+ core.functionCalls.run(agent, requests, messages, running);
5567
+ };
5568
+ const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => {
5569
+ core.manager.setActiveThread(agent.threadId);
5570
+ const latest = configRef.current;
5571
+ if (latest) setEnvelope(agent, latest);
5572
+ if (!watched.has(agent)) {
5573
+ watched.add(agent);
5574
+ agentSubscriptions.push(agent.subscribe({
5575
+ onMessagesChanged: ({ messages }) => readMessages(agent, messages, agent.isRunning),
5576
+ onRunFinalized: () => readMessages(agent, agent.messages, false),
5577
+ onRunFailed: () => readMessages(agent, agent.messages, false)
5578
+ }));
5579
+ }
5580
+ readMessages(agent, agent.messages, true);
5581
+ } });
5582
+ return () => {
5583
+ subscription.unsubscribe();
5584
+ for (const s of agentSubscriptions) s.unsubscribe();
5585
+ core.dropAllActions();
5586
+ removeEnvelope();
5587
+ if (copilotkit.ɵgenerativeUIDebugSource === debug.source) copilotkit.ɵsetGenerativeUIDebugSource(void 0);
5588
+ };
5589
+ }, [core, copilotkit]);
5590
+ useGenerativeUIMarkdownContext(copilotkit, core, {
5591
+ enabled: config?.transport === "markdown" && config.sendContext !== false,
5592
+ agentIds: config?.agentIds
5593
+ });
5594
+ return runtime;
5595
+ }
5596
+
5597
+ //#endregion
5598
+ //#region src/v2/generative-ui/runtime-context.ts
5599
+ const GenerativeUIRuntimeContext = (0, react.createContext)(null);
5600
+ function useGenerativeUIRuntime() {
5601
+ return (0, react.useContext)(GenerativeUIRuntimeContext);
5602
+ }
5603
+ function useRequiredGenerativeUIRuntime() {
5604
+ const runtime = (0, react.useContext)(GenerativeUIRuntimeContext);
5605
+ if (!runtime) throw new Error("Generative UI components must be rendered inside <CopilotKitProvider generativeUI={{ ui }}>.");
5606
+ return runtime;
5607
+ }
5608
+ /**
5609
+ * Reports an error without ever throwing: `reportError` reaches host code
5610
+ * (`onError`), and a throwing host callback must not break rendering or an
5611
+ * event handler.
5612
+ */
5613
+ function reportErrorSafely(runtime, info) {
5614
+ try {
5615
+ runtime.reportError(info);
5616
+ } catch {}
5617
+ }
5618
+ const GenerativeUINodeContext = (0, react.createContext)(null);
5619
+
5620
+ //#endregion
5621
+ //#region src/v2/generative-ui/hooks.ts
5622
+ const noopSubscribe$1 = () => () => {};
5623
+ const zero = () => 0;
5624
+ /** Re-renders on any surface-manager change. */
5625
+ function useManagerVersion(runtime) {
5626
+ return (0, react.useSyncExternalStore)(runtime?.manager.subscribe ?? noopSubscribe$1, runtime?.manager.getVersion ?? zero, zero);
5627
+ }
5628
+
5629
+ //#endregion
5630
+ //#region src/v2/generative-ui/boundaries.tsx
5631
+ function DefaultNodeFallback({ message, componentId, retry }) {
5632
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
5633
+ role: "alert",
5634
+ "data-generative-ui-error": componentId,
5635
+ style: {
5636
+ border: "1px solid #fca5a5",
5637
+ background: "#fef2f2",
5638
+ color: "#991b1b",
5639
+ borderRadius: 8,
5640
+ padding: "8px 12px",
5641
+ fontSize: 13
5642
+ },
5643
+ children: [
5644
+ "Couldn’t display this part: ",
5645
+ message,
5646
+ retry && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
5647
+ type: "button",
5648
+ onClick: retry,
5649
+ style: {
5650
+ marginLeft: 8,
5651
+ textDecoration: "underline"
5652
+ },
5653
+ children: "Retry"
5654
+ })
5655
+ ]
5656
+ });
5657
+ }
5658
+ /**
5659
+ * A child that has not streamed yet renders nothing. The prose keeps
5660
+ * streaming above the surface, and each component appears as soon as it is
5661
+ * complete. A grey block in its place would read as a broken layout.
5662
+ */
5663
+ function NodePlaceholder(_props) {
5664
+ return null;
5665
+ }
5666
+ /** Per-node boundary. Resets on retry or a new agent revision, not on data ticks. */
5667
+ var NodeBoundary = class extends react.Component {
5668
+ constructor(..._args) {
5669
+ super(..._args);
5670
+ this.state = {
5671
+ error: null,
5672
+ revision: this.props.revision
5673
+ };
5674
+ this.retry = () => this.setState({ error: null });
5675
+ }
5676
+ static getDerivedStateFromError(error) {
5677
+ return { error };
5678
+ }
5679
+ static getDerivedStateFromProps(props, state) {
5680
+ return props.revision !== state.revision ? {
5681
+ error: null,
5682
+ revision: props.revision
5683
+ } : null;
5684
+ }
5685
+ componentDidCatch(error) {
5686
+ const { runtime, surfaceId, componentId } = this.props;
5687
+ reportErrorSafely(runtime, {
5688
+ kind: "render",
5689
+ surfaceId,
5690
+ componentId,
5691
+ error
5692
+ });
5693
+ }
5694
+ render() {
5695
+ const { error } = this.state;
5696
+ if (!error) return this.props.children;
5697
+ const { runtime, surfaceId, componentId } = this.props;
5698
+ const fallback = runtime.errorFallback;
5699
+ return fallback ? fallback({
5700
+ error,
5701
+ retry: this.retry,
5702
+ surfaceId,
5703
+ componentId
5704
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
5705
+ message: error.message,
5706
+ componentId,
5707
+ retry: this.retry
5708
+ });
5709
+ }
5710
+ };
5711
+ /** Outer boundary: a failure here must not reach the chat or the host page. */
5712
+ var SurfaceBoundary = class extends react.Component {
5713
+ constructor(..._args2) {
5714
+ super(..._args2);
5715
+ this.state = { error: null };
5716
+ }
5717
+ static getDerivedStateFromError(error) {
5718
+ return { error };
5719
+ }
5720
+ componentDidCatch(error) {
5721
+ reportErrorSafely(this.props.runtime, {
5722
+ kind: "render",
5723
+ surfaceId: this.props.surfaceId,
5724
+ error
5725
+ });
5726
+ }
5727
+ render() {
5728
+ if (!this.state.error) return this.props.children;
5729
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
5730
+ message: "this generated UI failed to render",
5731
+ componentId: "surface"
5732
+ });
5733
+ }
5734
+ };
5735
+
5736
+ //#endregion
5737
+ //#region src/v2/generative-ui/accessibility.ts
5738
+ const LIVE = new Set([
5739
+ "off",
5740
+ "polite",
5741
+ "assertive"
5742
+ ]);
5743
+ /**
5744
+ * The accessibility of a component from its resolved `accessibility`
5745
+ * value. Fields of the wrong type are left out: a label that is still a
5746
+ * binding, or a list, names nothing.
5747
+ */
5748
+ function readAccessibility(value) {
5749
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
5750
+ const { label, description, live, hidden } = value;
5751
+ const result = {};
5752
+ if (typeof label === "string" && label !== "") result.label = label;
5753
+ if (typeof description === "string" && description !== "") result.description = description;
5754
+ if (typeof live === "string" && LIVE.has(live)) result.live = live;
5755
+ if (typeof hidden === "boolean") result.hidden = hidden;
5756
+ return Object.keys(result).length > 0 ? result : void 0;
5757
+ }
5758
+ /**
5759
+ * The ARIA attributes for an `accessibility`. `live: "off"` is written out:
5760
+ * a region inherits the live setting of its ancestors, and a `status` role
5761
+ * is live on its own, so only the explicit value silences it.
5762
+ *
5763
+ * @example
5764
+ * ```ts
5765
+ * accessibilityAttributes({ label: "Totals", live: "polite" });
5766
+ * // { "aria-label": "Totals", "aria-live": "polite" }
5767
+ * ```
5768
+ */
5769
+ function accessibilityAttributes(accessibility) {
5770
+ if (!accessibility) return {};
5771
+ const { label, description, live, hidden } = accessibility;
5772
+ return {
5773
+ ...label === void 0 ? {} : { "aria-label": label },
5774
+ ...description === void 0 ? {} : { "aria-description": description },
5775
+ ...live === void 0 ? {} : { "aria-live": live },
5776
+ ...hidden ? { "aria-hidden": true } : {}
5777
+ };
5778
+ }
5779
+ /**
5780
+ * The part of the attributes for the wrapper around a control: hidden and
5781
+ * live cover the label and the control together.
5782
+ */
5783
+ function wrapperAria(aria) {
5784
+ const { "aria-hidden": hidden, "aria-live": live } = aria;
5785
+ return {
5786
+ ...hidden === void 0 ? {} : { "aria-hidden": hidden },
5787
+ ...live === void 0 ? {} : { "aria-live": live }
5788
+ };
5789
+ }
5790
+
5791
+ //#endregion
5792
+ //#region src/v2/generative-ui/events.ts
5793
+ /**
5794
+ * The context of a running event binding: it reads the surface data model
5795
+ * and resolves relative paths against the template item of the component.
5796
+ * A function that needs a user gesture (openUrl) is not a value here
5797
+ * either; it runs through the dispatcher as the binding's functionCall.
5798
+ */
5799
+ function eventContext(surface, basePath) {
5800
+ return {
5801
+ data: surface.model.dataModel,
5802
+ basePath
5803
+ };
5804
+ }
5805
+ /**
5806
+ * A value of an event binding with its dynamic values resolved: `{"@path"}`
5807
+ * bindings and function values, at any depth.
5808
+ */
5809
+ function resolveValue(surface, basePath, value) {
5810
+ return resolveDynamicValue(value, eventContext(surface, basePath)).value;
5811
+ }
5812
+ /**
5813
+ * The entries of an args or context record, each resolved on its own. The
5814
+ * record is not resolved as a whole, because a record with one `event` or
5815
+ * `functionCall` key would look like an action binding and stay as it is.
5816
+ */
5817
+ function resolveValues(surface, basePath, values) {
5818
+ return Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [key, resolveValue(surface, basePath, value)]));
5819
+ }
5820
+ /**
5821
+ * The `userMessage` of an event binding, as text. A `{"@path"}` or a
5822
+ * function value is resolved. `undefined` when there is no message, or
5823
+ * the value is not a string.
5824
+ */
5825
+ function resolveUserMessage(surface, basePath, userMessage) {
5826
+ const value = resolveValue(surface, basePath, userMessage);
5827
+ return typeof value === "string" ? value : void 0;
5828
+ }
5829
+ /**
5830
+ * Validates the component's args with the event `parameters`, then runs
5831
+ * `send` with them. Never throws: every failure is reported and becomes
5832
+ * `{ ok: false, error }`.
5833
+ */
5834
+ async function runEvent(call, send) {
5835
+ const { runtime, surface, componentId, name, parameters, args } = call;
5836
+ const origin = {
5837
+ surfaceId: surface.surfaceId,
5838
+ componentId
5839
+ };
5840
+ try {
5841
+ if (!parameters) return await send(args ?? {}, origin);
5842
+ const result = validateSchema(parameters, args ?? {});
5843
+ const parsed = result instanceof Promise ? await result : result;
5844
+ if (!parsed.success) {
5845
+ const error = new GenerativeUIError("invalid_event_args", `${name}: ${formatIssues(parsed.issues, "args")}`);
5846
+ reportErrorSafely(runtime, {
5847
+ kind: "event",
5848
+ ...origin,
5849
+ error
5850
+ });
5851
+ return {
5852
+ ok: false,
5853
+ error
5854
+ };
5855
+ }
5856
+ return await send(parsed.data ?? {}, origin);
5857
+ } catch (cause) {
5858
+ const error = new GenerativeUIError("event_forward_failed", `${name}: ${cause instanceof Error ? cause.message : String(cause)}`);
5859
+ reportErrorSafely(runtime, {
5860
+ kind: "event",
5861
+ ...origin,
5862
+ error
5863
+ });
5864
+ return {
5865
+ ok: false,
5866
+ error
5867
+ };
5868
+ }
5869
+ }
5870
+ /**
5871
+ * Runs one call of an event that the model bound: validates the component's
5872
+ * args, merges them with the args from the binding (binding literals win),
5873
+ * then calls a declared function or forwards an agent event. Never throws.
5874
+ */
5875
+ function invokeBoundEvent(params) {
5876
+ const { runtime, surface, binding, basePath } = params;
5877
+ return runEvent(params, (args, origin) => {
5878
+ const componentArgs = args;
5879
+ if ("functionCall" in binding) return runtime.dispatcher.invoke(binding.functionCall["@call"], {
5880
+ ...componentArgs,
5881
+ ...resolveValues(surface, basePath, binding.functionCall.args)
5882
+ }, origin);
5883
+ const { event } = binding;
5884
+ const forwarded = {
5885
+ name: event.name,
5886
+ ...origin,
5887
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5888
+ userMessage: resolveUserMessage(surface, basePath, event.userMessage),
5889
+ context: {
5890
+ ...componentArgs,
5891
+ ...resolveValues(surface, basePath, event.context)
5892
+ }
5893
+ };
5894
+ return runtime.forwardEvent(forwarded, surface.agentId);
5895
+ });
5896
+ }
5897
+ /**
5898
+ * Runs one call of an event that matches a declared function: validates the
5899
+ * component's args with the event `parameters` (if any), then calls the
5900
+ * function, which validates them with its own schema. Never throws.
5901
+ */
5902
+ function invokeMatchedEvent(params) {
5903
+ const { runtime, functionName } = params;
5904
+ return runEvent(params, (componentArgs, origin) => runtime.dispatcher.invoke(functionName, componentArgs, origin));
5905
+ }
5906
+
5907
+ //#endregion
5908
+ //#region src/v2/generative-ui/theme.ts
5909
+ /**
5910
+ * The built-in dark values. The light values are the fallbacks in the
5911
+ * components, so a surface is light when no variable is set.
5912
+ */
5913
+ const DARK_THEME = {
5914
+ "--a2ui-color-text-default": "#ececec",
5915
+ "--a2ui-color-text-prose": "#ececec",
5916
+ "--a2ui-color-text-primary": "#ececec",
5917
+ "--a2ui-color-text-emphasis": "#fff",
5918
+ "--a2ui-color-text-secondary": "#b4b4b4",
5919
+ "--a2ui-color-text-tertiary": "#8e8e8e",
5920
+ "--a2ui-color-text-success": "#4fd1a5",
5921
+ "--a2ui-color-text-info": "#6cb6ff",
5922
+ "--a2ui-color-text-warning": "#e3b341",
5923
+ "--a2ui-color-text-caution": "#e3b341",
5924
+ "--a2ui-color-text-danger": "#ff7b72",
5925
+ "--a2ui-color-text-discovery": "#bc9cff",
5926
+ "--a2ui-color-surface": "#1f1f1f",
5927
+ "--a2ui-color-surface-secondary": "#2a2a2a",
5928
+ "--a2ui-color-surface-tertiary": "#3a3a3a",
5929
+ "--a2ui-color-surface-elevated": "#262626",
5930
+ "--a2ui-color-surface-elevated-secondary": "#2f2f2f",
5931
+ "--a2ui-color-surface-inverted": "#f2f2f2",
5932
+ "--a2ui-color-surface-soft": "#232323",
5933
+ "--a2ui-color-info": "rgba(80, 160, 255, 0.14)",
5934
+ "--a2ui-color-warning": "rgba(240, 180, 60, 0.14)",
5935
+ "--a2ui-color-caution": "rgba(240, 180, 60, 0.14)",
5936
+ "--a2ui-color-success": "rgba(60, 200, 150, 0.14)",
5937
+ "--a2ui-color-danger": "rgba(255, 110, 100, 0.14)",
5938
+ "--a2ui-color-discovery": "rgba(170, 130, 255, 0.14)",
5939
+ "--a2ui-color-info-soft": "rgba(80, 160, 255, 0.08)",
5940
+ "--a2ui-color-warning-soft": "rgba(240, 180, 60, 0.08)",
5941
+ "--a2ui-color-caution-soft": "rgba(240, 180, 60, 0.08)",
5942
+ "--a2ui-color-success-soft": "rgba(60, 200, 150, 0.08)",
5943
+ "--a2ui-color-danger-soft": "rgba(255, 110, 100, 0.08)",
5944
+ "--a2ui-color-discovery-soft": "rgba(170, 130, 255, 0.08)",
5945
+ "--a2ui-color-info-solid": "#3b8eea",
5946
+ "--a2ui-color-warning-solid": "#c99a2e",
5947
+ "--a2ui-color-caution-solid": "#c99a2e",
5948
+ "--a2ui-color-success-solid": "#2fae86",
5949
+ "--a2ui-color-danger-solid": "#e5534b",
5950
+ "--a2ui-color-discovery-solid": "#9a6ff0",
5951
+ "--a2ui-color-border-default": "rgba(255, 255, 255, 0.12)",
5952
+ "--a2ui-color-border-subtle": "rgba(255, 255, 255, 0.06)",
5953
+ "--a2ui-color-border-strong": "#4a4a4a",
5954
+ "--a2ui-color-border-info": "#2f5f8f",
5955
+ "--a2ui-color-border-warning": "#6b5420",
5956
+ "--a2ui-color-border-caution": "#6b5420",
5957
+ "--a2ui-color-border-success": "#1f5f4b",
5958
+ "--a2ui-color-border-danger": "#7a2f2b",
5959
+ "--a2ui-color-border-discovery": "#4f3a80",
5960
+ "--a2ui-color-border-control": "rgba(255, 255, 255, 0.2)",
5961
+ "--a2ui-color-accent": "#f2f2f2",
5962
+ "--a2ui-color-on-accent": "#0d0d0d",
5963
+ "--a2ui-color-panel": "#262626",
5964
+ "--a2ui-color-control": "#2f2f2f",
5965
+ "--a2ui-color-focus": "#3b9bff",
5966
+ "--a2ui-color-shimmer": "rgba(255, 255, 255, 0.12)",
5967
+ "--a2ui-color-chart-cursor": "rgba(255, 255, 255, 0.06)",
5968
+ "--a2ui-color-slider-track": "rgba(255, 255, 255, 0.1)",
5969
+ "--a2ui-color-badge-secondary": "rgba(255, 255, 255, 0.08)",
5970
+ "--a2ui-color-highlight-green": "#1d4a37",
5971
+ "--a2ui-color-highlight-orange": "#4d3418",
5972
+ "--a2ui-color-highlight-pink": "#4d2338",
5973
+ "--a2ui-shadow-xs": "0 1px 2px rgba(0, 0, 0, 0.5)",
5974
+ "--a2ui-shadow-sm": "0 1px 3px rgba(0, 0, 0, 0.5)",
5975
+ "--a2ui-shadow-soft": "0 1px 3px rgba(0, 0, 0, 0.3)",
5976
+ "--a2ui-shadow-md": "0 4px 12px rgba(0, 0, 0, 0.4)"
5977
+ };
5978
+ const VARIABLE_NAME = /^--a2ui-[a-z0-9-]+$/;
5979
+ const UNSAFE_VALUE = /[{};<>]/;
5980
+ /** Matches the `dark` class on an ancestor of a surface, or on the surface. */
5981
+ const DARK = ":where(.dark)";
5982
+ /** The default dark values, as a rule that any theme rule beats. */
5983
+ const DARK_THEME_CSS = `:where(.dark .a2ui-surface,.a2ui-surface.dark){${declarations(DARK_THEME)}}`;
5984
+ function declarations(values) {
5985
+ return Object.entries(values ?? {}).filter(([name, value]) => VARIABLE_NAME.test(name) && typeof value === "string" && !UNSAFE_VALUE.test(value)).map(([name, value]) => `${name}:${value}`).join(";");
5986
+ }
5987
+ /** A short, stable id for a stylesheet. */
5988
+ function hashOf(text) {
5989
+ let hash = 5381;
5990
+ for (let index = 0; index < text.length; index++) hash = hash * 33 ^ text.charCodeAt(index);
5991
+ return `t${(hash >>> 0).toString(36)}`;
5992
+ }
5993
+ /**
5994
+ * The stylesheet of a theme: its values on the surfaces that carry its id,
5995
+ * then its dark values in dark mode. `undefined` when the theme sets no
5996
+ * variable. Values that could break out of the rule are left out.
5997
+ *
5998
+ * @example
5999
+ * ```ts
6000
+ * themeStyleSheet({ "--a2ui-color-accent": "red" });
6001
+ * // { id: "t…", css: '.a2ui-surface[data-a2ui-theme="t…"]{--a2ui-color-accent:red}' }
6002
+ * ```
6003
+ */
6004
+ function themeStyleSheet(theme) {
6005
+ const { dark, ...base } = theme ?? {};
6006
+ const both = declarations(base);
6007
+ const darkOnly = declarations(dark);
6008
+ if (!both && !darkOnly) return void 0;
6009
+ const id = hashOf(`${both}|${darkOnly}`);
6010
+ const self = `.a2ui-surface[data-a2ui-theme="${id}"]`;
6011
+ return {
6012
+ id,
6013
+ css: [both && `${self}{${both}}`, darkOnly && `${DARK} ${self},${self}${DARK}{${darkOnly}}`].filter(Boolean).join("")
6014
+ };
6015
+ }
6016
+
6017
+ //#endregion
6018
+ //#region src/v2/generative-ui/SurfaceView.tsx
6019
+ const NO_ANCESTORS = [];
6020
+ const ROOT_STYLE = { display: "contents" };
6021
+ const undefinedSnapshot = () => void 0;
6022
+ const noopSubscribe = () => () => {};
6023
+ const zeroSnapshot = () => 0;
6024
+ /** A "multiple" slot value that repeats a component for each list item. */
6025
+ function isTemplateChildren(value) {
6026
+ return typeof value === "object" && value !== null && "componentId" in value && typeof value.componentId === "string" && "path" in value && typeof value.path === "string";
6027
+ }
6028
+ function SurfaceView({ surface }) {
6029
+ const runtime = useRequiredGenerativeUIRuntime();
6030
+ const { theme } = runtime;
6031
+ const sheet = (0, react.useMemo)(() => themeStyleSheet(theme), [theme]);
6032
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
6033
+ className: "a2ui-surface",
6034
+ "data-generative-ui-root": surface.surfaceId,
6035
+ "data-a2ui-theme": sheet?.id,
6036
+ style: ROOT_STYLE,
6037
+ children: [sheet ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { dangerouslySetInnerHTML: { __html: sheet.css } }) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceBoundary, {
6038
+ surfaceId: surface.surfaceId,
6039
+ runtime,
6040
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
6041
+ surface,
6042
+ componentId: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
6043
+ basePath: void 0,
6044
+ ancestors: NO_ANCESTORS
6045
+ })
6046
+ })]
6047
+ });
6048
+ }
6049
+ /**
6050
+ * Resolves a component by id. Subscribes to the manager rather than web_core's
6051
+ * `onCreated`/`onDeleted`: web_core's EventEmitter awaits each listener in turn,
6052
+ * so with several subscribers (one per slotted child, or one per mount of the
6053
+ * same surface) all but the first are notified a microtask late. That is only
6054
+ * visible inside synchronous flushes such as `act()` / `flushSync`, where the
6055
+ * old tree would still be on screen, but it makes updates order-dependent.
6056
+ * The manager notifies synchronously once an ingest has been fully applied.
6057
+ */
6058
+ function useComponentModel(manager, model, id) {
6059
+ return (0, react.useSyncExternalStore)(manager.subscribe, () => model.componentsModel.get(id), undefinedSnapshot);
6060
+ }
6061
+ /** Same reasoning as `useComponentModel`: never rely on web_core's emitters. */
6062
+ function useComponentProperties(manager, component) {
6063
+ return (0, react.useSyncExternalStore)(manager.subscribe, () => component?.properties, undefinedSnapshot);
6064
+ }
6065
+ /**
6066
+ * The id of a node in the ancestor list. A template renders the same
6067
+ * component once per item, so the item path is part of the id. A real cycle
6068
+ * repeats both.
6069
+ */
6070
+ function scopedId(componentId, basePath) {
6071
+ return `${basePath ?? ""}#${componentId}`;
6072
+ }
6073
+ const NodeView = (0, react.memo)(function NodeView({ surface, componentId, basePath, ancestors }) {
6074
+ const runtime = useRequiredGenerativeUIRuntime();
6075
+ const component = useComponentModel(runtime.manager, surface.model, componentId);
6076
+ const properties = useComponentProperties(runtime.manager, component);
6077
+ if (ancestors.includes(scopedId(componentId, basePath))) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
6078
+ message: `cyclic reference to ${componentId}`,
6079
+ componentId
6080
+ });
6081
+ if (!component || !properties) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodePlaceholder, { componentId });
6082
+ const definition = runtime.ui.components.get(component.type);
6083
+ if (!definition) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
6084
+ message: `unknown component "${component.type}"`,
6085
+ componentId
6086
+ });
6087
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeBoundary, {
6088
+ surfaceId: surface.surfaceId,
6089
+ componentId,
6090
+ revision: properties,
6091
+ runtime,
6092
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ResolvedNode, {
6093
+ surface,
6094
+ componentId,
6095
+ definition,
6096
+ properties,
6097
+ runtime,
6098
+ basePath,
6099
+ ancestors
6100
+ })
6101
+ }, component.type);
6102
+ });
6103
+ /**
6104
+ * Renders the component of a template once for each item of the list at the
6105
+ * template path, keyed by index. Renders nothing when there is no list.
6106
+ */
6107
+ function TemplateChildren({ surface, template, basePath, ancestors }) {
6108
+ const dataModel = surface.model.dataModel;
6109
+ const listPath = resolvePath(template.path, basePath);
6110
+ const subscribe = (0, react.useCallback)((onChange) => {
6111
+ const subscription = dataModel.subscribe(listPath, onChange);
6112
+ return () => subscription.unsubscribe();
6113
+ }, [dataModel, listPath]);
6114
+ const getCount = () => {
6115
+ const list = dataModel.get(listPath);
6116
+ return Array.isArray(list) ? list.length : 0;
6117
+ };
6118
+ const count = (0, react.useSyncExternalStore)(subscribe, getCount, zeroSnapshot);
6119
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: Array.from({ length: count }, (_, index) => index).map((index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
6120
+ surface,
6121
+ componentId: template.componentId,
6122
+ basePath: joinPath(listPath, String(index)),
6123
+ ancestors
6124
+ }, index)) });
6125
+ }
6126
+ /**
6127
+ * The props the model sets, with their dynamic values resolved from the
6128
+ * surface data model: `{"@path"}` bindings, `{"@call"}` function values and
6129
+ * `{"@call":"@index"}` in a template, at any depth. A literal writable prop
6130
+ * that the component set shows the local value from `overrides`. Bound
6131
+ * props, events and slots are left out, and so are the keys of the A2UI
6132
+ * component envelope; `accessibility` is resolved the same way and given
6133
+ * on its own.
6134
+ *
6135
+ * A prop is resolved again only when its raw value or a data model value it
6136
+ * read has changed, so the result keeps its identity otherwise. A function
6137
+ * value that cannot be computed gives a problem instead of values.
6138
+ */
6139
+ function useModelDataProps(surface, definition, properties, basePath, overrides) {
6140
+ const dataModel = surface.model.dataModel;
6141
+ const units = (0, react.useMemo)(() => {
6142
+ const list = [];
6143
+ for (const key of Object.keys(properties)) {
6144
+ if (definition.events?.[key] || definition.slots?.[key] || Object.hasOwn(definition.selectors, key) || _copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS.has(key)) continue;
6145
+ list.push({
6146
+ key,
6147
+ raw: properties[key]
6148
+ });
6149
+ }
6150
+ const a11y = properties.accessibility;
6151
+ if (typeof a11y === "object" && a11y !== null && !Array.isArray(a11y)) for (const [field, raw] of Object.entries(a11y)) list.push({
6152
+ key: `accessibility/${field}`,
6153
+ raw,
6154
+ field
6155
+ });
6156
+ return list;
6157
+ }, [properties, definition]);
6158
+ const [, rerender] = (0, react.useReducer)((n) => n + 1, 0);
6159
+ const cache = (0, react.useRef)(/* @__PURE__ */ new Map());
6160
+ const values = {};
6161
+ const a11yValues = {};
6162
+ const paths = /* @__PURE__ */ new Set();
6163
+ let problem;
6164
+ const next = /* @__PURE__ */ new Map();
6165
+ for (const { key, raw, field } of units) {
6166
+ const cached = cache.current.get(key);
6167
+ const isFresh = cached !== void 0 && cached.raw === raw && cached.basePath === basePath && [...cached.reads].every(([path, value]) => Object.is(dataModel.get(path), value));
6168
+ const resolve = () => {
6169
+ const resolved = tryResolveDynamicValue(raw, {
6170
+ data: dataModel,
6171
+ basePath
6172
+ }, { isChecks: key === "checks" });
6173
+ const reads = /* @__PURE__ */ new Map();
6174
+ for (const path of resolved.paths) reads.set(path, dataModel.get(path));
6175
+ return {
6176
+ raw,
6177
+ basePath,
6178
+ reads,
6179
+ outcome: resolved.ok ? {
6180
+ ok: true,
6181
+ value: resolved.value
6182
+ } : {
6183
+ ok: false,
6184
+ message: resolved.error.message
6185
+ }
6186
+ };
6187
+ };
6188
+ const entry = isFresh && cached ? cached : resolve();
6189
+ next.set(key, entry);
6190
+ if (field !== void 0) {
6191
+ if (entry.outcome.ok) a11yValues[field] = entry.outcome.value;
6192
+ } else if (entry.outcome.ok) values[key] = entry.outcome.value;
6193
+ else problem ?? (problem = `${key}: ${entry.outcome.message}`);
6194
+ for (const path of entry.reads.keys()) paths.add(path);
6195
+ }
6196
+ cache.current = next;
6197
+ const accessibility = readAccessibility(a11yValues);
6198
+ for (const [key, value] of Object.entries(overrides)) if (!(0, _copilotkit_shared.isPathBinding)(properties[key])) values[key] = value;
6199
+ const rendered = (0, react.useRef)(next);
6200
+ rendered.current = next;
6201
+ const pathKey = [...paths].sort().join("\n");
6202
+ (0, react.useEffect)(() => {
6203
+ const list = pathKey === "" ? [] : pathKey.split("\n");
6204
+ const onChange = () => {
6205
+ cache.current = /* @__PURE__ */ new Map();
6206
+ rerender();
6207
+ };
6208
+ const subscriptions = list.map((path) => dataModel.subscribe(path, onChange));
6209
+ if ([...rendered.current.values()].some((entry) => [...entry.reads].some(([path, value]) => !Object.is(dataModel.get(path), value)))) rerender();
6210
+ return () => subscriptions.forEach((s) => s.unsubscribe());
6211
+ }, [dataModel, pathKey]);
6212
+ const stable = (0, react.useRef)({
6213
+ ok: true,
6214
+ values: {},
6215
+ accessibility: void 0
6216
+ });
6217
+ const result = problem === void 0 ? {
6218
+ ok: true,
6219
+ values,
6220
+ accessibility
6221
+ } : {
6222
+ ok: false,
6223
+ problem
6224
+ };
6225
+ const last = stable.current;
6226
+ if (!(result.ok && last.ok ? shallowEqual(last.values, result.values) && shallowEqual(last.accessibility ?? {}, result.accessibility ?? {}) : !result.ok && !last.ok && last.problem === result.problem)) stable.current = result;
6227
+ return stable.current;
6228
+ }
6229
+ const NO_SELECTION = {
6230
+ ok: true,
6231
+ values: {}
6232
+ };
6233
+ function isSameSelection(a, b) {
6234
+ if (a.ok && b.ok) return shallowEqual(a.values, b.values);
6235
+ if (!a.ok && !b.ok) return a.problem === b.problem;
6236
+ return false;
6237
+ }
6238
+ /** Runs every selector of a node. A selector that throws gives a problem. */
6239
+ function select(definition, state, modelProps) {
6240
+ const values = {};
6241
+ const selectors = Object.entries(definition.selectors);
6242
+ for (const [key, selector] of selectors) try {
6243
+ values[key] = selector(state, modelProps);
6244
+ } catch (error) {
6245
+ return {
6246
+ ok: false,
6247
+ problem: `${key}: selector threw: ${error instanceof Error ? error.message : String(error)}`
6248
+ };
6249
+ }
6250
+ return {
6251
+ ok: true,
6252
+ values
6253
+ };
6254
+ }
6255
+ /**
6256
+ * The values of the bound props of a node, read from the app state.
6257
+ *
6258
+ * The selectors run again only when the state object or the parsed model
6259
+ * props change. When the new values are shallow-equal to the last ones, the
6260
+ * last snapshot is kept. So the node re-renders only when a selected value
6261
+ * changes. A selector that returns a new array on each call cannot cause a
6262
+ * render loop: with the same inputs, the cached snapshot comes back.
6263
+ *
6264
+ * A node without bound props does not subscribe to the state.
6265
+ */
6266
+ function useSelection(manager, definition, modelProps) {
6267
+ const hasSelectors = Object.keys(definition.selectors).length > 0;
6268
+ const cache = (0, react.useRef)(void 0);
6269
+ const getSnapshot = () => {
6270
+ if (!hasSelectors || modelProps === void 0) return NO_SELECTION;
6271
+ const state = manager.getState();
6272
+ const cached = cache.current;
6273
+ if (cached !== void 0 && cached.state === state && cached.modelProps === modelProps) return cached.selection;
6274
+ const next = select(definition, state, modelProps);
6275
+ const selection = cached !== void 0 && isSameSelection(cached.selection, next) ? cached.selection : next;
6276
+ cache.current = {
6277
+ state,
6278
+ modelProps,
6279
+ selection
6280
+ };
6281
+ return selection;
6282
+ };
6283
+ return (0, react.useSyncExternalStore)(hasSelectors ? manager.subscribe : noopSubscribe, getSnapshot, getSnapshot);
6284
+ }
6285
+ /**
6286
+ * Checks the model-set props with the props schema before the selectors run.
6287
+ * The bound props are not set yet, so their issues do not count. Neither do
6288
+ * issues with no path (a check over several props), which the full check
6289
+ * after the selectors reports.
6290
+ */
6291
+ function checkModelProps(definition, modelData) {
6292
+ if (!definition.props) return {
6293
+ ok: true,
6294
+ values: {}
6295
+ };
6296
+ let values = modelData;
6297
+ let result = validateSchemaSync(definition.props, values);
6298
+ if (!result.success) {
6299
+ const unset = withoutRejectedNulls(values, result.issues);
6300
+ if (unset) {
6301
+ values = unset;
6302
+ result = validateSchemaSync(definition.props, values);
6303
+ }
6304
+ }
6305
+ if (!result.success) {
6306
+ const issues = result.issues.filter((issue) => {
6307
+ const key = issueKey(issue);
6308
+ return key === void 0 ? isAsyncIssue(issue) : !Object.hasOwn(definition.selectors, key);
6309
+ });
6310
+ if (issues.length > 0) return {
6311
+ ok: false,
6312
+ problem: formatIssues(issues)
6313
+ };
6314
+ }
6315
+ return {
6316
+ ok: true,
6317
+ values
6318
+ };
6319
+ }
6320
+ /**
6321
+ * The data props of a node, in three steps: check the model-set props with
6322
+ * the props schema, run the selectors with them, then parse all props with
6323
+ * the props schema. Gives the reason when a step fails.
6324
+ */
6325
+ function useDataProps(runtime, surface, definition, properties, basePath, overrides) {
6326
+ const modelData = useModelDataProps(surface, definition, properties, basePath, overrides);
6327
+ const modelCheck = (0, react.useMemo)(() => modelData.ok ? checkModelProps(definition, modelData.values) : modelData, [definition, modelData]);
6328
+ const selection = useSelection(runtime.manager, definition, modelCheck.ok ? modelCheck.values : void 0);
6329
+ const accessibility = modelData.ok ? modelData.accessibility : void 0;
6330
+ return (0, react.useMemo)(() => {
6331
+ if (!modelCheck.ok) return modelCheck;
6332
+ if (!selection.ok) return selection;
6333
+ if (!definition.props) return {
6334
+ ok: true,
6335
+ props: {},
6336
+ accessibility
6337
+ };
6338
+ const input = {
6339
+ ...modelCheck.values,
6340
+ ...selection.values
6341
+ };
6342
+ let parsed = validateSchemaSync(definition.props, input);
6343
+ if (!parsed.success) {
6344
+ const unset = withoutRejectedNulls(input, parsed.issues);
6345
+ if (unset) parsed = validateSchemaSync(definition.props, unset);
6346
+ }
6347
+ if (!parsed.success) return {
6348
+ ok: false,
6349
+ problem: formatIssues(parsed.issues)
6350
+ };
6351
+ return {
6352
+ ok: true,
6353
+ props: parsed.data,
6354
+ accessibility
6355
+ };
6356
+ }, [
6357
+ definition,
6358
+ modelCheck,
6359
+ selection,
6360
+ accessibility
6361
+ ]);
6362
+ }
6363
+ /**
6364
+ * The event props of a node. A matched event (one that matches a declared
6365
+ * function) is always bound. An unmatched event is bound only when the model
6366
+ * bound it.
6367
+ */
6368
+ function useEventProps(runtime, surface, componentId, definition, properties, basePath) {
6369
+ const latest = (0, react.useRef)(properties);
6370
+ latest.current = properties;
6371
+ const boundNames = Object.keys(definition.events ?? {}).filter((name) => Object.hasOwn(definition.eventFunctions, name) || (0, _copilotkit_shared.isActionBinding)(properties[name])).join("|");
6372
+ return (0, react.useMemo)(() => {
6373
+ const handlers = {};
6374
+ const names = boundNames ? boundNames.split("|") : [];
6375
+ for (const name of names) {
6376
+ const call = {
6377
+ runtime,
6378
+ surface,
6379
+ componentId,
6380
+ name,
6381
+ parameters: definition.events?.[name]?.parameters
6382
+ };
6383
+ const functionName = Object.hasOwn(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
6384
+ handlers[name] = functionName === void 0 ? (args) => invokeBoundEvent({
6385
+ ...call,
6386
+ binding: latest.current[name],
6387
+ basePath,
6388
+ args
6389
+ }) : (args) => invokeMatchedEvent({
6390
+ ...call,
6391
+ functionName,
6392
+ args
6393
+ });
6394
+ }
6395
+ return handlers;
6396
+ }, [
6397
+ boundNames,
6398
+ runtime,
6399
+ surface,
6400
+ componentId,
6401
+ definition,
6402
+ basePath
6403
+ ]);
6404
+ }
6405
+ /**
6406
+ * The setter props of a node: `setValue` for the writable prop `value`. For
6407
+ * a prop the model bound to `{"@path"}`, the setter writes the data model
6408
+ * and makes the path user-owned. For a literal prop, it sets `overrides`, a
6409
+ * local value of this mounted node. The setters keep their identity.
6410
+ */
6411
+ function useSetterProps(runtime, surface, componentId, definition, properties, basePath) {
6412
+ const [overrides, setOverrides] = (0, react.useState)({});
6413
+ const latest = (0, react.useRef)(properties);
6414
+ latest.current = properties;
6415
+ return {
6416
+ overrides,
6417
+ setters: (0, react.useMemo)(() => {
6418
+ const result = {};
6419
+ const writable = definition.writable ?? [];
6420
+ for (const key of writable) result[setterNameOf(key)] = (value) => {
6421
+ const binding = latest.current[key];
6422
+ if (!(0, _copilotkit_shared.isPathBinding)(binding)) {
6423
+ setOverrides((current) => ({
6424
+ ...current,
6425
+ [key]: value
6426
+ }));
6427
+ return;
6428
+ }
6429
+ try {
6430
+ runtime.manager.setOwnedValue(surface.key, resolvePath(binding["@path"], basePath), value);
6431
+ } catch (cause) {
6432
+ const message = cause instanceof Error ? cause.message : String(cause);
6433
+ reportErrorSafely(runtime, {
6434
+ kind: "props",
6435
+ surfaceId: surface.surfaceId,
6436
+ componentId,
6437
+ error: /* @__PURE__ */ new Error(`${setterNameOf(key)}: ${message}`)
6438
+ });
6439
+ }
6440
+ };
6441
+ return result;
6442
+ }, [
6443
+ runtime,
6444
+ surface,
6445
+ componentId,
6446
+ definition,
6447
+ basePath
6448
+ ])
6449
+ };
6450
+ }
6451
+ function useSlotProps(surface, definition, properties, componentId, basePath, ancestors) {
6452
+ return (0, react.useMemo)(() => {
6453
+ const childAncestors = [...ancestors, scopedId(componentId, basePath)];
6454
+ const slots = {};
6455
+ for (const [name, kind] of Object.entries(definition.slots ?? {})) {
6456
+ const value = properties[name];
6457
+ if (kind === "single" && typeof value === "string") slots[name] = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
6458
+ surface,
6459
+ componentId: value,
6460
+ basePath,
6461
+ ancestors: childAncestors
6462
+ });
6463
+ else if (kind === "multiple" && isTemplateChildren(value)) slots[name] = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TemplateChildren, {
6464
+ surface,
6465
+ template: value,
6466
+ basePath,
6467
+ ancestors: childAncestors
6468
+ });
6469
+ else if (kind === "multiple" && Array.isArray(value)) slots[name] = [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
6470
+ surface,
6471
+ componentId: id,
6472
+ basePath,
6473
+ ancestors: childAncestors
6474
+ }, id));
6475
+ }
6476
+ return slots;
6477
+ }, [
6478
+ surface,
6479
+ definition,
6480
+ properties,
6481
+ componentId,
6482
+ basePath,
6483
+ ancestors
6484
+ ]);
6485
+ }
6486
+ /**
6487
+ * The parsed data props with every typed child reference (`child()`,
6488
+ * `childList()`, at any depth) replaced by the rendered component. Without
6489
+ * references, the parsed props come back as they are.
6490
+ */
6491
+ function useChildRefProps(surface, refs, props, componentId, basePath, ancestors) {
6492
+ return (0, react.useMemo)(() => {
6493
+ if (props === void 0 || refs.length === 0) return props;
6494
+ const childAncestors = [...ancestors, scopedId(componentId, basePath)];
6495
+ const render = (kind, value) => {
6496
+ if (kind === "single") return typeof value === "string" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
6497
+ surface,
6498
+ componentId: value,
6499
+ basePath,
6500
+ ancestors: childAncestors
6501
+ }) : void 0;
6502
+ if (isTemplateChildren(value)) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TemplateChildren, {
6503
+ surface,
6504
+ template: value,
6505
+ basePath,
6506
+ ancestors: childAncestors
6507
+ });
6508
+ if (!Array.isArray(value)) return void 0;
6509
+ return [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
6510
+ surface,
6511
+ componentId: id,
6512
+ basePath,
6513
+ ancestors: childAncestors
6514
+ }, id));
6515
+ };
6516
+ let result = props;
6517
+ for (const ref of refs) result = (0, _copilotkit_shared.mapAtChildRef)(result, ref.path, (found) => render(ref.kind, found));
6518
+ return result;
6519
+ }, [
6520
+ surface,
6521
+ refs,
6522
+ props,
6523
+ componentId,
6524
+ basePath,
6525
+ ancestors
6526
+ ]);
6527
+ }
6528
+ function ResolvedNode({ surface, componentId, definition, properties, runtime, basePath, ancestors }) {
6529
+ const { overrides, setters } = useSetterProps(runtime, surface, componentId, definition, properties, basePath);
6530
+ const dataProps = useDataProps(runtime, surface, definition, properties, basePath, overrides);
6531
+ const eventProps = useEventProps(runtime, surface, componentId, definition, properties, basePath);
6532
+ const slotProps = useSlotProps(surface, definition, properties, componentId, basePath, ancestors);
6533
+ const childRefProps = useChildRefProps(surface, definition.childRefs, dataProps.ok ? dataProps.props : void 0, componentId, basePath, ancestors);
6534
+ const accessibility = dataProps.ok ? dataProps.accessibility : void 0;
6535
+ const nodeContext = (0, react.useMemo)(() => ({
6536
+ surfaceKey: surface.key,
6537
+ surfaceId: surface.surfaceId,
6538
+ componentId,
6539
+ accessibility
6540
+ }), [
6541
+ surface.key,
6542
+ surface.surfaceId,
6543
+ componentId,
6544
+ accessibility
6545
+ ]);
6546
+ const problem = dataProps.ok ? void 0 : dataProps.problem;
6547
+ (0, react.useEffect)(() => {
6548
+ if (problem) reportErrorSafely(runtime, {
6549
+ kind: "props",
6550
+ surfaceId: surface.surfaceId,
6551
+ componentId,
6552
+ error: /* @__PURE__ */ new Error(`Invalid props: ${problem}`)
6553
+ });
6554
+ }, [
6555
+ problem,
6556
+ runtime,
6557
+ surface.surfaceId,
6558
+ componentId
6559
+ ]);
6560
+ if (!dataProps.ok) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
6561
+ message: `invalid props (${problem})`,
6562
+ componentId
6563
+ });
6564
+ const Component = definition.component;
6565
+ const rendered = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Component, {
6566
+ ...childRefProps,
6567
+ ...eventProps,
6568
+ ...slotProps,
6569
+ ...setters
6570
+ });
6571
+ const hasEnvelope = properties.accessibility !== void 0 && definition.accessibility !== "self";
6572
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GenerativeUINodeContext.Provider, {
6573
+ value: nodeContext,
6574
+ children: hasEnvelope ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
6575
+ "data-a2ui-accessibility": "",
6576
+ style: ROOT_STYLE,
6577
+ ...wrapperAria(accessibilityAttributes(accessibility)),
6578
+ children: rendered
6579
+ }) : rendered
6580
+ });
6581
+ }
6582
+
6583
+ //#endregion
6584
+ //#region src/v2/generative-ui/chat.tsx
6585
+ const GenerativeUIChatSlotContext = (0, react.createContext)(void 0);
6586
+ function DefaultGenerativeUIChatCard({ surfaceId, isStreaming, error, children }) {
6587
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
6588
+ "data-generative-ui-chat-surface": surfaceId,
6589
+ className: "cpk:my-2 cpk:w-full cpk:rounded-xl cpk:border cpk:border-gray-200 cpk:p-3",
6590
+ children: [children, error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
6591
+ role: "alert",
6592
+ className: "cpk:mt-2 cpk:text-xs cpk:text-red-600",
6593
+ children: "Part of this UI couldn't be shown."
6594
+ })]
6595
+ });
6596
+ }
6597
+ const ContentSchema = zod.z.object({
6598
+ surfaceId: zod.z.string(),
6599
+ target: zod.z.string(),
6600
+ catalogId: zod.z.string(),
6601
+ operations: zod.z.array(zod.z.any()),
6602
+ status: zod.z.enum([
6603
+ "streaming",
6604
+ "ready",
6605
+ "error"
6606
+ ]),
6607
+ rejected: zod.z.array(zod.z.object({
6608
+ index: zod.z.number(),
6609
+ reason: zod.z.string()
6610
+ })).default([])
6611
+ }).passthrough();
6612
+ function GenerativeUIChatActivity({ content, agent }) {
6613
+ const runtime = useGenerativeUIRuntime();
6614
+ const threadId = useCopilotChatConfiguration()?.threadId ?? agent?.threadId;
6615
+ const Wrapper = (0, react.useContext)(GenerativeUIChatSlotContext) ?? DefaultGenerativeUIChatCard;
6616
+ useManagerVersion(runtime);
6617
+ (0, react.useLayoutEffect)(() => {
6618
+ if (runtime && threadId) runtime.manager.ingest(threadId, agent?.agentId, content);
6619
+ }, [
6620
+ runtime,
6621
+ threadId,
6622
+ agent?.agentId,
6623
+ content
6624
+ ]);
6625
+ if (!runtime || !threadId || content.target !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET) return null;
6626
+ const surface = runtime.manager.getSurface(threadId, content.surfaceId) ?? runtime.manager.getFailedSurface(threadId, content.surfaceId);
6627
+ if (!surface) return null;
6628
+ const rejected = [...content.rejected ?? [], ...surface.clientRejected];
6629
+ const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
6630
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Wrapper, {
6631
+ surfaceId: content.surfaceId,
6632
+ isStreaming: content.status === "streaming",
6633
+ error,
6634
+ rejected,
6635
+ children: surface.failed ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceView, { surface })
6636
+ });
6637
+ }
6638
+ function createGenerativeUIActivityRenderer() {
6639
+ return {
6640
+ activityType: _copilotkit_shared.GENERATIVE_UI_ACTIVITY_TYPE,
6641
+ content: ContentSchema,
6642
+ render: GenerativeUIChatActivity
6643
+ };
6644
+ }
6645
+ /**
6646
+ * Shows nothing in the chat for an agent-called function. The root reads the
6647
+ * function-call activities from the messages and runs them. This renderer
6648
+ * only keeps a wildcard ("*") activity renderer from showing them.
6649
+ */
6650
+ function createGenerativeUIFunctionCallActivityRenderer() {
6651
+ return {
6652
+ activityType: _copilotkit_shared.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,
6653
+ content: zod.z.unknown(),
6654
+ render: () => null
6655
+ };
6656
+ }
6657
+ /** Hides the raw `render_ui` tool call; the surface activity owns the UX. */
6658
+ function GenerativeUIToolCallRenderer() {
6659
+ const { copilotkit } = useCopilotKit();
6660
+ (0, react.useEffect)(() => {
6661
+ const renderer = defineToolCallRenderer({
6662
+ name: _copilotkit_shared.GENERATIVE_UI_RENDER_TOOL,
6663
+ args: zod.z.any(),
6664
+ render: () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {})
6665
+ });
6666
+ const existing = copilotkit._renderToolCalls ?? [];
6667
+ copilotkit.setRenderToolCalls([...existing.filter((rc) => rc.name !== _copilotkit_shared.GENERATIVE_UI_RENDER_TOOL), renderer]);
6668
+ }, [copilotkit]);
6669
+ return null;
6670
+ }
6671
+
2226
6672
  //#endregion
2227
6673
  //#region src/v2/providers/CopilotKitProvider.tsx
2228
6674
  const zodToJsonSchemaAdapter = (schema, options) => {
@@ -2269,7 +6715,7 @@ react_markdown = __toESM(react_markdown);
2269
6715
  return value;
2270
6716
  }
2271
6717
  /** Provide a shared core instance and synchronize runtime, tool, and UI configuration. */
2272
- const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY_HEADERS, credentials, messageFilter, publicApiKey, publicLicenseKey, licenseToken, properties = EMPTY_PROPERTIES, agents__unsafe_dev_only: agents = EMPTY_AGENTS, selfManagedAgents = EMPTY_AGENTS, renderToolCalls, renderActivityMessages, renderCustomMessages, frontendTools, humanInTheLoop, openGenerativeUI, enableInspector, agentId, showIntelligenceIndicator = true, useSingleEndpoint, onError, a2ui, mcpApps, defaultThrottleMs, debug, learning }) => {
6718
+ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY_HEADERS, credentials, messageFilter, publicApiKey, publicLicenseKey, licenseToken, properties = EMPTY_PROPERTIES, agents__unsafe_dev_only: agents = EMPTY_AGENTS, selfManagedAgents = EMPTY_AGENTS, renderToolCalls, renderActivityMessages, renderCustomMessages, frontendTools, humanInTheLoop, openGenerativeUI, enableInspector, agentId, showIntelligenceIndicator = true, useSingleEndpoint, onError, a2ui, generativeUI, mcpApps, defaultThrottleMs, debug, learning }) => {
2273
6719
  const learningConfig = (0, react.useMemo)(() => toLearningConfig(learning), [learning]);
2274
6720
  const [shouldRenderInspector, setShouldRenderInspector] = (0, react.useState)(false);
2275
6721
  const [inspectorVisible, setInspectorVisible] = (0, react.useState)(false);
@@ -2291,6 +6737,7 @@ react_markdown = __toESM(react_markdown);
2291
6737
  const openGenUIActive = runtimeOpenGenUIEnabled || !!openGenerativeUI;
2292
6738
  const a2uiCatalogProvided = !!a2ui?.catalog;
2293
6739
  const a2uiActive = runtimeA2UIEnabled || a2uiCatalogProvided;
6740
+ const generativeUIActive = !!generativeUI?.ui;
2294
6741
  const [runtimeLicenseStatus, setRuntimeLicenseStatus] = (0, react.useState)(void 0);
2295
6742
  const [runtimeEntitlements, setRuntimeEntitlements] = (0, react.useState)(void 0);
2296
6743
  const [runtimeEntitlementRetryPending, setRuntimeEntitlementRetryPending] = (0, react.useState)(false);
@@ -2344,10 +6791,12 @@ react_markdown = __toESM(react_markdown);
2344
6791
  loadingComponent: a2ui?.loadingComponent,
2345
6792
  recovery: a2ui?.recovery
2346
6793
  }));
6794
+ if (generativeUIActive) renderers.push(createGenerativeUIActivityRenderer(), createGenerativeUIFunctionCallActivityRenderer());
2347
6795
  return renderers;
2348
6796
  }, [
2349
6797
  a2uiActive,
2350
6798
  openGenUIActive,
6799
+ generativeUIActive,
2351
6800
  a2ui,
2352
6801
  filteredCatalog,
2353
6802
  mcpAppsAllowSameOrigin
@@ -2514,6 +6963,7 @@ react_markdown = __toESM(react_markdown);
2514
6963
  if (defaultThrottleMs !== void 0) copilotkitRef.current.setDefaultThrottleMs(defaultThrottleMs);
2515
6964
  }
2516
6965
  const copilotkit = copilotkitRef.current;
6966
+ const generativeUIRuntime = useGenerativeUIRoot(copilotkit, generativeUI);
2517
6967
  (0, react.useEffect)(() => {
2518
6968
  if (!rawCatalog) return;
2519
6969
  if (!(rawCatalog instanceof _copilotkit_a2ui_renderer.Catalog)) return;
@@ -2752,6 +7202,7 @@ react_markdown = __toESM(react_markdown);
2752
7202
  value: licenseContextValue,
2753
7203
  children: [
2754
7204
  a2uiActive && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UIBuiltInToolCallRenderer, {}),
7205
+ generativeUIActive && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GenerativeUIToolCallRenderer, {}),
2755
7206
  a2uiActive && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(A2UICatalogContext, {
2756
7207
  catalog: filteredCatalog,
2757
7208
  includeSchema: a2ui?.includeSchema
@@ -2760,7 +7211,10 @@ react_markdown = __toESM(react_markdown);
2760
7211
  value: inspectorContextValue,
2761
7212
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitAgentIdContext.Provider, {
2762
7213
  value: agentId,
2763
- children
7214
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GenerativeUIRuntimeContext.Provider, {
7215
+ value: generativeUIRuntime,
7216
+ children
7217
+ })
2764
7218
  }), shouldRenderInspector ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitInspector, {
2765
7219
  core: copilotkit,
2766
7220
  openRequest: inspectorOpenRequest,