@copilotkit/react-core 1.84.2-canary.1793809041 → 1.84.2-canary.openbot-intel-fixes

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +1 -1
  2. package/dist/MarkdownSurfaces-3cGU5_0H.cjs +1619 -0
  3. package/dist/MarkdownSurfaces-3cGU5_0H.cjs.map +1 -0
  4. package/dist/MarkdownSurfaces-D-W4f9Dy.mjs +1442 -0
  5. package/dist/MarkdownSurfaces-D-W4f9Dy.mjs.map +1 -0
  6. package/dist/{copilotkit-OVo9Xjmp.d.cts → copilotkit-CuTAoQF2.d.cts} +5 -5
  7. package/dist/{copilotkit-OVo9Xjmp.d.cts.map → copilotkit-CuTAoQF2.d.cts.map} +1 -1
  8. package/dist/{copilotkit-BhV8iuX5.cjs → copilotkit-DYtl9zj0.cjs} +63 -1375
  9. package/dist/copilotkit-DYtl9zj0.cjs.map +1 -0
  10. package/dist/{copilotkit-CFqSAotl.d.mts → copilotkit-Dn4PbHJV.d.mts} +5 -5
  11. package/dist/{copilotkit-CFqSAotl.d.mts.map → copilotkit-Dn4PbHJV.d.mts.map} +1 -1
  12. package/dist/{copilotkit-dNtiaQqU.mjs → copilotkit-UHD9sXsS.mjs} +51 -1363
  13. package/dist/copilotkit-UHD9sXsS.mjs.map +1 -0
  14. package/dist/index.cjs +2 -2
  15. package/dist/index.d.cts +2 -2
  16. package/dist/index.d.mts +2 -2
  17. package/dist/index.mjs +2 -2
  18. package/dist/index.umd.js +165 -3347
  19. package/dist/index.umd.js.map +1 -1
  20. package/dist/runtime-context-DrVNUYLi.d.cts +228 -0
  21. package/dist/runtime-context-DrVNUYLi.d.cts.map +1 -0
  22. package/dist/runtime-context-Er5UIbZA.d.mts +228 -0
  23. package/dist/runtime-context-Er5UIbZA.d.mts.map +1 -0
  24. package/dist/v2/generative-ui.cjs +687 -2963
  25. package/dist/v2/generative-ui.cjs.map +1 -1
  26. package/dist/v2/generative-ui.d.cts +4506 -4712
  27. package/dist/v2/generative-ui.d.cts.map +1 -1
  28. package/dist/v2/generative-ui.d.mts +4506 -4712
  29. package/dist/v2/generative-ui.d.mts.map +1 -1
  30. package/dist/v2/generative-ui.mjs +299 -2585
  31. package/dist/v2/generative-ui.mjs.map +1 -1
  32. package/dist/v2/index.cjs +2 -20
  33. package/dist/v2/index.d.cts +3 -3
  34. package/dist/v2/index.d.mts +3 -3
  35. package/dist/v2/index.mjs +3 -3
  36. package/dist/v2/index.umd.js +156 -3377
  37. package/dist/v2/index.umd.js.map +1 -1
  38. package/package.json +11 -11
  39. package/dist/MarkdownSurfaces-DV9P0Gi9.mjs +0 -3573
  40. package/dist/MarkdownSurfaces-DV9P0Gi9.mjs.map +0 -1
  41. package/dist/MarkdownSurfaces-IUaWSJ0E.cjs +0 -3858
  42. package/dist/MarkdownSurfaces-IUaWSJ0E.cjs.map +0 -1
  43. package/dist/copilotkit-BhV8iuX5.cjs.map +0 -1
  44. package/dist/copilotkit-dNtiaQqU.mjs.map +0 -1
  45. package/dist/runtime-context-CrHq-iTf.d.mts +0 -924
  46. package/dist/runtime-context-CrHq-iTf.d.mts.map +0 -1
  47. package/dist/runtime-context-D3NcP9oE.d.cts +0 -924
  48. package/dist/runtime-context-D3NcP9oE.d.cts.map +0 -1
