@copilotkit/react-core 1.84.2-canary.1793807121 → 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-CP8oYU3L.cjs → copilotkit-DYtl9zj0.cjs} +56 -1347
  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-CdZ3W0B2.mjs → copilotkit-UHD9sXsS.mjs} +44 -1335
  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 +149 -3349
  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-CP8oYU3L.cjs.map +0 -1
  44. package/dist/copilotkit-CdZ3W0B2.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,4 +1,4 @@
1
- const require_MarkdownSurfaces = require('./MarkdownSurfaces-IUaWSJ0E.cjs');
1
+ const require_MarkdownSurfaces = require('./MarkdownSurfaces-3cGU5_0H.cjs');
2
2
  let react = require("react");
3
3
  react = require_MarkdownSurfaces.__toESM(react);
4
4
  let _copilotkit_core = require("@copilotkit/core");
@@ -20,8 +20,9 @@ let _ag_ui_core = require("@ag-ui/core");
20
20
  let zod = require("zod");
21
21
  let _copilotkit_mcp_apps_renderer_activity = require("@copilotkit/mcp-apps-renderer/activity");
22
22
  let _copilotkit_a2ui_renderer = require("@copilotkit/a2ui-renderer");
23
+ let _copilotkit_core_generative_ui = require("@copilotkit/core/generative-ui");
24
+ let _copilotkit_shared_generative_ui = require("@copilotkit/shared/generative-ui");
23
25
  let zod_to_json_schema = require("zod-to-json-schema");
24
- let _a2ui_web_core_v0_9 = require("@a2ui/web_core/v0_9");
25
26
  let _radix_ui_react_popover = require("@radix-ui/react-popover");
26
27
  _radix_ui_react_popover = require_MarkdownSurfaces.__toESM(_radix_ui_react_popover);
27
28
  let react_dom = require("react-dom");