@@ -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('./index.css'), require('@copilotkit/core'), require('@ag-ui/client'), require('react'), require('tailwind-merge'), require('lucide-react'), require('@copilotkit/shared'), require('react/jsx-runtime'), require('@radix-ui/react-slot'), require('class-variance-authority'), require('clsx'), require('@radix-ui/react-tooltip'), require('@radix-ui/react-dropdown-menu'), require('streamdown'), 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('@radix-ui/react-popover'), require('react-dom'), require('@tanstack/react-virtual'), require('use-stick-to-bottom'), require('@copilotkit/web-components/threads-drawer')) :
5
- typeof define === 'function' && define.amd ? define(['exports', './index.css', '@copilotkit/core', '@ag-ui/client', 'react', 'tailwind-merge', 'lucide-react', '@copilotkit/shared', 'react/jsx-runtime', '@radix-ui/react-slot', 'class-variance-authority', 'clsx', '@radix-ui/react-tooltip', '@radix-ui/react-dropdown-menu', 'streamdown', '@ag-ui/core', 'zod', '@copilotkit/mcp-apps-renderer/activity', '@copilotkit/a2ui-renderer', 'zod-to-json-schema', '@a2ui/web_core/v0_9', '@radix-ui/react-popover', 'react-dom', '@tanstack/react-virtual', 'use-stick-to-bottom', '@copilotkit/web-components/threads-drawer'], factory) :
6
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitReactCoreV2 = {}), global.src_v2_index_css,global.CopilotKitCore,global.AgUIClient,global.React,global.tailwindMerge,global.lucideReact,global.CopilotKitShared,global.ReactJsxRuntime,global.RadixReactSlot,global.classVarianceAuthority,global.clsx,global.RadixReactTooltip,global.RadixReactDropdownMenu,global.streamdown,global.AgUICore,global.Zod,global.CopilotKitMcpAppsRendererActivity,global.CopilotKitA2UIRenderer,global.zod_to_json_schema,global._a2ui_web_core_v0_9,global._radix_ui_react_popover,global.ReactDOM,global._tanstack_react_virtual,global.useStickToBottom,global._copilotkit_web_components_threads_drawer));
7
- })(this, function(exports, src_v2_index_css, _copilotkit_core, _ag_ui_client, react, tailwind_merge, lucide_react, _copilotkit_shared, react_jsx_runtime, _radix_ui_react_slot, class_variance_authority, clsx, _radix_ui_react_tooltip, _radix_ui_react_dropdown_menu, streamdown, _ag_ui_core, zod, _copilotkit_mcp_apps_renderer_activity, _copilotkit_a2ui_renderer, zod_to_json_schema, _a2ui_web_core_v0_9, _radix_ui_react_popover, react_dom, _tanstack_react_virtual, use_stick_to_bottom, _copilotkit_web_components_threads_drawer) {
4
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('./index.css'), require('@copilotkit/core'), require('@ag-ui/client'), require('react'), require('tailwind-merge'), require('lucide-react'), require('@copilotkit/shared'), require('react/jsx-runtime'), require('@radix-ui/react-slot'), require('class-variance-authority'), require('clsx'), require('@radix-ui/react-tooltip'), require('@radix-ui/react-dropdown-menu'), require('streamdown'), require('@ag-ui/core'), require('zod'), require('@copilotkit/mcp-apps-renderer/activity'), require('@copilotkit/a2ui-renderer'), require('@copilotkit/core/generative-ui'), require('@copilotkit/shared/generative-ui'), require('zod-to-json-schema'), require('@radix-ui/react-popover'), require('react-dom'), require('@tanstack/react-virtual'), require('use-stick-to-bottom'), require('@copilotkit/web-components/threads-drawer')) :
5
+ typeof define === 'function' && define.amd ? define(['exports', './index.css', '@copilotkit/core', '@ag-ui/client', 'react', 'tailwind-merge', 'lucide-react', '@copilotkit/shared', 'react/jsx-runtime', '@radix-ui/react-slot', 'class-variance-authority', 'clsx', '@radix-ui/react-tooltip', '@radix-ui/react-dropdown-menu', 'streamdown', '@ag-ui/core', 'zod', '@copilotkit/mcp-apps-renderer/activity', '@copilotkit/a2ui-renderer', '@copilotkit/core/generative-ui', '@copilotkit/shared/generative-ui', 'zod-to-json-schema', '@radix-ui/react-popover', 'react-dom', '@tanstack/react-virtual', 'use-stick-to-bottom', '@copilotkit/web-components/threads-drawer'], factory) :
6
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitReactCoreV2 = {}), global.src_v2_index_css,global.CopilotKitCore,global.AgUIClient,global.React,global.tailwindMerge,global.lucideReact,global.CopilotKitShared,global.ReactJsxRuntime,global.RadixReactSlot,global.classVarianceAuthority,global.clsx,global.RadixReactTooltip,global.RadixReactDropdownMenu,global.streamdown,global.AgUICore,global.Zod,global.CopilotKitMcpAppsRendererActivity,global.CopilotKitA2UIRenderer,global._copilotkit_core_generative_ui,global._copilotkit_shared_generative_ui,global.zod_to_json_schema,global._radix_ui_react_popover,global.ReactDOM,global._tanstack_react_virtual,global.useStickToBottom,global._copilotkit_web_components_threads_drawer));
7
+ })(this, function(exports, src_v2_index_css, _copilotkit_core, _ag_ui_client, react, tailwind_merge, lucide_react, _copilotkit_shared, react_jsx_runtime, _radix_ui_react_slot, class_variance_authority, clsx, _radix_ui_react_tooltip, _radix_ui_react_dropdown_menu, streamdown, _ag_ui_core, zod, _copilotkit_mcp_apps_renderer_activity, _copilotkit_a2ui_renderer, _copilotkit_core_generative_ui, _copilotkit_shared_generative_ui, zod_to_json_schema, _radix_ui_react_popover, react_dom, _tanstack_react_virtual, use_stick_to_bottom, _copilotkit_web_components_threads_drawer) {
8
8
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
9
9
  //#region \0rolldown/runtime.js
10
10
  var __create = Object.create;
@@ -1825,7 +1825,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
1825
1825
 
1826
1826
  //#endregion
1827
1827
  //#region package.json
1828
- var version = "1.84.2-canary.1793809041";
1828
+ var version = "1.84.2-canary.openbot-intel-fixes";
1829
1829
 
1830
1830
  //#endregion
1831
1831
  //#region src/v2/components/CopilotKitInspector.tsx
@@ -3130,7 +3130,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
3130
3130
  const groupedOperations = (0, react.useMemo)(() => {
3131
3131
  const groups = /* @__PURE__ */ new Map();
3132
3132
  for (const operation of operations) {
3133
- const surfaceId = getOperationSurfaceId$1(operation) ?? _copilotkit_a2ui_renderer.DEFAULT_SURFACE_ID;
3133
+ const surfaceId = getOperationSurfaceId(operation) ?? _copilotkit_a2ui_renderer.DEFAULT_SURFACE_ID;
3134
3134
  if (!groups.has(surfaceId)) groups.set(surfaceId, []);
3135
3135
  groups.get(surfaceId).push(operation);
3136
3136
  }
@@ -3298,7 +3298,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
3298
3298
  if (hash === lastHashRef.current) return;
3299
3299
  lastHashRef.current = hash;
3300
3300
  const ops = getSurface(surfaceId) ? operations.filter((op) => !op?.createSurface) : operations;
3301
- processMessages(ops);
3301
+ processMessages(ops.map(stripRoutingSurfaceId));
3302
3302
  if (onReady && surfaceHasRenderableContent(operations)) onReady();
3303
3303
  if (!IS_DEVELOPMENT) return;
3304
3304
  if (!getSurface(surfaceId)) {
@@ -3338,6 +3338,32 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
3338
3338
  return Object.values(v).some((x) => Array.isArray(x) ? x.length > 0 : x !== null && x !== void 0 && x !== "");
3339
3339
  });
3340
3340
  }
3341
+ const V0_9_ACTION_KEYS = [
3342
+ "createSurface",
3343
+ "updateComponents",
3344
+ "updateDataModel",
3345
+ "deleteSurface"
3346
+ ];
3347
+ /**
3348
+ * Drops a top-level `surfaceId` from a v0.9 message before it reaches
3349
+ * `MessageProcessor`.
3350
+ *
3351
+ * Compatibility with noncanonical agent payloads (see OSS-1048), not a key
3352
+ * added by react-core. `getOperationSurfaceId` reads it only as a routing
3353
+ * fallback. It is not part of the v0.9 envelope, and `@a2ui/web_core` 0.15
3354
+ * validates envelopes strictly, so leaving it in rejects the whole message
3355
+ * ("Unrecognized key(s) in object: 'surfaceId'"). The nested action keeps its
3356
+ * own `surfaceId`, which is the one the processor uses.
3357
+ *
3358
+ * @param operation - One A2UI operation, of any shape.
3359
+ * @returns The operation without a top-level `surfaceId` when it is a v0.9
3360
+ * message, otherwise the operation unchanged.
3361
+ */
3362
+ function stripRoutingSurfaceId(operation) {
3363
+ if (!operation || typeof operation !== "object" || !("surfaceId" in operation) || !V0_9_ACTION_KEYS.some((key) => key in operation)) return operation;
3364
+ const { surfaceId: _routingId, ...message } = operation;
3365
+ return message;
3366
+ }
3341
3367
  /**
3342
3368
  * Resolves the surface an operation addresses.
3343
3369
  *
@@ -3352,7 +3378,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
3352
3378
  * @param operation - One A2UI operation, of any shape.
3353
3379
  * @returns The surface id, or null when the operation names none.
3354
3380
  */
3355
- function getOperationSurfaceId$1(operation) {
3381
+ function getOperationSurfaceId(operation) {
3356
3382
  if (!operation || typeof operation !== "object") return null;
3357
3383
  const nested = operation?.createSurface?.surfaceId ?? operation?.updateComponents?.surfaceId ?? operation?.updateDataModel?.surfaceId ?? operation?.deleteSurface?.surfaceId;
3358
3384
  if (typeof nested === "string") return nested;
@@ -3466,3011 +3492,90 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
3466
3492
  }
3467
3493
 
3468
3494
  //#endregion
3469
- //#region src/v2/generative-ui/action-message.ts
3470
- /** Context keys that supply the message's first line, in priority order. */
3471
- const TEXT_KEYS = ["message", "label"];
3472
- function isNonEmptyString(value) {
3473
- return typeof value === "string" && value.trim().length > 0;
3474
- }
3475
- /** `choose_plan`, `choose-plan` and `choosePlan` all become "Choose plan". */
3476
- function humanize(name) {
3477
- const spaced = name.replace(/[_-]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").trim();
3478
- return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();
3479
- }
3480
- function formatContextValue(value) {
3481
- return typeof value === "object" ? JSON.stringify(value) : String(value);
3482
- }
3483
- /**
3484
- * Turns a user event that no function handles into the text of a visible
3485
- * user message.
3486
- *
3487
- * The first line is, in order: `userMessage`, `context.message`,
3488
- * `context.label`, the label of the source component (from `resolveLabel`),
3489
- * or the event name made readable (`choose_plan` becomes "Choose plan").
3490
- * Each other context field follows as one `key: value` line. Objects are
3491
- * written as JSON. `null` and `undefined` fields are skipped.
3492
- *
3493
- * @param event - The user event, as sent by a surface.
3494
- * @param resolveLabel - Finds the visible label of a component by id. Build
3495
- * one with {@link createComponentLabelResolver}.
3496
- *
3497
- * @example
3498
- * ```ts
3499
- * buildActionMessageText({
3500
- * name: "choose_plan",
3501
- * surfaceId: "plans",
3502
- * componentId: "team-button",
3503
- * userMessage: "I pick the Team plan",
3504
- * context: { seats: 12 },
3505
- * });
3506
- * // "I pick the Team plan\n\nseats: 12"
3507
- * ```
3508
- */
3509
- function buildActionMessageText(event, resolveLabel) {
3510
- const { context, userMessage } = event;
3511
- const explicit = [userMessage, ...TEXT_KEYS.map((key) => context[key])].find(isNonEmptyString);
3512
- const resolved = explicit ? void 0 : resolveLabel?.(event.componentId);
3513
- const head = explicit ?? (isNonEmptyString(resolved) ? resolved.trim() : humanize(event.name));
3514
- const lines = Object.entries(context).filter(([key, value]) => !TEXT_KEYS.includes(key) && value !== void 0 && value !== null).map(([key, value]) => `${key}: ${formatContextValue(value)}`);
3515
- return lines.length > 0 ? `${head}\n\n${lines.join("\n")}` : head;
3516
- }
3517
- function ownText(component) {
3518
- if (!component) return void 0;
3519
- if (isNonEmptyString(component.label)) return component.label;
3520
- if (isNonEmptyString(component.text)) return component.text;
3521
- }
3522
- function childIds(component) {
3523
- const { child, children } = component;
3524
- const single = typeof child === "string" ? [child] : [];
3525
- const multiple = Array.isArray(children) ? children.filter((id) => typeof id === "string") : [];
3526
- return [...single, ...multiple];
3527
- }
3528
- /** The components that an operation adds, inline or in an update. */
3529
- function componentsOf(operation) {
3530
- if ("createSurface" in operation) return operation.createSurface.components ?? [];
3531
- if ("updateComponents" in operation) return operation.updateComponents.components;
3532
- return [];
3533
- }
3534
- /**
3535
- * Builds a function that finds the visible label of a component on a surface.
3536
- *
3537
- * The label is the component's own string `label`, else its string `text`,
3538
- * else the first `child` or `children` component that has a string `label`
3539
- * or `text`. When a component id is defined more than once, the last
3540
- * definition wins, as in the renderer.
3541
- *
3542
- * @param operations - The committed operations of the surface.
3543
- *
3544
- * @example
3545
- * ```ts
3546
- * const resolveLabel = createComponentLabelResolver(surface.operations);
3547
- * buildActionMessageText(event, resolveLabel);
3548
- * ```
3549
- */
3550
- function createComponentLabelResolver(operations) {
3551
- const byId = /* @__PURE__ */ new Map();
3552
- for (const operation of operations) {
3553
- const components = componentsOf(operation);
3554
- for (const component of components) byId.set(component.id, component);
3555
- }
3556
- return (componentId) => {
3557
- const component = byId.get(componentId);
3558
- if (!component) return void 0;
3559
- const own = ownText(component);
3560
- if (own) return own;
3561
- const ids = childIds(component);
3562
- for (const id of ids) {
3563
- const text = ownText(byId.get(id));
3564
- if (text) return text;
3565
- }
3566
- };
3567
- }
3568
-
3569
- //#endregion
3570
- //#region src/v2/generative-ui/json-schema.ts
3571
- /**
3572
- * JSON Schema for a Standard Schema (zod v3 via zod-to-json-schema),
3573
- * inlined, no `$schema`. A prop marked by `child()` or `childList()`
3574
- * becomes an A2UI `$ref` to `ComponentId` or `ChildList`.
3575
- */
3576
- function toJsonSchema(schema) {
3577
- const { $schema: _omit, ...rest } = (0, _copilotkit_shared.schemaToJsonSchema)(schema, { zodToJsonSchema: (s) => (0, zod_to_json_schema.zodToJsonSchema)(s, { $refStrategy: "none" }) });
3578
- return (0, _copilotkit_shared.applyChildRefMarks)(rest);
3579
- }
3580
-
3581
- //#endregion
3582
- //#region src/v2/generative-ui/catalog.ts
3583
- /** The A2UI component envelope: `id`, `component`, `catalogId`, `accessibility`, `metadata`. */
3584
- const RESERVED_KEYS = new Set([
3585
- "id",
3586
- "component",
3587
- ..._copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS
3588
- ]);
3589
- /** The id of the catalog that declared each component, for the inspector. */
3590
- const componentCatalogs = /* @__PURE__ */ new WeakMap();
3591
- /**
3592
- * The id of the catalog that declared each component of `ui`. A component
3593
- * from `extends` keeps the id of its base. Not exported from the package.
3594
- */
3595
- function componentCatalogIds(ui) {
3596
- return componentCatalogs.get(ui) ?? /* @__PURE__ */ new Map();
3597
- }
3598
- /**
3599
- * The catalogs that an operation can name: the id of `ui`, then the ids of
3600
- * the catalogs in its `extends` that declared a component. Not exported
3601
- * from the package.
3602
- */
3603
- function catalogIdsOf(ui) {
3604
- const declared = componentCatalogs.get(ui)?.values() ?? [];
3605
- return [...new Set([ui.id, ...declared])];
3606
- }
3607
- /** The setter prop of a writable prop: `value` gives `setValue`. */
3608
- function setterNameOf(key) {
3609
- return `set${key.charAt(0).toUpperCase()}${key.slice(1)}`;
3610
- }
3611
-
3612
- //#endregion
3613
- //#region src/v2/generative-ui/manifest.ts
3614
- /**
3615
- * The built-in functions (the A2UI basic catalog plus calc and series) as
3616
- * manifest entries. Their args are described by the short signature, not
3617
- * by a full JSON Schema: the renderer checks them when they run. An app
3618
- * function of the same name replaces the entry.
3619
- */
3620
- function builtInFunctionManifests() {
3621
- return Object.fromEntries(Object.entries(_copilotkit_shared.GENERATIVE_UI_FUNCTIONS).map(([name, fn]) => [name, {
3622
- description: fn.description,
3623
- parameters: {
3624
- type: "object",
3625
- description: fn.parameters
3626
- },
3627
- returnType: fn.returnType,
3628
- allowedCallers: fn.allowedCallers,
3629
- ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
3630
- }]));
3631
- }
3632
- /**
3633
- * The manifest of a catalog, with no React runtime: the components of `ui`,
3634
- * the built-in functions (minus the names the app declares) and
3635
- * `options.functions`, the chat target and `options.targets`, and
3636
- * `options.surfaces`. `buildGenerativeUIManifest` builds the per-run
3637
- * manifest with it; tools that run outside React use it directly.
3638
- *
3639
- * @example
3640
- * ```ts
3641
- * const manifest = buildCatalogManifest(standardUI);
3642
- * manifest.targets; // [{ id: "chat", kind: "chat" }]
3643
- * ```
3644
- */
3645
- function buildCatalogManifest(ui, options = {}) {
3646
- return {
3647
- catalogId: ui.id,
3648
- catalogIds: catalogIdsOf(ui),
3649
- components: (0, _copilotkit_shared.applyDescriptionOverrides)({ components: ui.manifestComponents }, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().descriptions).manifest.components,
3650
- functions: {
3651
- ...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
3652
- ...options.functions
3653
- },
3654
- targets: [{
3655
- id: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
3656
- kind: "chat"
3657
- }, ...options.targets ?? []],
3658
- surfaces: options.surfaces ?? {}
3659
- };
3660
- }
3661
- /**
3662
- * Builds the per-run manifest. Never contains handlers or renderers.
3663
- *
3664
- * - `functions`: the built-in functions, then the declared functions with
3665
- * exactly one mounted handler.
3666
- * - `targets`: the chat first, then each mounted `<GenerativeUISurface>`,
3667
- * with its `description` and its `components` when it has them.
3668
- */
3669
- function buildGenerativeUIManifest(runtime, threadId) {
3670
- const { ui, manager, dispatcher } = runtime;
3671
- const inlineTargets = manager.getMountedTargets().filter((target) => target.id !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET).map(({ id, ...rest }) => ({
3672
- id,
3673
- kind: "inline",
3674
- ...rest
3675
- }));
3676
- return buildCatalogManifest(ui, {
3677
- functions: dispatcher.listExposed(),
3678
- targets: inlineTargets,
3679
- surfaces: threadId ? manager.describeSurfaces(threadId) : {}
3680
- });
3681
- }
3682
- /**
3683
- * Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
3684
- * from the per-run manifest. It has the A2UI v1.0 renderer capabilities
3685
- * shape: one inline catalog with the id of the UI, and the CopilotKit data
3686
- * in `metadata.extensions`.
3687
- *
3688
- * The inline catalog has no `components` only for the markdown transport
3689
- * with `includeCatalog: false`. It has `instructions` for the markdown
3690
- * transport, or when given.
3691
- *
3692
- * @param runtime - The generative UI runtime of the provider.
3693
- * @param threadId - The thread of the run. Its surfaces go in `copilotkit_surfaces`.
3694
- * @param options - The transport and what to send.
3695
- *
3696
- * @example
3697
- * ```ts
3698
- * const envelope = buildGenerativeUIEnvelope(runtime, agent.threadId, {
3699
- * transport: "tool",
3700
- * includeCatalog: true,
3701
- * contextSent: false,
3702
- * });
3703
- * envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
3704
- * ```
3705
- */
3706
- function buildGenerativeUIEnvelope(runtime, threadId, options) {
3707
- const { transport, includeCatalog, contextSent, action } = options;
3708
- const manifest = buildGenerativeUIManifest(runtime, threadId);
3709
- const instructions = options.instructions ?? (transport === "markdown" ? (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest)) : void 0);
3710
- const omitComponents = transport === "markdown" && !includeCatalog;
3711
- return {
3712
- "1.0": {
3713
- supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
3714
- inlineCatalogs: [{
3715
- catalogId: manifest.catalogId,
3716
- protocolVersion: "1.0",
3717
- ...omitComponents ? {} : { components: manifest.components },
3718
- functions: manifest.functions,
3719
- ...instructions === void 0 ? {} : { instructions }
3720
- }]
3721
- },
3722
- metadata: { extensions: {
3723
- copilotkit_format: _copilotkit_shared.COPILOTKIT_UI_ENVELOPE_FORMAT,
3724
- copilotkit_transport: transport,
3725
- copilotkit_targets: manifest.targets,
3726
- copilotkit_surfaces: manifest.surfaces,
3727
- copilotkit_contextSent: contextSent,
3728
- ...action === void 0 ? {} : { copilotkit_action: action }
3729
- } }
3730
- };
3731
- }
3732
-
3733
- //#endregion
3734
- //#region src/v2/generative-ui/debug-source.ts
3735
- /**
3736
- * What a run of `threadId` sends: its envelope, and the text that goes into
3737
- * the prompt of the model because of it.
3738
- *
3739
- * - Tool transport: the runtime adds the `render_ui` guide. It builds it
3740
- * from the envelope with `buildGenerativeUIPrompt`, as done here.
3741
- * - Markdown transport: the provider sends the guideline and the compact
3742
- * schema as context entries. With `sendContext: false`, the backend builds
3743
- * its own prompt, usually from the `instructions` of the envelope.
3744
- */
3745
- function describeGenerativeUIRun(runtime, threadId, options) {
3746
- const envelope = buildGenerativeUIEnvelope(runtime, threadId, options);
3747
- if (options.transport === "tool") return {
3748
- envelope,
3749
- prompt: [{
3750
- title: "render_ui guide",
3751
- source: "runtime",
3752
- text: (0, _copilotkit_shared.buildGenerativeUIPrompt)((0, _copilotkit_shared.envelopeToManifest)(envelope))
3753
- }]
3754
- };
3755
- const manifest = buildGenerativeUIManifest(runtime, threadId);
3756
- if (!options.contextSent) return {
3757
- envelope,
3758
- prompt: [{
3759
- title: "Envelope instructions",
3760
- source: "backend",
3761
- text: (0, _copilotkit_shared.envelopeToManifest)(envelope).instructions ?? ""
3762
- }]
3763
- };
3764
- const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
3765
- const schema = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
3766
- return {
3767
- envelope,
3768
- prompt: [{
3769
- title: "Markdown guideline",
3770
- source: "context",
3771
- text: guideline
3772
- }, {
3773
- title: "Component schema",
3774
- source: "context",
3775
- text: schema
3776
- }]
3777
- };
3778
- }
3779
- /** The declared functions, with the JSON Schema of their parameters. */
3780
- function debugFunctions(runtime) {
3781
- const functions = {};
3782
- for (const [name, declared] of runtime.ui.functions) {
3783
- let parameters = {};
3784
- try {
3785
- parameters = toJsonSchema(declared.parameters);
3786
- } catch {}
3787
- functions[name] = {
3788
- ...declared.description ? { description: declared.description } : {},
3789
- parameters,
3790
- handlers: runtime.dispatcher.handlerCount(name)
3791
- };
3792
- }
3793
- return functions;
3794
- }
3795
- /**
3796
- * The debug source that the provider gives core for the inspector. It builds
3797
- * a snapshot only when the inspector reads one.
3798
- *
3799
- * @param runtime - The generative UI parts of the provider.
3800
- * @param getOptions - The envelope options and agent ids of the current config.
3801
- * @returns The source, and `recordRun` for each run start.
3802
- */
3803
- function createGenerativeUIDebugSource(runtime, getOptions) {
3804
- const listeners = /* @__PURE__ */ new Set();
3805
- let lastRun;
3806
- const notify = () => {
3807
- for (const listener of [...listeners]) listener();
3808
- };
3809
- return {
3810
- source: {
3811
- getSnapshot() {
3812
- const { options, agentIds } = getOptions();
3813
- const threadId = runtime.manager.getActiveThread();
3814
- const manifest = buildGenerativeUIManifest(runtime, threadId);
3815
- return {
3816
- catalogId: runtime.ui.id,
3817
- transport: options.transport,
3818
- ...agentIds ? { agentIds } : {},
3819
- components: runtime.ui.manifestComponents,
3820
- componentCatalogs: Object.fromEntries(componentCatalogIds(runtime.ui)),
3821
- functions: debugFunctions(runtime),
3822
- state: { ...runtime.manager.getState() },
3823
- targets: manifest.targets,
3824
- activeThreadId: threadId,
3825
- surfaces: runtime.manager.debugSurfaces(),
3826
- lastRun,
3827
- nextRun: {
3828
- agentId: void 0,
3829
- threadId,
3830
- ...describeGenerativeUIRun(runtime, threadId, options)
3831
- }
3832
- };
3833
- },
3834
- subscribe(listener) {
3835
- listeners.add(listener);
3836
- const unsubscribe = runtime.manager.subscribe(listener);
3837
- return () => {
3838
- listeners.delete(listener);
3839
- unsubscribe();
3840
- };
3841
- }
3842
- },
3843
- recordRun(run) {
3844
- lastRun = run;
3845
- notify();
3846
- }
3847
- };
3848
- }
3849
-
3850
- //#endregion
3851
- //#region src/v2/generative-ui/errors.ts
3852
- var GenerativeUIError = class extends Error {
3853
- constructor(code, message) {
3854
- super(message);
3855
- this.name = "GenerativeUIError";
3856
- this.code = code;
3857
- }
3858
- };
3859
-
3860
- //#endregion
3861
- //#region src/v2/generative-ui/functions.ts
3495
+ //#region src/v2/generative-ui/markdown/context.ts
3862
3496
  /**
3863
- * The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes
3864
- * resolved args (no bindings left in them) and gives a plain value. They
3865
- * run synchronously, so a prop bound to one updates in the same render as
3866
- * the data it reads. The signatures the model sees are in
3867
- * `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).
3868
- */
3869
- /** Thrown for a bad call: an unknown function, bad args, or a bad value. */
3870
- var ExpressionError = class extends Error {
3871
- constructor(message) {
3872
- super(message);
3873
- this.name = "ExpressionError";
3874
- }
3875
- };
3876
- /** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */
3877
- function truthOf(value) {
3878
- if ((0, _copilotkit_shared.isValidationResult)(value)) return value.valid;
3879
- return Boolean(value);
3880
- }
3881
- const valid = () => ({ valid: true });
3882
- /** A failed result. `code` names the failure, the same for every locale. */
3883
- const invalid = (message, code) => ({
3884
- valid: false,
3885
- message,
3886
- code
3887
- });
3888
- function text(value) {
3889
- if (value === void 0 || value === null) return "";
3890
- return typeof value === "string" ? value : String(value);
3891
- }
3892
- function numberOf$1(value) {
3893
- if (typeof value === "number") return value;
3894
- if (typeof value === "string" && value.trim() !== "") return Number(value);
3895
- return NaN;
3896
- }
3897
- function optionalNumber(value, name) {
3898
- if (value === void 0 || value === null) return void 0;
3899
- const parsed = numberOf$1(value);
3900
- if (Number.isNaN(parsed)) throw new ExpressionError(`${name} must be a number`);
3901
- return parsed;
3902
- }
3903
- const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
3904
- /** The locale of the user. `undefined` lets Intl pick the default. */
3905
- function locale() {
3906
- return typeof navigator !== "undefined" ? navigator.language : void 0;
3907
- }
3908
- function numberFormat(args, options) {
3909
- const decimals = optionalNumber(args.decimals, "decimals");
3910
- return new Intl.NumberFormat(locale(), {
3911
- ...options,
3912
- useGrouping: args.grouping !== false,
3913
- ...decimals === void 0 ? {} : {
3914
- minimumFractionDigits: decimals,
3915
- maximumFractionDigits: decimals
3916
- }
3917
- });
3918
- }
3919
- /** A date from an ISO string, a timestamp, or a Date. */
3920
- function dateOf(value) {
3921
- 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;
3922
- if (date === void 0 || Number.isNaN(date.getTime())) throw new ExpressionError("value must be a date");
3923
- return date;
3924
- }
3925
- const pad = (value, width) => String(value).padStart(width, "0");
3926
- /**
3927
- * A TR35 field is a run of one letter ("EEE" is one abbreviated weekday,
3928
- * not three), and text in single quotes is literal. Letters that are not
3929
- * fields stay as they are.
3930
- */
3931
- const DATE_FIELD = /([A-Za-z])\1*|'(?:[^']|'')*'/g;
3932
- function formatDatePattern(date, pattern) {
3933
- const parts = (options) => new Intl.DateTimeFormat(locale(), options).format(date);
3934
- const hours12 = date.getHours() % 12 || 12;
3935
- const numeric = (value, width) => width >= 2 ? pad(value, 2) : String(value);
3936
- return pattern.replace(DATE_FIELD, (token) => {
3937
- if (token.startsWith("'")) return token.slice(1, -1).replace(/''/g, "'");
3938
- const width = token.length;
3939
- switch (token[0]) {
3940
- case "y": return width === 2 ? pad(date.getFullYear() % 100, 2) : String(date.getFullYear());
3941
- case "M":
3942
- if (width >= 4) return parts({ month: "long" });
3943
- if (width === 3) return parts({ month: "short" });
3944
- return numeric(date.getMonth() + 1, width);
3945
- case "d": return numeric(date.getDate(), width);
3946
- case "E": return parts({ weekday: width >= 4 ? "long" : "short" });
3947
- case "H": return numeric(date.getHours(), width);
3948
- case "h": return numeric(hours12, width);
3949
- case "m": return pad(date.getMinutes(), 2);
3950
- case "s": return pad(date.getSeconds(), 2);
3951
- case "a": return date.getHours() < 12 ? "AM" : "PM";
3952
- default: return token;
3953
- }
3954
- });
3955
- }
3956
- /** Opens an http(s) URL in a new tab. Any other scheme is refused. */
3957
- function openUrlSafely(url) {
3958
- if (typeof url !== "string" || url === "") throw new ExpressionError("url must be a string");
3959
- if (typeof window === "undefined") return;
3960
- let parsed;
3961
- try {
3962
- parsed = new URL(url, window.location.href);
3963
- } catch {
3964
- throw new ExpressionError(`"${url}" is not a URL`);
3965
- }
3966
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new ExpressionError(`openUrl takes only http(s) URLs, not ${parsed.protocol}`);
3967
- window.open(parsed.href, "_blank", "noopener,noreferrer");
3968
- }
3969
- /**
3970
- * The basic functions, except `formatString`, which needs the resolver.
3971
- * `calc` and `series` are added by `resolve.ts`, which imports both.
3972
- */
3973
- const BASIC_FUNCTIONS = {
3974
- required: ({ value }) => {
3975
- return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0 ? invalid("Required", "required") : valid();
3976
- },
3977
- regex: ({ value, pattern }) => {
3978
- if (typeof pattern !== "string") throw new ExpressionError("pattern must be a string");
3979
- let expression;
3980
- try {
3981
- expression = new RegExp(pattern, "u");
3982
- } catch {
3983
- throw new ExpressionError(`"${pattern}" is not a regular expression`);
3984
- }
3985
- return expression.test(text(value)) ? valid() : invalid("Invalid format", "pattern");
3986
- },
3987
- length: ({ value, min, max }) => {
3988
- const size = text(value).length;
3989
- const low = optionalNumber(min, "min");
3990
- const high = optionalNumber(max, "max");
3991
- if (low !== void 0 && size < low) return invalid(`At least ${low} characters`, "tooShort");
3992
- if (high !== void 0 && size > high) return invalid(`At most ${high} characters`, "tooLong");
3993
- return valid();
3994
- },
3995
- numeric: ({ value, min, max }) => {
3996
- const parsed = numberOf$1(value);
3997
- if (Number.isNaN(parsed)) return invalid("Must be a number", "notANumber");
3998
- const low = optionalNumber(min, "min");
3999
- const high = optionalNumber(max, "max");
4000
- if (low !== void 0 && parsed < low) return invalid(`At least ${low}`, "tooSmall");
4001
- if (high !== void 0 && parsed > high) return invalid(`At most ${high}`, "tooLarge");
4002
- return valid();
4003
- },
4004
- email: ({ value }) => EMAIL.test(text(value)) ? valid() : invalid("Invalid email address", "email"),
4005
- formatNumber: (args) => {
4006
- const parsed = numberOf$1(args.value);
4007
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
4008
- return numberFormat(args, {}).format(parsed);
4009
- },
4010
- formatCurrency: (args) => {
4011
- const parsed = numberOf$1(args.value);
4012
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
4013
- if (typeof args.currency !== "string" || args.currency === "") throw new ExpressionError("currency must be an ISO 4217 code");
4014
- try {
4015
- return numberFormat(args, {
4016
- style: "currency",
4017
- currency: args.currency
4018
- }).format(parsed);
4019
- } catch {
4020
- throw new ExpressionError(`"${args.currency}" is not a currency code`);
4021
- }
4022
- },
4023
- formatDate: ({ value, format }) => {
4024
- if (typeof format !== "string") throw new ExpressionError("format must be a string");
4025
- return formatDatePattern(dateOf(value), format);
4026
- },
4027
- pluralize: (args) => {
4028
- const parsed = numberOf$1(args.value);
4029
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
4030
- const category = new Intl.PluralRules(locale()).select(parsed);
4031
- return text((parsed === 0 ? args.zero : void 0) ?? args[category] ?? args.other);
4032
- },
4033
- and: ({ values }) => {
4034
- if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
4035
- return values.every(truthOf);
4036
- },
4037
- or: ({ values }) => {
4038
- if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
4039
- return values.some(truthOf);
4040
- },
4041
- not: ({ value }) => !truthOf(value),
4042
- openUrl: ({ url }) => {
4043
- openUrlSafely(url);
4044
- }
4045
- };
4046
- /** True when the basic function `name` must run from a user gesture. */
4047
- function requiresUserActivation(name) {
4048
- return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.requiresUserActivation === true;
4049
- }
4050
- /** True when a basic function gives a ValidationResult. */
4051
- function givesValidationResult(name) {
4052
- return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.returnType === "validationResult";
4053
- }
4054
-
4055
- //#endregion
4056
- //#region src/v2/generative-ui/dispatcher.ts
4057
- const messageOf = (error) => error instanceof Error ? error.message : String(error);
4058
- /**
4059
- * Creates the registry of functions that generated UI may call.
3497
+ * Registers the two context entries of the markdown transport: the compact
3498
+ * component schema and the fence guideline. Both go only to `agentIds`.
4060
3499
  *
4061
- * A function is callable when it is declared in `getDeclared()` and exactly
4062
- * one handler is mounted for it with `register`. Names are resolved at call
4063
- * time and fail closed. Nothing is sent to the agent.
4064
- * Neither `invoke` nor `listExposed` throws.
3500
+ * The schema is built again at each run start and when a
3501
+ * `<GenerativeUISurface>` mounts, unmounts, or changes its description or
3502
+ * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
4065
3503
  *
4066
- * @param options.getDeclared - Returns the declared functions.
4067
- * @param options.onError - Gets each failed call.
3504
+ * @param copilotkit - The CopilotKit core of the provider.
3505
+ * @param runtime - The generative UI runtime parts, or null without one.
3506
+ * @param options - `enabled` and `agentIds`.
4068
3507
  *
4069
- * @example
4070
- * ```ts
4071
- * const dispatcher = createGenerativeUIDispatcher({
4072
- * getDeclared: () => new Map(Object.entries(ui.functions)),
4073
- * });
4074
- * const unregister = dispatcher.register("addToCart", handlerRef);
4075
- * await dispatcher.invoke("addToCart", { productId: "p1" }, origin);
4076
- * unregister();
4077
- * ```
4078
- */
4079
- /**
4080
- * True while the browser counts the current task as user-activated (a
4081
- * click, a key press). Where the API is missing (older browsers, test
4082
- * environments), the gesture is assumed.
4083
- */
4084
- function hasUserActivation() {
4085
- if (typeof navigator === "undefined") return true;
4086
- const activation = navigator.userActivation;
4087
- return activation === void 0 || activation.isActive;
4088
- }
4089
- /**
4090
- * The permissions of a declared function as the manifest states them: the
4091
- * callers always written out, so a reader needs no default.
4092
- */
4093
- function permissionsOf(fn) {
4094
- const callers = (0, _copilotkit_shared.functionCallers)(fn);
4095
- return {
4096
- allowedCallers: callers.renderer && callers.agent ? "rendererOrAgent" : callers.agent ? "agentOnly" : "rendererOnly",
4097
- ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
4098
- };
4099
- }
4100
- function createGenerativeUIDispatcher(options) {
4101
- const handlers = /* @__PURE__ */ new Map();
4102
- const resolveUnchecked = (name) => {
4103
- const declared = options.getDeclared().get(name);
4104
- if (!declared) return {
4105
- ok: false,
4106
- error: new GenerativeUIError("function_not_found", `No generative UI function named "${name}" is declared in createGenerativeUI({ functions })`)
4107
- };
4108
- const mounted = [...handlers.get(name) ?? []];
4109
- const [ref] = mounted;
4110
- if (!ref) return {
4111
- ok: false,
4112
- error: new GenerativeUIError("function_not_found", `"${name}" is declared, but no useGenerativeUIFunction handler is mounted for it`)
4113
- };
4114
- if (mounted.length > 1) return {
4115
- ok: false,
4116
- error: new GenerativeUIError("function_conflict", `"${name}" has ${mounted.length} useGenerativeUIFunction handlers mounted. Mount exactly one.`)
4117
- };
4118
- return {
4119
- ok: true,
4120
- declared,
4121
- ref
4122
- };
4123
- };
4124
- const isDeclared = (name) => {
4125
- try {
4126
- return options.getDeclared().has(name);
4127
- } catch {
4128
- return false;
4129
- }
4130
- };
4131
- const resolve = (name) => {
4132
- try {
4133
- return resolveUnchecked(name);
4134
- } catch (error) {
4135
- return {
4136
- ok: false,
4137
- error: new GenerativeUIError("handler_failed", `"${name}" could not be resolved: ${messageOf(error)}`)
4138
- };
4139
- }
4140
- };
4141
- const validateArgs = async (name, schema, args) => {
4142
- try {
4143
- const validation = await schema["~standard"].validate(args);
4144
- if (!validation.issues) return {
4145
- ok: true,
4146
- value: validation.value
4147
- };
4148
- return {
4149
- ok: false,
4150
- 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("; ")}`)
4151
- };
4152
- } catch (error) {
4153
- return {
4154
- ok: false,
4155
- error: new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${messageOf(error)}`)
4156
- };
4157
- }
4158
- };
4159
- const failWith = (name, origin, error) => {
4160
- try {
4161
- options.onError?.({
4162
- name,
4163
- origin,
4164
- error
4165
- });
4166
- } catch {}
4167
- return {
4168
- ok: false,
4169
- error
4170
- };
4171
- };
4172
- /**
4173
- * Why `origin` may not call a function with these permissions now, as an
4174
- * error, or `undefined` when it may. The agent is refused what is for the
4175
- * renderer; a component is refused what is for the agent, and a gesture
4176
- * function when the browser counts no user activation.
4177
- */
4178
- const callerError = (name, fn, origin) => {
4179
- const isComponent = "componentId" in origin;
4180
- if (!isComponent && !_copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS) return new GenerativeUIError("invalid_function_call", _copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
4181
- const problem = (0, _copilotkit_shared.callerProblem)(name, fn, isComponent ? "renderer" : "agent");
4182
- if (problem !== void 0) return new GenerativeUIError("invalid_function_call", problem);
4183
- if (isComponent && fn.requiresUserActivation && !hasUserActivation()) return new GenerativeUIError("invalid_function_call", `function "${name}" runs only from a user gesture; this event was not one`);
4184
- };
4185
- /**
4186
- * Runs a basic function of the A2UI catalog. They are value functions of
4187
- * the renderer: the agent cannot call them, and one that needs a user
4188
- * gesture runs only from an event binding.
4189
- */
4190
- const invokeBasic = (name, args, origin) => {
4191
- const refused = callerError(name, _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name], origin);
4192
- if (refused) return failWith(name, origin, refused);
4193
- 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`));
4194
- try {
4195
- return {
4196
- ok: true,
4197
- result: BASIC_FUNCTIONS[name](args ?? {})
4198
- };
4199
- } catch (error) {
4200
- return failWith(name, origin, new GenerativeUIError(error instanceof ExpressionError ? "invalid_arguments" : "handler_failed", `"${name}" failed: ${messageOf(error)}`));
4201
- }
4202
- };
4203
- return {
4204
- async invoke(name, args, origin) {
4205
- const resolved = resolve(name);
4206
- if (!resolved.ok && resolved.error.code === "function_not_found" && !isDeclared(name) && Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name)) return invokeBasic(name, args, origin);
4207
- if (!resolved.ok) return failWith(name, origin, resolved.error);
4208
- const refused = callerError(name, resolved.declared, origin);
4209
- if (refused) return failWith(name, origin, refused);
4210
- const validated = await validateArgs(name, resolved.declared.parameters, args ?? {});
4211
- if (!validated.ok) return failWith(name, origin, validated.error);
4212
- try {
4213
- return {
4214
- ok: true,
4215
- result: await resolved.ref.current(validated.value)
4216
- };
4217
- } catch (error) {
4218
- return failWith(name, origin, new GenerativeUIError("handler_failed", `"${name}" failed: ${messageOf(error)}`));
4219
- }
4220
- },
4221
- listExposed() {
4222
- let names;
4223
- try {
4224
- names = [...options.getDeclared().keys()];
4225
- } catch {
4226
- return {};
4227
- }
4228
- const listed = {};
4229
- for (const name of names) {
4230
- const resolved = resolve(name);
4231
- if (!resolved.ok) continue;
4232
- if (!(0, _copilotkit_shared.functionCallers)(resolved.declared).renderer && !_copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS) continue;
4233
- const { description, parameters, returnType } = resolved.declared;
4234
- try {
4235
- listed[name] = {
4236
- ...description ? { description } : {},
4237
- parameters: toJsonSchema(parameters),
4238
- ...returnType ? { returnType } : {},
4239
- ...permissionsOf(resolved.declared)
4240
- };
4241
- } catch {}
4242
- }
4243
- return listed;
4244
- },
4245
- register(name, ref) {
4246
- const mounted = handlers.get(name) ?? /* @__PURE__ */ new Set();
4247
- mounted.add(ref);
4248
- handlers.set(name, mounted);
4249
- return () => {
4250
- mounted.delete(ref);
4251
- };
4252
- },
4253
- handlerCount: (name) => handlers.get(name)?.size ?? 0
4254
- };
4255
- }
4256
-
4257
- //#endregion
4258
- //#region src/v2/generative-ui/markdown/context.ts
4259
- /**
4260
- * Registers the two context entries of the markdown transport: the compact
4261
- * component schema and the fence guideline. Both go only to `agentIds`.
4262
- *
4263
- * The schema is built again at each run start and when a
4264
- * `<GenerativeUISurface>` mounts, unmounts, or changes its description or
4265
- * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
4266
- *
4267
- * @param copilotkit - The CopilotKit core of the provider.
4268
- * @param runtime - The generative UI runtime parts, or null without one.
4269
- * @param options - `enabled` and `agentIds`.
4270
- *
4271
- * @example
4272
- * ```ts
4273
- * useGenerativeUIMarkdownContext(copilotkit, core, {
4274
- * enabled: config?.transport === "markdown" && config.sendContext !== false,
4275
- * agentIds: config?.agentIds,
4276
- * });
4277
- * ```
4278
- */
4279
- function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
4280
- const { enabled, agentIds } = options;
4281
- const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
4282
- (0, react.useEffect)(() => {
4283
- if (!runtime || !enabled) return;
4284
- const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
4285
- const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
4286
- let guidelineId;
4287
- let guidelineValue;
4288
- let schemaId;
4289
- let schemaValue;
4290
- const refreshSchema = (threadId) => {
4291
- const manifest = buildGenerativeUIManifest(runtime, threadId);
4292
- const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
4293
- if (guideline !== guidelineValue) {
4294
- if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
4295
- guidelineValue = guideline;
4296
- guidelineId = copilotkit.addContext({
4297
- description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
4298
- value: guideline,
4299
- ...scope
4300
- });
4301
- }
4302
- const value = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
4303
- if (value === schemaValue) return;
4304
- if (schemaId !== void 0) copilotkit.removeContext(schemaId);
4305
- schemaValue = value;
4306
- schemaId = copilotkit.addContext({
4307
- description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
4308
- value,
4309
- ...scope
4310
- });
4311
- };
4312
- refreshSchema(runtime.manager.getActiveThread());
4313
- let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
4314
- const unsubscribeManager = runtime.manager.subscribe(() => {
4315
- const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
4316
- if (nextKey === targetsKey) return;
4317
- targetsKey = nextKey;
4318
- refreshSchema(runtime.manager.getActiveThread());
4319
- });
4320
- const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
4321
- return () => {
4322
- subscription.unsubscribe();
4323
- unsubscribeManager();
4324
- if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
4325
- if (schemaId !== void 0) copilotkit.removeContext(schemaId);
4326
- };
4327
- }, [
4328
- copilotkit,
4329
- runtime,
4330
- enabled,
4331
- agentIdsKey
4332
- ]);
4333
- }
4334
-
4335
- //#endregion
4336
- //#region src/v2/generative-ui/is-record.ts
4337
- /** True for a plain object: not null, not an array. Internal, not exported. */
4338
- function isRecord(value) {
4339
- return typeof value === "object" && value !== null && !Array.isArray(value);
4340
- }
4341
-
4342
- //#endregion
4343
- //#region src/v2/generative-ui/markdown/source.ts
4344
- /**
4345
- * Values by key, from the latest build. A value that a build does not use
4346
- * is dropped at the end of that build, so the cache does not grow.
4347
- */
4348
- var BuildMemo = class {
4349
- constructor() {
4350
- this.previous = /* @__PURE__ */ new Map();
4351
- this.current = /* @__PURE__ */ new Map();
4352
- }
4353
- /**
4354
- * The value of `key`. It is computed when no earlier value is there, or
4355
- * when `isFresh` says that the earlier value is out of date.
4356
- */
4357
- get(key, compute, isFresh = () => true) {
4358
- let value = this.current.get(key) ?? this.previous.get(key);
4359
- if (value === void 0 || !isFresh(value)) value = compute();
4360
- this.current.set(key, value);
4361
- return value;
4362
- }
4363
- endBuild() {
4364
- this.previous = this.current;
4365
- this.current = /* @__PURE__ */ new Map();
4366
- }
4367
- };
4368
- /** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */
4369
- var MarkdownBuildCache = class {
4370
- constructor() {
4371
- this.segments = new BuildMemo();
4372
- this.fences = new BuildMemo();
4373
- this.drafts = new BuildMemo();
4374
- this.readdressed = /* @__PURE__ */ new WeakMap();
4375
- }
4376
- endBuild() {
4377
- this.segments.endBuild();
4378
- this.fences.endBuild();
4379
- this.drafts.endBuild();
4380
- }
4381
- };
4382
- /** True when both lists hold the same objects in the same order. */
4383
- function sameItems(a, b) {
4384
- return a.length === b.length && a.every((item, index) => item === b[index]);
4385
- }
4386
- function isString(value) {
4387
- return typeof value === "string";
4388
- }
4389
- /** The key of one fence of one message. */
4390
- function fenceKey(messageId, fenceIndex) {
4391
- return `${messageId}:${fenceIndex}`;
4392
- }
4393
- /**
4394
- * The operations of a fence body. While the fence streams, the last object
4395
- * can be unfinished. Of an unfinished updateComponents or createSurface, the
4396
- * components that are complete render at once (a createSurface also keeps
4397
- * its data model when all of it arrived). Any other unfinished object is
4398
- * left out, because a part of a data model value can still change. A final
4399
- * fence keeps what can be saved from an unfinished object.
4400
- */
4401
- function fenceOperations(text, isStreaming) {
4402
- const parsed = (0, _copilotkit_core.extractFenceOperations)(text);
4403
- if (!isStreaming || parsed.partialObject === null) return parsed.operations;
4404
- const complete = (0, _copilotkit_core.extractFenceOperations)(text.slice(0, text.length - parsed.partialObject.length)).operations;
4405
- const partial = parsed.operations.length > complete.length ? parsed.operations[parsed.operations.length - 1] : void 0;
4406
- return partial !== void 0 && (isRecord(partial.updateComponents) || isRecord(partial.createSurface)) ? [...complete, partial] : complete;
4407
- }
4408
- /**
4409
- * An inline createSurface becomes a createSurface with only its surfaceId
4410
- * and catalog, then an updateDataModel for its data model, then an
4411
- * updateComponents for its components. The prose lift and the split per
4412
- * component read only updateComponents, so they then work for an inline
4413
- * surface too. A createSurface with a data model or components of a wrong
4414
- * shape does not change, so that validation rejects it with the reason.
4415
- */
4416
- function expandInlineCreate(operations) {
4417
- return operations.flatMap((op) => {
4418
- const create = op.createSurface;
4419
- if (!isRecord(create)) return [op];
4420
- const { dataModel, components, ...rest } = create;
4421
- const hasData = isRecord(dataModel);
4422
- const hasComponents = Array.isArray(components) && components.length > 0;
4423
- if (!((dataModel === void 0 || hasData) && (components === void 0 || hasComponents)) || !hasData && !hasComponents) return [op];
4424
- const { surfaceId } = create;
4425
- const expanded = [{
4426
- ...op,
4427
- createSurface: rest
4428
- }];
4429
- if (hasData) expanded.push({
4430
- version: op.version,
4431
- updateDataModel: {
4432
- surfaceId,
4433
- path: "/",
4434
- value: dataModel
4435
- }
4436
- });
4437
- if (hasComponents) expanded.push({
4438
- version: op.version,
4439
- updateComponents: {
4440
- surfaceId,
4441
- components
4442
- }
4443
- });
4444
- return expanded;
4445
- });
4446
- }
4447
- /**
4448
- * Each updateComponents becomes one operation per component, in order. The
4449
- * complete components of a streaming line then give the same first
4450
- * operations as the finished line, so the operation list only grows and the
4451
- * manager never has to start the surface again.
4452
- */
4453
- function splitComponentUpdates(operations) {
4454
- return operations.flatMap((op) => {
4455
- const update = op.updateComponents;
4456
- if (!isRecord(update) || !Array.isArray(update.components)) return [op];
4457
- if (update.components.length <= 1) return [op];
4458
- return update.components.map((component) => ({
4459
- ...op,
4460
- updateComponents: {
4461
- ...update,
4462
- components: [component]
4463
- }
4464
- }));
4465
- });
4466
- }
4467
- /** createSurface first, the other operations after it in their order. */
4468
- function createSurfaceFirst(operations) {
4469
- const creates = operations.filter((op) => isRecord(op.createSurface));
4470
- const others = operations.filter((op) => !isRecord(op.createSurface));
4471
- return [...creates, ...others];
4472
- }
4473
- /** True when the component of `name` has the prop `prop`. */
4474
- function hasProp(ui, name, prop) {
4475
- const properties = ui.manifestComponents[name]?.props.properties;
4476
- return isRecord(properties) && Object.hasOwn(properties, prop);
4477
- }
4478
- const childRefCache = /* @__PURE__ */ new WeakMap();
4479
- /** The ids in a slot value: an id, a list of ids, or a template. */
4480
- function slotIds(value) {
4481
- if (typeof value === "string") return [value];
4482
- if (Array.isArray(value)) return value.filter(isString);
4483
- return isRecord(value) && isString(value.componentId) ? [value.componentId] : [];
4484
- }
4485
- /**
4486
- * A reader of the ids a component renders beyond `child` and `children`:
4487
- * its declared slots (the `trigger` and `content` of a Modal) and its typed
4488
- * child references (the `child` of each entry of `tabs`), from its catalog
4489
- * entry. The prose lift follows these ids like `children`, so a panel is
4490
- * never cut off from its Tabs. A reference that is bound to the data
4491
- * model is "unknown": its ids exist only at render time.
4492
- */
4493
- function childIdsReader(ui) {
4494
- return (component) => {
4495
- const name = component.component;
4496
- const entry = typeof name === "string" && Object.hasOwn(ui.manifestComponents, name) ? ui.manifestComponents[name] : void 0;
4497
- if (!entry) return [];
4498
- const ids = [];
4499
- for (const slot of Object.keys(entry.slots ?? {})) if (slot !== "child" && slot !== "children") ids.push(...slotIds(component[slot]));
4500
- let refs = childRefCache.get(entry.props);
4501
- if (!refs) {
4502
- refs = (0, _copilotkit_shared.collectChildRefs)(entry.props);
4503
- childRefCache.set(entry.props, refs);
4504
- }
4505
- if (refs.length === 0) return ids;
4506
- if ((0, _copilotkit_shared.hasBoundChildRef)(component, refs)) return "unknown";
4507
- return [...ids, ...(0, _copilotkit_shared.childIdsAtRefs)(component, refs)];
4508
- };
4509
- }
4510
- /** Every component of the operations by id, last definition wins. */
4511
- function collectComponents(operations) {
4512
- const byId = /* @__PURE__ */ new Map();
4513
- for (const op of operations) {
4514
- const update = op.updateComponents;
4515
- const list = isRecord(update) ? update.components : void 0;
4516
- if (!Array.isArray(list)) continue;
4517
- for (const component of list) if (isRecord(component) && isString(component.id)) byId.set(component.id, component);
4518
- }
4519
- return [...byId.values()];
4520
- }
4521
- /**
4522
- * The data model must not be shared between two surfaces. A data model
4523
- * keeps the object it gets, so an input in one surface would change the
4524
- * data of the other one.
4525
- */
4526
- function cloneData(value) {
4527
- return value === void 0 ? void 0 : structuredClone(value);
4528
- }
4529
- /** The operation sent to `surfaceId`, with a copy of its data model value. */
4530
- function readdress(op, surfaceId) {
4531
- const kind = (0, _copilotkit_shared.getOperationKind)(op);
4532
- const payload = kind ? op[kind] : void 0;
4533
- if (!kind || !isRecord(payload)) return op;
4534
- const next = {
4535
- ...payload,
4536
- surfaceId
4537
- };
4538
- if (kind === "updateDataModel" && "value" in payload) next.value = cloneData(payload.value);
4539
- return {
4540
- ...op,
4541
- [kind]: next
4542
- };
4543
- }
4544
- /**
4545
- * The operations of one sub-surface. Each updateComponents keeps only the
4546
- * components of the sub-surface, with its own root. The other operations
4547
- * are sent to the sub-surface. The order stays the same, so a new operation
4548
- * of the fence only adds operations at the end.
4549
- */
4550
- function subSurfaceOperations(operations, components, surfaceId) {
4551
- const root = components.find((c) => c.id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID);
4552
- const ids = new Set(components.map((c) => c.id));
4553
- const out = [];
4554
- for (const op of operations) {
4555
- const update = op.updateComponents;
4556
- if (!isRecord(update) || !Array.isArray(update.components)) {
4557
- out.push(readdress(op, surfaceId));
4558
- continue;
4559
- }
4560
- 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);
4561
- if (kept.length === 0) continue;
4562
- out.push({
4563
- ...op,
4564
- updateComponents: {
4565
- ...update,
4566
- surfaceId,
4567
- components: kept
4568
- }
4569
- });
4570
- }
4571
- return out;
4572
- }
4573
- /**
4574
- * Prose lift. Text components in the main stack of the surface (titles,
4575
- * paragraphs, text lists and the dividers between them) become chat
4576
- * markdown. The surface splits around them: the first surface keeps
4577
- * `surfaceId`, the next ones are `<surfaceId>#1`, `<surfaceId>#2`, and so
4578
- * on. A surface with no prose comes back as one part with the same
4579
- * operations.
4580
- */
4581
- function liftProse(operations, surfaceId, childIds) {
4582
- const components = collectComponents(operations);
4583
- const segments = (0, _copilotkit_core.segmentSurfaceProse)(components, { childIds });
4584
- const [first] = segments;
4585
- if (segments.length === 1 && first?.kind === "surface" && first.components === components) return [{
4586
- kind: "surface",
4587
- surfaceId,
4588
- operations
4589
- }];
4590
- let surfaceIndex = 0;
4591
- return segments.map((segment) => {
4592
- if (segment.kind === "markdown") return segment;
4593
- const id = surfaceIndex === 0 ? surfaceId : `${surfaceId}#${surfaceIndex}`;
4594
- surfaceIndex++;
4595
- return {
4596
- kind: "surface",
4597
- surfaceId: id,
4598
- operations: subSurfaceOperations(operations, segment.components, id)
4599
- };
4600
- });
4601
- }
4602
- /** `validateOperation`, with the operation typed when it is valid. */
4603
- function checkOperation(op, options) {
4604
- const validation = (0, _copilotkit_shared.validateOperation)(op, options);
4605
- if (!validation.ok) return validation;
4606
- return {
4607
- ok: true,
4608
- operation: op
4609
- };
4610
- }
4611
- /**
4612
- * The content of one surface. Each operation is validated against the
4613
- * manifest. A valid operation goes in `operations`. A rejected one goes in
4614
- * `rejected`, with its position and the reason.
4615
- */
4616
- function surfaceContent(surfaceId, draft, operations, options) {
4617
- const { ui, functions } = options;
4618
- const knownSurfaces = /* @__PURE__ */ new Set();
4619
- const manifest = {
4620
- catalogId: ui.id,
4621
- catalogIds: catalogIdsOf(ui),
4622
- components: ui.manifestComponents
4623
- };
4624
- const valid = [];
4625
- const rejected = [];
4626
- operations.forEach((op, index) => {
4627
- const result = checkOperation(op, {
4628
- manifest,
4629
- knownSurfaces,
4630
- functions
4631
- });
4632
- if (!result.ok) {
4633
- rejected.push({
4634
- index,
4635
- reason: result.reason
4636
- });
4637
- return;
4638
- }
4639
- valid.push(result.operation);
4640
- const kind = (0, _copilotkit_shared.getOperationKind)(result.operation);
4641
- if (kind === "createSurface") knownSurfaces.add(surfaceId);
4642
- if (kind === "deleteSurface") knownSurfaces.delete(surfaceId);
4643
- });
4644
- const create = valid.find((op) => "createSurface" in op);
4645
- return {
4646
- surfaceId,
4647
- target: draft.target,
4648
- catalogId: create?.createSurface.catalogId ?? ui.id,
4649
- operations: valid,
4650
- status: draft.streaming ? "streaming" : "ready",
4651
- rejected
4652
- };
4653
- }
4654
- /**
4655
- * Builds the surfaces of a thread from the ```a2ui fences of its assistant
4656
- * messages, in message order.
4657
- *
4658
- * - Operations are grouped by surfaceId across all messages. An operation
4659
- * with no surfaceId goes to the first surface of its fence, else to
4660
- * `<messageId>-<fenceIndex>`.
4661
- * - The fence that first writes a surface creates it. The `target=<id>` of
4662
- * that fence sets the target. With no target, the surface goes to the
4663
- * chat.
4664
- * - A later fence of the same reply for the same surfaceId updates it. A
4665
- * later reply that reuses the id of a chat surface gets a surface of its
4666
- * own, `<id>@<messageId>`. A page target is updated from any reply.
4667
- * - The status is "streaming" while the creating fence streams, else
4668
- * "ready".
4669
- * - Each operation is validated with `validateOperation`. Rejected ones are
4670
- * left out and listed in `rejected`.
4671
- * - Chat surfaces get the prose lift: informational cards lose their box,
4672
- * and prose becomes markdown that renders between sub-surfaces
4673
- * (`<surfaceId>#<n>`). An inline createSurface is split into its
4674
- * createSurface, updateDataModel and updateComponents first.
4675
- * - A `callRendererFunction` line is not part of a surface. It goes to
4676
- * `functionCalls`. A streaming line gives nothing, so a function never
4677
- * runs with a part of its args.
4678
- *
4679
- * The function is pure. Call it again on each stream update. The manager
4680
- * applies only the new operations, so unchanged surfaces do not render
4681
- * again.
4682
- *
4683
- * @param messages - The messages of one thread.
4684
- * @param options - The generative UI, its declared functions, and whether
4685
- * the last message can still grow.
4686
- * @returns `surfaces`, one content for each surface and sub-surface;
4687
- * `fences`, the blocks that each fence renders, by `fenceKey` (a fence
4688
- * that is not in `fences` renders nothing); `functionCalls`, the function
4689
- * calls of the fences in order; and `parts`, the surface ids of the parts
4690
- * of each surface, by surface id.
4691
- *
4692
- * @example
4693
- * ```ts
4694
- * const { surfaces } = buildMarkdownSurfaces(agent.messages, {
4695
- * ui,
4696
- * functions: {},
4697
- * running: agent.isRunning,
4698
- * });
4699
- * for (const content of surfaces) manager.ingest(threadId, agentId, content);
4700
- * ```
4701
- */
4702
- function buildMarkdownSurfaces(messages, options) {
4703
- const { ui, cache } = options;
4704
- const drafts = /* @__PURE__ */ new Map();
4705
- const readdressOnce = (op, surfaceId) => {
4706
- if (!cache) return readdress(op, surfaceId);
4707
- let copies = cache.readdressed.get(op);
4708
- if (!copies) {
4709
- copies = /* @__PURE__ */ new Map();
4710
- cache.readdressed.set(op, copies);
4711
- }
4712
- let copy = copies.get(surfaceId);
4713
- if (!copy) {
4714
- copy = readdress(op, surfaceId);
4715
- copies.set(surfaceId, copy);
4716
- }
4717
- return copy;
4718
- };
4719
- /** The surfaces that each fence created, in order. */
4720
- const created = /* @__PURE__ */ new Map();
4721
- const functionCalls = [];
4722
- /** The message that owns each chat surface id, by the id the model wrote. */
4723
- const chatOwners = /* @__PURE__ */ new Map();
4724
- const lastMessage = messages[messages.length - 1];
4725
- /**
4726
- * A chat surface belongs to the reply that wrote it: the chat is a
4727
- * transcript, so a later reply that reuses an id gets a surface of its
4728
- * own (`<id>@<messageId>`) instead of changing the earlier reply. A fence
4729
- * for a page target keeps its id, because a target is a place on the
4730
- * page that a later reply updates on purpose.
4731
- */
4732
- const scopedSurfaceId = (requested, messageId, target) => {
4733
- if (target !== void 0) return requested;
4734
- const owner = chatOwners.get(requested);
4735
- if (owner === void 0) {
4736
- chatOwners.set(requested, messageId);
4737
- return requested;
4738
- }
4739
- return owner === messageId ? requested : `${requested}@${messageId}`;
4740
- };
4741
- for (const message of messages) {
4742
- if (message.role !== "assistant" || !isString(message.content)) continue;
4743
- const isLastMessage = message === lastMessage;
4744
- const content = message.content;
4745
- const segments = cache ? cache.segments.get(content, () => (0, _copilotkit_core.splitA2UIMarkdown)(content)) : (0, _copilotkit_core.splitA2UIMarkdown)(content);
4746
- for (const segment of segments) {
4747
- if (segment.type !== "a2ui") continue;
4748
- const isStreaming = !segment.closed && isLastMessage && options.running;
4749
- const parseFence = () => {
4750
- const parsed = fenceOperations(segment.text, isStreaming);
4751
- const { functionCalls } = (0, _copilotkit_core.prepareSurfaceOperations)({
4752
- operations: parsed,
4753
- fallbackSurfaceId: "",
4754
- catalogId: ui.id
4755
- });
4756
- return {
4757
- operations: parsed,
4758
- functionCalls
4759
- };
4760
- };
4761
- const fence = cache ? cache.fences.get(`${isStreaming}:${segment.text}`, parseFence) : parseFence();
4762
- const { operations } = fence;
4763
- const key = fenceKey(message.id, segment.index);
4764
- const fenceSurfaceId = operations.map(_copilotkit_core.getMarkdownOperationSurfaceId).find(isString) ?? `${message.id}-${segment.index}`;
4765
- for (const operation of fence.functionCalls) functionCalls.push({
4766
- messageId: message.id,
4767
- fenceIndex: segment.index,
4768
- operation
4769
- });
4770
- const surfaceOperations = operations.filter((op) => (0, _copilotkit_shared.getOperationKind)(op) !== "callRendererFunction");
4771
- for (const op of surfaceOperations) {
4772
- const requested = (0, _copilotkit_core.getMarkdownOperationSurfaceId)(op) ?? fenceSurfaceId;
4773
- const surfaceId = scopedSurfaceId(requested, message.id, segment.target);
4774
- let draft = drafts.get(surfaceId);
4775
- if (!draft) {
4776
- draft = {
4777
- surfaceId,
4778
- target: segment.target ?? _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
4779
- operations: [],
4780
- streaming: isStreaming
4781
- };
4782
- drafts.set(surfaceId, draft);
4783
- created.set(key, [...created.get(key) ?? [], surfaceId]);
4784
- }
4785
- draft.operations.push(surfaceId === requested ? op : readdressOnce(op, surfaceId));
4786
- }
4787
- }
4788
- }
4789
- const canFlattenCards = hasProp(ui, "Card", "variant");
4790
- const surfaces = [];
4791
- const partsBySurface = /* @__PURE__ */ new Map();
4792
- const childIds = childIdsReader(ui);
4793
- const buildDraft = (draft) => {
4794
- const operations = splitComponentUpdates(expandInlineCreate(createSurfaceFirst((0, _copilotkit_core.prepareSurfaceOperations)({
4795
- operations: draft.operations,
4796
- fallbackSurfaceId: draft.surfaceId,
4797
- catalogId: ui.id,
4798
- catalogIds: catalogIdsOf(ui)
4799
- }).operations)));
4800
- const parts = draft.target === _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET ? liftProse(canFlattenCards ? (0, _copilotkit_core.flattenInformationalCards)(operations, { childIds }) : operations, draft.surfaceId, childIds) : [{
4801
- kind: "surface",
4802
- surfaceId: draft.surfaceId,
4803
- operations
4804
- }];
4805
- const contents = parts.flatMap((part) => part.kind === "surface" ? [surfaceContent(part.surfaceId, draft, part.operations, options)] : []);
4806
- return {
4807
- ...draft,
4808
- parts,
4809
- contents
4810
- };
4811
- };
4812
- for (const draft of drafts.values()) {
4813
- 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);
4814
- partsBySurface.set(draft.surfaceId, built.parts);
4815
- surfaces.push(...built.contents);
4816
- }
4817
- cache?.endBuild();
4818
- /** The surface ids of the parts of each split surface, by surface id. */
4819
- const parts = /* @__PURE__ */ new Map();
4820
- for (const [surfaceId, surfaceParts] of partsBySurface) {
4821
- const ids = surfaceParts.flatMap((part) => part.kind === "surface" ? [part.surfaceId] : []);
4822
- parts.set(surfaceId, ids);
4823
- }
4824
- const fences = /* @__PURE__ */ new Map();
4825
- for (const [key, surfaceIds] of created) {
4826
- const blocks = [];
4827
- for (const surfaceId of surfaceIds) {
4828
- if (drafts.get(surfaceId)?.target !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET) continue;
4829
- for (const part of partsBySurface.get(surfaceId) ?? []) blocks.push(part.kind === "markdown" ? part : {
4830
- kind: "surface",
4831
- surfaceId: part.surfaceId
4832
- });
4833
- }
4834
- if (blocks.length > 0) fences.set(key, blocks);
4835
- }
4836
- return {
4837
- surfaces,
4838
- fences,
4839
- functionCalls,
4840
- parts
4841
- };
4842
- }
4843
- /** The declared functions, as `validateOperation` takes them. */
4844
- function declaredFunctions(ui) {
4845
- const functions = {};
4846
- for (const [name, fn] of ui.functions) try {
4847
- functions[name] = {
4848
- ...fn.description ? { description: fn.description } : {},
4849
- parameters: toJsonSchema(fn.parameters)
4850
- };
4851
- } catch {
4852
- functions[name] = { parameters: {} };
4853
- }
4854
- return functions;
4855
- }
4856
- /** True when `list` starts with all the items of `prefix`. */
4857
- function startsWith(list, prefix) {
4858
- return list.length >= prefix.length && prefix.every((item, index) => item === list[index]);
4859
- }
4860
- /** A content that deletes a surface that the fences no longer write. */
4861
- function removalContent(surfaceId, catalogId) {
4862
- return {
4863
- surfaceId,
4864
- target: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
4865
- catalogId,
4866
- status: "ready",
4867
- rejected: [],
4868
- operations: [{
4869
- version: _copilotkit_shared.A2UI_VERSION,
4870
- createSurface: {
4871
- surfaceId,
4872
- catalogId
4873
- }
4874
- }, {
4875
- version: _copilotkit_shared.A2UI_VERSION,
4876
- deleteSurface: { surfaceId }
4877
- }]
4878
- };
4879
- }
4880
- /**
4881
- * The markdown transport source of one surface manager. It turns the
4882
- * messages of a thread into surfaces in the manager, and keeps the blocks
4883
- * that each fence renders.
4884
- */
4885
- var MarkdownSurfaceSource = class {
4886
- constructor(manager, ui) {
4887
- this.manager = manager;
4888
- this.ui = ui;
4889
- this.fences = /* @__PURE__ */ new Map();
4890
- this.ingested = /* @__PURE__ */ new Map();
4891
- this.contents = /* @__PURE__ */ new Map();
4892
- this.caches = /* @__PURE__ */ new Map();
4893
- this.functions = declaredFunctions(ui);
4894
- }
4895
- /**
4896
- * Builds the surfaces of `threadId` from `messages` and gives them to the
4897
- * manager. A surface that an earlier sync of the thread made, and that the
4898
- * messages no longer write, is deleted. Other threads do not change.
4899
- *
4900
- * @param threadId - The thread of the messages.
4901
- * @param agentId - The agent that owns the thread.
4902
- * @param messages - All messages of the thread.
4903
- * @param options - `running`: the last message can still grow.
4904
- * @returns The function calls of the fences, in order. The source does
4905
- * not run them.
4906
- */
4907
- sync(threadId, agentId, messages, options) {
4908
- let cache = this.caches.get(threadId);
4909
- if (!cache) {
4910
- cache = new MarkdownBuildCache();
4911
- this.caches.set(threadId, cache);
4912
- }
4913
- const result = buildMarkdownSurfaces(messages, {
4914
- ui: this.ui,
4915
- functions: this.functions,
4916
- running: options.running,
4917
- cache
4918
- });
4919
- this.fences.set(threadId, result.fences);
4920
- for (const parts of result.parts.values()) this.manager.linkSurfaces(threadId, parts);
4921
- const previous = this.ingested.get(threadId) ?? /* @__PURE__ */ new Map();
4922
- const previousContents = this.contents.get(threadId) ?? /* @__PURE__ */ new Map();
4923
- const next = /* @__PURE__ */ new Map();
4924
- const nextContents = /* @__PURE__ */ new Map();
4925
- for (const content of result.surfaces) {
4926
- nextContents.set(content.surfaceId, content);
4927
- const before = previous.get(content.surfaceId);
4928
- if (before && previousContents.get(content.surfaceId) === content) {
4929
- next.set(content.surfaceId, before);
4930
- continue;
4931
- }
4932
- const fingerprints = content.operations.map((op) => JSON.stringify(op));
4933
- if (before && !startsWith(fingerprints, before)) this.manager.ingest(threadId, agentId, {
4934
- ...content,
4935
- operations: []
4936
- });
4937
- this.manager.ingest(threadId, agentId, content);
4938
- next.set(content.surfaceId, fingerprints);
4939
- }
4940
- for (const surfaceId of previous.keys()) {
4941
- if (next.has(surfaceId)) continue;
4942
- this.manager.ingest(threadId, agentId, removalContent(surfaceId, this.ui.id));
4943
- }
4944
- this.ingested.set(threadId, next);
4945
- this.contents.set(threadId, nextContents);
4946
- return result.functionCalls;
4947
- }
4948
- /**
4949
- * The blocks that a fence renders in the chat, from the latest sync of the
4950
- * thread. `undefined` when the fence renders nothing: it updates a surface
4951
- * of an earlier fence, its surface is for a named target, or it has no
4952
- * complete operation yet.
4953
- */
4954
- getFenceBlocks(threadId, messageId, fenceIndex) {
4955
- return this.fences.get(threadId)?.get(fenceKey(messageId, fenceIndex));
4956
- }
4957
- };
4958
- const sources = /* @__PURE__ */ new WeakMap();
4959
- /**
4960
- * The markdown source of a generative UI runtime. There is one source for
4961
- * each surface manager. The root syncs it, and the chat messages read the
4962
- * fence blocks from it.
4963
- */
4964
- function getMarkdownSurfaceSource(runtime) {
4965
- let source = sources.get(runtime.manager);
4966
- if (!source) {
4967
- source = new MarkdownSurfaceSource(runtime.manager, runtime.ui);
4968
- sources.set(runtime.manager, source);
4969
- }
4970
- return source;
4971
- }
4972
-
4973
- //#endregion
4974
- //#region src/v2/generative-ui/calc.ts
4975
- const MAX_SERIES = 1e3;
4976
- const OPERATORS = [
4977
- "&&",
4978
- "||",
4979
- "==",
4980
- "!=",
4981
- "<=",
4982
- ">=",
4983
- "<",
4984
- ">",
4985
- "+",
4986
- "-",
4987
- "*",
4988
- "/",
4989
- "%",
4990
- "^",
4991
- "(",
4992
- ")",
4993
- ",",
4994
- "?",
4995
- ":",
4996
- "!"
4997
- ];
4998
- function tokenize(source) {
4999
- const tokens = [];
5000
- let i = 0;
5001
- while (i < source.length) {
5002
- const char = source[i];
5003
- if (/\s/.test(char)) {
5004
- i++;
5005
- continue;
5006
- }
5007
- if (/[0-9.]/.test(char)) {
5008
- const match = /^\d*\.?\d+(?:[eE][-+]?\d+)?|^\d+\.?/.exec(source.slice(i));
5009
- if (!match) throw new ExpressionError(`calc: bad number at "${source.slice(i, i + 8)}"`);
5010
- tokens.push({
5011
- kind: "number",
5012
- value: Number(match[0])
5013
- });
5014
- i += match[0].length;
5015
- continue;
5016
- }
5017
- if (char === "'" || char === "\"") {
5018
- let value = "";
5019
- i++;
5020
- while (i < source.length && source[i] !== char) {
5021
- if (source[i] === "\\" && i + 1 < source.length) i++;
5022
- value += source[i++];
5023
- }
5024
- if (i >= source.length) throw new ExpressionError("calc: unclosed string");
5025
- i++;
5026
- tokens.push({
5027
- kind: "string",
5028
- value
5029
- });
5030
- continue;
5031
- }
5032
- if (/[A-Za-z_]/.test(char)) {
5033
- const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));
5034
- tokens.push({
5035
- kind: "name",
5036
- value: match[0]
5037
- });
5038
- i += match[0].length;
5039
- continue;
5040
- }
5041
- const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));
5042
- if (!op) throw new ExpressionError(`calc: unexpected "${char}"`);
5043
- tokens.push({
5044
- kind: "op",
5045
- value: op
5046
- });
5047
- i += op.length;
5048
- }
5049
- tokens.push({ kind: "end" });
5050
- return tokens;
5051
- }
5052
- function numberOf(value, what) {
5053
- if (typeof value === "number") {
5054
- if (!Number.isFinite(value)) throw new ExpressionError(`calc: ${what} is not finite`);
5055
- return value;
5056
- }
5057
- if (typeof value === "boolean") return value ? 1 : 0;
5058
- if (typeof value === "string" && value.trim() !== "") {
5059
- const parsed = Number(value);
5060
- if (Number.isFinite(parsed)) return parsed;
5061
- }
5062
- if (value === null || value === void 0) throw new ExpressionError(`calc: ${what} has no value`);
5063
- throw new ExpressionError(`calc: ${what} is not a number`);
5064
- }
5065
- function describe(value) {
5066
- return typeof value === "string" ? `"${value}"` : String(value);
5067
- }
5068
- const MATH = {
5069
- min: (args) => Math.min(...args),
5070
- max: (args) => Math.max(...args),
5071
- abs: ([x]) => Math.abs(x),
5072
- floor: ([x]) => Math.floor(x),
5073
- ceil: ([x]) => Math.ceil(x),
5074
- round: ([x, decimals = 0]) => {
5075
- const factor = 10 ** Math.trunc(decimals);
5076
- return Math.round(x * factor) / factor;
5077
- },
5078
- pow: ([x, y]) => x ** y,
5079
- sqrt: ([x]) => Math.sqrt(x),
5080
- exp: ([x]) => Math.exp(x),
5081
- ln: ([x]) => Math.log(x),
5082
- log10: ([x]) => Math.log10(x)
5083
- };
5084
- /** How many args a function takes, at least and at most; min and max take any. */
5085
- const ARITY = {
5086
- abs: [1, 1],
5087
- floor: [1, 1],
5088
- ceil: [1, 1],
5089
- round: [1, 2],
5090
- pow: [2, 2],
5091
- sqrt: [1, 1],
5092
- exp: [1, 1],
5093
- ln: [1, 1],
5094
- log10: [1, 1]
5095
- };
5096
- /** Named constants, when no arg of the same name is passed. */
5097
- const CONSTANTS = {
5098
- pi: Math.PI,
5099
- e: Math.E
5100
- };
5101
- var CalcParser = class {
5102
- constructor(tokens, scope, source) {
5103
- this.tokens = tokens;
5104
- this.scope = scope;
5105
- this.source = source;
5106
- this.pos = 0;
5107
- this.skipDepth = 0;
5108
- }
5109
- parse() {
5110
- const value = this.ternary();
5111
- if (this.tokens[this.pos].kind !== "end") this.fail(`unexpected "${this.text(this.tokens[this.pos])}"`);
5112
- return value;
5113
- }
5114
- fail(what) {
5115
- throw new ExpressionError(`calc: ${what} in "${this.source}"`);
5116
- }
5117
- text(token) {
5118
- return token.kind === "end" ? "end" : String(token.value);
5119
- }
5120
- peekOp(...ops) {
5121
- const token = this.tokens[this.pos];
5122
- return token.kind === "op" && ops.includes(token.value) ? token.value : void 0;
5123
- }
5124
- expectOp(op) {
5125
- if (this.peekOp(op) === void 0) this.fail(`expected "${op}" but found "${this.text(this.tokens[this.pos])}"`);
5126
- this.pos++;
5127
- }
5128
- /**
5129
- * Parses a part of the expression that the result does not need (the
5130
- * other branch of `?:`, the right side of a decided `&&` or `||`). It
5131
- * still has to be parsed to find where it ends, so syntax errors are
5132
- * reported, but no value is checked or computed: `n == 0 ? 0 : 10 / n`
5133
- * is a valid guard.
5134
- */
5135
- skipped(parse) {
5136
- this.skipDepth++;
5137
- try {
5138
- parse();
5139
- } finally {
5140
- this.skipDepth--;
5141
- }
5142
- return null;
5143
- }
5144
- /** The number of a value, or 0 while skipping. */
5145
- num(value, what) {
5146
- return this.skipDepth > 0 ? 0 : numberOf(value, what);
5147
- }
5148
- ternary() {
5149
- const condition = this.or();
5150
- if (this.peekOp("?") === void 0) return condition;
5151
- this.pos++;
5152
- const takesFirst = truthOf(condition);
5153
- const whenTrue = takesFirst ? this.ternary() : this.skipped(() => this.ternary());
5154
- this.expectOp(":");
5155
- const whenFalse = takesFirst ? this.skipped(() => this.ternary()) : this.ternary();
5156
- return takesFirst ? whenTrue : whenFalse;
5157
- }
5158
- or() {
5159
- let left = this.and();
5160
- while (this.peekOp("||")) {
5161
- this.pos++;
5162
- if (truthOf(left)) {
5163
- this.skipped(() => this.and());
5164
- left = true;
5165
- } else left = truthOf(this.and());
5166
- }
5167
- return left;
5168
- }
5169
- and() {
5170
- let left = this.equality();
5171
- while (this.peekOp("&&")) {
5172
- this.pos++;
5173
- if (!truthOf(left)) {
5174
- this.skipped(() => this.equality());
5175
- left = false;
5176
- } else left = truthOf(this.equality());
5177
- }
5178
- return left;
5179
- }
5180
- equality() {
5181
- let left = this.comparison();
5182
- for (let op = this.peekOp("==", "!="); op; op = this.peekOp("==", "!=")) {
5183
- this.pos++;
5184
- const right = this.comparison();
5185
- const isEqual = typeof left === "number" || typeof right === "number" ? this.num(left, "the left side of ==") === this.num(right, "the right side of ==") : left === right;
5186
- left = op === "==" ? isEqual : !isEqual;
5187
- }
5188
- return left;
5189
- }
5190
- comparison() {
5191
- let left = this.additive();
5192
- for (let op = this.peekOp("<", "<=", ">", ">="); op; op = this.peekOp("<", "<=", ">", ">=")) {
5193
- this.pos++;
5194
- const a = this.num(left, `the left side of ${op}`);
5195
- const b = this.num(this.additive(), `the right side of ${op}`);
5196
- left = op === "<" ? a < b : op === "<=" ? a <= b : op === ">" ? a > b : a >= b;
5197
- }
5198
- return left;
5199
- }
5200
- additive() {
5201
- let left = this.multiplicative();
5202
- for (let op = this.peekOp("+", "-"); op; op = this.peekOp("+", "-")) {
5203
- this.pos++;
5204
- const right = this.multiplicative();
5205
- if (op === "+" && (typeof left === "string" || typeof right === "string")) left = `${left ?? ""}${right ?? ""}`;
5206
- else {
5207
- const a = this.num(left, `the left side of ${op}`);
5208
- const b = this.num(right, `the right side of ${op}`);
5209
- left = op === "+" ? a + b : a - b;
5210
- }
5211
- }
5212
- return left;
5213
- }
5214
- multiplicative() {
5215
- let left = this.unary();
5216
- for (let op = this.peekOp("*", "/", "%"); op; op = this.peekOp("*", "/", "%")) {
5217
- this.pos++;
5218
- const a = this.num(left, `the left side of ${op}`);
5219
- const b = this.num(this.unary(), `the right side of ${op}`);
5220
- if (op !== "*" && b === 0 && this.skipDepth === 0) this.fail("division by zero");
5221
- left = op === "*" ? a * b : op === "/" ? a / b : a % b;
5222
- }
5223
- return left;
5224
- }
5225
- unary() {
5226
- if (this.peekOp("-")) {
5227
- this.pos++;
5228
- return -this.num(this.unary(), "the operand of -");
5229
- }
5230
- if (this.peekOp("!")) {
5231
- this.pos++;
5232
- return !truthOf(this.unary());
5233
- }
5234
- return this.power();
5235
- }
5236
- /** `a ^ b`: binds tighter than `*` and unary minus, right to left. */
5237
- power() {
5238
- const base = this.primary();
5239
- if (!this.peekOp("^")) return base;
5240
- this.pos++;
5241
- const exponent = this.unary();
5242
- if (this.skipDepth > 0) return null;
5243
- return this.finite(this.num(base, "the left side of ^") ** this.num(exponent, "the right side of ^"), "^");
5244
- }
5245
- finite(value, what) {
5246
- if (!Number.isFinite(value)) this.fail(`${what} has no finite result`);
5247
- return value;
5248
- }
5249
- primary() {
5250
- const token = this.tokens[this.pos++];
5251
- switch (token.kind) {
5252
- case "number": return token.value;
5253
- case "string": return token.value;
5254
- case "name": return this.name(token.value);
5255
- case "op":
5256
- if (token.value === "(") {
5257
- const value = this.ternary();
5258
- this.expectOp(")");
5259
- return value;
5260
- }
5261
- return this.fail(`unexpected "${token.value}"`);
5262
- case "end": return this.fail("missing value");
5263
- }
5264
- }
5265
- name(name) {
5266
- if (name === "true") return true;
5267
- if (name === "false") return false;
5268
- if (name === "null") return null;
5269
- if (this.peekOp("(")) {
5270
- this.pos++;
5271
- const args = [];
5272
- if (this.peekOp(")") === void 0) for (;;) {
5273
- args.push(this.num(this.ternary(), `an argument of ${name}`));
5274
- if (this.peekOp(",") === void 0) break;
5275
- this.pos++;
5276
- }
5277
- this.expectOp(")");
5278
- if (this.skipDepth > 0) return null;
5279
- const fn = Object.prototype.hasOwnProperty.call(MATH, name) ? MATH[name] : void 0;
5280
- if (!fn) this.fail(`unknown function ${name}`);
5281
- if (args.length === 0) this.fail(`${name} needs an argument`);
5282
- const [least, most] = ARITY[name] ?? [1, Infinity];
5283
- if (args.length < least || args.length > most) this.fail(`${name} takes ${least === most ? least : `${least} or ${most}`} argument${most === 1 ? "" : "s"}`);
5284
- return this.finite(fn(args), name);
5285
- }
5286
- if (this.skipDepth > 0) return null;
5287
- if (!Object.prototype.hasOwnProperty.call(this.scope, name)) {
5288
- if (Object.prototype.hasOwnProperty.call(CONSTANTS, name)) return CONSTANTS[name];
5289
- this.fail(`unknown name ${name}; pass it as an arg`);
5290
- }
5291
- const value = this.scope[name];
5292
- if (value !== null && typeof value !== "number" && typeof value !== "string" && typeof value !== "boolean") this.fail(`${name} is not a number, text or boolean (${describe(value)})`);
5293
- return value;
5294
- }
5295
- };
5296
- /**
5297
- * Evaluates `expression` with the names in `scope`. Gives a number, a
5298
- * string, a boolean or null. Throws an {@link ExpressionError} for a bad
5299
- * expression or a missing name.
5300
- */
5301
- function evaluateCalc(expression, scope) {
5302
- if (typeof expression !== "string" || expression.trim() === "") throw new ExpressionError("calc: expression must be a string");
5303
- return new CalcParser(tokenize(expression), scope, expression).parse();
5304
- }
5305
- /** The `calc` function: the expression is `args.expression`, the rest is the scope. */
5306
- function calc(args) {
5307
- const { expression, ...scope } = args;
5308
- return evaluateCalc(expression, scope);
5309
- }
5310
- const WHOLE_EXPRESSION = /^\$\{([^}]*)\}$/;
5311
- /**
5312
- * Fills `item` for one iteration: a string that is one `${...}` gives the
5313
- * typed value of the expression, a string with `${...}` inside it is
5314
- * interpolated as text, and objects and arrays are walked.
5315
- */
5316
- function fillItem(item, scope) {
5317
- if (typeof item === "string") {
5318
- const whole = WHOLE_EXPRESSION.exec(item);
5319
- if (whole) return evaluateCalc(whole[1], scope);
5320
- return item.replace(/\$\{([^}]*)\}/g, (_, expression) => {
5321
- const value = evaluateCalc(expression, scope);
5322
- return value === null ? "" : String(value);
5323
- });
5324
- }
5325
- if (Array.isArray(item)) return item.map((entry) => fillItem(entry, scope));
5326
- if (typeof item === "object" && item !== null) return Object.fromEntries(Object.entries(item).map(([key, value]) => [key, fillItem(value, scope)]));
5327
- return item;
5328
- }
5329
- /**
5330
- * The `series` function: `count` copies of `item`, with the loop variable
5331
- * (`variable`, default "i") counting from `start` (default 1) and the other
5332
- * args in scope of the `${...}` expressions of the item.
5333
- */
5334
- function series(args) {
5335
- const { count, item, variable, start, ...scope } = args;
5336
- const length = numberOf(count, "count");
5337
- if (!Number.isInteger(length) || length < 0) throw new ExpressionError("series: count must be a whole number");
5338
- if (length > MAX_SERIES) throw new ExpressionError(`series: count is at most ${MAX_SERIES}`);
5339
- if (item === void 0) throw new ExpressionError("series: item is required");
5340
- const name = variable === void 0 ? "i" : variable;
5341
- if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new ExpressionError("series: variable must be a name");
5342
- const first = start === void 0 ? 1 : numberOf(start, "start");
5343
- return Array.from({ length }, (_, index) => fillItem(item, {
5344
- ...scope,
5345
- [name]: first + index
5346
- }));
5347
- }
5348
-
5349
- //#endregion
5350
- //#region src/v2/generative-ui/resolve.ts
5351
- BASIC_FUNCTIONS.calc = calc;
5352
- BASIC_FUNCTIONS.series = series;
5353
- const NO_DATA = { get: () => void 0 };
5354
- BASIC_FUNCTIONS.formatString = (args) => resolveDynamicValue({
5355
- "@call": "formatString",
5356
- args
5357
- }, {
5358
- data: NO_DATA,
5359
- basePath: void 0
5360
- }).value;
5361
- /** Adds one segment to a JSON pointer: ("/items", "0") gives "/items/0". */
5362
- function joinPath(base, segment) {
5363
- return base === "/" ? `/${segment}` : `${base}/${segment}`;
5364
- }
5365
- /**
5366
- * The absolute data model path of a binding. A path without a leading "/"
5367
- * is relative to the current template item, or to the root outside of one.
5368
- */
5369
- function resolvePath(path, basePath) {
5370
- if (path.startsWith("/")) return path;
5371
- return joinPath(basePath ?? "/", path);
5372
- }
5373
- /**
5374
- * The index of the template item at `basePath`: its last segment.
5375
- * `undefined` outside of a template.
5376
- */
5377
- function templateIndex(basePath) {
5378
- if (basePath === void 0) return void 0;
5379
- const index = Number(basePath.slice(basePath.lastIndexOf("/") + 1));
5380
- return Number.isInteger(index) ? index : void 0;
5381
- }
5382
- /** The value of a ValidationResult where a boolean is expected. */
5383
- function coerce(value, keep) {
5384
- return !keep && (0, _copilotkit_shared.isValidationResult)(value) ? value.valid : value;
5385
- }
5386
- /**
5387
- * Resolves `value`. `keepValidation` keeps a ValidationResult as it is; by
5388
- * default it becomes its `valid` boolean, which is what every prop except
5389
- * a check condition wants.
5390
- */
5391
- function walk(value, state, keepValidation, scope = "outside") {
5392
- if (Array.isArray(value)) {
5393
- let changed = false;
5394
- const itemScope = scope === "list" ? "check" : "outside";
5395
- const items = value.map((item) => {
5396
- const next = walk(item, state, keepValidation, itemScope);
5397
- if (next !== item) changed = true;
5398
- return next;
5399
- });
5400
- return changed ? items : value;
5401
- }
5402
- if (!isRecord(value)) return value;
5403
- if ((0, _copilotkit_shared.isPathBinding)(value)) {
5404
- const path = resolvePath(value["@path"], state.context.basePath);
5405
- state.paths.add(path);
5406
- return state.context.data.get(path);
5407
- }
5408
- if ((0, _copilotkit_shared.isCallBinding)(value)) return call(value, state, keepValidation);
5409
- if ((0, _copilotkit_shared.isActionBinding)(value)) return value;
5410
- let changed = false;
5411
- const entries = Object.entries(value).map(([key, item]) => {
5412
- const next = walk(item, state, keepValidation || scope === "check" && key === "condition", key === "checks" ? "list" : "outside");
5413
- if (next !== item) changed = true;
5414
- return [key, next];
5415
- });
5416
- return changed ? Object.fromEntries(entries) : value;
5417
- }
5418
- function call(binding, state, keepValidation) {
5419
- const name = binding["@call"];
5420
- const rawArgs = binding.args ?? {};
5421
- if (!isRecord(rawArgs)) throw new ExpressionError(`the args of "${name}" must be an object`);
5422
- if (name === _copilotkit_shared.A2UI_INDEX_FUNCTION) {
5423
- const index = templateIndex(state.context.basePath);
5424
- if (index === void 0) return void 0;
5425
- const offset = walk(rawArgs.offset, state, false);
5426
- return index + (typeof offset === "number" ? offset : 0);
5427
- }
5428
- if (name === "formatString") {
5429
- const template = walk(rawArgs.value, state, false);
5430
- if (typeof template !== "string") throw new ExpressionError("formatString takes a string value");
5431
- return formatString(template, state);
5432
- }
5433
- const fn = Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name) ? BASIC_FUNCTIONS[name] : void 0;
5434
- if (!fn) throw new ExpressionError(`"${name}" is not a basic function`);
5435
- if (requiresUserActivation(name)) throw new ExpressionError(`"${name}" is not a value; bind it as the functionCall of an event`);
5436
- const result = fn(walk(rawArgs, state, false));
5437
- return givesValidationResult(name) ? coerce(result, keepValidation) : result;
5438
- }
5439
- function resolveDynamicValue(value, context, options = {}) {
5440
- const result = tryResolveDynamicValue(value, context, options);
5441
- if (!result.ok) throw result.error;
5442
- return result;
5443
- }
5444
- /**
5445
- * Like {@link resolveDynamicValue}, but a failure comes back as a result
5446
- * with the paths read so far, so the caller can keep watching them: a
5447
- * function that fails on an empty field works once the user fills it.
5448
- */
5449
- function tryResolveDynamicValue(value, context, options = {}) {
5450
- const state = {
5451
- context,
5452
- paths: /* @__PURE__ */ new Set()
5453
- };
5454
- try {
5455
- return {
5456
- ok: true,
5457
- value: walk(value, state, options.keepValidation ?? false, options.isChecks ? "list" : "outside"),
5458
- paths: state.paths
5459
- };
5460
- } catch (error) {
5461
- return {
5462
- ok: false,
5463
- error: error instanceof Error ? error : new Error(String(error)),
5464
- paths: state.paths
5465
- };
5466
- }
5467
- }
5468
- /** True when `value` holds a `{"@path"}` or `{"@call"}` at any depth. */
5469
- function containsDynamicValue(value) {
5470
- if (Array.isArray(value)) return value.some(containsDynamicValue);
5471
- if (!isRecord(value)) return false;
5472
- if ((0, _copilotkit_shared.isPathBinding)(value) || (0, _copilotkit_shared.isCallBinding)(value)) return true;
5473
- if ((0, _copilotkit_shared.isActionBinding)(value)) return false;
5474
- return Object.values(value).some(containsDynamicValue);
5475
- }
5476
- /**
5477
- * The `${...}` grammar of `formatString`:
5478
- *
5479
- * expression := path | literal | call
5480
- * path := "/" segments | identifier ("/" segments)*
5481
- * literal := 'text' | "text" | number | true | false | null
5482
- * call := identifier "(" [ name ":" expression ("," name ":" expression)* ] ")"
5483
- *
5484
- * A `\${` in the template is a literal `${`.
5485
- */
5486
- function formatString(template, state) {
5487
- let out = "";
5488
- let index = 0;
5489
- while (index < template.length) {
5490
- const start = template.indexOf("${", index);
5491
- if (start === -1) {
5492
- out += template.slice(index);
5493
- break;
5494
- }
5495
- if (start > 0 && template[start - 1] === "\\") {
5496
- out += `${template.slice(index, start - 1)}\${`;
5497
- index = start + 2;
5498
- continue;
5499
- }
5500
- out += template.slice(index, start);
5501
- const end = matchingBrace(template, start + 2);
5502
- if (end === -1) throw new ExpressionError("formatString: unclosed ${");
5503
- const value = new ExpressionParser(template.slice(start + 2, end).trim(), state).parse();
5504
- out += value === void 0 || value === null ? "" : String(value);
5505
- index = end + 1;
5506
- }
5507
- return out;
5508
- }
5509
- /** The index of the `}` that closes the block opened at `from`, or -1. */
5510
- function matchingBrace(template, from) {
5511
- let depth = 1;
5512
- let quote;
5513
- for (let i = from; i < template.length; i++) {
5514
- const char = template[i];
5515
- if (quote) {
5516
- if (char === "\\") i++;
5517
- else if (char === quote) quote = void 0;
5518
- continue;
5519
- }
5520
- if (char === "'" || char === "\"") quote = char;
5521
- else if (char === "{") depth++;
5522
- else if (char === "}" && --depth === 0) return i;
5523
- }
5524
- return -1;
5525
- }
5526
- const IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;
5527
- const NUMBER = /-?\d+(?:\.\d+)?/y;
5528
- const PATH_SEGMENT = /[^\s,():'"]+/y;
5529
- var ExpressionParser = class {
5530
- constructor(source, state) {
5531
- this.source = source;
5532
- this.state = state;
5533
- this.pos = 0;
5534
- }
5535
- parse() {
5536
- const value = this.expression();
5537
- this.skipSpace();
5538
- if (this.pos < this.source.length) throw new ExpressionError(`formatString: unexpected "${this.source.slice(this.pos)}" in \${${this.source}}`);
5539
- return value;
5540
- }
5541
- fail(what) {
5542
- throw new ExpressionError(`formatString: ${what} in \${${this.source}}`);
5543
- }
5544
- skipSpace() {
5545
- while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) this.pos++;
5546
- }
5547
- match(pattern) {
5548
- pattern.lastIndex = this.pos;
5549
- const found = pattern.exec(this.source);
5550
- if (!found) return void 0;
5551
- this.pos = pattern.lastIndex;
5552
- return found[0];
5553
- }
5554
- expression() {
5555
- this.skipSpace();
5556
- const char = this.source[this.pos];
5557
- if (char === void 0) this.fail("missing expression");
5558
- if (char === "'" || char === "\"") return this.quoted(char);
5559
- if (char === "/") return this.path(this.match(PATH_SEGMENT) ?? "/");
5560
- const number = this.match(NUMBER);
5561
- if (number !== void 0) return Number(number);
5562
- const name = this.match(IDENTIFIER);
5563
- if (name === void 0) this.fail(`unexpected "${char}"`);
5564
- if (name === "true") return true;
5565
- if (name === "false") return false;
5566
- if (name === "null") return null;
5567
- this.skipSpace();
5568
- if (this.source[this.pos] === "(") return this.call(name);
5569
- if (name.startsWith("@")) return call({ "@call": name }, this.state, false);
5570
- const rest = this.source[this.pos] === "/" ? this.match(PATH_SEGMENT) : "";
5571
- return this.path(`${name}${rest ?? ""}`);
5572
- }
5573
- quoted(quote) {
5574
- let value = "";
5575
- this.pos++;
5576
- while (this.pos < this.source.length) {
5577
- const char = this.source[this.pos++];
5578
- if (char === "\\" && this.pos < this.source.length) value += this.source[this.pos++];
5579
- else if (char === quote) return value;
5580
- else value += char;
5581
- }
5582
- return this.fail("unclosed string");
5583
- }
5584
- path(path) {
5585
- const absolute = resolvePath(path, this.state.context.basePath);
5586
- this.state.paths.add(absolute);
5587
- return this.state.context.data.get(absolute);
5588
- }
5589
- call(name) {
5590
- this.pos++;
5591
- const args = {};
5592
- this.skipSpace();
5593
- if (this.source[this.pos] === ")") {
5594
- this.pos++;
5595
- return call({
5596
- "@call": name,
5597
- args
5598
- }, this.state, false);
5599
- }
5600
- for (;;) {
5601
- this.skipSpace();
5602
- const key = this.match(IDENTIFIER);
5603
- if (key === void 0) this.fail("expected an argument name");
5604
- this.skipSpace();
5605
- if (this.source[this.pos] !== ":") this.fail(`expected ":" after ${key}`);
5606
- this.pos++;
5607
- args[key] = this.expression();
5608
- this.skipSpace();
5609
- const next = this.source[this.pos++];
5610
- if (next === ")") break;
5611
- if (next !== ",") this.fail(`expected "," or ")" after ${key}`);
5612
- }
5613
- return call({
5614
- "@call": name,
5615
- args
5616
- }, this.state, false);
5617
- }
5618
- };
5619
-
5620
- //#endregion
5621
- //#region src/v2/generative-ui/schema.ts
5622
- const ASYNC_ISSUE = { message: "the schema validates asynchronously; component props and state need a schema that validates synchronously" };
5623
- function toResult(result) {
5624
- return result.issues ? {
5625
- success: false,
5626
- issues: result.issues
5627
- } : {
5628
- success: true,
5629
- data: result.value
5630
- };
5631
- }
5632
- /**
5633
- * Validates `value` with `schema`. The result comes back at once when the
5634
- * schema validates synchronously, else as a promise.
5635
- */
5636
- function validateSchema(schema, value) {
5637
- const result = schema["~standard"].validate(value);
5638
- return result instanceof Promise ? result.then(toResult) : toResult(result);
5639
- }
5640
- /**
5641
- * Validates `value` synchronously, for code that runs during render. A
5642
- * schema that validates asynchronously fails with an issue that says so.
5643
- */
5644
- function validateSchemaSync(schema, value) {
5645
- const result = validateSchema(schema, value);
5646
- if (!(result instanceof Promise)) return result;
5647
- result.catch(() => {});
5648
- return {
5649
- success: false,
5650
- issues: [ASYNC_ISSUE]
5651
- };
5652
- }
5653
- /** True for the issue that `validateSchemaSync` gives for an async schema. */
5654
- function isAsyncIssue(issue) {
5655
- return issue === ASYNC_ISSUE;
5656
- }
5657
- /** The first key of an issue path: the prop the issue is about. */
5658
- function issueKey(issue) {
5659
- const first = issue.path?.[0];
5660
- const key = typeof first === "object" ? first.key : first;
5661
- return key === void 0 ? void 0 : String(key);
5662
- }
5663
- /**
5664
- * `props` without the top-level props whose `null` the schema rejected, or
5665
- * `undefined` when there are none. A model writes `null` for "not set" (an
5666
- * empty selection, a value it has not filled yet), and A2UI deletes a data
5667
- * model key that is set to `null`, so a rejected `null` is read as an unset
5668
- * prop. A prop whose schema accepts `null` keeps it.
5669
- */
5670
- function withoutRejectedNulls(props, issues) {
5671
- const rejected = /* @__PURE__ */ new Set();
5672
- for (const issue of issues) {
5673
- const key = issueKey(issue);
5674
- if (key !== void 0 && issue.path?.length === 1 && props[key] === null) rejected.add(key);
5675
- }
5676
- if (rejected.size === 0) return void 0;
5677
- return Object.fromEntries(Object.entries(props).filter(([key]) => !rejected.has(key)));
5678
- }
5679
- /** `"a.b: message; c: message"`. A path-less issue gets `fallback`. */
5680
- function formatIssues(issues, fallback = "props") {
5681
- return issues.map((issue) => {
5682
- return `${(issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".") || fallback}: ${issue.message}`;
5683
- }).join("; ");
5684
- }
5685
-
5686
- //#endregion
5687
- //#region src/v2/generative-ui/surface-manager.ts
5688
- function surfaceKey(threadId, surfaceId) {
5689
- return `${threadId}::${surfaceId}`;
5690
- }
5691
- let creationCounter = 0;
5692
- const FORBIDDEN_SEGMENTS = new Set([
5693
- "__proto__",
5694
- "constructor",
5695
- "prototype"
5696
- ]);
5697
- /** "/a/b/" to "/a/b". The root stays "/". */
5698
- function normalizePath(path) {
5699
- return (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path) || "/";
5700
- }
5701
- /** True when `path` is `ancestor` or below it. */
5702
- function isAtOrBelow(path, ancestor) {
5703
- if (ancestor === "/") return true;
5704
- return path === ancestor || path.startsWith(`${ancestor}/`);
5705
- }
5706
- /**
5707
- * Rejections as `"operation <index>: <reason>"` lines, cut to the size that
5708
- * the envelope reader accepts.
5709
- */
5710
- function summarizeRejections(rejections) {
5711
- 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));
5712
- }
5713
- /**
5714
- * Framework-agnostic store of generated surfaces. One web_core SurfaceModel per
5715
- * (threadId, surfaceId), shared by every mount. Applies only newly committed
5716
- * operations, validates each before applying it, and owns app state and the
5717
- * data model paths that the user wrote, so agent updates cannot overwrite
5718
- * them. App state never goes into a surface's data model. Selectors read it
5719
- * with `getState()`.
5720
- */
5721
- var GenerativeUISurfaceManager = class {
5722
- constructor(ui, options = {}) {
5723
- this.ui = ui;
5724
- this.options = options;
5725
- this.surfaces = /* @__PURE__ */ new Map();
5726
- this.bookkeeping = /* @__PURE__ */ new Map();
5727
- this.listeners = /* @__PURE__ */ new Set();
5728
- this.targets = /* @__PURE__ */ new Map();
5729
- this.state = {};
5730
- this.owned = /* @__PURE__ */ new Map();
5731
- this.deletedKeys = /* @__PURE__ */ new Set();
5732
- this.linked = /* @__PURE__ */ new Map();
5733
- this.version = 0;
5734
- this.subscribe = (listener) => {
5735
- this.listeners.add(listener);
5736
- return () => {
5737
- this.listeners.delete(listener);
5738
- };
5739
- };
5740
- this.getVersion = () => this.version;
5741
- this.getState = () => this.state;
5742
- this.webCoreCatalog = new _a2ui_web_core_v0_9.Catalog(ui.id, [...ui.components.keys()].map((name) => ({
5743
- name,
5744
- schema: zod.z.any()
5745
- })), []);
5746
- }
5747
- notify() {
5748
- this.version++;
5749
- for (const listener of [...this.listeners]) listener();
5750
- }
5751
- setActiveThread(threadId) {
5752
- if (threadId === this.activeThreadId) return;
5753
- this.activeThreadId = threadId;
5754
- this.notify();
5755
- }
5756
- getActiveThread() {
5757
- return this.activeThreadId;
5758
- }
5759
- ingest(threadId, agentId, content) {
5760
- const key = surfaceKey(threadId, content.surfaceId);
5761
- const operations = content.operations ?? [];
5762
- let surface = this.surfaces.get(key);
5763
- let book = this.bookkeeping.get(key);
5764
- let changed = false;
5765
- if (surface && book && !this.extendsApplied(book, operations)) {
5766
- this.disposeSurface(key);
5767
- surface = void 0;
5768
- book = void 0;
5769
- }
5770
- if (!surface || !book) {
5771
- surface = this.createSurface(key, threadId, agentId, content);
5772
- this.restoreOwnedValues(surface);
5773
- book = {
5774
- appliedCount: 0,
5775
- lastFingerprint: void 0
5776
- };
5777
- this.surfaces.set(key, surface);
5778
- this.bookkeeping.set(key, book);
5779
- changed = true;
5780
- }
5781
- const serverRejected = content.rejected ?? [];
5782
- if (surface.clientRejected.length > 0 && (surface.status !== "streaming" && content.status === "streaming" || serverRejected.length < surface.serverRejected.length)) {
5783
- surface.clientRejected = [];
5784
- changed = true;
5785
- }
5786
- if (operations.length > 0) {
5787
- const lastFingerprint = JSON.stringify(operations[operations.length - 1]);
5788
- const isReplay = operations.some((op) => (0, _copilotkit_shared.getOperationKind)(op) === "deleteSurface");
5789
- for (let index = book.appliedCount; index < operations.length; index++) {
5790
- this.applyOperation(surface, operations[index], {
5791
- index,
5792
- isReplay
5793
- });
5794
- changed = true;
5795
- }
5796
- book.appliedCount = operations.length;
5797
- surface.operations = operations;
5798
- book.lastFingerprint = lastFingerprint;
5799
- }
5800
- if (surface.status !== content.status || surface.target !== content.target || surface.serverRejected.length !== serverRejected.length) {
5801
- surface.status = content.status;
5802
- surface.target = content.target;
5803
- surface.serverRejected = serverRejected;
5804
- changed = true;
5805
- }
5806
- if (changed) this.notify();
5807
- }
5808
- /** The surface of a `key` (see `surfaceKey`), unless it is deleted. */
5809
- getSurfaceByKey(key) {
5810
- const surface = this.surfaces.get(key);
5811
- return surface && !surface.deleted ? surface : void 0;
5812
- }
5813
- getSurface(threadId, surfaceId) {
5814
- const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
5815
- return surface && !surface.deleted ? surface : void 0;
5816
- }
5817
- getSurfaceForTarget(target, threadId = this.activeThreadId) {
5818
- if (!threadId) return void 0;
5819
- let latest;
5820
- for (const surface of this.surfaces.values()) {
5821
- if (surface.threadId !== threadId || surface.target !== target || surface.deleted) continue;
5822
- if (!latest || surface.createdAt > latest.createdAt) latest = surface;
5823
- }
5824
- return latest;
5825
- }
5826
- /**
5827
- * A surface whose first createSurface was rejected, so the chat can show
5828
- * the error where the surface would be. `undefined` for any other surface.
5829
- */
5830
- getFailedSurface(threadId, surfaceId) {
5831
- const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
5832
- return surface?.failed ? surface : void 0;
5833
- }
5834
- /**
5835
- * The surfaces of a thread, for the model. A surface with user-owned
5836
- * values lists them in `dataModel`, so the model can read what the user
5837
- * entered. A surface with dropped operations lists them in `rejected`, so
5838
- * the model can fix them on the next run. A deleted surface, or one that
5839
- * was never created, has a `status`, so the model knows that the id is
5840
- * not a live surface.
5841
- */
5842
- describeSurfaces(threadId) {
5843
- const described = {};
5844
- for (const surface of this.surfaces.values()) {
5845
- if (surface.threadId !== threadId) continue;
5846
- const owned = this.owned.get(surface.key);
5847
- const rejections = [...surface.serverRejected, ...surface.clientRejected];
5848
- const status = this.deletedKeys.has(surface.key) ? "deleted" : surface.failed ? "failed" : void 0;
5849
- described[surface.surfaceId] = {
5850
- target: surface.target,
5851
- ...owned && owned.size > 0 ? { dataModel: Object.fromEntries(owned) } : {},
5852
- ...rejections.length > 0 && status !== "deleted" ? { rejected: summarizeRejections(rejections) } : {},
5853
- ...status ? { status } : {}
5854
- };
5855
- }
5856
- return described;
5857
- }
5858
- /** Every surface that is not deleted, oldest first, for the inspector. */
5859
- debugSurfaces() {
5860
- return [...this.surfaces.values()].filter((surface) => !surface.deleted).sort((a, b) => a.createdAt - b.createdAt).map((surface) => ({
5861
- surfaceId: surface.surfaceId,
5862
- threadId: surface.threadId,
5863
- agentId: surface.agentId,
5864
- target: surface.target,
5865
- status: surface.status,
5866
- operations: surface.operations,
5867
- dataModel: surface.model.dataModel.get("/"),
5868
- userValues: Object.fromEntries(this.owned.get(surface.key) ?? []),
5869
- rejected: [...surface.serverRejected.map((r) => ({
5870
- ...r,
5871
- source: "runtime"
5872
- })), ...surface.clientRejected.map((r) => ({
5873
- ...r,
5874
- source: "browser"
5875
- }))]
5876
- }));
5877
- }
5878
- /**
5879
- * Marks a target as mounted. Returns the function that unmounts it. Calling
5880
- * that function more than once has no effect.
5881
- *
5882
- * @param id - The target id.
5883
- * @param options - The description and the allowed components of this mount.
5884
- */
5885
- registerTarget(id, options = {}) {
5886
- const registration = { ...options };
5887
- const registrations = this.targets.get(id) ?? /* @__PURE__ */ new Set();
5888
- registrations.add(registration);
5889
- this.targets.set(id, registrations);
5890
- this.notify();
5891
- let released = false;
5892
- return () => {
5893
- if (released) return;
5894
- released = true;
5895
- registrations.delete(registration);
5896
- if (registrations.size === 0) this.targets.delete(id);
5897
- this.notify();
5898
- };
5899
- }
5900
- /**
5901
- * The mounted targets. Each has the description and the component list of
5902
- * its earliest mount that has one.
5903
- */
5904
- getMountedTargets() {
5905
- const mounted = [];
5906
- for (const [id, registrations] of this.targets) {
5907
- const description = [...registrations].find((registration) => registration.description !== void 0)?.description;
5908
- const components = this.targetComponents(id);
5909
- mounted.push({
5910
- id,
5911
- ...description === void 0 ? {} : { description },
5912
- ...components === void 0 ? {} : { components: [...components] }
5913
- });
5914
- }
5915
- return mounted;
5916
- }
5917
- /**
5918
- * The component list of the earliest mount of `id` that has one.
5919
- * `undefined` when no mount of `id` limits its components.
5920
- */
5921
- targetComponents(id) {
5922
- return [...this.targets.get(id) ?? /* @__PURE__ */ new Set()].find((registration) => registration.components !== void 0)?.components;
5923
- }
5924
- /** The components that `validateOperation` allows on a surface. */
5925
- allowedComponentsFor(surface) {
5926
- const components = this.targetComponents(surface.target);
5927
- return components === void 0 ? void 0 : {
5928
- target: surface.target,
5929
- names: new Set(components)
5930
- };
5931
- }
5932
- /** Sets one state key. Notifies only when the value changed. */
5933
- setState(key, value) {
5934
- if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
5935
- this.state = {
5936
- ...this.state,
5937
- [key]: value
5938
- };
5939
- this.notify();
5940
- }
5941
- /** Removes one state key. Notifies only when the key was set. */
5942
- removeState(key) {
5943
- if (!Object.hasOwn(this.state, key)) return;
5944
- const { [key]: _removed, ...rest } = this.state;
5945
- this.state = rest;
5946
- this.notify();
5947
- }
5948
- /**
5949
- * Makes the surfaces of `surfaceIds` share their data model: a user write
5950
- * to one of them goes to all of them (see `setOwnedValue`). The markdown
5951
- * transport links the parts of a chat surface that the prose lift split.
5952
- * A later call for one of the surfaces replaces its group.
5953
- *
5954
- * @param threadId - The thread of the surfaces.
5955
- * @param surfaceIds - The surface ids of the group. One id clears a link.
5956
- */
5957
- linkSurfaces(threadId, surfaceIds) {
5958
- const keys = new Set(surfaceIds.map((id) => surfaceKey(threadId, id)));
5959
- for (const key of keys) if (keys.size > 1) this.linked.set(key, keys);
5960
- else this.linked.delete(key);
5961
- }
5962
- /**
5963
- * Writes a user value into the data model of a surface, and marks `path`
5964
- * as user-owned. Then agent writes to that path, or below it, are ignored.
5965
- * An agent write above it keeps the user value. Ownership ends when the
5966
- * surface is deleted. Does nothing for an unknown or deleted surface. The
5967
- * surfaces linked to it (see `linkSurfaces`) get the same write.
5968
- *
5969
- * @param key - The `key` of the surface.
5970
- * @param path - An absolute JSON pointer, for example "/form/email".
5971
- * @param value - The new value. It is copied.
5972
- * @throws Error when a path segment is "__proto__", "constructor" or
5973
- * "prototype", or when the path does not fit the data (for example, a
5974
- * segment above it holds a string).
5975
- */
5976
- setOwnedValue(key, path, value) {
5977
- const normalized = normalizePath(path);
5978
- const forbidden = normalized.split("/").find((segment) => FORBIDDEN_SEGMENTS.has(segment));
5979
- if (forbidden !== void 0) throw new Error(`[generativeUI] path segment "${forbidden}" is not allowed in "${path}".`);
5980
- for (const target of this.linked.get(key) ?? [key]) this.writeOwnedValue(target, normalized, value);
5981
- }
5982
- writeOwnedValue(key, path, value) {
5983
- const surface = this.surfaces.get(key);
5984
- if (!surface || surface.deleted) return;
5985
- surface.model.dataModel.set(path, structuredClone(value));
5986
- const owned = this.owned.get(key) ?? /* @__PURE__ */ new Map();
5987
- owned.set(path, structuredClone(value));
5988
- this.owned.set(key, owned);
5989
- }
5990
- /**
5991
- * Writes the user-owned values into the new, empty data model of a rebuilt
5992
- * surface. The agent operations are applied after it.
5993
- */
5994
- restoreOwnedValues(surface) {
5995
- const owned = this.owned.get(surface.key) ?? /* @__PURE__ */ new Map();
5996
- for (const [path, value] of owned) surface.model.dataModel.set(path, structuredClone(value));
5997
- }
5998
- /**
5999
- * The value that an agent write puts at `path`, with the user-owned values
6000
- * below `path` written back into it. `undefined` when `path` is user-owned
6001
- * or below a user-owned path, so the agent cannot write it. Throws when a
6002
- * user value does not fit the new value.
6003
- */
6004
- mergeOwnedValues(key, path, value) {
6005
- const merged = { value: structuredClone(value) };
6006
- const owned = this.owned.get(key);
6007
- if (!owned) return merged;
6008
- const ownedPaths = [...owned.keys()];
6009
- if (ownedPaths.some((ownedPath) => isAtOrBelow(path, ownedPath))) return void 0;
6010
- const below = ownedPaths.filter((ownedPath) => isAtOrBelow(ownedPath, path));
6011
- if (below.length === 0) return merged;
6012
- const scratch = new _a2ui_web_core_v0_9.DataModel({ value: merged.value });
6013
- const prefix = path === "/" ? "" : path;
6014
- for (const ownedPath of below) {
6015
- const relative = ownedPath.slice(prefix.length);
6016
- scratch.set(`/value${relative}`, structuredClone(owned.get(ownedPath)));
6017
- }
6018
- return { value: scratch.get("/value") };
6019
- }
6020
- extendsApplied(book, operations) {
6021
- if (operations.length < book.appliedCount) return false;
6022
- if (book.appliedCount === 0) return true;
6023
- return JSON.stringify(operations[book.appliedCount - 1]) === book.lastFingerprint;
6024
- }
6025
- createSurface(key, threadId, agentId, content) {
6026
- return {
6027
- key,
6028
- threadId,
6029
- surfaceId: content.surfaceId,
6030
- agentId,
6031
- model: new _a2ui_web_core_v0_9.SurfaceModel(content.surfaceId, this.webCoreCatalog),
6032
- createdAt: ++creationCounter,
6033
- target: content.target,
6034
- status: content.status,
6035
- deleted: false,
6036
- failed: false,
6037
- serverRejected: content.rejected ?? [],
6038
- clientRejected: [],
6039
- operations: []
6040
- };
6041
- }
6042
- disposeSurface(key) {
6043
- this.surfaces.get(key)?.model.dispose();
6044
- this.surfaces.delete(key);
6045
- this.bookkeeping.delete(key);
6046
- }
6047
- /**
6048
- * Marks a surface deleted and frees its components and data. The record
6049
- * stays, so the model is still told about the id and the bookkeeping does
6050
- * not rebuild the surface for content that was already applied.
6051
- */
6052
- closeSurface(surface) {
6053
- surface.deleted = true;
6054
- surface.model.dispose();
6055
- surface.model = new _a2ui_web_core_v0_9.SurfaceModel(surface.surfaceId, this.webCoreCatalog);
6056
- this.owned.delete(surface.key);
6057
- this.linked.delete(surface.key);
6058
- }
6059
- /** The surfaces of a thread that a part of `surfaceId` reads, for tests. */
6060
- getLinkedSurfaceIds(threadId, surfaceId) {
6061
- const keys = this.linked.get(surfaceKey(threadId, surfaceId));
6062
- if (!keys) return [surfaceId];
6063
- const prefix = `${threadId}::`;
6064
- return [...keys].map((key) => key.slice(prefix.length));
6065
- }
6066
- /**
6067
- * Drops the node keys that the app sets: bound props and matched events.
6068
- * The model does not see them, so a model value for one is ignored, not
6069
- * rejected. This runs before validation, because validation rejects keys
6070
- * that are not in the manifest. It never changes the given operation.
6071
- */
6072
- dropAppSetKeys(op) {
6073
- const kind = (0, _copilotkit_shared.getOperationKind)(op);
6074
- if (kind !== "updateComponents" && kind !== "createSurface") return op;
6075
- const record = op;
6076
- const payload = record[kind];
6077
- const nodes = payload?.components;
6078
- if (!Array.isArray(nodes)) return op;
6079
- return {
6080
- ...record,
6081
- [kind]: {
6082
- ...payload,
6083
- components: nodes.map((node) => this.dropAppSetNodeKeys(node))
6084
- }
6085
- };
6086
- }
6087
- dropAppSetNodeKeys(node) {
6088
- if (typeof node !== "object" || node === null || !("component" in node)) return node;
6089
- const { component } = node;
6090
- if (typeof component !== "string") return node;
6091
- const definition = this.ui.components.get(component);
6092
- if (!definition) return node;
6093
- return Object.fromEntries(Object.entries(node).filter(([key]) => !Object.hasOwn(definition.selectors, key) && !Object.hasOwn(definition.eventFunctions, key)));
6094
- }
6095
- /**
6096
- * The surfaces that `validateOperation` gets for one operation of the
6097
- * content of `surface`.
6098
- *
6099
- * - `knownSurfaces`: the surface, when it exists before the operation. It
6100
- * does not exist before its first createSurface, or after a delete.
6101
- * - `createdSurfaces`: the surface, when a createSurface at this position
6102
- * uses its id again. That is the case after the first operation, and for
6103
- * a surface that was deleted before, unless the content replays that
6104
- * delete.
6105
- */
6106
- surfacesFor(surface, kind, position) {
6107
- const isFirstCreate = kind === "createSurface" && position.index === 0;
6108
- const exists = !surface.deleted && !isFirstCreate;
6109
- const isRecreate = this.deletedKeys.has(surface.key) && !position.isReplay;
6110
- const isUsedAgain = position.index > 0 || isRecreate;
6111
- return {
6112
- knownSurfaces: new Set(exists ? [surface.surfaceId] : []),
6113
- createdSurfaces: new Set(isUsedAgain ? [surface.surfaceId] : [])
6114
- };
6115
- }
6116
- applyOperation(surface, received, position) {
6117
- const { index } = position;
6118
- const kind = (0, _copilotkit_shared.getOperationKind)(received);
6119
- if (kind === "callRendererFunction") return;
6120
- const reject = (reason) => {
6121
- if (kind === "createSurface" && index === 0) {
6122
- this.closeSurface(surface);
6123
- surface.failed = true;
3508
+ * @example
3509
+ * ```ts
3510
+ * useGenerativeUIMarkdownContext(copilotkit, core, {
3511
+ * enabled: config?.transport === "markdown" && config.sendContext !== false,
3512
+ * agentIds: config?.agentIds,
3513
+ * });
3514
+ * ```
3515
+ */
3516
+ function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
3517
+ const { enabled, agentIds } = options;
3518
+ const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
3519
+ (0, react.useEffect)(() => {
3520
+ if (!runtime || !enabled) return;
3521
+ const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
3522
+ const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
3523
+ let guidelineId;
3524
+ let guidelineValue;
3525
+ let schemaId;
3526
+ let schemaValue;
3527
+ const refreshSchema = (threadId) => {
3528
+ const manifest = (0, _copilotkit_core_generative_ui.buildGenerativeUIManifest)(runtime, threadId);
3529
+ const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
3530
+ if (guideline !== guidelineValue) {
3531
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
3532
+ guidelineValue = guideline;
3533
+ guidelineId = copilotkit.addContext({
3534
+ description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
3535
+ value: guideline,
3536
+ ...scope
3537
+ });
6124
3538
  }
6125
- surface.clientRejected.push({
6126
- index,
6127
- reason
6128
- });
6129
- this.options.onOperationRejected?.({
6130
- surfaceId: surface.surfaceId,
6131
- index,
6132
- reason
3539
+ const value = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
3540
+ if (value === schemaValue) return;
3541
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
3542
+ schemaValue = value;
3543
+ schemaId = copilotkit.addContext({
3544
+ description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
3545
+ value,
3546
+ ...scope
6133
3547
  });
6134
3548
  };
6135
- const targetId = (0, _copilotkit_shared.getOperationSurfaceId)(received);
6136
- if (targetId !== void 0 && targetId !== surface.surfaceId) return reject(`operation is for surface "${targetId}", not "${surface.surfaceId}"`);
6137
- const op = this.dropAppSetKeys(received);
6138
- const validation = (0, _copilotkit_shared.validateOperation)(op, {
6139
- manifest: {
6140
- catalogId: this.ui.id,
6141
- catalogIds: catalogIdsOf(this.ui),
6142
- components: this.ui.manifestComponents
6143
- },
6144
- ...this.surfacesFor(surface, kind, position),
6145
- allowedComponents: this.allowedComponentsFor(surface)
6146
- });
6147
- if (!validation.ok) return reject(validation.reason);
6148
- const typed = op;
6149
- if ("createSurface" in typed) {
6150
- const { dataModel, components = [] } = typed.createSurface;
6151
- const problem = this.nodesProblem(components);
6152
- if (problem) return reject(problem);
6153
- if (dataModel) {
6154
- const failure = this.writeAgentData(surface, "/", dataModel);
6155
- if (failure) return reject(failure);
6156
- }
6157
- for (const node of components) this.upsertNode(surface.model, node);
6158
- return;
6159
- }
6160
- if ("updateComponents" in typed) {
6161
- const nodes = typed.updateComponents.components;
6162
- const problem = this.nodesProblem(nodes);
6163
- if (problem) return reject(problem);
6164
- for (const node of nodes) this.upsertNode(surface.model, node);
6165
- return;
6166
- }
6167
- if ("updateDataModel" in typed) {
6168
- const { path = "/", value } = typed.updateDataModel;
6169
- const written = value === null ? void 0 : value;
6170
- const failure = this.writeAgentData(surface, normalizePath(path), written);
6171
- if (failure) return reject(failure);
6172
- return;
6173
- }
6174
- if ("deleteSurface" in typed) {
6175
- this.closeSurface(surface);
6176
- this.deletedKeys.add(surface.key);
6177
- }
6178
- }
6179
- /** The first node with props of the wrong type, as a reason. */
6180
- nodesProblem(nodes) {
6181
- for (const node of nodes) {
6182
- const problem = this.checkNodeProps(node);
6183
- if (problem) return `component "${node.id}": ${problem}`;
6184
- }
6185
- }
6186
- /**
6187
- * Writes an agent value at `path` and keeps the user-owned values. A write
6188
- * to a user-owned path is ignored, not rejected. Gives the reason when the
6189
- * value does not fit the data, else `undefined`.
6190
- */
6191
- writeAgentData(surface, path, value) {
6192
- try {
6193
- const merged = this.mergeOwnedValues(surface.key, path, value);
6194
- if (merged) surface.model.dataModel.set(path, merged.value);
6195
- return;
6196
- } catch (error) {
6197
- return error instanceof Error ? error.message : String(error);
6198
- }
6199
- }
6200
- checkNodeProps(node) {
6201
- const definition = this.ui.components.get(node.component);
6202
- if (!definition) return `unknown component "${node.component}"`;
6203
- const { id: _id, component: _component, ...rest } = node;
6204
- const dataProps = Object.fromEntries(Object.entries(rest).filter(([key]) => !definition.events?.[key] && !definition.slots?.[key] && !_copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS.has(key)));
6205
- if (!definition.props) return void 0;
6206
- const unknownNow = new Set(Object.keys(definition.selectors));
6207
- const literals = {};
6208
- for (const [key, value] of Object.entries(dataProps)) if (containsDynamicValue(value)) unknownNow.add(key);
6209
- else literals[key] = value;
6210
- let result = validateSchemaSync(definition.props, literals);
6211
- if (!result.success) {
6212
- const unset = withoutRejectedNulls(literals, result.issues);
6213
- if (unset) result = validateSchemaSync(definition.props, unset);
6214
- }
6215
- if (result.success) return void 0;
6216
- const issues = result.issues.filter((issue) => {
6217
- const key = issueKey(issue);
6218
- return key === void 0 ? isAsyncIssue(issue) : !unknownNow.has(key);
3549
+ refreshSchema(runtime.manager.getActiveThread());
3550
+ let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
3551
+ const unsubscribeManager = runtime.manager.subscribe(() => {
3552
+ const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
3553
+ if (nextKey === targetsKey) return;
3554
+ targetsKey = nextKey;
3555
+ refreshSchema(runtime.manager.getActiveThread());
6219
3556
  });
6220
- return issues.length > 0 ? formatIssues(issues) : void 0;
6221
- }
6222
- upsertNode(model, node) {
6223
- const { id, component, ...rest } = node;
6224
- const properties = structuredClone(rest);
6225
- const existing = model.componentsModel.get(id);
6226
- if (existing && existing.type === component) {
6227
- existing.properties = properties;
6228
- return;
6229
- }
6230
- if (existing) model.componentsModel.removeComponent(id);
6231
- model.componentsModel.addComponent(new _a2ui_web_core_v0_9.ComponentModel(id, component, properties));
6232
- }
6233
- };
3557
+ const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
3558
+ return () => {
3559
+ subscription.unsubscribe();
3560
+ unsubscribeManager();
3561
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
3562
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
3563
+ };
3564
+ }, [
3565
+ copilotkit,
3566
+ runtime,
3567
+ enabled,
3568
+ agentIdsKey
3569
+ ]);
3570
+ }
6234
3571
 
6235
3572
  //#endregion
6236
3573
  //#region src/v2/generative-ui/use-generative-ui-root.ts
6237
3574
  const isDevelopment = () => process.env.NODE_ENV !== "production";
6238
- /** At most this many function follow-up runs for each user turn. */
6239
- const MAX_FUNCTION_FOLLOW_UPS = 5;
6240
3575
  function ingestMessages(manager, agent, messages) {
6241
3576
  if (!agent.threadId) return;
6242
3577
  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);
6243
3578
  }
6244
- /** What the envelope of a run says, from the provider config. */
6245
- function envelopeOptionsFor(config) {
6246
- if (config.transport === "markdown") return {
6247
- transport: "markdown",
6248
- includeCatalog: config.includeCatalog !== false,
6249
- contextSent: config.sendContext !== false
6250
- };
6251
- return {
6252
- transport: "tool",
6253
- includeCatalog: true,
6254
- contextSent: false
6255
- };
6256
- }
6257
- /**
6258
- * The components of a surface as one `updateComponents` operation, so that
6259
- * the label of the component that sent an event can be found.
6260
- */
6261
- function surfaceComponents(surface) {
6262
- const components = [...surface.model.componentsModel.entries].map(([id, model]) => ({
6263
- ...model.properties,
6264
- id,
6265
- component: model.type
6266
- }));
6267
- return [{
6268
- version: _copilotkit_shared.A2UI_VERSION,
6269
- updateComponents: {
6270
- surfaceId: surface.surfaceId,
6271
- components
6272
- }
6273
- }];
6274
- }
6275
- /** True when `value` names a `functionCallId`. */
6276
- function hasFunctionCallId(value) {
6277
- return typeof value === "object" && value !== null && "functionCallId" in value && typeof value.functionCallId === "string" && value.functionCallId !== "";
6278
- }
6279
- /** The `functionCallId` that a developer message answers, if any. */
6280
- function answeredCallId(content) {
6281
- if (!content.includes("rendererFunctionResponse")) return void 0;
6282
- try {
6283
- const parsed = JSON.parse(content);
6284
- const response = typeof parsed === "object" && parsed !== null && "rendererFunctionResponse" in parsed ? parsed.rendererFunctionResponse : void 0;
6285
- return hasFunctionCallId(response) ? response.functionCallId : void 0;
6286
- } catch {
6287
- return;
6288
- }
6289
- }
6290
- /** The function calls that a developer message in `messages` answers. */
6291
- function answeredCallIds(messages) {
6292
- const ids = /* @__PURE__ */ new Set();
6293
- for (const message of messages) {
6294
- if (message.role !== "developer") continue;
6295
- const id = answeredCallId(message.content);
6296
- if (id !== void 0) ids.add(id);
6297
- }
6298
- return ids;
6299
- }
6300
- /** The id of the last user message. A user turn starts with it. */
6301
- function lastUserMessageId(messages) {
6302
- for (let index = messages.length - 1; index >= 0; index--) {
6303
- const message = messages[index];
6304
- if (message?.role === "user") return message.id;
6305
- }
6306
- }
6307
- /** The function calls of the tool transport: its function-call activities. */
6308
- function activityFunctionCalls(messages) {
6309
- const requests = [];
6310
- for (const message of messages) {
6311
- if (!(message.role === "activity" && message.activityType === _copilotkit_shared.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE) || !hasFunctionCallId(message.content)) continue;
6312
- requests.push({
6313
- functionCallId: message.content.functionCallId,
6314
- operation: {
6315
- version: _copilotkit_shared.A2UI_VERSION,
6316
- callRendererFunction: message.content
6317
- }
6318
- });
6319
- }
6320
- return requests;
6321
- }
6322
- /** The function calls of the markdown transport: its fence lines. */
6323
- function markdownFunctionCalls(calls) {
6324
- const requests = [];
6325
- for (const { operation } of calls) {
6326
- const payload = operation.callRendererFunction;
6327
- if (!hasFunctionCallId(payload)) continue;
6328
- requests.push({
6329
- functionCallId: payload.functionCallId,
6330
- operation
6331
- });
6332
- }
6333
- return requests;
6334
- }
6335
- /** The text of a `rendererFunctionResponse` developer message. */
6336
- function responseContent(response) {
6337
- return JSON.stringify({
6338
- version: _copilotkit_shared.A2UI_VERSION,
6339
- rendererFunctionResponse: response
6340
- });
6341
- }
6342
- function errorAnswer(functionCallId, code, message) {
6343
- return {
6344
- content: responseContent({
6345
- functionCallId,
6346
- error: {
6347
- code,
6348
- message
6349
- }
6350
- }),
6351
- followUp: true
6352
- };
6353
- }
6354
- const overCapAnswer = (functionCallId) => ({
6355
- content: responseContent({
6356
- functionCallId,
6357
- error: {
6358
- code: "follow_up_limit",
6359
- 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.`
6360
- }
6361
- }),
6362
- followUp: false
6363
- });
6364
- /**
6365
- * Runs the functions that the agent calls with `callRendererFunction`, for
6366
- * both transports, and answers each call.
6367
- *
6368
- * - Each `functionCallId` runs once for each thread. A replay, a sync of
6369
- * the same messages again, or a call that already has an answer message
6370
- * does not run it again.
6371
- * - The answer is a hidden developer message with a `rendererFunctionResponse`.
6372
- * The answers go to the agent only when it is not running. Then one
6373
- * follow-up run starts for all of them.
6374
- * - A user turn has at most {@link MAX_FUNCTION_FOLLOW_UPS} follow-up runs.
6375
- * A call after that does not run. It gets a `follow_up_limit` error and
6376
- * starts no follow-up run.
6377
- */
6378
- function createFunctionCallRunner(options) {
6379
- const { copilotkit, dispatcher, manifest } = options;
6380
- const threads = /* @__PURE__ */ new Map();
6381
- const threadState = (threadId) => {
6382
- let state = threads.get(threadId);
6383
- if (!state) {
6384
- state = {
6385
- done: /* @__PURE__ */ new Set(),
6386
- pending: [],
6387
- turn: void 0,
6388
- followUps: 0,
6389
- flushing: false
6390
- };
6391
- threads.set(threadId, state);
6392
- }
6393
- return state;
6394
- };
6395
- const answer = async (request) => {
6396
- const { functionCallId } = request;
6397
- const validation = (0, _copilotkit_shared.validateOperation)(request.operation, {
6398
- manifest,
6399
- knownSurfaces: /* @__PURE__ */ new Set()
6400
- });
6401
- if (!validation.ok) return errorAnswer(functionCallId, "invalid_arguments", validation.reason);
6402
- const operation = request.operation;
6403
- if (!("callRendererFunction" in operation)) return errorAnswer(functionCallId, "invalid_arguments", "the operation is not a callRendererFunction");
6404
- const { callFunction } = operation.callRendererFunction;
6405
- const name = callFunction["@call"];
6406
- const result = await dispatcher.invoke(name, callFunction.args ?? {}, { functionCallId });
6407
- if (!result.ok) return errorAnswer(functionCallId, result.error.code, result.error.message);
6408
- try {
6409
- return {
6410
- content: responseContent({
6411
- functionCallId,
6412
- value: result.result ?? null
6413
- }),
6414
- followUp: true
6415
- };
6416
- } catch (cause) {
6417
- return errorAnswer(functionCallId, "handler_failed", `The result of "${name}" is not JSON: ${cause instanceof Error ? cause.message : String(cause)}`);
6418
- }
6419
- };
6420
- /**
6421
- * Adds the pending answers of a thread to the agent, then starts one
6422
- * follow-up run. It waits while the agent runs: the next read of the
6423
- * thread, at the end of the run, flushes again.
6424
- */
6425
- const flush = async (agent, threadId, state) => {
6426
- if (state.flushing) return;
6427
- state.flushing = true;
6428
- try {
6429
- while (state.pending.length > 0) {
6430
- const batch = [...state.pending];
6431
- const answers = await Promise.all(batch);
6432
- await copilotkit.waitForPendingFrameworkUpdates();
6433
- if (agent.isRunning || agent.threadId !== threadId) return;
6434
- if (state.pending.length > batch.length) continue;
6435
- state.pending = [];
6436
- for (const { content } of answers) agent.addMessage({
6437
- id: (0, _copilotkit_shared.randomUUID)(),
6438
- role: "developer",
6439
- content
6440
- });
6441
- if (!answers.some((item) => item.followUp)) continue;
6442
- state.followUps++;
6443
- await copilotkit.runAgent({ agent });
6444
- }
6445
- } catch (error) {
6446
- if (isDevelopment()) console.warn("[generativeUI] function follow-up run failed:", error);
6447
- } finally {
6448
- state.flushing = false;
6449
- }
6450
- };
6451
- return { run(agent, requests, messages, running) {
6452
- const { threadId } = agent;
6453
- if (!threadId) return;
6454
- const state = threadState(threadId);
6455
- const turn = lastUserMessageId(messages);
6456
- if (turn !== state.turn) {
6457
- state.turn = turn;
6458
- state.followUps = 0;
6459
- }
6460
- const isNew = (request) => !state.done.has(request.functionCallId);
6461
- const fresh = requests.filter(isNew);
6462
- const answered = fresh.length > 0 ? answeredCallIds(messages) : /* @__PURE__ */ new Set();
6463
- for (const request of fresh) {
6464
- const { functionCallId } = request;
6465
- if (state.done.has(functionCallId)) continue;
6466
- state.done.add(functionCallId);
6467
- if (answered.has(functionCallId)) continue;
6468
- const isOverCap = state.followUps >= MAX_FUNCTION_FOLLOW_UPS;
6469
- state.pending.push(isOverCap ? Promise.resolve(overCapAnswer(functionCallId)) : answer(request));
6470
- }
6471
- if (!running) flush(agent, threadId, state);
6472
- } };
6473
- }
6474
3579
  /** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */
6475
3580
  function useGenerativeUIRoot(copilotkit, config) {
6476
3581
  const configRef = (0, react.useRef)(config);
@@ -6488,12 +3593,12 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6488
3593
  }
6489
3594
  if (isDevelopment()) console.warn(`[generativeUI] ${info.kind} error in ${info.surfaceId}${info.componentId ? `/${info.componentId}` : ""}: ${info.error?.message}`);
6490
3595
  };
6491
- const manager = new GenerativeUISurfaceManager(ui, { onOperationRejected: ({ surfaceId, index, reason }) => reportError({
3596
+ const manager = new _copilotkit_core_generative_ui.GenerativeUISurfaceManager(ui, { onOperationRejected: ({ surfaceId, index, reason }) => reportError({
6492
3597
  kind: "operation",
6493
3598
  surfaceId,
6494
3599
  error: /* @__PURE__ */ new Error(`operation ${index} rejected: ${reason}`)
6495
3600
  }) });
6496
- const dispatcher = createGenerativeUIDispatcher({
3601
+ const dispatcher = (0, _copilotkit_core_generative_ui.createGenerativeUIDispatcher)({
6497
3602
  getDeclared: () => ui.functions,
6498
3603
  onError: ({ name, origin, error }) => {
6499
3604
  if ("functionCallId" in origin) {
@@ -6507,13 +3612,17 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6507
3612
  });
6508
3613
  }
6509
3614
  });
6510
- const functionCalls = createFunctionCallRunner({
6511
- copilotkit,
3615
+ const functionCalls = (0, _copilotkit_core_generative_ui.createFunctionCallRunner)({
3616
+ core: copilotkit,
6512
3617
  dispatcher,
6513
3618
  manifest: {
6514
3619
  catalogId: ui.id,
6515
- catalogIds: catalogIdsOf(ui),
3620
+ catalogIds: (0, _copilotkit_shared_generative_ui.catalogIdsOf)(ui),
6516
3621
  components: ui.manifestComponents
3622
+ },
3623
+ settle: () => copilotkit.waitForPendingFrameworkUpdates(),
3624
+ warn: (message, error) => {
3625
+ if (isDevelopment()) console.warn(message, error);
6517
3626
  }
6518
3627
  });
6519
3628
  const forwardingAgents = /* @__PURE__ */ new Set();
@@ -6542,12 +3651,12 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6542
3651
  actions.delete(agent);
6543
3652
  const latest = configRef.current;
6544
3653
  if (!latest) return;
6545
- const envelope = buildGenerativeUIEnvelope({
3654
+ const envelope = (0, _copilotkit_core_generative_ui.buildGenerativeUIEnvelope)({
6546
3655
  ui,
6547
3656
  manager,
6548
3657
  dispatcher
6549
3658
  }, agent.threadId, {
6550
- ...envelopeOptionsFor(latest),
3659
+ ...(0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest),
6551
3660
  action
6552
3661
  });
6553
3662
  const id = copilotkit.addScopedProperties({
@@ -6572,7 +3681,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6572
3681
  };
6573
3682
  const forwardEvent = async (event, agentId) => {
6574
3683
  const fail = (message) => {
6575
- const error = new GenerativeUIError("event_forward_failed", message);
3684
+ const error = new _copilotkit_shared_generative_ui.GenerativeUIError("event_forward_failed", message);
6576
3685
  reportError({
6577
3686
  kind: "event",
6578
3687
  surfaceId: event.surfaceId,
@@ -6588,16 +3697,16 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6588
3697
  if (!agent) return fail(`No agent "${agentId}" to receive "${event.name}"`);
6589
3698
  if (agent.isRunning || forwardingAgents.has(agent)) return {
6590
3699
  ok: false,
6591
- error: new GenerativeUIError("agent_busy", `"${event.name}" was not sent: the agent is running`)
3700
+ error: new _copilotkit_shared_generative_ui.GenerativeUIError("agent_busy", `"${event.name}" was not sent: the agent is running`)
6592
3701
  };
6593
3702
  forwardingAgents.add(agent);
6594
3703
  try {
6595
3704
  const surface = agent.threadId ? manager.getSurface(agent.threadId, event.surfaceId) : void 0;
6596
- const resolveLabel = surface ? createComponentLabelResolver(surfaceComponents(surface)) : void 0;
3705
+ const resolveLabel = surface ? (0, _copilotkit_core_generative_ui.surfaceLabelResolver)(surface) : void 0;
6597
3706
  agent.addMessage({
6598
3707
  id: (0, _copilotkit_shared.randomUUID)(),
6599
3708
  role: "user",
6600
- content: buildActionMessageText(event, resolveLabel)
3709
+ content: (0, _copilotkit_core_generative_ui.buildActionMessageText)(event, resolveLabel)
6601
3710
  });
6602
3711
  setAction(agent, (0, _copilotkit_shared.toA2UIActionMessage)(event));
6603
3712
  await copilotkit.runAgent({ agent });
@@ -6651,10 +3760,10 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6651
3760
  const watched = /* @__PURE__ */ new WeakSet();
6652
3761
  const agentSubscriptions = [];
6653
3762
  let envelopeId;
6654
- const debug = createGenerativeUIDebugSource(core, () => {
3763
+ const debug = (0, _copilotkit_core_generative_ui.createGenerativeUIDebugSource)(core, () => {
6655
3764
  const latest = configRef.current ?? { ui: core.ui };
6656
3765
  return {
6657
- options: envelopeOptionsFor(latest),
3766
+ options: (0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest),
6658
3767
  agentIds: latest.agentIds
6659
3768
  };
6660
3769
  });
@@ -6671,7 +3780,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6671
3780
  */
6672
3781
  const setEnvelope = (agent, latest) => {
6673
3782
  removeEnvelope();
6674
- const run = describeGenerativeUIRun(core, agent.threadId, envelopeOptionsFor(latest));
3783
+ const run = (0, _copilotkit_core_generative_ui.describeGenerativeUIRun)(core, agent.threadId, (0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest));
6675
3784
  envelopeId = copilotkit.addScopedProperties({
6676
3785
  properties: { [_copilotkit_shared.COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: run.envelope } },
6677
3786
  agentIds: latest.agentIds
@@ -6691,13 +3800,13 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6691
3800
  * Both give their function calls to the one runner.
6692
3801
  */
6693
3802
  const readMessages = (agent, messages, running) => {
6694
- const requests = activityFunctionCalls(messages);
3803
+ const requests = (0, _copilotkit_core_generative_ui.activityFunctionCalls)(messages);
6695
3804
  const { threadId } = agent;
6696
3805
  if (configRef.current?.transport !== "markdown") ingestMessages(core.manager, agent, messages);
6697
3806
  else if (threadId) {
6698
3807
  core.manager.setActiveThread(threadId);
6699
- const calls = getMarkdownSurfaceSource(core).sync(threadId, agent.agentId, messages, { running });
6700
- requests.push(...markdownFunctionCalls(calls));
3808
+ const calls = (0, _copilotkit_core_generative_ui.getMarkdownSurfaceSource)(core).sync(threadId, agent.agentId, messages, { running });
3809
+ requests.push(...(0, _copilotkit_core_generative_ui.markdownFunctionCalls)(calls));
6701
3810
  }
6702
3811
  core.functionCalls.run(agent, requests, messages, running);
6703
3812
  };
@@ -6741,16 +3850,6 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6741
3850
  if (!runtime) throw new Error("Generative UI components must be rendered inside <CopilotKitProvider generativeUI={{ ui }}>.");
6742
3851
  return runtime;
6743
3852
  }
6744
- /**
6745
- * Reports an error without ever throwing: `reportError` reaches host code
6746
- * (`onError`), and a throwing host callback must not break rendering or an
6747
- * event handler.
6748
- */
6749
- function reportErrorSafely(runtime, info) {
6750
- try {
6751
- runtime.reportError(info);
6752
- } catch {}
6753
- }
6754
3853
  const GenerativeUINodeContext = (0, react.createContext)(null);
6755
3854
 
6756
3855
  //#endregion
@@ -6820,7 +3919,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6820
3919
  }
6821
3920
  componentDidCatch(error) {
6822
3921
  const { runtime, surfaceId, componentId } = this.props;
6823
- reportErrorSafely(runtime, {
3922
+ (0, _copilotkit_core_generative_ui.reportErrorSafely)(runtime, {
6824
3923
  kind: "render",
6825
3924
  surfaceId,
6826
3925
  componentId,
@@ -6854,7 +3953,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6854
3953
  return { error };
6855
3954
  }
6856
3955
  componentDidCatch(error) {
6857
- reportErrorSafely(this.props.runtime, {
3956
+ (0, _copilotkit_core_generative_ui.reportErrorSafely)(this.props.runtime, {
6858
3957
  kind: "render",
6859
3958
  surfaceId: this.props.surfaceId,
6860
3959
  error
@@ -6869,287 +3968,6 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6869
3968
  }
6870
3969
  };
6871
3970
 
6872
- //#endregion
6873
- //#region src/v2/generative-ui/accessibility.ts
6874
- const LIVE = new Set([
6875
- "off",
6876
- "polite",
6877
- "assertive"
6878
- ]);
6879
- /**
6880
- * The accessibility of a component from its resolved `accessibility`
6881
- * value. Fields of the wrong type are left out: a label that is still a
6882
- * binding, or a list, names nothing.
6883
- */
6884
- function readAccessibility(value) {
6885
- if (typeof value !== "object" || value === null || Array.isArray(value)) return;
6886
- const { label, description, live, hidden } = value;
6887
- const result = {};
6888
- if (typeof label === "string" && label !== "") result.label = label;
6889
- if (typeof description === "string" && description !== "") result.description = description;
6890
- if (typeof live === "string" && LIVE.has(live)) result.live = live;
6891
- if (typeof hidden === "boolean") result.hidden = hidden;
6892
- return Object.keys(result).length > 0 ? result : void 0;
6893
- }
6894
- /**
6895
- * The ARIA attributes for an `accessibility`. `live: "off"` is written out:
6896
- * a region inherits the live setting of its ancestors, and a `status` role
6897
- * is live on its own, so only the explicit value silences it.
6898
- *
6899
- * @example
6900
- * ```ts
6901
- * accessibilityAttributes({ label: "Totals", live: "polite" });
6902
- * // { "aria-label": "Totals", "aria-live": "polite" }
6903
- * ```
6904
- */
6905
- function accessibilityAttributes(accessibility) {
6906
- if (!accessibility) return {};
6907
- const { label, description, live, hidden } = accessibility;
6908
- return {
6909
- ...label === void 0 ? {} : { "aria-label": label },
6910
- ...description === void 0 ? {} : { "aria-description": description },
6911
- ...live === void 0 ? {} : { "aria-live": live },
6912
- ...hidden ? { "aria-hidden": true } : {}
6913
- };
6914
- }
6915
- /**
6916
- * The part of the attributes for the wrapper around a control: hidden and
6917
- * live cover the label and the control together.
6918
- */
6919
- function wrapperAria(aria) {
6920
- const { "aria-hidden": hidden, "aria-live": live } = aria;
6921
- return {
6922
- ...hidden === void 0 ? {} : { "aria-hidden": hidden },
6923
- ...live === void 0 ? {} : { "aria-live": live }
6924
- };
6925
- }
6926
-
6927
- //#endregion
6928
- //#region src/v2/generative-ui/events.ts
6929
- /**
6930
- * The context of a running event binding: it reads the surface data model
6931
- * and resolves relative paths against the template item of the component.
6932
- * A function that needs a user gesture (openUrl) is not a value here
6933
- * either; it runs through the dispatcher as the binding's functionCall.
6934
- */
6935
- function eventContext(surface, basePath) {
6936
- return {
6937
- data: surface.model.dataModel,
6938
- basePath
6939
- };
6940
- }
6941
- /**
6942
- * A value of an event binding with its dynamic values resolved: `{"@path"}`
6943
- * bindings and function values, at any depth.
6944
- */
6945
- function resolveValue(surface, basePath, value) {
6946
- return resolveDynamicValue(value, eventContext(surface, basePath)).value;
6947
- }
6948
- /**
6949
- * The entries of an args or context record, each resolved on its own. The
6950
- * record is not resolved as a whole, because a record with one `event` or
6951
- * `functionCall` key would look like an action binding and stay as it is.
6952
- */
6953
- function resolveValues(surface, basePath, values) {
6954
- return Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [key, resolveValue(surface, basePath, value)]));
6955
- }
6956
- /**
6957
- * The `userMessage` of an event binding, as text. A `{"@path"}` or a
6958
- * function value is resolved. `undefined` when there is no message, or
6959
- * the value is not a string.
6960
- */
6961
- function resolveUserMessage(surface, basePath, userMessage) {
6962
- const value = resolveValue(surface, basePath, userMessage);
6963
- return typeof value === "string" ? value : void 0;
6964
- }
6965
- /**
6966
- * Validates the component's args with the event `parameters`, then runs
6967
- * `send` with them. Never throws: every failure is reported and becomes
6968
- * `{ ok: false, error }`.
6969
- */
6970
- async function runEvent(call, send) {
6971
- const { runtime, surface, componentId, name, parameters, args } = call;
6972
- const origin = {
6973
- surfaceId: surface.surfaceId,
6974
- componentId
6975
- };
6976
- try {
6977
- if (!parameters) return await send(args ?? {}, origin);
6978
- const result = validateSchema(parameters, args ?? {});
6979
- const parsed = result instanceof Promise ? await result : result;
6980
- if (!parsed.success) {
6981
- const error = new GenerativeUIError("invalid_event_args", `${name}: ${formatIssues(parsed.issues, "args")}`);
6982
- reportErrorSafely(runtime, {
6983
- kind: "event",
6984
- ...origin,
6985
- error
6986
- });
6987
- return {
6988
- ok: false,
6989
- error
6990
- };
6991
- }
6992
- return await send(parsed.data ?? {}, origin);
6993
- } catch (cause) {
6994
- const error = new GenerativeUIError("event_forward_failed", `${name}: ${cause instanceof Error ? cause.message : String(cause)}`);
6995
- reportErrorSafely(runtime, {
6996
- kind: "event",
6997
- ...origin,
6998
- error
6999
- });
7000
- return {
7001
- ok: false,
7002
- error
7003
- };
7004
- }
7005
- }
7006
- /**
7007
- * Runs one call of an event that the model bound: validates the component's
7008
- * args, merges them with the args from the binding (binding literals win),
7009
- * then calls a declared function or forwards an agent event. Never throws.
7010
- */
7011
- function invokeBoundEvent(params) {
7012
- const { runtime, surface, binding, basePath } = params;
7013
- return runEvent(params, (args, origin) => {
7014
- const componentArgs = args;
7015
- if ("functionCall" in binding) return runtime.dispatcher.invoke(binding.functionCall["@call"], {
7016
- ...componentArgs,
7017
- ...resolveValues(surface, basePath, binding.functionCall.args)
7018
- }, origin);
7019
- const { event } = binding;
7020
- const forwarded = {
7021
- name: event.name,
7022
- ...origin,
7023
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
7024
- userMessage: resolveUserMessage(surface, basePath, event.userMessage),
7025
- context: {
7026
- ...componentArgs,
7027
- ...resolveValues(surface, basePath, event.context)
7028
- }
7029
- };
7030
- return runtime.forwardEvent(forwarded, surface.agentId);
7031
- });
7032
- }
7033
- /**
7034
- * Runs one call of an event that matches a declared function: validates the
7035
- * component's args with the event `parameters` (if any), then calls the
7036
- * function, which validates them with its own schema. Never throws.
7037
- */
7038
- function invokeMatchedEvent(params) {
7039
- const { runtime, functionName } = params;
7040
- return runEvent(params, (componentArgs, origin) => runtime.dispatcher.invoke(functionName, componentArgs, origin));
7041
- }
7042
-
7043
- //#endregion
7044
- //#region src/v2/generative-ui/theme.ts
7045
- /**
7046
- * The built-in dark values. The light values are the fallbacks in the
7047
- * components, so a surface is light when no variable is set.
7048
- */
7049
- const DARK_THEME = {
7050
- "--a2ui-color-text-default": "#ececec",
7051
- "--a2ui-color-text-prose": "#ececec",
7052
- "--a2ui-color-text-primary": "#ececec",
7053
- "--a2ui-color-text-emphasis": "#fff",
7054
- "--a2ui-color-text-secondary": "#b4b4b4",
7055
- "--a2ui-color-text-tertiary": "#8e8e8e",
7056
- "--a2ui-color-text-success": "#4fd1a5",
7057
- "--a2ui-color-text-info": "#6cb6ff",
7058
- "--a2ui-color-text-warning": "#e3b341",
7059
- "--a2ui-color-text-caution": "#e3b341",
7060
- "--a2ui-color-text-danger": "#ff7b72",
7061
- "--a2ui-color-text-discovery": "#bc9cff",
7062
- "--a2ui-color-surface": "#1f1f1f",
7063
- "--a2ui-color-surface-secondary": "#2a2a2a",
7064
- "--a2ui-color-surface-tertiary": "#3a3a3a",
7065
- "--a2ui-color-surface-elevated": "#262626",
7066
- "--a2ui-color-surface-elevated-secondary": "#2f2f2f",
7067
- "--a2ui-color-surface-inverted": "#f2f2f2",
7068
- "--a2ui-color-surface-soft": "#232323",
7069
- "--a2ui-color-info": "rgba(80, 160, 255, 0.14)",
7070
- "--a2ui-color-warning": "rgba(240, 180, 60, 0.14)",
7071
- "--a2ui-color-caution": "rgba(240, 180, 60, 0.14)",
7072
- "--a2ui-color-success": "rgba(60, 200, 150, 0.14)",
7073
- "--a2ui-color-danger": "rgba(255, 110, 100, 0.14)",
7074
- "--a2ui-color-discovery": "rgba(170, 130, 255, 0.14)",
7075
- "--a2ui-color-info-soft": "rgba(80, 160, 255, 0.08)",
7076
- "--a2ui-color-warning-soft": "rgba(240, 180, 60, 0.08)",
7077
- "--a2ui-color-caution-soft": "rgba(240, 180, 60, 0.08)",
7078
- "--a2ui-color-success-soft": "rgba(60, 200, 150, 0.08)",
7079
- "--a2ui-color-danger-soft": "rgba(255, 110, 100, 0.08)",
7080
- "--a2ui-color-discovery-soft": "rgba(170, 130, 255, 0.08)",
7081
- "--a2ui-color-info-solid": "#3b8eea",
7082
- "--a2ui-color-warning-solid": "#c99a2e",
7083
- "--a2ui-color-caution-solid": "#c99a2e",
7084
- "--a2ui-color-success-solid": "#2fae86",
7085
- "--a2ui-color-danger-solid": "#e5534b",
7086
- "--a2ui-color-discovery-solid": "#9a6ff0",
7087
- "--a2ui-color-border-default": "rgba(255, 255, 255, 0.12)",
7088
- "--a2ui-color-border-subtle": "rgba(255, 255, 255, 0.06)",
7089
- "--a2ui-color-border-strong": "#4a4a4a",
7090
- "--a2ui-color-border-info": "#2f5f8f",
7091
- "--a2ui-color-border-warning": "#6b5420",
7092
- "--a2ui-color-border-caution": "#6b5420",
7093
- "--a2ui-color-border-success": "#1f5f4b",
7094
- "--a2ui-color-border-danger": "#7a2f2b",
7095
- "--a2ui-color-border-discovery": "#4f3a80",
7096
- "--a2ui-color-border-control": "rgba(255, 255, 255, 0.2)",
7097
- "--a2ui-color-accent": "#f2f2f2",
7098
- "--a2ui-color-on-accent": "#0d0d0d",
7099
- "--a2ui-color-panel": "#262626",
7100
- "--a2ui-color-control": "#2f2f2f",
7101
- "--a2ui-color-focus": "#3b9bff",
7102
- "--a2ui-color-shimmer": "rgba(255, 255, 255, 0.12)",
7103
- "--a2ui-color-chart-cursor": "rgba(255, 255, 255, 0.06)",
7104
- "--a2ui-color-slider-track": "rgba(255, 255, 255, 0.1)",
7105
- "--a2ui-color-badge-secondary": "rgba(255, 255, 255, 0.08)",
7106
- "--a2ui-color-highlight-green": "#1d4a37",
7107
- "--a2ui-color-highlight-orange": "#4d3418",
7108
- "--a2ui-color-highlight-pink": "#4d2338",
7109
- "--a2ui-shadow-xs": "0 1px 2px rgba(0, 0, 0, 0.5)",
7110
- "--a2ui-shadow-sm": "0 1px 3px rgba(0, 0, 0, 0.5)",
7111
- "--a2ui-shadow-soft": "0 1px 3px rgba(0, 0, 0, 0.3)",
7112
- "--a2ui-shadow-md": "0 4px 12px rgba(0, 0, 0, 0.4)"
7113
- };
7114
- const VARIABLE_NAME = /^--a2ui-[a-z0-9-]+$/;
7115
- const UNSAFE_VALUE = /[{};<>]/;
7116
- /** Matches the `dark` class on an ancestor of a surface, or on the surface. */
7117
- const DARK = ":where(.dark)";
7118
- /** The default dark values, as a rule that any theme rule beats. */
7119
- const DARK_THEME_CSS = `:where(.dark .a2ui-surface,.a2ui-surface.dark){${declarations(DARK_THEME)}}`;
7120
- function declarations(values) {
7121
- return Object.entries(values ?? {}).filter(([name, value]) => VARIABLE_NAME.test(name) && typeof value === "string" && !UNSAFE_VALUE.test(value)).map(([name, value]) => `${name}:${value}`).join(";");
7122
- }
7123
- /** A short, stable id for a stylesheet. */
7124
- function hashOf(text) {
7125
- let hash = 5381;
7126
- for (let index = 0; index < text.length; index++) hash = hash * 33 ^ text.charCodeAt(index);
7127
- return `t${(hash >>> 0).toString(36)}`;
7128
- }
7129
- /**
7130
- * The stylesheet of a theme: its values on the surfaces that carry its id,
7131
- * then its dark values in dark mode. `undefined` when the theme sets no
7132
- * variable. Values that could break out of the rule are left out.
7133
- *
7134
- * @example
7135
- * ```ts
7136
- * themeStyleSheet({ "--a2ui-color-accent": "red" });
7137
- * // { id: "t…", css: '.a2ui-surface[data-a2ui-theme="t…"]{--a2ui-color-accent:red}' }
7138
- * ```
7139
- */
7140
- function themeStyleSheet(theme) {
7141
- const { dark, ...base } = theme ?? {};
7142
- const both = declarations(base);
7143
- const darkOnly = declarations(dark);
7144
- if (!both && !darkOnly) return void 0;
7145
- const id = hashOf(`${both}|${darkOnly}`);
7146
- const self = `.a2ui-surface[data-a2ui-theme="${id}"]`;
7147
- return {
7148
- id,
7149
- css: [both && `${self}{${both}}`, darkOnly && `${DARK} ${self},${self}${DARK}{${darkOnly}}`].filter(Boolean).join("")
7150
- };
7151
- }
7152
-
7153
3971
  //#endregion
7154
3972
  //#region src/v2/generative-ui/SurfaceView.tsx
7155
3973
  const NO_ANCESTORS = [];
@@ -7164,7 +3982,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7164
3982
  function SurfaceView({ surface }) {
7165
3983
  const runtime = useRequiredGenerativeUIRuntime();
7166
3984
  const { theme } = runtime;
7167
- const sheet = (0, react.useMemo)(() => themeStyleSheet(theme), [theme]);
3985
+ const sheet = (0, react.useMemo)(() => (0, _copilotkit_shared_generative_ui.themeStyleSheet)(theme), [theme]);
7168
3986
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
7169
3987
  className: "a2ui-surface",
7170
3988
  "data-generative-ui-root": surface.surfaceId,
@@ -7242,7 +4060,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7242
4060
  */
7243
4061
  function TemplateChildren({ surface, template, basePath, ancestors }) {
7244
4062
  const dataModel = surface.model.dataModel;
7245
- const listPath = resolvePath(template.path, basePath);
4063
+ const listPath = (0, _copilotkit_core_generative_ui.resolvePath)(template.path, basePath);
7246
4064
  const subscribe = (0, react.useCallback)((onChange) => {
7247
4065
  const subscription = dataModel.subscribe(listPath, onChange);
7248
4066
  return () => subscription.unsubscribe();
@@ -7255,7 +4073,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7255
4073
  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, {
7256
4074
  surface,
7257
4075
  componentId: template.componentId,
7258
- basePath: joinPath(listPath, String(index)),
4076
+ basePath: (0, _copilotkit_core_generative_ui.joinPath)(listPath, String(index)),
7259
4077
  ancestors
7260
4078
  }, index)) });
7261
4079
  }
@@ -7302,7 +4120,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7302
4120
  const cached = cache.current.get(key);
7303
4121
  const isFresh = cached !== void 0 && cached.raw === raw && cached.basePath === basePath && [...cached.reads].every(([path, value]) => Object.is(dataModel.get(path), value));
7304
4122
  const resolve = () => {
7305
- const resolved = tryResolveDynamicValue(raw, {
4123
+ const resolved = (0, _copilotkit_core_generative_ui.tryResolveDynamicValue)(raw, {
7306
4124
  data: dataModel,
7307
4125
  basePath
7308
4126
  }, { isChecks: key === "checks" });
@@ -7330,7 +4148,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7330
4148
  for (const path of entry.reads.keys()) paths.add(path);
7331
4149
  }
7332
4150
  cache.current = next;
7333
- const accessibility = readAccessibility(a11yValues);
4151
+ const accessibility = (0, _copilotkit_core_generative_ui.readAccessibility)(a11yValues);
7334
4152
  for (const [key, value] of Object.entries(overrides)) if (!(0, _copilotkit_shared.isPathBinding)(properties[key])) values[key] = value;
7335
4153
  const rendered = (0, react.useRef)(next);
7336
4154
  rendered.current = next;
@@ -7430,22 +4248,22 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7430
4248
  values: {}
7431
4249
  };
7432
4250
  let values = modelData;
7433
- let result = validateSchemaSync(definition.props, values);
4251
+ let result = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, values);
7434
4252
  if (!result.success) {
7435
- const unset = withoutRejectedNulls(values, result.issues);
4253
+ const unset = (0, _copilotkit_shared_generative_ui.withoutRejectedNulls)(values, result.issues);
7436
4254
  if (unset) {
7437
4255
  values = unset;
7438
- result = validateSchemaSync(definition.props, values);
4256
+ result = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, values);
7439
4257
  }
7440
4258
  }
7441
4259
  if (!result.success) {
7442
4260
  const issues = result.issues.filter((issue) => {
7443
- const key = issueKey(issue);
7444
- return key === void 0 ? isAsyncIssue(issue) : !Object.hasOwn(definition.selectors, key);
4261
+ const key = (0, _copilotkit_shared_generative_ui.issueKey)(issue);
4262
+ return key === void 0 ? (0, _copilotkit_shared_generative_ui.isAsyncIssue)(issue) : !Object.hasOwn(definition.selectors, key);
7445
4263
  });
7446
4264
  if (issues.length > 0) return {
7447
4265
  ok: false,
7448
- problem: formatIssues(issues)
4266
+ problem: (0, _copilotkit_shared_generative_ui.formatIssues)(issues)
7449
4267
  };
7450
4268
  }
7451
4269
  return {
@@ -7475,14 +4293,14 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7475
4293
  ...modelCheck.values,
7476
4294
  ...selection.values
7477
4295
  };
7478
- let parsed = validateSchemaSync(definition.props, input);
4296
+ let parsed = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, input);
7479
4297
  if (!parsed.success) {
7480
- const unset = withoutRejectedNulls(input, parsed.issues);
7481
- if (unset) parsed = validateSchemaSync(definition.props, unset);
4298
+ const unset = (0, _copilotkit_shared_generative_ui.withoutRejectedNulls)(input, parsed.issues);
4299
+ if (unset) parsed = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, unset);
7482
4300
  }
7483
4301
  if (!parsed.success) return {
7484
4302
  ok: false,
7485
- problem: formatIssues(parsed.issues)
4303
+ problem: (0, _copilotkit_shared_generative_ui.formatIssues)(parsed.issues)
7486
4304
  };
7487
4305
  return {
7488
4306
  ok: true,
@@ -7517,12 +4335,12 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7517
4335
  parameters: definition.events?.[name]?.parameters
7518
4336
  };
7519
4337
  const functionName = Object.hasOwn(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
7520
- handlers[name] = functionName === void 0 ? (args) => invokeBoundEvent({
4338
+ handlers[name] = functionName === void 0 ? (args) => (0, _copilotkit_core_generative_ui.invokeBoundEvent)({
7521
4339
  ...call,
7522
4340
  binding: latest.current[name],
7523
4341
  basePath,
7524
4342
  args
7525
- }) : (args) => invokeMatchedEvent({
4343
+ }) : (args) => (0, _copilotkit_core_generative_ui.invokeMatchedEvent)({
7526
4344
  ...call,
7527
4345
  functionName,
7528
4346
  args
@@ -7553,7 +4371,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7553
4371
  setters: (0, react.useMemo)(() => {
7554
4372
  const result = {};
7555
4373
  const writable = definition.writable ?? [];
7556
- for (const key of writable) result[setterNameOf(key)] = (value) => {
4374
+ for (const key of writable) result[(0, _copilotkit_shared_generative_ui.setterNameOf)(key)] = (value) => {
7557
4375
  const binding = latest.current[key];
7558
4376
  if (!(0, _copilotkit_shared.isPathBinding)(binding)) {
7559
4377
  setOverrides((current) => ({
@@ -7563,14 +4381,14 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7563
4381
  return;
7564
4382
  }
7565
4383
  try {
7566
- runtime.manager.setOwnedValue(surface.key, resolvePath(binding["@path"], basePath), value);
4384
+ runtime.manager.setOwnedValue(surface.key, (0, _copilotkit_core_generative_ui.resolvePath)(binding["@path"], basePath), value);
7567
4385
  } catch (cause) {
7568
4386
  const message = cause instanceof Error ? cause.message : String(cause);
7569
- reportErrorSafely(runtime, {
4387
+ (0, _copilotkit_core_generative_ui.reportErrorSafely)(runtime, {
7570
4388
  kind: "props",
7571
4389
  surfaceId: surface.surfaceId,
7572
4390
  componentId,
7573
- error: /* @__PURE__ */ new Error(`${setterNameOf(key)}: ${message}`)
4391
+ error: /* @__PURE__ */ new Error(`${(0, _copilotkit_shared_generative_ui.setterNameOf)(key)}: ${message}`)
7574
4392
  });
7575
4393
  }
7576
4394
  };
@@ -7681,7 +4499,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7681
4499
  ]);
7682
4500
  const problem = dataProps.ok ? void 0 : dataProps.problem;
7683
4501
  (0, react.useEffect)(() => {
7684
- if (problem) reportErrorSafely(runtime, {
4502
+ if (problem) (0, _copilotkit_core_generative_ui.reportErrorSafely)(runtime, {
7685
4503
  kind: "props",
7686
4504
  surfaceId: surface.surfaceId,
7687
4505
  componentId,
@@ -7710,7 +4528,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
7710
4528
  children: hasEnvelope ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
7711
4529
  "data-a2ui-accessibility": "",
7712
4530
  style: ROOT_STYLE,
7713
- ...wrapperAria(accessibilityAttributes(accessibility)),
4531
+ ...(0, _copilotkit_core_generative_ui.wrapperAria)((0, _copilotkit_core_generative_ui.accessibilityAttributes)(accessibility)),
7714
4532
  children: rendered
7715
4533
  }) : rendered
7716
4534
  });
@@ -11636,7 +8454,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
11636
8454
  useManagerVersion(runtime);
11637
8455
  const segments = (0, react.useMemo)(() => (0, _copilotkit_core.splitA2UIMarkdown)(content), [content]);
11638
8456
  const threadId = chatThreadId ?? runtime.manager.getActiveThread();
11639
- const source = getMarkdownSurfaceSource(runtime);
8457
+ const source = (0, _copilotkit_core_generative_ui.getMarkdownSurfaceSource)(runtime);
11640
8458
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: segments.map((segment, index) => {
11641
8459
  if (segment.type === "markdown") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(streamdown.Streamdown, {
11642
8460
  ...markdownProps,
@@ -13622,7 +10440,6 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
13622
10440
  };
13623
10441
  }
13624
10442
  const GROUP_ROW_KEY_PREFIX = "copilotkit-group:";
13625
- const MESSAGE_ROW_KEY_PREFIX = "copilotkit-message:";
13626
10443
  const VIRTUALIZE_THRESHOLD = 50;
13627
10444
  function CopilotChatMessageView({ messages = [], assistantMessage, userMessage, reasoningMessage, cursor, intelligenceIndicator, workSummary, isRunning = false, transformMessages, groupMessages, messageFeedback = true, toolCallDisplay = "grouped", children, className, ...props }) {
13628
10445
  const isPinnedToBottom = (0, react.useContext)(ScrollPinnedContext);
@@ -13796,14 +10613,6 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
13796
10613
  (0, _copilotkit_shared.commitRowKeyStore)(rowKeyStore, renderedMessages);
13797
10614
  }, [rowKeyStore, renderedMessages]);
13798
10615
  const stableGroupKey = (key) => rowRenderKeys.get(key) ?? key;
13799
- const rowKey = (row) => row.type === "group" ? `${GROUP_ROW_KEY_PREFIX}${stableGroupKey(row.key)}` : `${MESSAGE_ROW_KEY_PREFIX}${rowRenderKeys.get(row.message.id) ?? row.message.id}`;
13800
- const previousRowKeysRef = (0, react.useRef)([]);
13801
- const rowKeys = (0, react.useMemo)(() => {
13802
- const next = rows.map(rowKey);
13803
- const previous = previousRowKeysRef.current;
13804
- return next.length === previous.length && next.every((key, index) => key === previous[index]) ? previous : next;
13805
- }, [rows, rowRenderKeys]);
13806
- previousRowKeysRef.current = rowKeys;
13807
10616
  const groupStateRef = (0, react.useRef)(/* @__PURE__ */ new Map());
13808
10617
  const groupSettersRef = (0, react.useRef)(/* @__PURE__ */ new Map());
13809
10618
  const groupStateThreadRef = (0, react.useRef)(config?.threadId);
@@ -13889,8 +10698,6 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
13889
10698
  total: 0,
13890
10699
  sizes: /* @__PURE__ */ new Map()
13891
10700
  });
13892
- const rowKeysRef = react.default.useRef(rowKeys);
13893
- rowKeysRef.current = rowKeys;
13894
10701
  const resizeAnchorRef = react.default.useRef(null);
13895
10702
  const restoringVisibilityRef = react.default.useRef(false);
13896
10703
  const firstMessageId = deduplicatedMessages[0]?.id;
@@ -13903,21 +10710,10 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
13903
10710
  sizes: /* @__PURE__ */ new Map()
13904
10711
  };
13905
10712
  }
13906
- const measuredKeysRef = react.default.useRef(rowKeys);
13907
- if (measuredKeysRef.current !== rowKeys) {
13908
- measuredKeysRef.current = rowKeys;
13909
- const live = new Set(rowKeys);
13910
- const measured = measuredRef.current;
13911
- for (const [key, height] of measured.sizes) if (!live.has(key)) {
13912
- measured.sizes.delete(key);
13913
- measured.total -= height;
13914
- }
13915
- }
13916
10713
  const estimateRowSize = react.default.useCallback(() => {
13917
10714
  const { total, sizes } = measuredRef.current;
13918
10715
  return sizes.size > 0 ? Math.max(1, Math.round(total / sizes.size)) : 100;
13919
10716
  }, []);
13920
- const getRowKey = react.default.useCallback((index) => rowKeys[index] ?? index, [rowKeys]);
13921
10717
  const isPinnedToBottomRef = react.default.useRef(isPinnedToBottom);
13922
10718
  const measuredWidthRef = react.default.useRef(null);
13923
10719
  const captureResizeAnchor = react.default.useCallback((instance) => {
@@ -13942,13 +10738,12 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
13942
10738
  captureResizeAnchor(instance);
13943
10739
  const height = el?.getBoundingClientRect().height ?? 0;
13944
10740
  const index = Number(el?.dataset?.index);
13945
- const key = Number.isInteger(index) ? rowKeysRef.current[index] : void 0;
13946
- if (height > 0 && key !== void 0) {
10741
+ if (height > 0 && Number.isInteger(index)) {
13947
10742
  const { total, sizes } = measuredRef.current;
13948
- measuredRef.current.total = total - (sizes.get(key) ?? 0) + height;
13949
- sizes.set(key, height);
10743
+ measuredRef.current.total = total - (sizes.get(index) ?? 0) + height;
10744
+ sizes.set(index, height);
13950
10745
  }
13951
- return height > 0 ? height : (key === void 0 ? void 0 : measuredRef.current.sizes.get(key)) ?? 100;
10746
+ return height > 0 ? height : measuredRef.current.sizes.get(index) ?? 100;
13952
10747
  }, [captureResizeAnchor]);
13953
10748
  const shouldAdjustScrollOnResize = react.default.useCallback((item, _delta, instance) => {
13954
10749
  if (isPinnedToBottomRef.current || resizeAnchorRef.current || restoringVisibilityRef.current) return false;
@@ -14014,7 +10809,6 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
14014
10809
  getScrollElement: () => shouldVirtualize ? scrollElement : null,
14015
10810
  observeElementRect: observeScrollRect,
14016
10811
  estimateSize: estimateRowSize,
14017
- getItemKey: getRowKey,
14018
10812
  overscan: 5,
14019
10813
  measureElement: measureRowElement,
14020
10814
  initialRect: {
@@ -14102,6 +10896,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
14102
10896
  }, `intelligence-${intelligenceTurnId}`));
14103
10897
  return elements.filter(Boolean);
14104
10898
  };
10899
+ const rowKey = (row) => row.type === "group" ? `${GROUP_ROW_KEY_PREFIX}${stableGroupKey(row.key)}` : rowRenderKeys.get(row.message.id) ?? row.message.id;
14105
10900
  const renderRow = (row) => {
14106
10901
  if (row.type === "message") return renderMessageBlock(row.message);
14107
10902
  const Wrapper = row.wrapper;
@@ -14114,6 +10909,8 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
14114
10909
  children: row.messages.flatMap(renderMessageBlock)
14115
10910
  }, rowKey(row))];
14116
10911
  };
10912
+ const rowKeysRef = (0, react.useRef)([]);
10913
+ rowKeysRef.current = rows.map(rowKey);
14117
10914
  const virtualModeRef = (0, react.useRef)(shouldVirtualize);
14118
10915
  virtualModeRef.current = shouldVirtualize;
14119
10916
  (0, react.useEffect)(() => {
@@ -19165,12 +15962,6 @@ Object.defineProperty(exports, 'AGUIConnectNotImplementedError', {
19165
15962
  return _ag_ui_client.AGUIConnectNotImplementedError;
19166
15963
  }
19167
15964
  });
19168
- Object.defineProperty(exports, 'AGUIEnforcementLimitError', {
19169
- enumerable: true,
19170
- get: function () {
19171
- return _ag_ui_client.AGUIEnforcementLimitError;
19172
- }
19173
- });
19174
15965
  Object.defineProperty(exports, 'AGUIError', {
19175
15966
  enumerable: true,
19176
15967
  get: function () {
@@ -19401,12 +16192,6 @@ Object.defineProperty(exports, 'CustomEventSchema', {
19401
16192
  return _ag_ui_core_schemas.CustomEventSchema;
19402
16193
  }
19403
16194
  });
19404
- Object.defineProperty(exports, 'DEFAULT_MAX_ENFORCED_ENTRIES', {
19405
- enumerable: true,
19406
- get: function () {
19407
- return _ag_ui_client.DEFAULT_MAX_ENFORCED_ENTRIES;
19408
- }
19409
- });
19410
16195
  Object.defineProperty(exports, 'DataSourceSchema', {
19411
16196
  enumerable: true,
19412
16197
  get: function () {
@@ -19574,12 +16359,6 @@ Object.defineProperty(exports, 'IntelligenceAgent', {
19574
16359
  });
19575
16360
  exports.IntelligenceIndicator = IntelligenceIndicator;
19576
16361
  exports.IntelligenceIndicatorView = IntelligenceIndicatorView;
19577
- Object.defineProperty(exports, 'IntelligenceReplayFailedError', {
19578
- enumerable: true,
19579
- get: function () {
19580
- return _copilotkit_core.IntelligenceReplayFailedError;
19581
- }
19582
- });
19583
16362
  Object.defineProperty(exports, 'InterruptSchema', {
19584
16363
  enumerable: true,
19585
16364
  get: function () {