@@ -1325,7 +1326,7 @@ function useRenderToolCall() {
1325
1326
 
1326
1327
  //#endregion
1327
1328
  //#region package.json
1328
- var version = "1.84.2-canary.1793807121";
1329
+ var version = "1.84.2-canary.openbot-intel-fixes";
1329
1330
 
1330
1331
  //#endregion
1331
1332
  //#region src/v2/components/CopilotKitInspector.tsx
@@ -2630,7 +2631,7 @@ function createA2UIMessageRenderer(options) {
2630
2631
  const groupedOperations = (0, react.useMemo)(() => {
2631
2632
  const groups = /* @__PURE__ */ new Map();
2632
2633
  for (const operation of operations) {
2633
- const surfaceId = getOperationSurfaceId$1(operation) ?? _copilotkit_a2ui_renderer.DEFAULT_SURFACE_ID;
2634
+ const surfaceId = getOperationSurfaceId(operation) ?? _copilotkit_a2ui_renderer.DEFAULT_SURFACE_ID;
2634
2635
  if (!groups.has(surfaceId)) groups.set(surfaceId, []);
2635
2636
  groups.get(surfaceId).push(operation);
2636
2637
  }
@@ -2798,7 +2799,7 @@ function SurfaceMessageProcessor({ surfaceId, operations, onReady }) {
2798
2799
  if (hash === lastHashRef.current) return;
2799
2800
  lastHashRef.current = hash;
2800
2801
  const ops = getSurface(surfaceId) ? operations.filter((op) => !op?.createSurface) : operations;
2801
- processMessages(ops);
2802
+ processMessages(ops.map(stripRoutingSurfaceId));
2802
2803
  if (onReady && surfaceHasRenderableContent(operations)) onReady();
2803
2804
  if (!IS_DEVELOPMENT) return;
2804
2805
  if (!getSurface(surfaceId)) {
@@ -2838,6 +2839,32 @@ function surfaceHasRenderableContent(operations) {
2838
2839
  return Object.values(v).some((x) => Array.isArray(x) ? x.length > 0 : x !== null && x !== void 0 && x !== "");
2839
2840
  });
2840
2841
  }
2842
+ const V0_9_ACTION_KEYS = [
2843
+ "createSurface",
2844
+ "updateComponents",
2845
+ "updateDataModel",
2846
+ "deleteSurface"
2847
+ ];
2848
+ /**
2849
+ * Drops a top-level `surfaceId` from a v0.9 message before it reaches
2850
+ * `MessageProcessor`.
2851
+ *
2852
+ * Compatibility with noncanonical agent payloads (see OSS-1048), not a key
2853
+ * added by react-core. `getOperationSurfaceId` reads it only as a routing
2854
+ * fallback. It is not part of the v0.9 envelope, and `@a2ui/web_core` 0.15
2855
+ * validates envelopes strictly, so leaving it in rejects the whole message
2856
+ * ("Unrecognized key(s) in object: 'surfaceId'"). The nested action keeps its
2857
+ * own `surfaceId`, which is the one the processor uses.
2858
+ *
2859
+ * @param operation - One A2UI operation, of any shape.
2860
+ * @returns The operation without a top-level `surfaceId` when it is a v0.9
2861
+ * message, otherwise the operation unchanged.
2862
+ */
2863
+ function stripRoutingSurfaceId(operation) {
2864
+ if (!operation || typeof operation !== "object" || !("surfaceId" in operation) || !V0_9_ACTION_KEYS.some((key) => key in operation)) return operation;
2865
+ const { surfaceId: _routingId, ...message } = operation;
2866
+ return message;
2867
+ }
2841
2868
  /**
2842
2869
  * Resolves the surface an operation addresses.
2843
2870
  *
@@ -2852,7 +2879,7 @@ function surfaceHasRenderableContent(operations) {
2852
2879
  * @param operation - One A2UI operation, of any shape.
2853
2880
  * @returns The surface id, or null when the operation names none.
2854
2881
  */
2855
- function getOperationSurfaceId$1(operation) {
2882
+ function getOperationSurfaceId(operation) {
2856
2883
  if (!operation || typeof operation !== "object") return null;
2857
2884
  const nested = operation?.createSurface?.surfaceId ?? operation?.updateComponents?.surfaceId ?? operation?.updateDataModel?.surfaceId ?? operation?.deleteSurface?.surfaceId;
2858
2885
  if (typeof nested === "string") return nested;
@@ -2952,547 +2979,6 @@ function A2UICatalogContext({ catalog, includeSchema }) {
2952
2979
  return null;
2953
2980
  }
2954
2981
 
2955
- //#endregion
2956
- //#region src/v2/generative-ui/action-message.ts
2957
- /** Context keys that supply the message's first line, in priority order. */
2958
- const TEXT_KEYS = ["message", "label"];
2959
- function isNonEmptyString(value) {
2960
- return typeof value === "string" && value.trim().length > 0;
2961
- }
2962
- /** `choose_plan`, `choose-plan` and `choosePlan` all become "Choose plan". */
2963
- function humanize(name) {
2964
- const spaced = name.replace(/[_-]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").trim();
2965
- return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();
2966
- }
2967
- function formatContextValue(value) {
2968
- return typeof value === "object" ? JSON.stringify(value) : String(value);
2969
- }
2970
- /**
2971
- * Turns a user event that no function handles into the text of a visible
2972
- * user message.
2973
- *
2974
- * The first line is, in order: `userMessage`, `context.message`,
2975
- * `context.label`, the label of the source component (from `resolveLabel`),
2976
- * or the event name made readable (`choose_plan` becomes "Choose plan").
2977
- * Each other context field follows as one `key: value` line. Objects are
2978
- * written as JSON. `null` and `undefined` fields are skipped.
2979
- *
2980
- * @param event - The user event, as sent by a surface.
2981
- * @param resolveLabel - Finds the visible label of a component by id. Build
2982
- * one with {@link createComponentLabelResolver}.
2983
- *
2984
- * @example
2985
- * ```ts
2986
- * buildActionMessageText({
2987
- * name: "choose_plan",
2988
- * surfaceId: "plans",
2989
- * componentId: "team-button",
2990
- * userMessage: "I pick the Team plan",
2991
- * context: { seats: 12 },
2992
- * });
2993
- * // "I pick the Team plan\n\nseats: 12"
2994
- * ```
2995
- */
2996
- function buildActionMessageText(event, resolveLabel) {
2997
- const { context, userMessage } = event;
2998
- const explicit = [userMessage, ...TEXT_KEYS.map((key) => context[key])].find(isNonEmptyString);
2999
- const resolved = explicit ? void 0 : resolveLabel?.(event.componentId);
3000
- const head = explicit ?? (isNonEmptyString(resolved) ? resolved.trim() : humanize(event.name));
3001
- const lines = Object.entries(context).filter(([key, value]) => !TEXT_KEYS.includes(key) && value !== void 0 && value !== null).map(([key, value]) => `${key}: ${formatContextValue(value)}`);
3002
- return lines.length > 0 ? `${head}\n\n${lines.join("\n")}` : head;
3003
- }
3004
- function ownText(component) {
3005
- if (!component) return void 0;
3006
- if (isNonEmptyString(component.label)) return component.label;
3007
- if (isNonEmptyString(component.text)) return component.text;
3008
- }
3009
- function childIds(component) {
3010
- const { child, children } = component;
3011
- const single = typeof child === "string" ? [child] : [];
3012
- const multiple = Array.isArray(children) ? children.filter((id) => typeof id === "string") : [];
3013
- return [...single, ...multiple];
3014
- }
3015
- /** The components that an operation adds, inline or in an update. */
3016
- function componentsOf(operation) {
3017
- if ("createSurface" in operation) return operation.createSurface.components ?? [];
3018
- if ("updateComponents" in operation) return operation.updateComponents.components;
3019
- return [];
3020
- }
3021
- /**
3022
- * Builds a function that finds the visible label of a component on a surface.
3023
- *
3024
- * The label is the component's own string `label`, else its string `text`,
3025
- * else the first `child` or `children` component that has a string `label`
3026
- * or `text`. When a component id is defined more than once, the last
3027
- * definition wins, as in the renderer.
3028
- *
3029
- * @param operations - The committed operations of the surface.
3030
- *
3031
- * @example
3032
- * ```ts
3033
- * const resolveLabel = createComponentLabelResolver(surface.operations);
3034
- * buildActionMessageText(event, resolveLabel);
3035
- * ```
3036
- */
3037
- function createComponentLabelResolver(operations) {
3038
- const byId = /* @__PURE__ */ new Map();
3039
- for (const operation of operations) {
3040
- const components = componentsOf(operation);
3041
- for (const component of components) byId.set(component.id, component);
3042
- }
3043
- return (componentId) => {
3044
- const component = byId.get(componentId);
3045
- if (!component) return void 0;
3046
- const own = ownText(component);
3047
- if (own) return own;
3048
- const ids = childIds(component);
3049
- for (const id of ids) {
3050
- const text = ownText(byId.get(id));
3051
- if (text) return text;
3052
- }
3053
- };
3054
- }
3055
-
3056
- //#endregion
3057
- //#region src/v2/generative-ui/manifest.ts
3058
- /**
3059
- * The built-in functions (the A2UI basic catalog plus calc and series) as
3060
- * manifest entries. Their args are described by the short signature, not
3061
- * by a full JSON Schema: the renderer checks them when they run. An app
3062
- * function of the same name replaces the entry.
3063
- */
3064
- function builtInFunctionManifests() {
3065
- return Object.fromEntries(Object.entries(_copilotkit_shared.GENERATIVE_UI_FUNCTIONS).map(([name, fn]) => [name, {
3066
- description: fn.description,
3067
- parameters: {
3068
- type: "object",
3069
- description: fn.parameters
3070
- },
3071
- returnType: fn.returnType,
3072
- allowedCallers: fn.allowedCallers,
3073
- ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
3074
- }]));
3075
- }
3076
- /**
3077
- * The manifest of a catalog, with no React runtime: the components of `ui`,
3078
- * the built-in functions (minus the names the app declares) and
3079
- * `options.functions`, the chat target and `options.targets`, and
3080
- * `options.surfaces`. `buildGenerativeUIManifest` builds the per-run
3081
- * manifest with it; tools that run outside React use it directly.
3082
- *
3083
- * @example
3084
- * ```ts
3085
- * const manifest = buildCatalogManifest(standardUI);
3086
- * manifest.targets; // [{ id: "chat", kind: "chat" }]
3087
- * ```
3088
- */
3089
- function buildCatalogManifest(ui, options = {}) {
3090
- return {
3091
- catalogId: ui.id,
3092
- catalogIds: require_MarkdownSurfaces.catalogIdsOf(ui),
3093
- components: (0, _copilotkit_shared.applyDescriptionOverrides)({ components: ui.manifestComponents }, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().descriptions).manifest.components,
3094
- functions: {
3095
- ...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
3096
- ...options.functions
3097
- },
3098
- targets: [{
3099
- id: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
3100
- kind: "chat"
3101
- }, ...options.targets ?? []],
3102
- surfaces: options.surfaces ?? {}
3103
- };
3104
- }
3105
- /**
3106
- * Builds the per-run manifest. Never contains handlers or renderers.
3107
- *
3108
- * - `functions`: the built-in functions, then the declared functions with
3109
- * exactly one mounted handler.
3110
- * - `targets`: the chat first, then each mounted `<GenerativeUISurface>`,
3111
- * with its `description` and its `components` when it has them.
3112
- */
3113
- function buildGenerativeUIManifest(runtime, threadId) {
3114
- const { ui, manager, dispatcher } = runtime;
3115
- const inlineTargets = manager.getMountedTargets().filter((target) => target.id !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET).map(({ id, ...rest }) => ({
3116
- id,
3117
- kind: "inline",
3118
- ...rest
3119
- }));
3120
- return buildCatalogManifest(ui, {
3121
- functions: dispatcher.listExposed(),
3122
- targets: inlineTargets,
3123
- surfaces: threadId ? manager.describeSurfaces(threadId) : {}
3124
- });
3125
- }
3126
- /**
3127
- * Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
3128
- * from the per-run manifest. It has the A2UI v1.0 renderer capabilities
3129
- * shape: one inline catalog with the id of the UI, and the CopilotKit data
3130
- * in `metadata.extensions`.
3131
- *
3132
- * The inline catalog has no `components` only for the markdown transport
3133
- * with `includeCatalog: false`. It has `instructions` for the markdown
3134
- * transport, or when given.
3135
- *
3136
- * @param runtime - The generative UI runtime of the provider.
3137
- * @param threadId - The thread of the run. Its surfaces go in `copilotkit_surfaces`.
3138
- * @param options - The transport and what to send.
3139
- *
3140
- * @example
3141
- * ```ts
3142
- * const envelope = buildGenerativeUIEnvelope(runtime, agent.threadId, {
3143
- * transport: "tool",
3144
- * includeCatalog: true,
3145
- * contextSent: false,
3146
- * });
3147
- * envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
3148
- * ```
3149
- */
3150
- function buildGenerativeUIEnvelope(runtime, threadId, options) {
3151
- const { transport, includeCatalog, contextSent, action } = options;
3152
- const manifest = buildGenerativeUIManifest(runtime, threadId);
3153
- const instructions = options.instructions ?? (transport === "markdown" ? (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest)) : void 0);
3154
- const omitComponents = transport === "markdown" && !includeCatalog;
3155
- return {
3156
- "1.0": {
3157
- supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
3158
- inlineCatalogs: [{
3159
- catalogId: manifest.catalogId,
3160
- protocolVersion: "1.0",
3161
- ...omitComponents ? {} : { components: manifest.components },
3162
- functions: manifest.functions,
3163
- ...instructions === void 0 ? {} : { instructions }
3164
- }]
3165
- },
3166
- metadata: { extensions: {
3167
- copilotkit_format: _copilotkit_shared.COPILOTKIT_UI_ENVELOPE_FORMAT,
3168
- copilotkit_transport: transport,
3169
- copilotkit_targets: manifest.targets,
3170
- copilotkit_surfaces: manifest.surfaces,
3171
- copilotkit_contextSent: contextSent,
3172
- ...action === void 0 ? {} : { copilotkit_action: action }
3173
- } }
3174
- };
3175
- }
3176
-
3177
- //#endregion
3178
- //#region src/v2/generative-ui/debug-source.ts
3179
- /**
3180
- * What a run of `threadId` sends: its envelope, and the text that goes into
3181
- * the prompt of the model because of it.
3182
- *
3183
- * - Tool transport: the runtime adds the `render_ui` guide. It builds it
3184
- * from the envelope with `buildGenerativeUIPrompt`, as done here.
3185
- * - Markdown transport: the provider sends the guideline and the compact
3186
- * schema as context entries. With `sendContext: false`, the backend builds
3187
- * its own prompt, usually from the `instructions` of the envelope.
3188
- */
3189
- function describeGenerativeUIRun(runtime, threadId, options) {
3190
- const envelope = buildGenerativeUIEnvelope(runtime, threadId, options);
3191
- if (options.transport === "tool") return {
3192
- envelope,
3193
- prompt: [{
3194
- title: "render_ui guide",
3195
- source: "runtime",
3196
- text: (0, _copilotkit_shared.buildGenerativeUIPrompt)((0, _copilotkit_shared.envelopeToManifest)(envelope))
3197
- }]
3198
- };
3199
- const manifest = buildGenerativeUIManifest(runtime, threadId);
3200
- if (!options.contextSent) return {
3201
- envelope,
3202
- prompt: [{
3203
- title: "Envelope instructions",
3204
- source: "backend",
3205
- text: (0, _copilotkit_shared.envelopeToManifest)(envelope).instructions ?? ""
3206
- }]
3207
- };
3208
- const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
3209
- const schema = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
3210
- return {
3211
- envelope,
3212
- prompt: [{
3213
- title: "Markdown guideline",
3214
- source: "context",
3215
- text: guideline
3216
- }, {
3217
- title: "Component schema",
3218
- source: "context",
3219
- text: schema
3220
- }]
3221
- };
3222
- }
3223
- /** The declared functions, with the JSON Schema of their parameters. */
3224
- function debugFunctions(runtime) {
3225
- const functions = {};
3226
- for (const [name, declared] of runtime.ui.functions) {
3227
- let parameters = {};
3228
- try {
3229
- parameters = require_MarkdownSurfaces.toJsonSchema(declared.parameters);
3230
- } catch {}
3231
- functions[name] = {
3232
- ...declared.description ? { description: declared.description } : {},
3233
- parameters,
3234
- handlers: runtime.dispatcher.handlerCount(name)
3235
- };
3236
- }
3237
- return functions;
3238
- }
3239
- /**
3240
- * The debug source that the provider gives core for the inspector. It builds
3241
- * a snapshot only when the inspector reads one.
3242
- *
3243
- * @param runtime - The generative UI parts of the provider.
3244
- * @param getOptions - The envelope options and agent ids of the current config.
3245
- * @returns The source, and `recordRun` for each run start.
3246
- */
3247
- function createGenerativeUIDebugSource(runtime, getOptions) {
3248
- const listeners = /* @__PURE__ */ new Set();
3249
- let lastRun;
3250
- const notify = () => {
3251
- for (const listener of [...listeners]) listener();
3252
- };
3253
- return {
3254
- source: {
3255
- getSnapshot() {
3256
- const { options, agentIds } = getOptions();
3257
- const threadId = runtime.manager.getActiveThread();
3258
- const manifest = buildGenerativeUIManifest(runtime, threadId);
3259
- return {
3260
- catalogId: runtime.ui.id,
3261
- transport: options.transport,
3262
- ...agentIds ? { agentIds } : {},
3263
- components: runtime.ui.manifestComponents,
3264
- componentCatalogs: Object.fromEntries(require_MarkdownSurfaces.componentCatalogIds(runtime.ui)),
3265
- functions: debugFunctions(runtime),
3266
- state: { ...runtime.manager.getState() },
3267
- targets: manifest.targets,
3268
- activeThreadId: threadId,
3269
- surfaces: runtime.manager.debugSurfaces(),
3270
- lastRun,
3271
- nextRun: {
3272
- agentId: void 0,
3273
- threadId,
3274
- ...describeGenerativeUIRun(runtime, threadId, options)
3275
- }
3276
- };
3277
- },
3278
- subscribe(listener) {
3279
- listeners.add(listener);
3280
- const unsubscribe = runtime.manager.subscribe(listener);
3281
- return () => {
3282
- listeners.delete(listener);
3283
- unsubscribe();
3284
- };
3285
- }
3286
- },
3287
- recordRun(run) {
3288
- lastRun = run;
3289
- notify();
3290
- }
3291
- };
3292
- }
3293
-
3294
- //#endregion
3295
- //#region src/v2/generative-ui/dispatcher.ts
3296
- const messageOf = (error) => error instanceof Error ? error.message : String(error);
3297
- /**
3298
- * Creates the registry of functions that generated UI may call.
3299
- *
3300
- * A function is callable when it is declared in `getDeclared()` and exactly
3301
- * one handler is mounted for it with `register`. Names are resolved at call
3302
- * time and fail closed. Nothing is sent to the agent.
3303
- * Neither `invoke` nor `listExposed` throws.
3304
- *
3305
- * @param options.getDeclared - Returns the declared functions.
3306
- * @param options.onError - Gets each failed call.
3307
- *
3308
- * @example
3309
- * ```ts
3310
- * const dispatcher = createGenerativeUIDispatcher({
3311
- * getDeclared: () => new Map(Object.entries(ui.functions)),
3312
- * });
3313
- * const unregister = dispatcher.register("addToCart", handlerRef);
3314
- * await dispatcher.invoke("addToCart", { productId: "p1" }, origin);
3315
- * unregister();
3316
- * ```
3317
- */
3318
- /**
3319
- * True while the browser counts the current task as user-activated (a
3320
- * click, a key press). Where the API is missing (older browsers, test
3321
- * environments), the gesture is assumed.
3322
- */
3323
- function hasUserActivation() {
3324
- if (typeof navigator === "undefined") return true;
3325
- const activation = navigator.userActivation;
3326
- return activation === void 0 || activation.isActive;
3327
- }
3328
- /**
3329
- * The permissions of a declared function as the manifest states them: the
3330
- * callers always written out, so a reader needs no default.
3331
- */
3332
- function permissionsOf(fn) {
3333
- const callers = (0, _copilotkit_shared.functionCallers)(fn);
3334
- return {
3335
- allowedCallers: callers.renderer && callers.agent ? "rendererOrAgent" : callers.agent ? "agentOnly" : "rendererOnly",
3336
- ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
3337
- };
3338
- }
3339
- function createGenerativeUIDispatcher(options) {
3340
- const handlers = /* @__PURE__ */ new Map();
3341
- const resolveUnchecked = (name) => {
3342
- const declared = options.getDeclared().get(name);
3343
- if (!declared) return {
3344
- ok: false,
3345
- error: new require_MarkdownSurfaces.GenerativeUIError("function_not_found", `No generative UI function named "${name}" is declared in createGenerativeUI({ functions })`)
3346
- };
3347
- const mounted = [...handlers.get(name) ?? []];
3348
- const [ref] = mounted;
3349
- if (!ref) return {
3350
- ok: false,
3351
- error: new require_MarkdownSurfaces.GenerativeUIError("function_not_found", `"${name}" is declared, but no useGenerativeUIFunction handler is mounted for it`)
3352
- };
3353
- if (mounted.length > 1) return {
3354
- ok: false,
3355
- error: new require_MarkdownSurfaces.GenerativeUIError("function_conflict", `"${name}" has ${mounted.length} useGenerativeUIFunction handlers mounted. Mount exactly one.`)
3356
- };
3357
- return {
3358
- ok: true,
3359
- declared,
3360
- ref
3361
- };
3362
- };
3363
- const isDeclared = (name) => {
3364
- try {
3365
- return options.getDeclared().has(name);
3366
- } catch {
3367
- return false;
3368
- }
3369
- };
3370
- const resolve = (name) => {
3371
- try {
3372
- return resolveUnchecked(name);
3373
- } catch (error) {
3374
- return {
3375
- ok: false,
3376
- error: new require_MarkdownSurfaces.GenerativeUIError("handler_failed", `"${name}" could not be resolved: ${messageOf(error)}`)
3377
- };
3378
- }
3379
- };
3380
- const validateArgs = async (name, schema, args) => {
3381
- try {
3382
- const validation = await schema["~standard"].validate(args);
3383
- if (!validation.issues) return {
3384
- ok: true,
3385
- value: validation.value
3386
- };
3387
- return {
3388
- ok: false,
3389
- error: new require_MarkdownSurfaces.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("; ")}`)
3390
- };
3391
- } catch (error) {
3392
- return {
3393
- ok: false,
3394
- error: new require_MarkdownSurfaces.GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${messageOf(error)}`)
3395
- };
3396
- }
3397
- };
3398
- const failWith = (name, origin, error) => {
3399
- try {
3400
- options.onError?.({
3401
- name,
3402
- origin,
3403
- error
3404
- });
3405
- } catch {}
3406
- return {
3407
- ok: false,
3408
- error
3409
- };
3410
- };
3411
- /**
3412
- * Why `origin` may not call a function with these permissions now, as an
3413
- * error, or `undefined` when it may. The agent is refused what is for the
3414
- * renderer; a component is refused what is for the agent, and a gesture
3415
- * function when the browser counts no user activation.
3416
- */
3417
- const callerError = (name, fn, origin) => {
3418
- const isComponent = "componentId" in origin;
3419
- if (!isComponent && !_copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS) return new require_MarkdownSurfaces.GenerativeUIError("invalid_function_call", _copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
3420
- const problem = (0, _copilotkit_shared.callerProblem)(name, fn, isComponent ? "renderer" : "agent");
3421
- if (problem !== void 0) return new require_MarkdownSurfaces.GenerativeUIError("invalid_function_call", problem);
3422
- if (isComponent && fn.requiresUserActivation && !hasUserActivation()) return new require_MarkdownSurfaces.GenerativeUIError("invalid_function_call", `function "${name}" runs only from a user gesture; this event was not one`);
3423
- };
3424
- /**
3425
- * Runs a basic function of the A2UI catalog. They are value functions of
3426
- * the renderer: the agent cannot call them, and one that needs a user
3427
- * gesture runs only from an event binding.
3428
- */
3429
- const invokeBasic = (name, args, origin) => {
3430
- const refused = callerError(name, _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name], origin);
3431
- if (refused) return failWith(name, origin, refused);
3432
- if (args !== void 0 && !(typeof args === "object" && args !== null && !Array.isArray(args))) return failWith(name, origin, new require_MarkdownSurfaces.GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": args must be an object`));
3433
- try {
3434
- return {
3435
- ok: true,
3436
- result: require_MarkdownSurfaces.BASIC_FUNCTIONS[name](args ?? {})
3437
- };
3438
- } catch (error) {
3439
- return failWith(name, origin, new require_MarkdownSurfaces.GenerativeUIError(error instanceof require_MarkdownSurfaces.ExpressionError ? "invalid_arguments" : "handler_failed", `"${name}" failed: ${messageOf(error)}`));
3440
- }
3441
- };
3442
- return {
3443
- async invoke(name, args, origin) {
3444
- const resolved = resolve(name);
3445
- if (!resolved.ok && resolved.error.code === "function_not_found" && !isDeclared(name) && Object.prototype.hasOwnProperty.call(require_MarkdownSurfaces.BASIC_FUNCTIONS, name)) return invokeBasic(name, args, origin);
3446
- if (!resolved.ok) return failWith(name, origin, resolved.error);
3447
- const refused = callerError(name, resolved.declared, origin);
3448
- if (refused) return failWith(name, origin, refused);
3449
- const validated = await validateArgs(name, resolved.declared.parameters, args ?? {});
3450
- if (!validated.ok) return failWith(name, origin, validated.error);
3451
- try {
3452
- return {
3453
- ok: true,
3454
- result: await resolved.ref.current(validated.value)
3455
- };
3456
- } catch (error) {
3457
- return failWith(name, origin, new require_MarkdownSurfaces.GenerativeUIError("handler_failed", `"${name}" failed: ${messageOf(error)}`));
3458
- }
3459
- },
3460
- listExposed() {
3461
- let names;
3462
- try {
3463
- names = [...options.getDeclared().keys()];
3464
- } catch {
3465
- return {};
3466
- }
3467
- const listed = {};
3468
- for (const name of names) {
3469
- const resolved = resolve(name);
3470
- if (!resolved.ok) continue;
3471
- if (!(0, _copilotkit_shared.functionCallers)(resolved.declared).renderer && !_copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS) continue;
3472
- const { description, parameters, returnType } = resolved.declared;
3473
- try {
3474
- listed[name] = {
3475
- ...description ? { description } : {},
3476
- parameters: require_MarkdownSurfaces.toJsonSchema(parameters),
3477
- ...returnType ? { returnType } : {},
3478
- ...permissionsOf(resolved.declared)
3479
- };
3480
- } catch {}
3481
- }
3482
- return listed;
3483
- },
3484
- register(name, ref) {
3485
- const mounted = handlers.get(name) ?? /* @__PURE__ */ new Set();
3486
- mounted.add(ref);
3487
- handlers.set(name, mounted);
3488
- return () => {
3489
- mounted.delete(ref);
3490
- };
3491
- },
3492
- handlerCount: (name) => handlers.get(name)?.size ?? 0
3493
- };
3494
- }
3495
-
3496
2982
  //#endregion
3497
2983
  //#region src/v2/generative-ui/markdown/context.ts
3498
2984
  /**
@@ -3527,7 +3013,7 @@ function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
3527
3013
  let schemaId;
3528
3014
  let schemaValue;
3529
3015
  const refreshSchema = (threadId) => {
3530
- const manifest = buildGenerativeUIManifest(runtime, threadId);
3016
+ const manifest = (0, _copilotkit_core_generative_ui.buildGenerativeUIManifest)(runtime, threadId);
3531
3017
  const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
3532
3018
  if (guideline !== guidelineValue) {
3533
3019
  if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
@@ -3571,794 +3057,13 @@ function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
3571
3057
  ]);
3572
3058
  }
3573
3059
 
3574
- //#endregion
3575
- //#region src/v2/generative-ui/surface-manager.ts
3576
- function surfaceKey(threadId, surfaceId) {
3577
- return `${threadId}::${surfaceId}`;
3578
- }
3579
- let creationCounter = 0;
3580
- const FORBIDDEN_SEGMENTS = new Set([
3581
- "__proto__",
3582
- "constructor",
3583
- "prototype"
3584
- ]);
3585
- /** "/a/b/" to "/a/b". The root stays "/". */
3586
- function normalizePath(path) {
3587
- return (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path) || "/";
3588
- }
3589
- /** True when `path` is `ancestor` or below it. */
3590
- function isAtOrBelow(path, ancestor) {
3591
- if (ancestor === "/") return true;
3592
- return path === ancestor || path.startsWith(`${ancestor}/`);
3593
- }
3594
- /**
3595
- * Rejections as `"operation <index>: <reason>"` lines, cut to the size that
3596
- * the envelope reader accepts.
3597
- */
3598
- function summarizeRejections(rejections) {
3599
- 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));
3600
- }
3601
- /**
3602
- * Framework-agnostic store of generated surfaces. One web_core SurfaceModel per
3603
- * (threadId, surfaceId), shared by every mount. Applies only newly committed
3604
- * operations, validates each before applying it, and owns app state and the
3605
- * data model paths that the user wrote, so agent updates cannot overwrite
3606
- * them. App state never goes into a surface's data model. Selectors read it
3607
- * with `getState()`.
3608
- */
3609
- var GenerativeUISurfaceManager = class {
3610
- constructor(ui, options = {}) {
3611
- this.ui = ui;
3612
- this.options = options;
3613
- this.surfaces = /* @__PURE__ */ new Map();
3614
- this.bookkeeping = /* @__PURE__ */ new Map();
3615
- this.listeners = /* @__PURE__ */ new Set();
3616
- this.targets = /* @__PURE__ */ new Map();
3617
- this.state = {};
3618
- this.owned = /* @__PURE__ */ new Map();
3619
- this.deletedKeys = /* @__PURE__ */ new Set();
3620
- this.linked = /* @__PURE__ */ new Map();
3621
- this.version = 0;
3622
- this.subscribe = (listener) => {
3623
- this.listeners.add(listener);
3624
- return () => {
3625
- this.listeners.delete(listener);
3626
- };
3627
- };
3628
- this.getVersion = () => this.version;
3629
- this.getState = () => this.state;
3630
- this.webCoreCatalog = new _a2ui_web_core_v0_9.Catalog(ui.id, [...ui.components.keys()].map((name) => ({
3631
- name,
3632
- schema: zod.z.any()
3633
- })), []);
3634
- }
3635
- notify() {
3636
- this.version++;
3637
- for (const listener of [...this.listeners]) listener();
3638
- }
3639
- setActiveThread(threadId) {
3640
- if (threadId === this.activeThreadId) return;
3641
- this.activeThreadId = threadId;
3642
- this.notify();
3643
- }
3644
- getActiveThread() {
3645
- return this.activeThreadId;
3646
- }
3647
- ingest(threadId, agentId, content) {
3648
- const key = surfaceKey(threadId, content.surfaceId);
3649
- const operations = content.operations ?? [];
3650
- let surface = this.surfaces.get(key);
3651
- let book = this.bookkeeping.get(key);
3652
- let changed = false;
3653
- if (surface && book && !this.extendsApplied(book, operations)) {
3654
- this.disposeSurface(key);
3655
- surface = void 0;
3656
- book = void 0;
3657
- }
3658
- if (!surface || !book) {
3659
- surface = this.createSurface(key, threadId, agentId, content);
3660
- this.restoreOwnedValues(surface);
3661
- book = {
3662
- appliedCount: 0,
3663
- lastFingerprint: void 0
3664
- };
3665
- this.surfaces.set(key, surface);
3666
- this.bookkeeping.set(key, book);
3667
- changed = true;
3668
- }
3669
- const serverRejected = content.rejected ?? [];
3670
- if (surface.clientRejected.length > 0 && (surface.status !== "streaming" && content.status === "streaming" || serverRejected.length < surface.serverRejected.length)) {
3671
- surface.clientRejected = [];
3672
- changed = true;
3673
- }
3674
- if (operations.length > 0) {
3675
- const lastFingerprint = JSON.stringify(operations[operations.length - 1]);
3676
- const isReplay = operations.some((op) => (0, _copilotkit_shared.getOperationKind)(op) === "deleteSurface");
3677
- for (let index = book.appliedCount; index < operations.length; index++) {
3678
- this.applyOperation(surface, operations[index], {
3679
- index,
3680
- isReplay
3681
- });
3682
- changed = true;
3683
- }
3684
- book.appliedCount = operations.length;
3685
- surface.operations = operations;
3686
- book.lastFingerprint = lastFingerprint;
3687
- }
3688
- if (surface.status !== content.status || surface.target !== content.target || surface.serverRejected.length !== serverRejected.length) {
3689
- surface.status = content.status;
3690
- surface.target = content.target;
3691
- surface.serverRejected = serverRejected;
3692
- changed = true;
3693
- }
3694
- if (changed) this.notify();
3695
- }
3696
- /** The surface of a `key` (see `surfaceKey`), unless it is deleted. */
3697
- getSurfaceByKey(key) {
3698
- const surface = this.surfaces.get(key);
3699
- return surface && !surface.deleted ? surface : void 0;
3700
- }
3701
- getSurface(threadId, surfaceId) {
3702
- const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
3703
- return surface && !surface.deleted ? surface : void 0;
3704
- }
3705
- getSurfaceForTarget(target, threadId = this.activeThreadId) {
3706
- if (!threadId) return void 0;
3707
- let latest;
3708
- for (const surface of this.surfaces.values()) {
3709
- if (surface.threadId !== threadId || surface.target !== target || surface.deleted) continue;
3710
- if (!latest || surface.createdAt > latest.createdAt) latest = surface;
3711
- }
3712
- return latest;
3713
- }
3714
- /**
3715
- * A surface whose first createSurface was rejected, so the chat can show
3716
- * the error where the surface would be. `undefined` for any other surface.
3717
- */
3718
- getFailedSurface(threadId, surfaceId) {
3719
- const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
3720
- return surface?.failed ? surface : void 0;
3721
- }
3722
- /**
3723
- * The surfaces of a thread, for the model. A surface with user-owned
3724
- * values lists them in `dataModel`, so the model can read what the user
3725
- * entered. A surface with dropped operations lists them in `rejected`, so
3726
- * the model can fix them on the next run. A deleted surface, or one that
3727
- * was never created, has a `status`, so the model knows that the id is
3728
- * not a live surface.
3729
- */
3730
- describeSurfaces(threadId) {
3731
- const described = {};
3732
- for (const surface of this.surfaces.values()) {
3733
- if (surface.threadId !== threadId) continue;
3734
- const owned = this.owned.get(surface.key);
3735
- const rejections = [...surface.serverRejected, ...surface.clientRejected];
3736
- const status = this.deletedKeys.has(surface.key) ? "deleted" : surface.failed ? "failed" : void 0;
3737
- described[surface.surfaceId] = {
3738
- target: surface.target,
3739
- ...owned && owned.size > 0 ? { dataModel: Object.fromEntries(owned) } : {},
3740
- ...rejections.length > 0 && status !== "deleted" ? { rejected: summarizeRejections(rejections) } : {},
3741
- ...status ? { status } : {}
3742
- };
3743
- }
3744
- return described;
3745
- }
3746
- /** Every surface that is not deleted, oldest first, for the inspector. */
3747
- debugSurfaces() {
3748
- return [...this.surfaces.values()].filter((surface) => !surface.deleted).sort((a, b) => a.createdAt - b.createdAt).map((surface) => ({
3749
- surfaceId: surface.surfaceId,
3750
- threadId: surface.threadId,
3751
- agentId: surface.agentId,
3752
- target: surface.target,
3753
- status: surface.status,
3754
- operations: surface.operations,
3755
- dataModel: surface.model.dataModel.get("/"),
3756
- userValues: Object.fromEntries(this.owned.get(surface.key) ?? []),
3757
- rejected: [...surface.serverRejected.map((r) => ({
3758
- ...r,
3759
- source: "runtime"
3760
- })), ...surface.clientRejected.map((r) => ({
3761
- ...r,
3762
- source: "browser"
3763
- }))]
3764
- }));
3765
- }
3766
- /**
3767
- * Marks a target as mounted. Returns the function that unmounts it. Calling
3768
- * that function more than once has no effect.
3769
- *
3770
- * @param id - The target id.
3771
- * @param options - The description and the allowed components of this mount.
3772
- */
3773
- registerTarget(id, options = {}) {
3774
- const registration = { ...options };
3775
- const registrations = this.targets.get(id) ?? /* @__PURE__ */ new Set();
3776
- registrations.add(registration);
3777
- this.targets.set(id, registrations);
3778
- this.notify();
3779
- let released = false;
3780
- return () => {
3781
- if (released) return;
3782
- released = true;
3783
- registrations.delete(registration);
3784
- if (registrations.size === 0) this.targets.delete(id);
3785
- this.notify();
3786
- };
3787
- }
3788
- /**
3789
- * The mounted targets. Each has the description and the component list of
3790
- * its earliest mount that has one.
3791
- */
3792
- getMountedTargets() {
3793
- const mounted = [];
3794
- for (const [id, registrations] of this.targets) {
3795
- const description = [...registrations].find((registration) => registration.description !== void 0)?.description;
3796
- const components = this.targetComponents(id);
3797
- mounted.push({
3798
- id,
3799
- ...description === void 0 ? {} : { description },
3800
- ...components === void 0 ? {} : { components: [...components] }
3801
- });
3802
- }
3803
- return mounted;
3804
- }
3805
- /**
3806
- * The component list of the earliest mount of `id` that has one.
3807
- * `undefined` when no mount of `id` limits its components.
3808
- */
3809
- targetComponents(id) {
3810
- return [...this.targets.get(id) ?? /* @__PURE__ */ new Set()].find((registration) => registration.components !== void 0)?.components;
3811
- }
3812
- /** The components that `validateOperation` allows on a surface. */
3813
- allowedComponentsFor(surface) {
3814
- const components = this.targetComponents(surface.target);
3815
- return components === void 0 ? void 0 : {
3816
- target: surface.target,
3817
- names: new Set(components)
3818
- };
3819
- }
3820
- /** Sets one state key. Notifies only when the value changed. */
3821
- setState(key, value) {
3822
- if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
3823
- this.state = {
3824
- ...this.state,
3825
- [key]: value
3826
- };
3827
- this.notify();
3828
- }
3829
- /** Removes one state key. Notifies only when the key was set. */
3830
- removeState(key) {
3831
- if (!Object.hasOwn(this.state, key)) return;
3832
- const { [key]: _removed, ...rest } = this.state;
3833
- this.state = rest;
3834
- this.notify();
3835
- }
3836
- /**
3837
- * Makes the surfaces of `surfaceIds` share their data model: a user write
3838
- * to one of them goes to all of them (see `setOwnedValue`). The markdown
3839
- * transport links the parts of a chat surface that the prose lift split.
3840
- * A later call for one of the surfaces replaces its group.
3841
- *
3842
- * @param threadId - The thread of the surfaces.
3843
- * @param surfaceIds - The surface ids of the group. One id clears a link.
3844
- */
3845
- linkSurfaces(threadId, surfaceIds) {
3846
- const keys = new Set(surfaceIds.map((id) => surfaceKey(threadId, id)));
3847
- for (const key of keys) if (keys.size > 1) this.linked.set(key, keys);
3848
- else this.linked.delete(key);
3849
- }
3850
- /**
3851
- * Writes a user value into the data model of a surface, and marks `path`
3852
- * as user-owned. Then agent writes to that path, or below it, are ignored.
3853
- * An agent write above it keeps the user value. Ownership ends when the
3854
- * surface is deleted. Does nothing for an unknown or deleted surface. The
3855
- * surfaces linked to it (see `linkSurfaces`) get the same write.
3856
- *
3857
- * @param key - The `key` of the surface.
3858
- * @param path - An absolute JSON pointer, for example "/form/email".
3859
- * @param value - The new value. It is copied.
3860
- * @throws Error when a path segment is "__proto__", "constructor" or
3861
- * "prototype", or when the path does not fit the data (for example, a
3862
- * segment above it holds a string).
3863
- */
3864
- setOwnedValue(key, path, value) {
3865
- const normalized = normalizePath(path);
3866
- const forbidden = normalized.split("/").find((segment) => FORBIDDEN_SEGMENTS.has(segment));
3867
- if (forbidden !== void 0) throw new Error(`[generativeUI] path segment "${forbidden}" is not allowed in "${path}".`);
3868
- for (const target of this.linked.get(key) ?? [key]) this.writeOwnedValue(target, normalized, value);
3869
- }
3870
- writeOwnedValue(key, path, value) {
3871
- const surface = this.surfaces.get(key);
3872
- if (!surface || surface.deleted) return;
3873
- surface.model.dataModel.set(path, structuredClone(value));
3874
- const owned = this.owned.get(key) ?? /* @__PURE__ */ new Map();
3875
- owned.set(path, structuredClone(value));
3876
- this.owned.set(key, owned);
3877
- }
3878
- /**
3879
- * Writes the user-owned values into the new, empty data model of a rebuilt
3880
- * surface. The agent operations are applied after it.
3881
- */
3882
- restoreOwnedValues(surface) {
3883
- const owned = this.owned.get(surface.key) ?? /* @__PURE__ */ new Map();
3884
- for (const [path, value] of owned) surface.model.dataModel.set(path, structuredClone(value));
3885
- }
3886
- /**
3887
- * The value that an agent write puts at `path`, with the user-owned values
3888
- * below `path` written back into it. `undefined` when `path` is user-owned
3889
- * or below a user-owned path, so the agent cannot write it. Throws when a
3890
- * user value does not fit the new value.
3891
- */
3892
- mergeOwnedValues(key, path, value) {
3893
- const merged = { value: structuredClone(value) };
3894
- const owned = this.owned.get(key);
3895
- if (!owned) return merged;
3896
- const ownedPaths = [...owned.keys()];
3897
- if (ownedPaths.some((ownedPath) => isAtOrBelow(path, ownedPath))) return void 0;
3898
- const below = ownedPaths.filter((ownedPath) => isAtOrBelow(ownedPath, path));
3899
- if (below.length === 0) return merged;
3900
- const scratch = new _a2ui_web_core_v0_9.DataModel({ value: merged.value });
3901
- const prefix = path === "/" ? "" : path;
3902
- for (const ownedPath of below) {
3903
- const relative = ownedPath.slice(prefix.length);
3904
- scratch.set(`/value${relative}`, structuredClone(owned.get(ownedPath)));
3905
- }
3906
- return { value: scratch.get("/value") };
3907
- }
3908
- extendsApplied(book, operations) {
3909
- if (operations.length < book.appliedCount) return false;
3910
- if (book.appliedCount === 0) return true;
3911
- return JSON.stringify(operations[book.appliedCount - 1]) === book.lastFingerprint;
3912
- }
3913
- createSurface(key, threadId, agentId, content) {
3914
- return {
3915
- key,
3916
- threadId,
3917
- surfaceId: content.surfaceId,
3918
- agentId,
3919
- model: new _a2ui_web_core_v0_9.SurfaceModel(content.surfaceId, this.webCoreCatalog),
3920
- createdAt: ++creationCounter,
3921
- target: content.target,
3922
- status: content.status,
3923
- deleted: false,
3924
- failed: false,
3925
- serverRejected: content.rejected ?? [],
3926
- clientRejected: [],
3927
- operations: []
3928
- };
3929
- }
3930
- disposeSurface(key) {
3931
- this.surfaces.get(key)?.model.dispose();
3932
- this.surfaces.delete(key);
3933
- this.bookkeeping.delete(key);
3934
- }
3935
- /**
3936
- * Marks a surface deleted and frees its components and data. The record
3937
- * stays, so the model is still told about the id and the bookkeeping does
3938
- * not rebuild the surface for content that was already applied.
3939
- */
3940
- closeSurface(surface) {
3941
- surface.deleted = true;
3942
- surface.model.dispose();
3943
- surface.model = new _a2ui_web_core_v0_9.SurfaceModel(surface.surfaceId, this.webCoreCatalog);
3944
- this.owned.delete(surface.key);
3945
- this.linked.delete(surface.key);
3946
- }
3947
- /** The surfaces of a thread that a part of `surfaceId` reads, for tests. */
3948
- getLinkedSurfaceIds(threadId, surfaceId) {
3949
- const keys = this.linked.get(surfaceKey(threadId, surfaceId));
3950
- if (!keys) return [surfaceId];
3951
- const prefix = `${threadId}::`;
3952
- return [...keys].map((key) => key.slice(prefix.length));
3953
- }
3954
- /**
3955
- * Drops the node keys that the app sets: bound props and matched events.
3956
- * The model does not see them, so a model value for one is ignored, not
3957
- * rejected. This runs before validation, because validation rejects keys
3958
- * that are not in the manifest. It never changes the given operation.
3959
- */
3960
- dropAppSetKeys(op) {
3961
- const kind = (0, _copilotkit_shared.getOperationKind)(op);
3962
- if (kind !== "updateComponents" && kind !== "createSurface") return op;
3963
- const record = op;
3964
- const payload = record[kind];
3965
- const nodes = payload?.components;
3966
- if (!Array.isArray(nodes)) return op;
3967
- return {
3968
- ...record,
3969
- [kind]: {
3970
- ...payload,
3971
- components: nodes.map((node) => this.dropAppSetNodeKeys(node))
3972
- }
3973
- };
3974
- }
3975
- dropAppSetNodeKeys(node) {
3976
- if (typeof node !== "object" || node === null || !("component" in node)) return node;
3977
- const { component } = node;
3978
- if (typeof component !== "string") return node;
3979
- const definition = this.ui.components.get(component);
3980
- if (!definition) return node;
3981
- return Object.fromEntries(Object.entries(node).filter(([key]) => !Object.hasOwn(definition.selectors, key) && !Object.hasOwn(definition.eventFunctions, key)));
3982
- }
3983
- /**
3984
- * The surfaces that `validateOperation` gets for one operation of the
3985
- * content of `surface`.
3986
- *
3987
- * - `knownSurfaces`: the surface, when it exists before the operation. It
3988
- * does not exist before its first createSurface, or after a delete.
3989
- * - `createdSurfaces`: the surface, when a createSurface at this position
3990
- * uses its id again. That is the case after the first operation, and for
3991
- * a surface that was deleted before, unless the content replays that
3992
- * delete.
3993
- */
3994
- surfacesFor(surface, kind, position) {
3995
- const isFirstCreate = kind === "createSurface" && position.index === 0;
3996
- const exists = !surface.deleted && !isFirstCreate;
3997
- const isRecreate = this.deletedKeys.has(surface.key) && !position.isReplay;
3998
- const isUsedAgain = position.index > 0 || isRecreate;
3999
- return {
4000
- knownSurfaces: new Set(exists ? [surface.surfaceId] : []),
4001
- createdSurfaces: new Set(isUsedAgain ? [surface.surfaceId] : [])
4002
- };
4003
- }
4004
- applyOperation(surface, received, position) {
4005
- const { index } = position;
4006
- const kind = (0, _copilotkit_shared.getOperationKind)(received);
4007
- if (kind === "callRendererFunction") return;
4008
- const reject = (reason) => {
4009
- if (kind === "createSurface" && index === 0) {
4010
- this.closeSurface(surface);
4011
- surface.failed = true;
4012
- }
4013
- surface.clientRejected.push({
4014
- index,
4015
- reason
4016
- });
4017
- this.options.onOperationRejected?.({
4018
- surfaceId: surface.surfaceId,
4019
- index,
4020
- reason
4021
- });
4022
- };
4023
- const targetId = (0, _copilotkit_shared.getOperationSurfaceId)(received);
4024
- if (targetId !== void 0 && targetId !== surface.surfaceId) return reject(`operation is for surface "${targetId}", not "${surface.surfaceId}"`);
4025
- const op = this.dropAppSetKeys(received);
4026
- const validation = (0, _copilotkit_shared.validateOperation)(op, {
4027
- manifest: {
4028
- catalogId: this.ui.id,
4029
- catalogIds: require_MarkdownSurfaces.catalogIdsOf(this.ui),
4030
- components: this.ui.manifestComponents
4031
- },
4032
- ...this.surfacesFor(surface, kind, position),
4033
- allowedComponents: this.allowedComponentsFor(surface)
4034
- });
4035
- if (!validation.ok) return reject(validation.reason);
4036
- const typed = op;
4037
- if ("createSurface" in typed) {
4038
- const { dataModel, components = [] } = typed.createSurface;
4039
- const problem = this.nodesProblem(components);
4040
- if (problem) return reject(problem);
4041
- if (dataModel) {
4042
- const failure = this.writeAgentData(surface, "/", dataModel);
4043
- if (failure) return reject(failure);
4044
- }
4045
- for (const node of components) this.upsertNode(surface.model, node);
4046
- return;
4047
- }
4048
- if ("updateComponents" in typed) {
4049
- const nodes = typed.updateComponents.components;
4050
- const problem = this.nodesProblem(nodes);
4051
- if (problem) return reject(problem);
4052
- for (const node of nodes) this.upsertNode(surface.model, node);
4053
- return;
4054
- }
4055
- if ("updateDataModel" in typed) {
4056
- const { path = "/", value } = typed.updateDataModel;
4057
- const written = value === null ? void 0 : value;
4058
- const failure = this.writeAgentData(surface, normalizePath(path), written);
4059
- if (failure) return reject(failure);
4060
- return;
4061
- }
4062
- if ("deleteSurface" in typed) {
4063
- this.closeSurface(surface);
4064
- this.deletedKeys.add(surface.key);
4065
- }
4066
- }
4067
- /** The first node with props of the wrong type, as a reason. */
4068
- nodesProblem(nodes) {
4069
- for (const node of nodes) {
4070
- const problem = this.checkNodeProps(node);
4071
- if (problem) return `component "${node.id}": ${problem}`;
4072
- }
4073
- }
4074
- /**
4075
- * Writes an agent value at `path` and keeps the user-owned values. A write
4076
- * to a user-owned path is ignored, not rejected. Gives the reason when the
4077
- * value does not fit the data, else `undefined`.
4078
- */
4079
- writeAgentData(surface, path, value) {
4080
- try {
4081
- const merged = this.mergeOwnedValues(surface.key, path, value);
4082
- if (merged) surface.model.dataModel.set(path, merged.value);
4083
- return;
4084
- } catch (error) {
4085
- return error instanceof Error ? error.message : String(error);
4086
- }
4087
- }
4088
- checkNodeProps(node) {
4089
- const definition = this.ui.components.get(node.component);
4090
- if (!definition) return `unknown component "${node.component}"`;
4091
- const { id: _id, component: _component, ...rest } = node;
4092
- const dataProps = Object.fromEntries(Object.entries(rest).filter(([key]) => !definition.events?.[key] && !definition.slots?.[key] && !_copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS.has(key)));
4093
- if (!definition.props) return void 0;
4094
- const unknownNow = new Set(Object.keys(definition.selectors));
4095
- const literals = {};
4096
- for (const [key, value] of Object.entries(dataProps)) if (require_MarkdownSurfaces.containsDynamicValue(value)) unknownNow.add(key);
4097
- else literals[key] = value;
4098
- let result = require_MarkdownSurfaces.validateSchemaSync(definition.props, literals);
4099
- if (!result.success) {
4100
- const unset = require_MarkdownSurfaces.withoutRejectedNulls(literals, result.issues);
4101
- if (unset) result = require_MarkdownSurfaces.validateSchemaSync(definition.props, unset);
4102
- }
4103
- if (result.success) return void 0;
4104
- const issues = result.issues.filter((issue) => {
4105
- const key = require_MarkdownSurfaces.issueKey(issue);
4106
- return key === void 0 ? require_MarkdownSurfaces.isAsyncIssue(issue) : !unknownNow.has(key);
4107
- });
4108
- return issues.length > 0 ? require_MarkdownSurfaces.formatIssues(issues) : void 0;
4109
- }
4110
- upsertNode(model, node) {
4111
- const { id, component, ...rest } = node;
4112
- const properties = structuredClone(rest);
4113
- const existing = model.componentsModel.get(id);
4114
- if (existing && existing.type === component) {
4115
- existing.properties = properties;
4116
- return;
4117
- }
4118
- if (existing) model.componentsModel.removeComponent(id);
4119
- model.componentsModel.addComponent(new _a2ui_web_core_v0_9.ComponentModel(id, component, properties));
4120
- }
4121
- };
4122
-
4123
3060
  //#endregion
4124
3061
  //#region src/v2/generative-ui/use-generative-ui-root.ts
4125
3062
  const isDevelopment = () => process.env.NODE_ENV !== "production";
4126
- /** At most this many function follow-up runs for each user turn. */
4127
- const MAX_FUNCTION_FOLLOW_UPS = 5;
4128
3063
  function ingestMessages(manager, agent, messages) {
4129
3064
  if (!agent.threadId) return;
4130
3065
  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);
4131
3066
  }
4132
- /** What the envelope of a run says, from the provider config. */
4133
- function envelopeOptionsFor(config) {
4134
- if (config.transport === "markdown") return {
4135
- transport: "markdown",
4136
- includeCatalog: config.includeCatalog !== false,
4137
- contextSent: config.sendContext !== false
4138
- };
4139
- return {
4140
- transport: "tool",
4141
- includeCatalog: true,
4142
- contextSent: false
4143
- };
4144
- }
4145
- /**
4146
- * The components of a surface as one `updateComponents` operation, so that
4147
- * the label of the component that sent an event can be found.
4148
- */
4149
- function surfaceComponents(surface) {
4150
- const components = [...surface.model.componentsModel.entries].map(([id, model]) => ({
4151
- ...model.properties,
4152
- id,
4153
- component: model.type
4154
- }));
4155
- return [{
4156
- version: _copilotkit_shared.A2UI_VERSION,
4157
- updateComponents: {
4158
- surfaceId: surface.surfaceId,
4159
- components
4160
- }
4161
- }];
4162
- }
4163
- /** True when `value` names a `functionCallId`. */
4164
- function hasFunctionCallId(value) {
4165
- return typeof value === "object" && value !== null && "functionCallId" in value && typeof value.functionCallId === "string" && value.functionCallId !== "";
4166
- }
4167
- /** The `functionCallId` that a developer message answers, if any. */
4168
- function answeredCallId(content) {
4169
- if (!content.includes("rendererFunctionResponse")) return void 0;
4170
- try {
4171
- const parsed = JSON.parse(content);
4172
- const response = typeof parsed === "object" && parsed !== null && "rendererFunctionResponse" in parsed ? parsed.rendererFunctionResponse : void 0;
4173
- return hasFunctionCallId(response) ? response.functionCallId : void 0;
4174
- } catch {
4175
- return;
4176
- }
4177
- }
4178
- /** The function calls that a developer message in `messages` answers. */
4179
- function answeredCallIds(messages) {
4180
- const ids = /* @__PURE__ */ new Set();
4181
- for (const message of messages) {
4182
- if (message.role !== "developer") continue;
4183
- const id = answeredCallId(message.content);
4184
- if (id !== void 0) ids.add(id);
4185
- }
4186
- return ids;
4187
- }
4188
- /** The id of the last user message. A user turn starts with it. */
4189
- function lastUserMessageId(messages) {
4190
- for (let index = messages.length - 1; index >= 0; index--) {
4191
- const message = messages[index];
4192
- if (message?.role === "user") return message.id;
4193
- }
4194
- }
4195
- /** The function calls of the tool transport: its function-call activities. */
4196
- function activityFunctionCalls(messages) {
4197
- const requests = [];
4198
- for (const message of messages) {
4199
- if (!(message.role === "activity" && message.activityType === _copilotkit_shared.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE) || !hasFunctionCallId(message.content)) continue;
4200
- requests.push({
4201
- functionCallId: message.content.functionCallId,
4202
- operation: {
4203
- version: _copilotkit_shared.A2UI_VERSION,
4204
- callRendererFunction: message.content
4205
- }
4206
- });
4207
- }
4208
- return requests;
4209
- }
4210
- /** The function calls of the markdown transport: its fence lines. */
4211
- function markdownFunctionCalls(calls) {
4212
- const requests = [];
4213
- for (const { operation } of calls) {
4214
- const payload = operation.callRendererFunction;
4215
- if (!hasFunctionCallId(payload)) continue;
4216
- requests.push({
4217
- functionCallId: payload.functionCallId,
4218
- operation
4219
- });
4220
- }
4221
- return requests;
4222
- }
4223
- /** The text of a `rendererFunctionResponse` developer message. */
4224
- function responseContent(response) {
4225
- return JSON.stringify({
4226
- version: _copilotkit_shared.A2UI_VERSION,
4227
- rendererFunctionResponse: response
4228
- });
4229
- }
4230
- function errorAnswer(functionCallId, code, message) {
4231
- return {
4232
- content: responseContent({
4233
- functionCallId,
4234
- error: {
4235
- code,
4236
- message
4237
- }
4238
- }),
4239
- followUp: true
4240
- };
4241
- }
4242
- const overCapAnswer = (functionCallId) => ({
4243
- content: responseContent({
4244
- functionCallId,
4245
- error: {
4246
- code: "follow_up_limit",
4247
- 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.`
4248
- }
4249
- }),
4250
- followUp: false
4251
- });
4252
- /**
4253
- * Runs the functions that the agent calls with `callRendererFunction`, for
4254
- * both transports, and answers each call.
4255
- *
4256
- * - Each `functionCallId` runs once for each thread. A replay, a sync of
4257
- * the same messages again, or a call that already has an answer message
4258
- * does not run it again.
4259
- * - The answer is a hidden developer message with a `rendererFunctionResponse`.
4260
- * The answers go to the agent only when it is not running. Then one
4261
- * follow-up run starts for all of them.
4262
- * - A user turn has at most {@link MAX_FUNCTION_FOLLOW_UPS} follow-up runs.
4263
- * A call after that does not run. It gets a `follow_up_limit` error and
4264
- * starts no follow-up run.
4265
- */
4266
- function createFunctionCallRunner(options) {
4267
- const { copilotkit, dispatcher, manifest } = options;
4268
- const threads = /* @__PURE__ */ new Map();
4269
- const threadState = (threadId) => {
4270
- let state = threads.get(threadId);
4271
- if (!state) {
4272
- state = {
4273
- done: /* @__PURE__ */ new Set(),
4274
- pending: [],
4275
- turn: void 0,
4276
- followUps: 0,
4277
- flushing: false
4278
- };
4279
- threads.set(threadId, state);
4280
- }
4281
- return state;
4282
- };
4283
- const answer = async (request) => {
4284
- const { functionCallId } = request;
4285
- const validation = (0, _copilotkit_shared.validateOperation)(request.operation, {
4286
- manifest,
4287
- knownSurfaces: /* @__PURE__ */ new Set()
4288
- });
4289
- if (!validation.ok) return errorAnswer(functionCallId, "invalid_arguments", validation.reason);
4290
- const operation = request.operation;
4291
- if (!("callRendererFunction" in operation)) return errorAnswer(functionCallId, "invalid_arguments", "the operation is not a callRendererFunction");
4292
- const { callFunction } = operation.callRendererFunction;
4293
- const name = callFunction["@call"];
4294
- const result = await dispatcher.invoke(name, callFunction.args ?? {}, { functionCallId });
4295
- if (!result.ok) return errorAnswer(functionCallId, result.error.code, result.error.message);
4296
- try {
4297
- return {
4298
- content: responseContent({
4299
- functionCallId,
4300
- value: result.result ?? null
4301
- }),
4302
- followUp: true
4303
- };
4304
- } catch (cause) {
4305
- return errorAnswer(functionCallId, "handler_failed", `The result of "${name}" is not JSON: ${cause instanceof Error ? cause.message : String(cause)}`);
4306
- }
4307
- };
4308
- /**
4309
- * Adds the pending answers of a thread to the agent, then starts one
4310
- * follow-up run. It waits while the agent runs: the next read of the
4311
- * thread, at the end of the run, flushes again.
4312
- */
4313
- const flush = async (agent, threadId, state) => {
4314
- if (state.flushing) return;
4315
- state.flushing = true;
4316
- try {
4317
- while (state.pending.length > 0) {
4318
- const batch = [...state.pending];
4319
- const answers = await Promise.all(batch);
4320
- await copilotkit.waitForPendingFrameworkUpdates();
4321
- if (agent.isRunning || agent.threadId !== threadId) return;
4322
- if (state.pending.length > batch.length) continue;
4323
- state.pending = [];
4324
- for (const { content } of answers) agent.addMessage({
4325
- id: (0, _copilotkit_shared.randomUUID)(),
4326
- role: "developer",
4327
- content
4328
- });
4329
- if (!answers.some((item) => item.followUp)) continue;
4330
- state.followUps++;
4331
- await copilotkit.runAgent({ agent });
4332
- }
4333
- } catch (error) {
4334
- if (isDevelopment()) console.warn("[generativeUI] function follow-up run failed:", error);
4335
- } finally {
4336
- state.flushing = false;
4337
- }
4338
- };
4339
- return { run(agent, requests, messages, running) {
4340
- const { threadId } = agent;
4341
- if (!threadId) return;
4342
- const state = threadState(threadId);
4343
- const turn = lastUserMessageId(messages);
4344
- if (turn !== state.turn) {
4345
- state.turn = turn;
4346
- state.followUps = 0;
4347
- }
4348
- const isNew = (request) => !state.done.has(request.functionCallId);
4349
- const fresh = requests.filter(isNew);
4350
- const answered = fresh.length > 0 ? answeredCallIds(messages) : /* @__PURE__ */ new Set();
4351
- for (const request of fresh) {
4352
- const { functionCallId } = request;
4353
- if (state.done.has(functionCallId)) continue;
4354
- state.done.add(functionCallId);
4355
- if (answered.has(functionCallId)) continue;
4356
- const isOverCap = state.followUps >= MAX_FUNCTION_FOLLOW_UPS;
4357
- state.pending.push(isOverCap ? Promise.resolve(overCapAnswer(functionCallId)) : answer(request));
4358
- }
4359
- if (!running) flush(agent, threadId, state);
4360
- } };
4361
- }
4362
3067
  /** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */
4363
3068
  function useGenerativeUIRoot(copilotkit, config) {
4364
3069
  const configRef = (0, react.useRef)(config);
@@ -4376,12 +3081,12 @@ function useGenerativeUIRoot(copilotkit, config) {
4376
3081
  }
4377
3082
  if (isDevelopment()) console.warn(`[generativeUI] ${info.kind} error in ${info.surfaceId}${info.componentId ? `/${info.componentId}` : ""}: ${info.error?.message}`);
4378
3083
  };
4379
- const manager = new GenerativeUISurfaceManager(ui, { onOperationRejected: ({ surfaceId, index, reason }) => reportError({
3084
+ const manager = new _copilotkit_core_generative_ui.GenerativeUISurfaceManager(ui, { onOperationRejected: ({ surfaceId, index, reason }) => reportError({
4380
3085
  kind: "operation",
4381
3086
  surfaceId,
4382
3087
  error: /* @__PURE__ */ new Error(`operation ${index} rejected: ${reason}`)
4383
3088
  }) });
4384
- const dispatcher = createGenerativeUIDispatcher({
3089
+ const dispatcher = (0, _copilotkit_core_generative_ui.createGenerativeUIDispatcher)({
4385
3090
  getDeclared: () => ui.functions,
4386
3091
  onError: ({ name, origin, error }) => {
4387
3092
  if ("functionCallId" in origin) {
@@ -4395,13 +3100,17 @@ function useGenerativeUIRoot(copilotkit, config) {
4395
3100
  });
4396
3101
  }
4397
3102
  });
4398
- const functionCalls = createFunctionCallRunner({
4399
- copilotkit,
3103
+ const functionCalls = (0, _copilotkit_core_generative_ui.createFunctionCallRunner)({
3104
+ core: copilotkit,
4400
3105
  dispatcher,
4401
3106
  manifest: {
4402
3107
  catalogId: ui.id,
4403
- catalogIds: require_MarkdownSurfaces.catalogIdsOf(ui),
3108
+ catalogIds: (0, _copilotkit_shared_generative_ui.catalogIdsOf)(ui),
4404
3109
  components: ui.manifestComponents
3110
+ },
3111
+ settle: () => copilotkit.waitForPendingFrameworkUpdates(),
3112
+ warn: (message, error) => {
3113
+ if (isDevelopment()) console.warn(message, error);
4405
3114
  }
4406
3115
  });
4407
3116
  const forwardingAgents = /* @__PURE__ */ new Set();
@@ -4430,12 +3139,12 @@ function useGenerativeUIRoot(copilotkit, config) {
4430
3139
  actions.delete(agent);
4431
3140
  const latest = configRef.current;
4432
3141
  if (!latest) return;
4433
- const envelope = buildGenerativeUIEnvelope({
3142
+ const envelope = (0, _copilotkit_core_generative_ui.buildGenerativeUIEnvelope)({
4434
3143
  ui,
4435
3144
  manager,
4436
3145
  dispatcher
4437
3146
  }, agent.threadId, {
4438
- ...envelopeOptionsFor(latest),
3147
+ ...(0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest),
4439
3148
  action
4440
3149
  });
4441
3150
  const id = copilotkit.addScopedProperties({
@@ -4460,7 +3169,7 @@ function useGenerativeUIRoot(copilotkit, config) {
4460
3169
  };
4461
3170
  const forwardEvent = async (event, agentId) => {
4462
3171
  const fail = (message) => {
4463
- const error = new require_MarkdownSurfaces.GenerativeUIError("event_forward_failed", message);
3172
+ const error = new _copilotkit_shared_generative_ui.GenerativeUIError("event_forward_failed", message);
4464
3173
  reportError({
4465
3174
  kind: "event",
4466
3175
  surfaceId: event.surfaceId,
@@ -4476,16 +3185,16 @@ function useGenerativeUIRoot(copilotkit, config) {
4476
3185
  if (!agent) return fail(`No agent "${agentId}" to receive "${event.name}"`);
4477
3186
  if (agent.isRunning || forwardingAgents.has(agent)) return {
4478
3187
  ok: false,
4479
- error: new require_MarkdownSurfaces.GenerativeUIError("agent_busy", `"${event.name}" was not sent: the agent is running`)
3188
+ error: new _copilotkit_shared_generative_ui.GenerativeUIError("agent_busy", `"${event.name}" was not sent: the agent is running`)
4480
3189
  };
4481
3190
  forwardingAgents.add(agent);
4482
3191
  try {
4483
3192
  const surface = agent.threadId ? manager.getSurface(agent.threadId, event.surfaceId) : void 0;
4484
- const resolveLabel = surface ? createComponentLabelResolver(surfaceComponents(surface)) : void 0;
3193
+ const resolveLabel = surface ? (0, _copilotkit_core_generative_ui.surfaceLabelResolver)(surface) : void 0;
4485
3194
  agent.addMessage({
4486
3195
  id: (0, _copilotkit_shared.randomUUID)(),
4487
3196
  role: "user",
4488
- content: buildActionMessageText(event, resolveLabel)
3197
+ content: (0, _copilotkit_core_generative_ui.buildActionMessageText)(event, resolveLabel)
4489
3198
  });
4490
3199
  setAction(agent, (0, _copilotkit_shared.toA2UIActionMessage)(event));
4491
3200
  await copilotkit.runAgent({ agent });
@@ -4539,10 +3248,10 @@ function useGenerativeUIRoot(copilotkit, config) {
4539
3248
  const watched = /* @__PURE__ */ new WeakSet();
4540
3249
  const agentSubscriptions = [];
4541
3250
  let envelopeId;
4542
- const debug = createGenerativeUIDebugSource(core, () => {
3251
+ const debug = (0, _copilotkit_core_generative_ui.createGenerativeUIDebugSource)(core, () => {
4543
3252
  const latest = configRef.current ?? { ui: core.ui };
4544
3253
  return {
4545
- options: envelopeOptionsFor(latest),
3254
+ options: (0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest),
4546
3255
  agentIds: latest.agentIds
4547
3256
  };
4548
3257
  });
@@ -4559,7 +3268,7 @@ function useGenerativeUIRoot(copilotkit, config) {
4559
3268
  */
4560
3269
  const setEnvelope = (agent, latest) => {
4561
3270
  removeEnvelope();
4562
- const run = describeGenerativeUIRun(core, agent.threadId, envelopeOptionsFor(latest));
3271
+ const run = (0, _copilotkit_core_generative_ui.describeGenerativeUIRun)(core, agent.threadId, (0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest));
4563
3272
  envelopeId = copilotkit.addScopedProperties({
4564
3273
  properties: { [_copilotkit_shared.COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: run.envelope } },
4565
3274
  agentIds: latest.agentIds
@@ -4579,13 +3288,13 @@ function useGenerativeUIRoot(copilotkit, config) {
4579
3288
  * Both give their function calls to the one runner.
4580
3289
  */
4581
3290
  const readMessages = (agent, messages, running) => {
4582
- const requests = activityFunctionCalls(messages);
3291
+ const requests = (0, _copilotkit_core_generative_ui.activityFunctionCalls)(messages);
4583
3292
  const { threadId } = agent;
4584
3293
  if (configRef.current?.transport !== "markdown") ingestMessages(core.manager, agent, messages);
4585
3294
  else if (threadId) {
4586
3295
  core.manager.setActiveThread(threadId);
4587
- const calls = require_MarkdownSurfaces.getMarkdownSurfaceSource(core).sync(threadId, agent.agentId, messages, { running });
4588
- requests.push(...markdownFunctionCalls(calls));
3296
+ const calls = (0, _copilotkit_core_generative_ui.getMarkdownSurfaceSource)(core).sync(threadId, agent.agentId, messages, { running });
3297
+ requests.push(...(0, _copilotkit_core_generative_ui.markdownFunctionCalls)(calls));
4589
3298
  }
4590
3299
  core.functionCalls.run(agent, requests, messages, running);
4591
3300
  };
@@ -16533,4 +15242,4 @@ Object.defineProperty(exports, 'useToast', {
16533
15242
  return useToast;
16534
15243
  }
16535
15244
  });
16536
- //# sourceMappingURL=copilotkit-CP8oYU3L.cjs.map
15245
+ //# sourceMappingURL=copilotkit-DYtl9zj0.cjs.map