@copilotkit/react-core 2.0.0-rc.31 → 2.0.0-rc.32

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 (34) hide show
  1. package/README.md +1 -1
  2. package/dist/MarkdownRendererContext-CPfNVyde.d.mts +241 -0
  3. package/dist/MarkdownRendererContext-CPfNVyde.d.mts.map +1 -0
  4. package/dist/MarkdownRendererContext-iOl2pj9l.d.cts +241 -0
  5. package/dist/MarkdownRendererContext-iOl2pj9l.d.cts.map +1 -0
  6. package/dist/MarkdownSurfaces-BFoO6wSB.cjs +1650 -0
  7. package/dist/MarkdownSurfaces-BFoO6wSB.cjs.map +1 -0
  8. package/dist/MarkdownSurfaces-BQ1HGCzB.mjs +1442 -0
  9. package/dist/MarkdownSurfaces-BQ1HGCzB.mjs.map +1 -0
  10. package/dist/generative-ui.cjs +687 -2964
  11. package/dist/generative-ui.cjs.map +1 -1
  12. package/dist/generative-ui.d.cts +2478 -2683
  13. package/dist/generative-ui.d.cts.map +1 -1
  14. package/dist/generative-ui.d.mts +2477 -2682
  15. package/dist/generative-ui.d.mts.map +1 -1
  16. package/dist/generative-ui.mjs +299 -2585
  17. package/dist/generative-ui.mjs.map +1 -1
  18. package/dist/index.cjs +26 -1367
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +1 -1
  21. package/dist/index.d.mts +1 -1
  22. package/dist/index.mjs +11 -1352
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/index.umd.js +124 -3358
  25. package/dist/index.umd.js.map +1 -1
  26. package/package.json +9 -9
  27. package/dist/MarkdownRendererContext-BX26QLwl.d.cts +0 -937
  28. package/dist/MarkdownRendererContext-BX26QLwl.d.cts.map +0 -1
  29. package/dist/MarkdownRendererContext-DAOMewji.d.mts +0 -937
  30. package/dist/MarkdownRendererContext-DAOMewji.d.mts.map +0 -1
  31. package/dist/MarkdownSurfaces-BbrHcSHN.cjs +0 -3903
  32. package/dist/MarkdownSurfaces-BbrHcSHN.cjs.map +0 -1
  33. package/dist/MarkdownSurfaces-DQbRS91-.mjs +0 -3587
  34. package/dist/MarkdownSurfaces-DQbRS91-.mjs.map +0 -1
package/dist/index.umd.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use client";
2
2
 
3
3
  (function(global, factory) {
4
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@copilotkit/core'), require('react'), require('@copilotkit/markdown/react'), require('@copilotkit/markdown'), require('react/jsx-runtime'), require('@radix-ui/react-tooltip'), require('@radix-ui/react-dropdown-menu'), require('@copilotkit/shared'), require('@copilotkit/web-inspector/mount'), require('@copilotkit/mcp-apps-renderer/activity'), require('@copilotkit/a2ui-renderer'), require('@copilotkit/a2ui-renderer/engine-core'), require('zod'), require('@a2ui/web_core/v0_9'), require('@copilotkit/a2ui-renderer/catalog-schema'), require('@copilotkit/core/styles'), 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', '@copilotkit/core', 'react', '@copilotkit/markdown/react', '@copilotkit/markdown', 'react/jsx-runtime', '@radix-ui/react-tooltip', '@radix-ui/react-dropdown-menu', '@copilotkit/shared', '@copilotkit/web-inspector/mount', '@copilotkit/mcp-apps-renderer/activity', '@copilotkit/a2ui-renderer', '@copilotkit/a2ui-renderer/engine-core', 'zod', '@a2ui/web_core/v0_9', '@copilotkit/a2ui-renderer/catalog-schema', '@copilotkit/core/styles', '@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.CopilotKitReactCore = {}), global.CopilotKitCore,global.React,global.CopilotKitMarkdownReact,global.CopilotKitMarkdown,global.ReactJsxRuntime,global.RadixReactTooltip,global.RadixReactDropdownMenu,global.CopilotKitShared,global._copilotkit_web_inspector_mount,global.CopilotKitMcpAppsRendererActivity,global.CopilotKitA2UIRenderer,global._copilotkit_a2ui_renderer_engine_core,global.Zod,global._a2ui_web_core_v0_9,global._copilotkit_a2ui_renderer_catalog_schema,global._copilotkit_core_styles,global._radix_ui_react_popover,global.ReactDOM,global._tanstack_react_virtual,global.useStickToBottom,global._copilotkit_web_components_threads_drawer));
7
- })(this, function(exports, _copilotkit_core, react, _copilotkit_markdown_react, _copilotkit_markdown, react_jsx_runtime, _radix_ui_react_tooltip, _radix_ui_react_dropdown_menu, _copilotkit_shared, _copilotkit_web_inspector_mount, _copilotkit_mcp_apps_renderer_activity, _copilotkit_a2ui_renderer, _copilotkit_a2ui_renderer_engine_core, zod, _a2ui_web_core_v0_9, _copilotkit_a2ui_renderer_catalog_schema, _copilotkit_core_styles, _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('@copilotkit/core'), require('react'), require('@copilotkit/markdown/react'), require('@copilotkit/markdown'), require('react/jsx-runtime'), require('@radix-ui/react-tooltip'), require('@radix-ui/react-dropdown-menu'), require('@copilotkit/shared'), require('@copilotkit/web-inspector/mount'), require('@copilotkit/mcp-apps-renderer/activity'), require('@copilotkit/a2ui-renderer'), require('@copilotkit/a2ui-renderer/engine-core'), require('zod'), require('@copilotkit/core/generative-ui'), require('@copilotkit/shared/generative-ui'), require('@copilotkit/a2ui-renderer/catalog-schema'), require('@copilotkit/core/styles'), 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', '@copilotkit/core', 'react', '@copilotkit/markdown/react', '@copilotkit/markdown', 'react/jsx-runtime', '@radix-ui/react-tooltip', '@radix-ui/react-dropdown-menu', '@copilotkit/shared', '@copilotkit/web-inspector/mount', '@copilotkit/mcp-apps-renderer/activity', '@copilotkit/a2ui-renderer', '@copilotkit/a2ui-renderer/engine-core', 'zod', '@copilotkit/core/generative-ui', '@copilotkit/shared/generative-ui', '@copilotkit/a2ui-renderer/catalog-schema', '@copilotkit/core/styles', '@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.CopilotKitReactCore = {}), global.CopilotKitCore,global.React,global.CopilotKitMarkdownReact,global.CopilotKitMarkdown,global.ReactJsxRuntime,global.RadixReactTooltip,global.RadixReactDropdownMenu,global.CopilotKitShared,global._copilotkit_web_inspector_mount,global.CopilotKitMcpAppsRendererActivity,global.CopilotKitA2UIRenderer,global._copilotkit_a2ui_renderer_engine_core,global.Zod,global._copilotkit_core_generative_ui,global._copilotkit_shared_generative_ui,global._copilotkit_a2ui_renderer_catalog_schema,global._copilotkit_core_styles,global._radix_ui_react_popover,global.ReactDOM,global._tanstack_react_virtual,global.useStickToBottom,global._copilotkit_web_components_threads_drawer));
7
+ })(this, function(exports, _copilotkit_core, react, _copilotkit_markdown_react, _copilotkit_markdown, react_jsx_runtime, _radix_ui_react_tooltip, _radix_ui_react_dropdown_menu, _copilotkit_shared, _copilotkit_web_inspector_mount, _copilotkit_mcp_apps_renderer_activity, _copilotkit_a2ui_renderer, _copilotkit_a2ui_renderer_engine_core, zod, _copilotkit_core_generative_ui, _copilotkit_shared_generative_ui, _copilotkit_a2ui_renderer_catalog_schema, _copilotkit_core_styles, _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;
@@ -1358,7 +1358,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
1358
1358
 
1359
1359
  //#endregion
1360
1360
  //#region package.json
1361
- var version$1 = "2.0.0-rc.31";
1361
+ var version$1 = "2.0.0-rc.32";
1362
1362
 
1363
1363
  //#endregion
1364
1364
  //#region src/components/CopilotKitInspector.tsx
@@ -2019,3037 +2019,90 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
2019
2019
  }
2020
2020
 
2021
2021
  //#endregion
2022
- //#region src/generative-ui/action-message.ts
2023
- /** Context keys that supply the message's first line, in priority order. */
2024
- const TEXT_KEYS = ["message", "label"];
2025
- function isNonEmptyString(value) {
2026
- return typeof value === "string" && value.trim().length > 0;
2027
- }
2028
- /** `choose_plan`, `choose-plan` and `choosePlan` all become "Choose plan". */
2029
- function humanize(name) {
2030
- const spaced = name.replace(/[_-]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").trim();
2031
- return spaced.charAt(0).toUpperCase() + spaced.slice(1).toLowerCase();
2032
- }
2033
- function formatContextValue(value) {
2034
- return typeof value === "object" ? JSON.stringify(value) : String(value);
2035
- }
2036
- /**
2037
- * Turns a user event that no function handles into the text of a visible
2038
- * user message.
2039
- *
2040
- * The first line is, in order: `userMessage`, `context.message`,
2041
- * `context.label`, the label of the source component (from `resolveLabel`),
2042
- * or the event name made readable (`choose_plan` becomes "Choose plan").
2043
- * Each other context field follows as one `key: value` line. Objects are
2044
- * written as JSON. `null` and `undefined` fields are skipped.
2045
- *
2046
- * @param event - The user event, as sent by a surface.
2047
- * @param resolveLabel - Finds the visible label of a component by id. Build
2048
- * one with {@link createComponentLabelResolver}.
2049
- *
2050
- * @example
2051
- * ```ts
2052
- * buildActionMessageText({
2053
- * name: "choose_plan",
2054
- * surfaceId: "plans",
2055
- * componentId: "team-button",
2056
- * userMessage: "I pick the Team plan",
2057
- * context: { seats: 12 },
2058
- * });
2059
- * // "I pick the Team plan\n\nseats: 12"
2060
- * ```
2061
- */
2062
- function buildActionMessageText(event, resolveLabel) {
2063
- const { context, userMessage } = event;
2064
- const explicit = [userMessage, ...TEXT_KEYS.map((key) => context[key])].find(isNonEmptyString);
2065
- const resolved = explicit ? void 0 : resolveLabel?.(event.componentId);
2066
- const head = explicit ?? (isNonEmptyString(resolved) ? resolved.trim() : humanize(event.name));
2067
- const lines = Object.entries(context).filter(([key, value]) => !TEXT_KEYS.includes(key) && value !== void 0 && value !== null).map(([key, value]) => `${key}: ${formatContextValue(value)}`);
2068
- return lines.length > 0 ? `${head}\n\n${lines.join("\n")}` : head;
2069
- }
2070
- function ownText(component) {
2071
- if (!component) return void 0;
2072
- if (isNonEmptyString(component.label)) return component.label;
2073
- if (isNonEmptyString(component.text)) return component.text;
2074
- }
2075
- function childIds(component) {
2076
- const { child, children } = component;
2077
- const single = typeof child === "string" ? [child] : [];
2078
- const multiple = Array.isArray(children) ? children.filter((id) => typeof id === "string") : [];
2079
- return [...single, ...multiple];
2080
- }
2081
- /** The components that an operation adds, inline or in an update. */
2082
- function componentsOf(operation) {
2083
- if ("createSurface" in operation) return operation.createSurface.components ?? [];
2084
- if ("updateComponents" in operation) return operation.updateComponents.components;
2085
- return [];
2086
- }
2087
- /**
2088
- * Builds a function that finds the visible label of a component on a surface.
2089
- *
2090
- * The label is the component's own string `label`, else its string `text`,
2091
- * else the first `child` or `children` component that has a string `label`
2092
- * or `text`. When a component id is defined more than once, the last
2093
- * definition wins, as in the renderer.
2094
- *
2095
- * @param operations - The committed operations of the surface.
2096
- *
2097
- * @example
2098
- * ```ts
2099
- * const resolveLabel = createComponentLabelResolver(surface.operations);
2100
- * buildActionMessageText(event, resolveLabel);
2101
- * ```
2102
- */
2103
- function createComponentLabelResolver(operations) {
2104
- const byId = /* @__PURE__ */ new Map();
2105
- for (const operation of operations) {
2106
- const components = componentsOf(operation);
2107
- for (const component of components) byId.set(component.id, component);
2108
- }
2109
- return (componentId) => {
2110
- const component = byId.get(componentId);
2111
- if (!component) return void 0;
2112
- const own = ownText(component);
2113
- if (own) return own;
2114
- const ids = childIds(component);
2115
- for (const id of ids) {
2116
- const text = ownText(byId.get(id));
2117
- if (text) return text;
2118
- }
2119
- };
2120
- }
2121
-
2122
- //#endregion
2123
- //#region src/generative-ui/json-schema.ts
2124
- /**
2125
- * JSON Schema for a Standard Schema, without `$schema`. A prop marked by `child()` or `childList()`
2126
- * becomes an A2UI `$ref` to `ComponentId` or `ChildList`.
2127
- */
2128
- function toJsonSchema(schema) {
2129
- const { $schema: _omit, ...rest } = (0, _copilotkit_shared.schemaToJsonSchema)(schema);
2130
- return (0, _copilotkit_shared.applyChildRefMarks)(rest);
2131
- }
2132
-
2133
- //#endregion
2134
- //#region src/generative-ui/catalog.ts
2135
- /** The A2UI component envelope: `id`, `component`, `catalogId`, `accessibility`, `metadata`. */
2136
- const RESERVED_KEYS = new Set([
2137
- "id",
2138
- "component",
2139
- ..._copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS
2140
- ]);
2141
- /** The id of the catalog that declared each component, for the inspector. */
2142
- const componentCatalogs = /* @__PURE__ */ new WeakMap();
2143
- /**
2144
- * The id of the catalog that declared each component of `ui`. A component
2145
- * from `extends` keeps the id of its base. Not exported from the package.
2146
- */
2147
- function componentCatalogIds(ui) {
2148
- return componentCatalogs.get(ui) ?? /* @__PURE__ */ new Map();
2149
- }
2150
- /**
2151
- * The catalogs that an operation can name: the id of `ui`, then the ids of
2152
- * the catalogs in its `extends` that declared a component. Not exported
2153
- * from the package.
2154
- */
2155
- function catalogIdsOf(ui) {
2156
- const declared = componentCatalogs.get(ui)?.values() ?? [];
2157
- return [...new Set([ui.id, ...declared])];
2158
- }
2159
- /** The setter prop of a writable prop: `value` gives `setValue`. */
2160
- function setterNameOf(key) {
2161
- return `set${key.charAt(0).toUpperCase()}${key.slice(1)}`;
2162
- }
2163
-
2164
- //#endregion
2165
- //#region src/generative-ui/manifest.ts
2166
- /**
2167
- * The built-in functions (the A2UI basic catalog plus calc and series) as
2168
- * manifest entries. Their args are described by the short signature, not
2169
- * by a full JSON Schema: the renderer checks them when they run. An app
2170
- * function of the same name replaces the entry.
2171
- */
2172
- function builtInFunctionManifests() {
2173
- return Object.fromEntries(Object.entries(_copilotkit_shared.GENERATIVE_UI_FUNCTIONS).map(([name, fn]) => [name, {
2174
- description: fn.description,
2175
- parameters: {
2176
- type: "object",
2177
- description: fn.parameters
2178
- },
2179
- returnType: fn.returnType,
2180
- allowedCallers: fn.allowedCallers,
2181
- ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
2182
- }]));
2183
- }
2184
- /**
2185
- * The manifest of a catalog, with no React runtime: the components of `ui`,
2186
- * the built-in functions (minus the names the app declares) and
2187
- * `options.functions`, the chat target and `options.targets`, and
2188
- * `options.surfaces`. `buildGenerativeUIManifest` builds the per-run
2189
- * manifest with it; tools that run outside React use it directly.
2190
- *
2191
- * @example
2192
- * ```ts
2193
- * const manifest = buildCatalogManifest(standardUI);
2194
- * manifest.targets; // [{ id: "chat", kind: "chat" }]
2195
- * ```
2196
- */
2197
- function buildCatalogManifest(ui, options = {}) {
2198
- return {
2199
- catalogId: ui.id,
2200
- catalogIds: catalogIdsOf(ui),
2201
- components: (0, _copilotkit_shared.applyDescriptionOverrides)({ components: ui.manifestComponents }, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().descriptions).manifest.components,
2202
- functions: {
2203
- ...Object.fromEntries(Object.entries(builtInFunctionManifests()).filter(([name]) => !ui.functions.has(name))),
2204
- ...options.functions
2205
- },
2206
- targets: [{
2207
- id: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
2208
- kind: "chat"
2209
- }, ...options.targets ?? []],
2210
- surfaces: options.surfaces ?? {}
2211
- };
2212
- }
2213
- /**
2214
- * Builds the per-run manifest. Never contains handlers or renderers.
2215
- *
2216
- * - `functions`: the built-in functions, then the declared functions with
2217
- * exactly one mounted handler.
2218
- * - `targets`: the chat first, then each mounted `<GenerativeUISurface>`,
2219
- * with its `description` and its `components` when it has them.
2220
- */
2221
- function buildGenerativeUIManifest(runtime, threadId) {
2222
- const { ui, manager, dispatcher } = runtime;
2223
- const inlineTargets = manager.getMountedTargets().filter((target) => target.id !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET).map(({ id, ...rest }) => ({
2224
- id,
2225
- kind: "inline",
2226
- ...rest
2227
- }));
2228
- return buildCatalogManifest(ui, {
2229
- functions: dispatcher.listExposed(),
2230
- targets: inlineTargets,
2231
- surfaces: threadId ? manager.describeSurfaces(threadId) : {}
2232
- });
2233
- }
2234
- /**
2235
- * Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
2236
- * from the per-run manifest. It has the A2UI v1.0 renderer capabilities
2237
- * shape: one inline catalog with the id of the UI, and the CopilotKit data
2238
- * in `metadata.extensions`.
2239
- *
2240
- * The inline catalog has no `components` only for the markdown transport
2241
- * with `includeCatalog: false`. It has `instructions` for the markdown
2242
- * transport, or when given.
2243
- *
2244
- * @param runtime - The generative UI runtime of the provider.
2245
- * @param threadId - The thread of the run. Its surfaces go in `copilotkit_surfaces`.
2246
- * @param options - The transport and what to send.
2247
- *
2248
- * @example
2249
- * ```ts
2250
- * const envelope = buildGenerativeUIEnvelope(runtime, agent.threadId, {
2251
- * transport: "tool",
2252
- * includeCatalog: true,
2253
- * contextSent: false,
2254
- * });
2255
- * envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
2256
- * ```
2257
- */
2258
- function buildGenerativeUIEnvelope(runtime, threadId, options) {
2259
- const { transport, includeCatalog, contextSent, action } = options;
2260
- const manifest = buildGenerativeUIManifest(runtime, threadId);
2261
- const instructions = options.instructions ?? (transport === "markdown" ? (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest)) : void 0);
2262
- const omitComponents = transport === "markdown" && !includeCatalog;
2263
- return {
2264
- "1.0": {
2265
- supportedCatalogIds: manifest.catalogIds ?? [manifest.catalogId],
2266
- inlineCatalogs: [{
2267
- catalogId: manifest.catalogId,
2268
- protocolVersion: "1.0",
2269
- ...omitComponents ? {} : { components: manifest.components },
2270
- functions: manifest.functions,
2271
- ...instructions === void 0 ? {} : { instructions }
2272
- }]
2273
- },
2274
- metadata: { extensions: {
2275
- copilotkit_format: _copilotkit_shared.COPILOTKIT_UI_ENVELOPE_FORMAT,
2276
- copilotkit_transport: transport,
2277
- copilotkit_targets: manifest.targets,
2278
- copilotkit_surfaces: manifest.surfaces,
2279
- copilotkit_contextSent: contextSent,
2280
- ...action === void 0 ? {} : { copilotkit_action: action }
2281
- } }
2282
- };
2283
- }
2284
-
2285
- //#endregion
2286
- //#region src/generative-ui/debug-source.ts
2287
- /**
2288
- * What a run of `threadId` sends: its envelope, and the text that goes into
2289
- * the prompt of the model because of it.
2290
- *
2291
- * - Tool transport: the runtime adds the `render_ui` guide. It builds it
2292
- * from the envelope with `buildGenerativeUIPrompt`, as done here.
2293
- * - Markdown transport: the provider sends the guideline and the compact
2294
- * schema as context entries. With `sendContext: false`, the backend builds
2295
- * its own prompt, usually from the `instructions` of the envelope.
2296
- */
2297
- function describeGenerativeUIRun(runtime, threadId, options) {
2298
- const envelope = buildGenerativeUIEnvelope(runtime, threadId, options);
2299
- if (options.transport === "tool") return {
2300
- envelope,
2301
- prompt: [{
2302
- title: "render_ui guide",
2303
- source: "runtime",
2304
- text: (0, _copilotkit_shared.buildGenerativeUIPrompt)((0, _copilotkit_shared.envelopeToManifest)(envelope))
2305
- }]
2306
- };
2307
- const manifest = buildGenerativeUIManifest(runtime, threadId);
2308
- if (!options.contextSent) return {
2309
- envelope,
2310
- prompt: [{
2311
- title: "Envelope instructions",
2312
- source: "backend",
2313
- text: (0, _copilotkit_shared.envelopeToManifest)(envelope).instructions ?? ""
2314
- }]
2315
- };
2316
- const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
2317
- const schema = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
2318
- return {
2319
- envelope,
2320
- prompt: [{
2321
- title: "Markdown guideline",
2322
- source: "context",
2323
- text: guideline
2324
- }, {
2325
- title: "Component schema",
2326
- source: "context",
2327
- text: schema
2328
- }]
2329
- };
2330
- }
2331
- /** The declared functions, with the JSON Schema of their parameters. */
2332
- function debugFunctions(runtime) {
2333
- const functions = {};
2334
- for (const [name, declared] of runtime.ui.functions) {
2335
- let parameters = {};
2336
- try {
2337
- parameters = toJsonSchema(declared.parameters);
2338
- } catch {}
2339
- functions[name] = {
2340
- ...declared.description ? { description: declared.description } : {},
2341
- parameters,
2342
- handlers: runtime.dispatcher.handlerCount(name)
2343
- };
2344
- }
2345
- return functions;
2346
- }
2347
- /**
2348
- * The debug source that the provider gives core for the inspector. It builds
2349
- * a snapshot only when the inspector reads one.
2350
- *
2351
- * @param runtime - The generative UI parts of the provider.
2352
- * @param getOptions - The envelope options and agent ids of the current config.
2353
- * @returns The source, and `recordRun` for each run start.
2354
- */
2355
- function createGenerativeUIDebugSource(runtime, getOptions) {
2356
- const listeners = /* @__PURE__ */ new Set();
2357
- let lastRun;
2358
- const notify = () => {
2359
- for (const listener of [...listeners]) listener();
2360
- };
2361
- return {
2362
- source: {
2363
- getSnapshot() {
2364
- const { options, agentIds } = getOptions();
2365
- const threadId = runtime.manager.getActiveThread();
2366
- const manifest = buildGenerativeUIManifest(runtime, threadId);
2367
- return {
2368
- catalogId: runtime.ui.id,
2369
- transport: options.transport,
2370
- ...agentIds ? { agentIds } : {},
2371
- components: runtime.ui.manifestComponents,
2372
- componentCatalogs: Object.fromEntries(componentCatalogIds(runtime.ui)),
2373
- functions: debugFunctions(runtime),
2374
- state: { ...runtime.manager.getState() },
2375
- targets: manifest.targets,
2376
- activeThreadId: threadId,
2377
- surfaces: runtime.manager.debugSurfaces(),
2378
- lastRun,
2379
- nextRun: {
2380
- agentId: void 0,
2381
- threadId,
2382
- ...describeGenerativeUIRun(runtime, threadId, options)
2383
- }
2384
- };
2385
- },
2386
- subscribe(listener) {
2387
- listeners.add(listener);
2388
- const unsubscribe = runtime.manager.subscribe(listener);
2389
- return () => {
2390
- listeners.delete(listener);
2391
- unsubscribe();
2392
- };
2393
- }
2394
- },
2395
- recordRun(run) {
2396
- lastRun = run;
2397
- notify();
2398
- }
2399
- };
2400
- }
2401
-
2402
- //#endregion
2403
- //#region src/generative-ui/errors.ts
2404
- var GenerativeUIError = class extends Error {
2405
- constructor(code, message) {
2406
- super(message);
2407
- _defineProperty(this, "code", void 0);
2408
- this.name = "GenerativeUIError";
2409
- this.code = code;
2410
- }
2411
- };
2412
-
2413
- //#endregion
2414
- //#region src/generative-ui/functions.ts
2415
- /**
2416
- * The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes
2417
- * resolved args (no bindings left in them) and gives a plain value. They
2418
- * run synchronously, so a prop bound to one updates in the same render as
2419
- * the data it reads. The signatures the model sees are in
2420
- * `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).
2421
- */
2422
- /** Thrown for a bad call: an unknown function, bad args, or a bad value. */
2423
- var ExpressionError = class extends Error {
2424
- constructor(message) {
2425
- super(message);
2426
- this.name = "ExpressionError";
2427
- }
2428
- };
2429
- /** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */
2430
- function truthOf(value) {
2431
- if ((0, _copilotkit_shared.isValidationResult)(value)) return value.valid;
2432
- return Boolean(value);
2433
- }
2434
- const valid = () => ({ valid: true });
2435
- /** A failed result. `code` names the failure, the same for every locale. */
2436
- const invalid = (message, code) => ({
2437
- valid: false,
2438
- message,
2439
- code
2440
- });
2441
- function text(value) {
2442
- if (value === void 0 || value === null) return "";
2443
- return typeof value === "string" ? value : String(value);
2444
- }
2445
- function numberOf$1(value) {
2446
- if (typeof value === "number") return value;
2447
- if (typeof value === "string" && value.trim() !== "") return Number(value);
2448
- return NaN;
2449
- }
2450
- function optionalNumber(value, name) {
2451
- if (value === void 0 || value === null) return void 0;
2452
- const parsed = numberOf$1(value);
2453
- if (Number.isNaN(parsed)) throw new ExpressionError(`${name} must be a number`);
2454
- return parsed;
2455
- }
2456
- const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
2457
- /** The locale of the user. `undefined` lets Intl pick the default. */
2458
- function locale() {
2459
- return typeof navigator !== "undefined" ? navigator.language : void 0;
2460
- }
2461
- function numberFormat(args, options) {
2462
- const decimals = optionalNumber(args.decimals, "decimals");
2463
- return new Intl.NumberFormat(locale(), {
2464
- ...options,
2465
- useGrouping: args.grouping !== false,
2466
- ...decimals === void 0 ? {} : {
2467
- minimumFractionDigits: decimals,
2468
- maximumFractionDigits: decimals
2469
- }
2470
- });
2471
- }
2472
- /** A date from an ISO string, a timestamp, or a Date. */
2473
- function dateOf(value) {
2474
- 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;
2475
- if (date === void 0 || Number.isNaN(date.getTime())) throw new ExpressionError("value must be a date");
2476
- return date;
2477
- }
2478
- const pad = (value, width) => String(value).padStart(width, "0");
2479
- /**
2480
- * A TR35 field is a run of one letter ("EEE" is one abbreviated weekday,
2481
- * not three), and text in single quotes is literal. Letters that are not
2482
- * fields stay as they are.
2483
- */
2484
- const DATE_FIELD = /([A-Za-z])\1*|'(?:[^']|'')*'/g;
2485
- function formatDatePattern(date, pattern) {
2486
- const parts = (options) => new Intl.DateTimeFormat(locale(), options).format(date);
2487
- const hours12 = date.getHours() % 12 || 12;
2488
- const numeric = (value, width) => width >= 2 ? pad(value, 2) : String(value);
2489
- return pattern.replace(DATE_FIELD, (token) => {
2490
- if (token.startsWith("'")) return token.slice(1, -1).replace(/''/g, "'");
2491
- const width = token.length;
2492
- switch (token[0]) {
2493
- case "y": return width === 2 ? pad(date.getFullYear() % 100, 2) : String(date.getFullYear());
2494
- case "M":
2495
- if (width >= 4) return parts({ month: "long" });
2496
- if (width === 3) return parts({ month: "short" });
2497
- return numeric(date.getMonth() + 1, width);
2498
- case "d": return numeric(date.getDate(), width);
2499
- case "E": return parts({ weekday: width >= 4 ? "long" : "short" });
2500
- case "H": return numeric(date.getHours(), width);
2501
- case "h": return numeric(hours12, width);
2502
- case "m": return pad(date.getMinutes(), 2);
2503
- case "s": return pad(date.getSeconds(), 2);
2504
- case "a": return date.getHours() < 12 ? "AM" : "PM";
2505
- case void 0:
2506
- default: return token;
2507
- }
2508
- });
2509
- }
2510
- /** Opens an http(s) URL in a new tab. Any other scheme is refused. */
2511
- function openUrlSafely(url) {
2512
- if (typeof url !== "string" || url === "") throw new ExpressionError("url must be a string");
2513
- if (typeof window === "undefined") return;
2514
- let parsed;
2515
- try {
2516
- parsed = new URL(url, window.location.href);
2517
- } catch {
2518
- throw new ExpressionError(`"${url}" is not a URL`);
2519
- }
2520
- if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new ExpressionError(`openUrl takes only http(s) URLs, not ${parsed.protocol}`);
2521
- window.open(parsed.href, "_blank", "noopener,noreferrer");
2522
- }
2523
- /**
2524
- * The basic functions, except `formatString`, which needs the resolver.
2525
- * `calc` and `series` are added by `resolve.ts`, which imports both.
2526
- */
2527
- const BASIC_FUNCTIONS = {
2528
- required: ({ value }) => {
2529
- return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0 ? invalid("Required", "required") : valid();
2530
- },
2531
- regex: ({ value, pattern }) => {
2532
- if (typeof pattern !== "string") throw new ExpressionError("pattern must be a string");
2533
- let expression;
2534
- try {
2535
- expression = new RegExp(pattern, "u");
2536
- } catch {
2537
- throw new ExpressionError(`"${pattern}" is not a regular expression`);
2538
- }
2539
- return expression.test(text(value)) ? valid() : invalid("Invalid format", "pattern");
2540
- },
2541
- length: ({ value, min, max }) => {
2542
- const size = text(value).length;
2543
- const low = optionalNumber(min, "min");
2544
- const high = optionalNumber(max, "max");
2545
- if (low !== void 0 && size < low) return invalid(`At least ${low} characters`, "tooShort");
2546
- if (high !== void 0 && size > high) return invalid(`At most ${high} characters`, "tooLong");
2547
- return valid();
2548
- },
2549
- numeric: ({ value, min, max }) => {
2550
- const parsed = numberOf$1(value);
2551
- if (Number.isNaN(parsed)) return invalid("Must be a number", "notANumber");
2552
- const low = optionalNumber(min, "min");
2553
- const high = optionalNumber(max, "max");
2554
- if (low !== void 0 && parsed < low) return invalid(`At least ${low}`, "tooSmall");
2555
- if (high !== void 0 && parsed > high) return invalid(`At most ${high}`, "tooLarge");
2556
- return valid();
2557
- },
2558
- email: ({ value }) => EMAIL.test(text(value)) ? valid() : invalid("Invalid email address", "email"),
2559
- formatNumber: (args) => {
2560
- const parsed = numberOf$1(args.value);
2561
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
2562
- return numberFormat(args, {}).format(parsed);
2563
- },
2564
- formatCurrency: (args) => {
2565
- const parsed = numberOf$1(args.value);
2566
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
2567
- if (typeof args.currency !== "string" || args.currency === "") throw new ExpressionError("currency must be an ISO 4217 code");
2568
- try {
2569
- return numberFormat(args, {
2570
- style: "currency",
2571
- currency: args.currency
2572
- }).format(parsed);
2573
- } catch {
2574
- throw new ExpressionError(`"${args.currency}" is not a currency code`);
2575
- }
2576
- },
2577
- formatDate: ({ value, format }) => {
2578
- if (typeof format !== "string") throw new ExpressionError("format must be a string");
2579
- return formatDatePattern(dateOf(value), format);
2580
- },
2581
- pluralize: (args) => {
2582
- const parsed = numberOf$1(args.value);
2583
- if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
2584
- const category = new Intl.PluralRules(locale()).select(parsed);
2585
- return text((parsed === 0 ? args.zero : void 0) ?? args[category] ?? args.other);
2586
- },
2587
- and: ({ values }) => {
2588
- if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
2589
- return values.every(truthOf);
2590
- },
2591
- or: ({ values }) => {
2592
- if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
2593
- return values.some(truthOf);
2594
- },
2595
- not: ({ value }) => !truthOf(value),
2596
- openUrl: ({ url }) => {
2597
- openUrlSafely(url);
2598
- }
2599
- };
2600
- /** True when the basic function `name` must run from a user gesture. */
2601
- function requiresUserActivation(name) {
2602
- return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.requiresUserActivation === true;
2603
- }
2604
- /** True when a basic function gives a ValidationResult. */
2605
- function givesValidationResult(name) {
2606
- return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.returnType === "validationResult";
2607
- }
2608
-
2609
- //#endregion
2610
- //#region src/generative-ui/dispatcher.ts
2611
- const messageOf = (error) => error instanceof Error ? error.message : String(error);
2612
- /**
2613
- * Creates the registry of functions that generated UI may call.
2614
- *
2615
- * A function is callable when it is declared in `getDeclared()` and exactly
2616
- * one handler is mounted for it with `register`. Names are resolved at call
2617
- * time and fail closed. Nothing is sent to the agent.
2618
- * Neither `invoke` nor `listExposed` throws.
2619
- *
2620
- * @param options.getDeclared - Returns the declared functions.
2621
- * @param options.onError - Gets each failed call.
2622
- *
2623
- * @example
2624
- * ```ts
2625
- * const dispatcher = createGenerativeUIDispatcher({
2626
- * getDeclared: () => new Map(Object.entries(ui.functions)),
2627
- * });
2628
- * const unregister = dispatcher.register("addToCart", handlerRef);
2629
- * await dispatcher.invoke("addToCart", { productId: "p1" }, origin);
2630
- * unregister();
2631
- * ```
2632
- */
2633
- /**
2634
- * True while the browser counts the current task as user-activated (a
2635
- * click, a key press). Where the API is missing (older browsers, test
2636
- * environments), the gesture is assumed.
2637
- */
2638
- function hasUserActivation() {
2639
- if (typeof navigator === "undefined") return true;
2640
- const activation = navigator.userActivation;
2641
- return activation === void 0 || activation.isActive;
2642
- }
2643
- /**
2644
- * The permissions of a declared function as the manifest states them: the
2645
- * callers always written out, so a reader needs no default.
2646
- */
2647
- function permissionsOf(fn) {
2648
- const callers = (0, _copilotkit_shared.functionCallers)(fn);
2649
- return {
2650
- allowedCallers: callers.renderer && callers.agent ? "rendererOrAgent" : callers.agent ? "agentOnly" : "rendererOnly",
2651
- ...fn.requiresUserActivation ? { requiresUserActivation: true } : {}
2652
- };
2653
- }
2654
- function createGenerativeUIDispatcher(options) {
2655
- const handlers = /* @__PURE__ */ new Map();
2656
- const resolveUnchecked = (name) => {
2657
- const declared = options.getDeclared().get(name);
2658
- if (!declared) return {
2659
- ok: false,
2660
- error: new GenerativeUIError("function_not_found", `No generative UI function named "${name}" is declared in createGenerativeUI({ functions })`)
2661
- };
2662
- const mounted = [...handlers.get(name) ?? []];
2663
- const [ref] = mounted;
2664
- if (!ref) return {
2665
- ok: false,
2666
- error: new GenerativeUIError("function_not_found", `"${name}" is declared, but no useGenerativeUIFunction handler is mounted for it`)
2667
- };
2668
- if (mounted.length > 1) return {
2669
- ok: false,
2670
- error: new GenerativeUIError("function_conflict", `"${name}" has ${mounted.length} useGenerativeUIFunction handlers mounted. Mount exactly one.`)
2671
- };
2672
- return {
2673
- ok: true,
2674
- declared,
2675
- ref
2676
- };
2677
- };
2678
- const isDeclared = (name) => {
2679
- try {
2680
- return options.getDeclared().has(name);
2681
- } catch {
2682
- return false;
2683
- }
2684
- };
2685
- const resolve = (name) => {
2686
- try {
2687
- return resolveUnchecked(name);
2688
- } catch (error) {
2689
- return {
2690
- ok: false,
2691
- error: new GenerativeUIError("handler_failed", `"${name}" could not be resolved: ${messageOf(error)}`)
2692
- };
2693
- }
2694
- };
2695
- const validateArgs = async (name, schema, args) => {
2696
- try {
2697
- const validation = await schema["~standard"].validate(args);
2698
- if (!validation.issues) return {
2699
- ok: true,
2700
- value: validation.value
2701
- };
2702
- return {
2703
- ok: false,
2704
- 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("; ")}`)
2705
- };
2706
- } catch (error) {
2707
- return {
2708
- ok: false,
2709
- error: new GenerativeUIError("invalid_arguments", `Invalid arguments for "${name}": ${messageOf(error)}`)
2710
- };
2711
- }
2712
- };
2713
- const failWith = (name, origin, error) => {
2714
- try {
2715
- options.onError?.({
2716
- name,
2717
- origin,
2718
- error
2719
- });
2720
- } catch {}
2721
- return {
2722
- ok: false,
2723
- error
2724
- };
2725
- };
2726
- /**
2727
- * Why `origin` may not call a function with these permissions now, as an
2728
- * error, or `undefined` when it may. The agent is refused what is for the
2729
- * renderer; a component is refused what is for the agent, and a gesture
2730
- * function when the browser counts no user activation.
2731
- */
2732
- const callerError = (name, fn, origin) => {
2733
- const isComponent = "componentId" in origin;
2734
- if (!isComponent && !_copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS) return new GenerativeUIError("invalid_function_call", _copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
2735
- const problem = (0, _copilotkit_shared.callerProblem)(name, fn, isComponent ? "renderer" : "agent");
2736
- if (problem !== void 0) return new GenerativeUIError("invalid_function_call", problem);
2737
- if (isComponent && fn.requiresUserActivation && !hasUserActivation()) return new GenerativeUIError("invalid_function_call", `function "${name}" runs only from a user gesture; this event was not one`);
2738
- };
2739
- /**
2740
- * Runs a basic function of the A2UI catalog. They are value functions of
2741
- * the renderer: the agent cannot call them, and one that needs a user
2742
- * gesture runs only from an event binding.
2743
- */
2744
- const invokeBasic = (name, args, origin) => {
2745
- const info = _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name];
2746
- const run = BASIC_FUNCTIONS[name];
2747
- if (info === void 0 || run === void 0) throw new Error(`"${name}" is not a basic function`);
2748
- const refused = callerError(name, info, origin);
2749
- if (refused) return failWith(name, origin, refused);
2750
- 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`));
2751
- try {
2752
- return {
2753
- ok: true,
2754
- result: run(args ?? {})
2755
- };
2756
- } catch (error) {
2757
- return failWith(name, origin, new GenerativeUIError(error instanceof ExpressionError ? "invalid_arguments" : "handler_failed", `"${name}" failed: ${messageOf(error)}`));
2758
- }
2759
- };
2760
- return {
2761
- async invoke(name, args, origin) {
2762
- const resolved = resolve(name);
2763
- if (!resolved.ok && resolved.error.code === "function_not_found" && !isDeclared(name) && Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name)) return invokeBasic(name, args, origin);
2764
- if (!resolved.ok) return failWith(name, origin, resolved.error);
2765
- const refused = callerError(name, resolved.declared, origin);
2766
- if (refused) return failWith(name, origin, refused);
2767
- const validated = await validateArgs(name, resolved.declared.parameters, args ?? {});
2768
- if (!validated.ok) return failWith(name, origin, validated.error);
2769
- try {
2770
- return {
2771
- ok: true,
2772
- result: await resolved.ref.current(validated.value)
2773
- };
2774
- } catch (error) {
2775
- return failWith(name, origin, new GenerativeUIError("handler_failed", `"${name}" failed: ${messageOf(error)}`));
2776
- }
2777
- },
2778
- listExposed() {
2779
- let names;
2780
- try {
2781
- names = [...options.getDeclared().keys()];
2782
- } catch {
2783
- return {};
2784
- }
2785
- const listed = {};
2786
- for (const name of names) {
2787
- const resolved = resolve(name);
2788
- if (!resolved.ok) continue;
2789
- if (!(0, _copilotkit_shared.functionCallers)(resolved.declared).renderer && !_copilotkit_shared.GENERATIVE_UI_AGENT_FUNCTION_CALLS) continue;
2790
- const { description, parameters, returnType } = resolved.declared;
2791
- try {
2792
- listed[name] = {
2793
- ...description ? { description } : {},
2794
- parameters: toJsonSchema(parameters),
2795
- ...returnType ? { returnType } : {},
2796
- ...permissionsOf(resolved.declared)
2797
- };
2798
- } catch {}
2799
- }
2800
- return listed;
2801
- },
2802
- register(name, ref) {
2803
- const mounted = handlers.get(name) ?? /* @__PURE__ */ new Set();
2804
- mounted.add(ref);
2805
- handlers.set(name, mounted);
2806
- return () => {
2807
- mounted.delete(ref);
2808
- };
2809
- },
2810
- handlerCount: (name) => handlers.get(name)?.size ?? 0
2811
- };
2812
- }
2813
-
2814
- //#endregion
2815
- //#region src/generative-ui/markdown/context.ts
2816
- /**
2817
- * Registers the two context entries of the markdown transport: the compact
2818
- * component schema and the fence guideline. Both go only to `agentIds`.
2819
- *
2820
- * The schema is built again at each run start and when a
2821
- * `<GenerativeUISurface>` mounts, unmounts, or changes its description or
2822
- * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
2823
- *
2824
- * @param copilotkit - The CopilotKit core of the provider.
2825
- * @param runtime - The generative UI runtime parts, or null without one.
2826
- * @param options - `enabled` and `agentIds`.
2827
- *
2828
- * @example
2829
- * ```ts
2830
- * useGenerativeUIMarkdownContext(copilotkit, core, {
2831
- * enabled: config?.transport === "markdown" && config.sendContext !== false,
2832
- * agentIds: config?.agentIds,
2833
- * });
2834
- * ```
2835
- */
2836
- function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
2837
- const { enabled, agentIds } = options;
2838
- const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
2839
- (0, react.useEffect)(() => {
2840
- if (!runtime || !enabled) return;
2841
- const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
2842
- const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
2843
- let guidelineId;
2844
- let guidelineValue;
2845
- let schemaId;
2846
- let schemaValue;
2847
- const refreshSchema = (threadId) => {
2848
- const manifest = buildGenerativeUIManifest(runtime, threadId);
2849
- const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
2850
- if (guideline !== guidelineValue) {
2851
- if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
2852
- guidelineValue = guideline;
2853
- guidelineId = copilotkit.addContext({
2854
- description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
2855
- value: guideline,
2856
- ...scope
2857
- });
2858
- }
2859
- const value = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
2860
- if (value === schemaValue) return;
2861
- if (schemaId !== void 0) copilotkit.removeContext(schemaId);
2862
- schemaValue = value;
2863
- schemaId = copilotkit.addContext({
2864
- description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
2865
- value,
2866
- ...scope
2867
- });
2868
- };
2869
- refreshSchema(runtime.manager.getActiveThread());
2870
- let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
2871
- const unsubscribeManager = runtime.manager.subscribe(() => {
2872
- const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
2873
- if (nextKey === targetsKey) return;
2874
- targetsKey = nextKey;
2875
- refreshSchema(runtime.manager.getActiveThread());
2876
- });
2877
- const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
2878
- return () => {
2879
- subscription.unsubscribe();
2880
- unsubscribeManager();
2881
- if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
2882
- if (schemaId !== void 0) copilotkit.removeContext(schemaId);
2883
- };
2884
- }, [
2885
- copilotkit,
2886
- runtime,
2887
- enabled,
2888
- agentIdsKey
2889
- ]);
2890
- }
2891
-
2892
- //#endregion
2893
- //#region src/generative-ui/is-record.ts
2894
- /** True for a plain object: not null, not an array. Internal, not exported. */
2895
- function isRecord(value) {
2896
- return typeof value === "object" && value !== null && !Array.isArray(value);
2897
- }
2898
-
2899
- //#endregion
2900
- //#region src/generative-ui/markdown/source.ts
2901
- /**
2902
- * Values by key, from the latest build. A value that a build does not use
2903
- * is dropped at the end of that build, so the cache does not grow.
2904
- */
2905
- var BuildMemo = class {
2906
- constructor() {
2907
- _defineProperty(this, "previous", /* @__PURE__ */ new Map());
2908
- _defineProperty(this, "current", /* @__PURE__ */ new Map());
2909
- }
2910
- /**
2911
- * The value of `key`. It is computed when no earlier value is there, or
2912
- * when `isFresh` says that the earlier value is out of date.
2913
- */
2914
- get(key, compute, isFresh = () => true) {
2915
- let value = this.current.get(key) ?? this.previous.get(key);
2916
- if (value === void 0 || !isFresh(value)) value = compute();
2917
- this.current.set(key, value);
2918
- return value;
2919
- }
2920
- endBuild() {
2921
- this.previous = this.current;
2922
- this.current = /* @__PURE__ */ new Map();
2923
- }
2924
- };
2925
- /** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */
2926
- var MarkdownBuildCache = class {
2927
- constructor() {
2928
- _defineProperty(this, "segments", new BuildMemo());
2929
- _defineProperty(this, "fences", new BuildMemo());
2930
- _defineProperty(this, "drafts", new BuildMemo());
2931
- _defineProperty(this, "readdressed", /* @__PURE__ */ new WeakMap());
2932
- }
2933
- endBuild() {
2934
- this.segments.endBuild();
2935
- this.fences.endBuild();
2936
- this.drafts.endBuild();
2937
- }
2938
- };
2939
- /** True when both lists hold the same objects in the same order. */
2940
- function sameItems(a, b) {
2941
- return a.length === b.length && a.every((item, index) => item === b[index]);
2942
- }
2943
- function isString(value) {
2944
- return typeof value === "string";
2945
- }
2946
- /** The key of one fence of one message. */
2947
- function fenceKey(messageId, fenceIndex) {
2948
- return `${messageId}:${fenceIndex}`;
2949
- }
2950
- /**
2951
- * The operations of a fence body. While the fence streams, the last object
2952
- * can be unfinished. Of an unfinished updateComponents or createSurface, the
2953
- * components that are complete render at once (a createSurface also keeps
2954
- * its data model when all of it arrived). Any other unfinished object is
2955
- * left out, because a part of a data model value can still change. A final
2956
- * fence keeps what can be saved from an unfinished object.
2957
- */
2958
- function fenceOperations(text, isStreaming) {
2959
- const parsed = (0, _copilotkit_core.extractFenceOperations)(text);
2960
- if (!isStreaming || parsed.partialObject === null) return parsed.operations;
2961
- const complete = (0, _copilotkit_core.extractFenceOperations)(text.slice(0, text.length - parsed.partialObject.length)).operations;
2962
- const partial = parsed.operations.length > complete.length ? parsed.operations[parsed.operations.length - 1] : void 0;
2963
- return partial !== void 0 && (isRecord(partial.updateComponents) || isRecord(partial.createSurface)) ? [...complete, partial] : complete;
2964
- }
2965
- /**
2966
- * An inline createSurface becomes a createSurface with only its surfaceId
2967
- * and catalog, then an updateDataModel for its data model, then an
2968
- * updateComponents for its components. The prose lift and the split per
2969
- * component read only updateComponents, so they then work for an inline
2970
- * surface too. A createSurface with a data model or components of a wrong
2971
- * shape does not change, so that validation rejects it with the reason.
2972
- */
2973
- function expandInlineCreate(operations) {
2974
- return operations.flatMap((op) => {
2975
- const create = op.createSurface;
2976
- if (!isRecord(create)) return [op];
2977
- const { dataModel, components, ...rest } = create;
2978
- const hasData = isRecord(dataModel);
2979
- const hasComponents = Array.isArray(components) && components.length > 0;
2980
- if (!((dataModel === void 0 || hasData) && (components === void 0 || hasComponents)) || !hasData && !hasComponents) return [op];
2981
- const { surfaceId } = create;
2982
- const expanded = [{
2983
- ...op,
2984
- createSurface: rest
2985
- }];
2986
- if (hasData) expanded.push({
2987
- version: op.version,
2988
- updateDataModel: {
2989
- surfaceId,
2990
- path: "/",
2991
- value: dataModel
2992
- }
2993
- });
2994
- if (hasComponents) expanded.push({
2995
- version: op.version,
2996
- updateComponents: {
2997
- surfaceId,
2998
- components
2999
- }
3000
- });
3001
- return expanded;
3002
- });
3003
- }
3004
- /**
3005
- * Each updateComponents becomes one operation per component, in order. The
3006
- * complete components of a streaming line then give the same first
3007
- * operations as the finished line, so the operation list only grows and the
3008
- * manager never has to start the surface again.
3009
- */
3010
- function splitComponentUpdates(operations) {
3011
- return operations.flatMap((op) => {
3012
- const update = op.updateComponents;
3013
- if (!isRecord(update) || !Array.isArray(update.components)) return [op];
3014
- if (update.components.length <= 1) return [op];
3015
- return update.components.map((component) => ({
3016
- ...op,
3017
- updateComponents: {
3018
- ...update,
3019
- components: [component]
3020
- }
3021
- }));
3022
- });
3023
- }
3024
- /** createSurface first, the other operations after it in their order. */
3025
- function createSurfaceFirst(operations) {
3026
- const creates = operations.filter((op) => isRecord(op.createSurface));
3027
- const others = operations.filter((op) => !isRecord(op.createSurface));
3028
- return [...creates, ...others];
3029
- }
3030
- /** True when the component of `name` has the prop `prop`. */
3031
- function hasProp(ui, name, prop) {
3032
- const properties = ui.manifestComponents[name]?.props.properties;
3033
- return isRecord(properties) && Object.hasOwn(properties, prop);
3034
- }
3035
- const childRefCache = /* @__PURE__ */ new WeakMap();
3036
- /** The ids in a slot value: an id, a list of ids, or a template. */
3037
- function slotIds(value) {
3038
- if (typeof value === "string") return [value];
3039
- if (Array.isArray(value)) return value.filter(isString);
3040
- return isRecord(value) && isString(value.componentId) ? [value.componentId] : [];
3041
- }
3042
- /**
3043
- * A reader of the ids a component renders beyond `child` and `children`:
3044
- * its declared slots (the `trigger` and `content` of a Modal) and its typed
3045
- * child references (the `child` of each entry of `tabs`), from its catalog
3046
- * entry. The prose lift follows these ids like `children`, so a panel is
3047
- * never cut off from its Tabs. A reference that is bound to the data
3048
- * model is "unknown": its ids exist only at render time.
3049
- */
3050
- function childIdsReader(ui) {
3051
- return (component) => {
3052
- const name = component.component;
3053
- const entry = typeof name === "string" && Object.hasOwn(ui.manifestComponents, name) ? ui.manifestComponents[name] : void 0;
3054
- if (!entry) return [];
3055
- const ids = [];
3056
- for (const slot of Object.keys(entry.slots ?? {})) if (slot !== "child" && slot !== "children") ids.push(...slotIds(component[slot]));
3057
- let refs = childRefCache.get(entry.props);
3058
- if (!refs) {
3059
- refs = (0, _copilotkit_shared.collectChildRefs)(entry.props);
3060
- childRefCache.set(entry.props, refs);
3061
- }
3062
- if (refs.length === 0) return ids;
3063
- if ((0, _copilotkit_shared.hasBoundChildRef)(component, refs)) return "unknown";
3064
- return [...ids, ...(0, _copilotkit_shared.childIdsAtRefs)(component, refs)];
3065
- };
3066
- }
3067
- /** Every component of the operations by id, last definition wins. */
3068
- function collectComponents(operations) {
3069
- const byId = /* @__PURE__ */ new Map();
3070
- for (const op of operations) {
3071
- const update = op.updateComponents;
3072
- const list = isRecord(update) ? update.components : void 0;
3073
- if (!Array.isArray(list)) continue;
3074
- for (const component of list) if (isRecord(component) && isString(component.id)) byId.set(component.id, component);
3075
- }
3076
- return [...byId.values()];
3077
- }
3078
- /**
3079
- * The data model must not be shared between two surfaces. A data model
3080
- * keeps the object it gets, so an input in one surface would change the
3081
- * data of the other one.
3082
- */
3083
- function cloneData(value) {
3084
- return value === void 0 ? void 0 : structuredClone(value);
3085
- }
3086
- /** The operation sent to `surfaceId`, with a copy of its data model value. */
3087
- function readdress(op, surfaceId) {
3088
- const kind = (0, _copilotkit_shared.getOperationKind)(op);
3089
- const payload = kind ? op[kind] : void 0;
3090
- if (!kind || !isRecord(payload)) return op;
3091
- const next = {
3092
- ...payload,
3093
- surfaceId
3094
- };
3095
- if (kind === "updateDataModel" && "value" in payload) next.value = cloneData(payload.value);
3096
- return {
3097
- ...op,
3098
- [kind]: next
3099
- };
3100
- }
3101
- /**
3102
- * The operations of one sub-surface. Each updateComponents keeps only the
3103
- * components of the sub-surface, with its own root. The other operations
3104
- * are sent to the sub-surface. The order stays the same, so a new operation
3105
- * of the fence only adds operations at the end.
3106
- */
3107
- function subSurfaceOperations(operations, components, surfaceId) {
3108
- const root = components.find((c) => c.id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID);
3109
- const ids = new Set(components.map((c) => c.id));
3110
- const out = [];
3111
- for (const op of operations) {
3112
- const update = op.updateComponents;
3113
- if (!isRecord(update) || !Array.isArray(update.components)) {
3114
- out.push(readdress(op, surfaceId));
3115
- continue;
3116
- }
3117
- 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);
3118
- if (kept.length === 0) continue;
3119
- out.push({
3120
- ...op,
3121
- updateComponents: {
3122
- ...update,
3123
- surfaceId,
3124
- components: kept
3125
- }
3126
- });
3127
- }
3128
- return out;
3129
- }
3130
- /**
3131
- * Prose lift. Text components in the main stack of the surface (titles,
3132
- * paragraphs, text lists and the dividers between them) become chat
3133
- * markdown. The surface splits around them: the first surface keeps
3134
- * `surfaceId`, the next ones are `<surfaceId>#1`, `<surfaceId>#2`, and so
3135
- * on. A surface with no prose comes back as one part with the same
3136
- * operations.
3137
- */
3138
- function liftProse(operations, surfaceId, childIds) {
3139
- const components = collectComponents(operations);
3140
- const segments = (0, _copilotkit_core.segmentSurfaceProse)(components, { childIds });
3141
- const [first] = segments;
3142
- if (segments.length === 1 && first?.kind === "surface" && first.components === components) return [{
3143
- kind: "surface",
3144
- surfaceId,
3145
- operations
3146
- }];
3147
- let surfaceIndex = 0;
3148
- return segments.map((segment) => {
3149
- if (segment.kind === "markdown") return segment;
3150
- const id = surfaceIndex === 0 ? surfaceId : `${surfaceId}#${surfaceIndex}`;
3151
- surfaceIndex++;
3152
- return {
3153
- kind: "surface",
3154
- surfaceId: id,
3155
- operations: subSurfaceOperations(operations, segment.components, id)
3156
- };
3157
- });
3158
- }
3159
- /** `validateOperation`, with the operation typed when it is valid. */
3160
- function checkOperation(op, options) {
3161
- const validation = (0, _copilotkit_shared.validateOperation)(op, options);
3162
- if (!validation.ok) return validation;
3163
- return {
3164
- ok: true,
3165
- operation: op
3166
- };
3167
- }
3168
- /**
3169
- * The content of one surface. Each operation is validated against the
3170
- * manifest. A valid operation goes in `operations`. A rejected one goes in
3171
- * `rejected`, with its position and the reason.
3172
- */
3173
- function surfaceContent(surfaceId, draft, operations, options) {
3174
- const { ui, functions } = options;
3175
- const knownSurfaces = /* @__PURE__ */ new Set();
3176
- const manifest = {
3177
- catalogId: ui.id,
3178
- catalogIds: catalogIdsOf(ui),
3179
- components: ui.manifestComponents
3180
- };
3181
- const valid = [];
3182
- const rejected = [];
3183
- operations.forEach((op, index) => {
3184
- const result = checkOperation(op, {
3185
- manifest,
3186
- knownSurfaces,
3187
- functions
3188
- });
3189
- if (!result.ok) {
3190
- rejected.push({
3191
- index,
3192
- reason: result.reason
3193
- });
3194
- return;
3195
- }
3196
- valid.push(result.operation);
3197
- const kind = (0, _copilotkit_shared.getOperationKind)(result.operation);
3198
- if (kind === "createSurface") knownSurfaces.add(surfaceId);
3199
- if (kind === "deleteSurface") knownSurfaces.delete(surfaceId);
3200
- });
3201
- const create = valid.find((op) => "createSurface" in op);
3202
- return {
3203
- surfaceId,
3204
- target: draft.target,
3205
- catalogId: create?.createSurface.catalogId ?? ui.id,
3206
- operations: valid,
3207
- status: draft.streaming ? "streaming" : "ready",
3208
- rejected
3209
- };
3210
- }
3211
- /**
3212
- * Builds the surfaces of a thread from the ```a2ui fences of its assistant
3213
- * messages, in message order.
3214
- *
3215
- * - Operations are grouped by surfaceId across all messages. An operation
3216
- * with no surfaceId goes to the first surface of its fence, else to
3217
- * `<messageId>-<fenceIndex>`.
3218
- * - The fence that first writes a surface creates it. The `target=<id>` of
3219
- * that fence sets the target. With no target, the surface goes to the
3220
- * chat.
3221
- * - A later fence of the same reply for the same surfaceId updates it. A
3222
- * later reply that reuses the id of a chat surface gets a surface of its
3223
- * own, `<id>@<messageId>`. A page target is updated from any reply.
3224
- * - The status is "streaming" while the creating fence streams, else
3225
- * "ready".
3226
- * - Each operation is validated with `validateOperation`. Rejected ones are
3227
- * left out and listed in `rejected`.
3228
- * - Chat surfaces get the prose lift: informational cards lose their box,
3229
- * and prose becomes markdown that renders between sub-surfaces
3230
- * (`<surfaceId>#<n>`). An inline createSurface is split into its
3231
- * createSurface, updateDataModel and updateComponents first.
3232
- * - A `callRendererFunction` line is not part of a surface. It goes to
3233
- * `functionCalls`. A streaming line gives nothing, so a function never
3234
- * runs with a part of its args.
3235
- *
3236
- * The function is pure. Call it again on each stream update. The manager
3237
- * applies only the new operations, so unchanged surfaces do not render
3238
- * again.
3239
- *
3240
- * @param messages - The messages of one thread.
3241
- * @param options - The generative UI, its declared functions, and whether
3242
- * the last message can still grow.
3243
- * @returns `surfaces`, one content for each surface and sub-surface;
3244
- * `fences`, the blocks that each fence renders, by `fenceKey` (a fence
3245
- * that is not in `fences` renders nothing); `functionCalls`, the function
3246
- * calls of the fences in order; and `parts`, the surface ids of the parts
3247
- * of each surface, by surface id.
3248
- *
3249
- * @example
3250
- * ```ts
3251
- * const { surfaces } = buildMarkdownSurfaces(agent.messages, {
3252
- * ui,
3253
- * functions: {},
3254
- * running: agent.isRunning,
3255
- * });
3256
- * for (const content of surfaces) manager.ingest(threadId, agentId, content);
3257
- * ```
3258
- */
3259
- function buildMarkdownSurfaces(messages, options) {
3260
- const { ui, cache } = options;
3261
- const drafts = /* @__PURE__ */ new Map();
3262
- const readdressOnce = (op, surfaceId) => {
3263
- if (!cache) return readdress(op, surfaceId);
3264
- let copies = cache.readdressed.get(op);
3265
- if (!copies) {
3266
- copies = /* @__PURE__ */ new Map();
3267
- cache.readdressed.set(op, copies);
3268
- }
3269
- let copy = copies.get(surfaceId);
3270
- if (!copy) {
3271
- copy = readdress(op, surfaceId);
3272
- copies.set(surfaceId, copy);
3273
- }
3274
- return copy;
3275
- };
3276
- /** The surfaces that each fence created, in order. */
3277
- const created = /* @__PURE__ */ new Map();
3278
- const functionCalls = [];
3279
- /** The message that owns each chat surface id, by the id the model wrote. */
3280
- const chatOwners = /* @__PURE__ */ new Map();
3281
- const lastMessage = messages[messages.length - 1];
3282
- /**
3283
- * A chat surface belongs to the reply that wrote it: the chat is a
3284
- * transcript, so a later reply that reuses an id gets a surface of its
3285
- * own (`<id>@<messageId>`) instead of changing the earlier reply. A fence
3286
- * for a page target keeps its id, because a target is a place on the
3287
- * page that a later reply updates on purpose.
3288
- */
3289
- const scopedSurfaceId = (requested, messageId, target) => {
3290
- if (target !== void 0) return requested;
3291
- const owner = chatOwners.get(requested);
3292
- if (owner === void 0) {
3293
- chatOwners.set(requested, messageId);
3294
- return requested;
3295
- }
3296
- return owner === messageId ? requested : `${requested}@${messageId}`;
3297
- };
3298
- for (const message of messages) {
3299
- if (message.role !== "assistant" || !isString(message.content)) continue;
3300
- const isLastMessage = message === lastMessage;
3301
- const content = message.content;
3302
- const segments = cache ? cache.segments.get(content, () => (0, _copilotkit_core.splitA2UIMarkdown)(content)) : (0, _copilotkit_core.splitA2UIMarkdown)(content);
3303
- for (const segment of segments) {
3304
- if (segment.type !== "a2ui") continue;
3305
- const isStreaming = !segment.closed && isLastMessage && options.running;
3306
- const parseFence = () => {
3307
- const parsed = fenceOperations(segment.text, isStreaming);
3308
- const { functionCalls } = (0, _copilotkit_core.prepareSurfaceOperations)({
3309
- operations: parsed,
3310
- fallbackSurfaceId: "",
3311
- catalogId: ui.id
3312
- });
3313
- return {
3314
- operations: parsed,
3315
- functionCalls
3316
- };
3317
- };
3318
- const fence = cache ? cache.fences.get(`${isStreaming}:${segment.text}`, parseFence) : parseFence();
3319
- const { operations } = fence;
3320
- const key = fenceKey(message.id, segment.index);
3321
- const fenceSurfaceId = operations.map(_copilotkit_core.getMarkdownOperationSurfaceId).find(isString) ?? `${message.id}-${segment.index}`;
3322
- for (const operation of fence.functionCalls) functionCalls.push({
3323
- messageId: message.id,
3324
- fenceIndex: segment.index,
3325
- operation
3326
- });
3327
- const surfaceOperations = operations.filter((op) => (0, _copilotkit_shared.getOperationKind)(op) !== "callRendererFunction");
3328
- for (const op of surfaceOperations) {
3329
- const requested = (0, _copilotkit_core.getMarkdownOperationSurfaceId)(op) ?? fenceSurfaceId;
3330
- const surfaceId = scopedSurfaceId(requested, message.id, segment.target);
3331
- let draft = drafts.get(surfaceId);
3332
- if (!draft) {
3333
- draft = {
3334
- surfaceId,
3335
- target: segment.target ?? _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
3336
- operations: [],
3337
- streaming: isStreaming
3338
- };
3339
- drafts.set(surfaceId, draft);
3340
- created.set(key, [...created.get(key) ?? [], surfaceId]);
3341
- }
3342
- draft.operations.push(surfaceId === requested ? op : readdressOnce(op, surfaceId));
3343
- }
3344
- }
3345
- }
3346
- const canFlattenCards = hasProp(ui, "Card", "variant");
3347
- const surfaces = [];
3348
- const partsBySurface = /* @__PURE__ */ new Map();
3349
- const childIds = childIdsReader(ui);
3350
- const buildDraft = (draft) => {
3351
- const operations = splitComponentUpdates(expandInlineCreate(createSurfaceFirst((0, _copilotkit_core.prepareSurfaceOperations)({
3352
- operations: draft.operations,
3353
- fallbackSurfaceId: draft.surfaceId,
3354
- catalogId: ui.id,
3355
- catalogIds: catalogIdsOf(ui)
3356
- }).operations)));
3357
- const parts = draft.target === _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET ? liftProse(canFlattenCards ? (0, _copilotkit_core.flattenInformationalCards)(operations, { childIds }) : operations, draft.surfaceId, childIds) : [{
3358
- kind: "surface",
3359
- surfaceId: draft.surfaceId,
3360
- operations
3361
- }];
3362
- const contents = parts.flatMap((part) => part.kind === "surface" ? [surfaceContent(part.surfaceId, draft, part.operations, options)] : []);
3363
- return {
3364
- ...draft,
3365
- parts,
3366
- contents
3367
- };
3368
- };
3369
- for (const draft of drafts.values()) {
3370
- 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);
3371
- partsBySurface.set(draft.surfaceId, built.parts);
3372
- surfaces.push(...built.contents);
3373
- }
3374
- cache?.endBuild();
3375
- /** The surface ids of the parts of each split surface, by surface id. */
3376
- const parts = /* @__PURE__ */ new Map();
3377
- for (const [surfaceId, surfaceParts] of partsBySurface) {
3378
- const ids = surfaceParts.flatMap((part) => part.kind === "surface" ? [part.surfaceId] : []);
3379
- parts.set(surfaceId, ids);
3380
- }
3381
- const fences = /* @__PURE__ */ new Map();
3382
- for (const [key, surfaceIds] of created) {
3383
- const blocks = [];
3384
- for (const surfaceId of surfaceIds) {
3385
- if (drafts.get(surfaceId)?.target !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET) continue;
3386
- for (const part of partsBySurface.get(surfaceId) ?? []) blocks.push(part.kind === "markdown" ? part : {
3387
- kind: "surface",
3388
- surfaceId: part.surfaceId
3389
- });
3390
- }
3391
- if (blocks.length > 0) fences.set(key, blocks);
3392
- }
3393
- return {
3394
- surfaces,
3395
- fences,
3396
- functionCalls,
3397
- parts
3398
- };
3399
- }
3400
- /** The declared functions, as `validateOperation` takes them. */
3401
- function declaredFunctions(ui) {
3402
- const functions = {};
3403
- for (const [name, fn] of ui.functions) try {
3404
- functions[name] = {
3405
- ...fn.description ? { description: fn.description } : {},
3406
- parameters: toJsonSchema(fn.parameters)
3407
- };
3408
- } catch {
3409
- functions[name] = { parameters: {} };
3410
- }
3411
- return functions;
3412
- }
3413
- /** True when `list` starts with all the items of `prefix`. */
3414
- function startsWith(list, prefix) {
3415
- return list.length >= prefix.length && prefix.every((item, index) => item === list[index]);
3416
- }
3417
- /** A content that deletes a surface that the fences no longer write. */
3418
- function removalContent(surfaceId, catalogId) {
3419
- return {
3420
- surfaceId,
3421
- target: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
3422
- catalogId,
3423
- status: "ready",
3424
- rejected: [],
3425
- operations: [{
3426
- version: _copilotkit_shared.A2UI_VERSION,
3427
- createSurface: {
3428
- surfaceId,
3429
- catalogId
3430
- }
3431
- }, {
3432
- version: _copilotkit_shared.A2UI_VERSION,
3433
- deleteSurface: { surfaceId }
3434
- }]
3435
- };
3436
- }
3437
- /**
3438
- * The markdown transport source of one surface manager. It turns the
3439
- * messages of a thread into surfaces in the manager, and keeps the blocks
3440
- * that each fence renders.
3441
- */
3442
- var MarkdownSurfaceSource = class {
3443
- constructor(manager, ui) {
3444
- this.manager = manager;
3445
- this.ui = ui;
3446
- _defineProperty(this, "functions", void 0);
3447
- _defineProperty(this, "fences", /* @__PURE__ */ new Map());
3448
- _defineProperty(this, "ingested", /* @__PURE__ */ new Map());
3449
- _defineProperty(this, "contents", /* @__PURE__ */ new Map());
3450
- _defineProperty(this, "caches", /* @__PURE__ */ new Map());
3451
- this.functions = declaredFunctions(ui);
3452
- }
3453
- /**
3454
- * Builds the surfaces of `threadId` from `messages` and gives them to the
3455
- * manager. A surface that an earlier sync of the thread made, and that the
3456
- * messages no longer write, is deleted. Other threads do not change.
3457
- *
3458
- * @param threadId - The thread of the messages.
3459
- * @param agentId - The agent that owns the thread.
3460
- * @param messages - All messages of the thread.
3461
- * @param options - `running`: the last message can still grow.
3462
- * @returns The function calls of the fences, in order. The source does
3463
- * not run them.
3464
- */
3465
- sync(threadId, agentId, messages, options) {
3466
- let cache = this.caches.get(threadId);
3467
- if (!cache) {
3468
- cache = new MarkdownBuildCache();
3469
- this.caches.set(threadId, cache);
3470
- }
3471
- const result = buildMarkdownSurfaces(messages, {
3472
- ui: this.ui,
3473
- functions: this.functions,
3474
- running: options.running,
3475
- cache
3476
- });
3477
- this.fences.set(threadId, result.fences);
3478
- for (const parts of result.parts.values()) this.manager.linkSurfaces(threadId, parts);
3479
- const previous = this.ingested.get(threadId) ?? /* @__PURE__ */ new Map();
3480
- const previousContents = this.contents.get(threadId) ?? /* @__PURE__ */ new Map();
3481
- const next = /* @__PURE__ */ new Map();
3482
- const nextContents = /* @__PURE__ */ new Map();
3483
- for (const content of result.surfaces) {
3484
- nextContents.set(content.surfaceId, content);
3485
- const before = previous.get(content.surfaceId);
3486
- if (before && previousContents.get(content.surfaceId) === content) {
3487
- next.set(content.surfaceId, before);
3488
- continue;
3489
- }
3490
- const fingerprints = content.operations.map((op) => JSON.stringify(op));
3491
- if (before && !startsWith(fingerprints, before)) this.manager.ingest(threadId, agentId, {
3492
- ...content,
3493
- operations: []
3494
- });
3495
- this.manager.ingest(threadId, agentId, content);
3496
- next.set(content.surfaceId, fingerprints);
3497
- }
3498
- for (const surfaceId of previous.keys()) {
3499
- if (next.has(surfaceId)) continue;
3500
- this.manager.ingest(threadId, agentId, removalContent(surfaceId, this.ui.id));
3501
- }
3502
- this.ingested.set(threadId, next);
3503
- this.contents.set(threadId, nextContents);
3504
- return result.functionCalls;
3505
- }
3506
- /**
3507
- * The blocks that a fence renders in the chat, from the latest sync of the
3508
- * thread. `undefined` when the fence renders nothing: it updates a surface
3509
- * of an earlier fence, its surface is for a named target, or it has no
3510
- * complete operation yet.
3511
- */
3512
- getFenceBlocks(threadId, messageId, fenceIndex) {
3513
- return this.fences.get(threadId)?.get(fenceKey(messageId, fenceIndex));
3514
- }
3515
- };
3516
- const sources = /* @__PURE__ */ new WeakMap();
3517
- /**
3518
- * The markdown source of a generative UI runtime. There is one source for
3519
- * each surface manager. The root syncs it, and the chat messages read the
3520
- * fence blocks from it.
3521
- */
3522
- function getMarkdownSurfaceSource(runtime) {
3523
- let source = sources.get(runtime.manager);
3524
- if (!source) {
3525
- source = new MarkdownSurfaceSource(runtime.manager, runtime.ui);
3526
- sources.set(runtime.manager, source);
3527
- }
3528
- return source;
3529
- }
3530
-
3531
- //#endregion
3532
- //#region src/generative-ui/calc.ts
3533
- const MAX_SERIES = 1e3;
3534
- const OPERATORS = [
3535
- "&&",
3536
- "||",
3537
- "==",
3538
- "!=",
3539
- "<=",
3540
- ">=",
3541
- "<",
3542
- ">",
3543
- "+",
3544
- "-",
3545
- "*",
3546
- "/",
3547
- "%",
3548
- "^",
3549
- "(",
3550
- ")",
3551
- ",",
3552
- "?",
3553
- ":",
3554
- "!"
3555
- ];
3556
- function tokenize(source) {
3557
- const tokens = [];
3558
- let i = 0;
3559
- while (i < source.length) {
3560
- const char = source[i];
3561
- if (/\s/.test(char)) {
3562
- i++;
3563
- continue;
3564
- }
3565
- if (/[0-9.]/.test(char)) {
3566
- const match = /^\d*\.?\d+(?:[eE][-+]?\d+)?|^\d+\.?/.exec(source.slice(i));
3567
- if (!match) throw new ExpressionError(`calc: bad number at "${source.slice(i, i + 8)}"`);
3568
- tokens.push({
3569
- kind: "number",
3570
- value: Number(match[0])
3571
- });
3572
- i += match[0].length;
3573
- continue;
3574
- }
3575
- if (char === "'" || char === "\"") {
3576
- let value = "";
3577
- i++;
3578
- while (i < source.length && source[i] !== char) {
3579
- if (source[i] === "\\" && i + 1 < source.length) i++;
3580
- value += source[i++];
3581
- }
3582
- if (i >= source.length) throw new ExpressionError("calc: unclosed string");
3583
- i++;
3584
- tokens.push({
3585
- kind: "string",
3586
- value
3587
- });
3588
- continue;
3589
- }
3590
- if (/[A-Za-z_]/.test(char)) {
3591
- const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));
3592
- tokens.push({
3593
- kind: "name",
3594
- value: match[0]
3595
- });
3596
- i += match[0].length;
3597
- continue;
3598
- }
3599
- const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));
3600
- if (!op) throw new ExpressionError(`calc: unexpected "${char}"`);
3601
- tokens.push({
3602
- kind: "op",
3603
- value: op
3604
- });
3605
- i += op.length;
3606
- }
3607
- tokens.push({ kind: "end" });
3608
- return tokens;
3609
- }
3610
- function numberOf(value, what) {
3611
- if (typeof value === "number") {
3612
- if (!Number.isFinite(value)) throw new ExpressionError(`calc: ${what} is not finite`);
3613
- return value;
3614
- }
3615
- if (typeof value === "boolean") return value ? 1 : 0;
3616
- if (typeof value === "string" && value.trim() !== "") {
3617
- const parsed = Number(value);
3618
- if (Number.isFinite(parsed)) return parsed;
3619
- }
3620
- if (value === null || value === void 0) throw new ExpressionError(`calc: ${what} has no value`);
3621
- throw new ExpressionError(`calc: ${what} is not a number`);
3622
- }
3623
- function describe(value) {
3624
- return typeof value === "string" ? `"${value}"` : String(value);
3625
- }
3626
- const MATH = {
3627
- min: (args) => Math.min(...args),
3628
- max: (args) => Math.max(...args),
3629
- abs: ([x = NaN]) => Math.abs(x),
3630
- floor: ([x = NaN]) => Math.floor(x),
3631
- ceil: ([x = NaN]) => Math.ceil(x),
3632
- round: ([x = NaN, decimals = 0]) => {
3633
- const factor = 10 ** Math.trunc(decimals);
3634
- return Math.round(x * factor) / factor;
3635
- },
3636
- pow: ([x = NaN, y = NaN]) => x ** y,
3637
- sqrt: ([x = NaN]) => Math.sqrt(x),
3638
- exp: ([x = NaN]) => Math.exp(x),
3639
- ln: ([x = NaN]) => Math.log(x),
3640
- log10: ([x = NaN]) => Math.log10(x)
3641
- };
3642
- /** How many args a function takes, at least and at most; min and max take any. */
3643
- const ARITY = {
3644
- abs: [1, 1],
3645
- floor: [1, 1],
3646
- ceil: [1, 1],
3647
- round: [1, 2],
3648
- pow: [2, 2],
3649
- sqrt: [1, 1],
3650
- exp: [1, 1],
3651
- ln: [1, 1],
3652
- log10: [1, 1]
3653
- };
3654
- /** Named constants, when no arg of the same name is passed. */
3655
- const CONSTANTS = {
3656
- pi: Math.PI,
3657
- e: Math.E
3658
- };
3659
- var CalcParser = class {
3660
- constructor(tokens, scope, source) {
3661
- this.tokens = tokens;
3662
- this.scope = scope;
3663
- this.source = source;
3664
- _defineProperty(this, "pos", 0);
3665
- _defineProperty(this, "skipDepth", 0);
3666
- }
3667
- parse() {
3668
- const value = this.ternary();
3669
- const token = this.peek();
3670
- if (token.kind !== "end") this.fail(`unexpected "${this.text(token)}"`);
3671
- return value;
3672
- }
3673
- /**
3674
- * The token at `pos`. The parser never moves past the "end" token, which
3675
- * `tokenize` always adds last, so there is always one.
3676
- */
3677
- peek() {
3678
- const token = this.tokens[this.pos];
3679
- if (token === void 0) throw new Error(`calc: no token at ${this.pos} in "${this.source}"`);
3680
- return token;
3681
- }
3682
- fail(what) {
3683
- throw new ExpressionError(`calc: ${what} in "${this.source}"`);
3684
- }
3685
- text(token) {
3686
- return token.kind === "end" ? "end" : String(token.value);
3687
- }
3688
- peekOp(...ops) {
3689
- const token = this.peek();
3690
- return token.kind === "op" && ops.includes(token.value) ? token.value : void 0;
3691
- }
3692
- expectOp(op) {
3693
- if (this.peekOp(op) === void 0) this.fail(`expected "${op}" but found "${this.text(this.peek())}"`);
3694
- this.pos++;
3695
- }
3696
- /**
3697
- * Parses a part of the expression that the result does not need (the
3698
- * other branch of `?:`, the right side of a decided `&&` or `||`). It
3699
- * still has to be parsed to find where it ends, so syntax errors are
3700
- * reported, but no value is checked or computed: `n == 0 ? 0 : 10 / n`
3701
- * is a valid guard.
3702
- */
3703
- skipped(parse) {
3704
- this.skipDepth++;
3705
- try {
3706
- parse();
3707
- } finally {
3708
- this.skipDepth--;
3709
- }
3710
- return null;
3711
- }
3712
- /** The number of a value, or 0 while skipping. */
3713
- num(value, what) {
3714
- return this.skipDepth > 0 ? 0 : numberOf(value, what);
3715
- }
3716
- ternary() {
3717
- const condition = this.or();
3718
- if (this.peekOp("?") === void 0) return condition;
3719
- this.pos++;
3720
- const takesFirst = truthOf(condition);
3721
- const whenTrue = takesFirst ? this.ternary() : this.skipped(() => this.ternary());
3722
- this.expectOp(":");
3723
- const whenFalse = takesFirst ? this.skipped(() => this.ternary()) : this.ternary();
3724
- return takesFirst ? whenTrue : whenFalse;
3725
- }
3726
- or() {
3727
- let left = this.and();
3728
- while (this.peekOp("||")) {
3729
- this.pos++;
3730
- if (truthOf(left)) {
3731
- this.skipped(() => this.and());
3732
- left = true;
3733
- } else left = truthOf(this.and());
3734
- }
3735
- return left;
3736
- }
3737
- and() {
3738
- let left = this.equality();
3739
- while (this.peekOp("&&")) {
3740
- this.pos++;
3741
- if (!truthOf(left)) {
3742
- this.skipped(() => this.equality());
3743
- left = false;
3744
- } else left = truthOf(this.equality());
3745
- }
3746
- return left;
3747
- }
3748
- equality() {
3749
- let left = this.comparison();
3750
- for (let op = this.peekOp("==", "!="); op; op = this.peekOp("==", "!=")) {
3751
- this.pos++;
3752
- const right = this.comparison();
3753
- const isEqual = typeof left === "number" || typeof right === "number" ? this.num(left, "the left side of ==") === this.num(right, "the right side of ==") : left === right;
3754
- left = op === "==" ? isEqual : !isEqual;
3755
- }
3756
- return left;
3757
- }
3758
- comparison() {
3759
- let left = this.additive();
3760
- for (let op = this.peekOp("<", "<=", ">", ">="); op; op = this.peekOp("<", "<=", ">", ">=")) {
3761
- this.pos++;
3762
- const a = this.num(left, `the left side of ${op}`);
3763
- const b = this.num(this.additive(), `the right side of ${op}`);
3764
- left = op === "<" ? a < b : op === "<=" ? a <= b : op === ">" ? a > b : a >= b;
3765
- }
3766
- return left;
3767
- }
3768
- additive() {
3769
- let left = this.multiplicative();
3770
- for (let op = this.peekOp("+", "-"); op; op = this.peekOp("+", "-")) {
3771
- this.pos++;
3772
- const right = this.multiplicative();
3773
- if (op === "+" && (typeof left === "string" || typeof right === "string")) left = `${left ?? ""}${right ?? ""}`;
3774
- else {
3775
- const a = this.num(left, `the left side of ${op}`);
3776
- const b = this.num(right, `the right side of ${op}`);
3777
- left = op === "+" ? a + b : a - b;
3778
- }
3779
- }
3780
- return left;
3781
- }
3782
- multiplicative() {
3783
- let left = this.unary();
3784
- for (let op = this.peekOp("*", "/", "%"); op; op = this.peekOp("*", "/", "%")) {
3785
- this.pos++;
3786
- const a = this.num(left, `the left side of ${op}`);
3787
- const b = this.num(this.unary(), `the right side of ${op}`);
3788
- if (op !== "*" && b === 0 && this.skipDepth === 0) this.fail("division by zero");
3789
- left = op === "*" ? a * b : op === "/" ? a / b : a % b;
3790
- }
3791
- return left;
3792
- }
3793
- unary() {
3794
- if (this.peekOp("-")) {
3795
- this.pos++;
3796
- return -this.num(this.unary(), "the operand of -");
3797
- }
3798
- if (this.peekOp("!")) {
3799
- this.pos++;
3800
- return !truthOf(this.unary());
3801
- }
3802
- return this.power();
3803
- }
3804
- /** `a ^ b`: binds tighter than `*` and unary minus, right to left. */
3805
- power() {
3806
- const base = this.primary();
3807
- if (!this.peekOp("^")) return base;
3808
- this.pos++;
3809
- const exponent = this.unary();
3810
- if (this.skipDepth > 0) return null;
3811
- return this.finite(this.num(base, "the left side of ^") ** this.num(exponent, "the right side of ^"), "^");
3812
- }
3813
- finite(value, what) {
3814
- if (!Number.isFinite(value)) this.fail(`${what} has no finite result`);
3815
- return value;
3816
- }
3817
- primary() {
3818
- const token = this.peek();
3819
- this.pos++;
3820
- switch (token.kind) {
3821
- case "number": return token.value;
3822
- case "string": return token.value;
3823
- case "name": return this.name(token.value);
3824
- case "op":
3825
- if (token.value === "(") {
3826
- const value = this.ternary();
3827
- this.expectOp(")");
3828
- return value;
3829
- }
3830
- return this.fail(`unexpected "${token.value}"`);
3831
- case "end": return this.fail("missing value");
3832
- }
3833
- }
3834
- name(name) {
3835
- if (name === "true") return true;
3836
- if (name === "false") return false;
3837
- if (name === "null") return null;
3838
- if (this.peekOp("(")) {
3839
- this.pos++;
3840
- const args = [];
3841
- if (this.peekOp(")") === void 0) for (;;) {
3842
- args.push(this.num(this.ternary(), `an argument of ${name}`));
3843
- if (this.peekOp(",") === void 0) break;
3844
- this.pos++;
3845
- }
3846
- this.expectOp(")");
3847
- if (this.skipDepth > 0) return null;
3848
- const fn = Object.prototype.hasOwnProperty.call(MATH, name) ? MATH[name] : void 0;
3849
- if (!fn) this.fail(`unknown function ${name}`);
3850
- if (args.length === 0) this.fail(`${name} needs an argument`);
3851
- const [least, most] = ARITY[name] ?? [1, Infinity];
3852
- if (args.length < least || args.length > most) this.fail(`${name} takes ${least === most ? least : `${least} or ${most}`} argument${most === 1 ? "" : "s"}`);
3853
- return this.finite(fn(args), name);
3854
- }
3855
- if (this.skipDepth > 0) return null;
3856
- if (!Object.prototype.hasOwnProperty.call(this.scope, name)) {
3857
- if (Object.prototype.hasOwnProperty.call(CONSTANTS, name)) return CONSTANTS[name];
3858
- this.fail(`unknown name ${name}; pass it as an arg`);
3859
- }
3860
- const value = this.scope[name];
3861
- if (value !== null && typeof value !== "number" && typeof value !== "string" && typeof value !== "boolean") this.fail(`${name} is not a number, text or boolean (${describe(value)})`);
3862
- return value;
3863
- }
3864
- };
3865
- /**
3866
- * Evaluates `expression` with the names in `scope`. Gives a number, a
3867
- * string, a boolean or null. Throws an {@link ExpressionError} for a bad
3868
- * expression or a missing name.
3869
- */
3870
- function evaluateCalc(expression, scope) {
3871
- if (typeof expression !== "string" || expression.trim() === "") throw new ExpressionError("calc: expression must be a string");
3872
- return new CalcParser(tokenize(expression), scope, expression).parse();
3873
- }
3874
- /** The `calc` function: the expression is `args.expression`, the rest is the scope. */
3875
- function calc(args) {
3876
- const { expression, ...scope } = args;
3877
- return evaluateCalc(expression, scope);
3878
- }
3879
- const WHOLE_EXPRESSION = /^\$\{([^}]*)\}$/;
3880
- /**
3881
- * Fills `item` for one iteration: a string that is one `${...}` gives the
3882
- * typed value of the expression, a string with `${...}` inside it is
3883
- * interpolated as text, and objects and arrays are walked.
3884
- */
3885
- function fillItem(item, scope) {
3886
- if (typeof item === "string") {
3887
- const whole = WHOLE_EXPRESSION.exec(item);
3888
- if (whole) return evaluateCalc(whole[1], scope);
3889
- return item.replace(/\$\{([^}]*)\}/g, (_, expression) => {
3890
- const value = evaluateCalc(expression, scope);
3891
- return value === null ? "" : String(value);
3892
- });
3893
- }
3894
- if (Array.isArray(item)) return item.map((entry) => fillItem(entry, scope));
3895
- if (typeof item === "object" && item !== null) return Object.fromEntries(Object.entries(item).map(([key, value]) => [key, fillItem(value, scope)]));
3896
- return item;
3897
- }
3898
- /**
3899
- * The `series` function: `count` copies of `item`, with the loop variable
3900
- * (`variable`, default "i") counting from `start` (default 1) and the other
3901
- * args in scope of the `${...}` expressions of the item.
3902
- */
3903
- function series(args) {
3904
- const { count, item, variable, start, ...scope } = args;
3905
- const length = numberOf(count, "count");
3906
- if (!Number.isInteger(length) || length < 0) throw new ExpressionError("series: count must be a whole number");
3907
- if (length > MAX_SERIES) throw new ExpressionError(`series: count is at most ${MAX_SERIES}`);
3908
- if (item === void 0) throw new ExpressionError("series: item is required");
3909
- const name = variable === void 0 ? "i" : variable;
3910
- if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new ExpressionError("series: variable must be a name");
3911
- const first = start === void 0 ? 1 : numberOf(start, "start");
3912
- return Array.from({ length }, (_, index) => fillItem(item, {
3913
- ...scope,
3914
- [name]: first + index
3915
- }));
3916
- }
3917
-
3918
- //#endregion
3919
- //#region src/generative-ui/resolve.ts
3920
- BASIC_FUNCTIONS.calc = calc;
3921
- BASIC_FUNCTIONS.series = series;
3922
- const NO_DATA = { get: () => void 0 };
3923
- BASIC_FUNCTIONS.formatString = (args) => resolveDynamicValue({
3924
- "@call": "formatString",
3925
- args
3926
- }, {
3927
- data: NO_DATA,
3928
- basePath: void 0
3929
- }).value;
3930
- /** Adds one segment to a JSON pointer: ("/items", "0") gives "/items/0". */
3931
- function joinPath(base, segment) {
3932
- return base === "/" ? `/${segment}` : `${base}/${segment}`;
3933
- }
3934
- /**
3935
- * The absolute data model path of a binding. A path without a leading "/"
3936
- * is relative to the current template item, or to the root outside of one.
3937
- */
3938
- function resolvePath(path, basePath) {
3939
- if (path.startsWith("/")) return path;
3940
- return joinPath(basePath ?? "/", path);
3941
- }
3942
- /**
3943
- * The index of the template item at `basePath`: its last segment.
3944
- * `undefined` outside of a template.
3945
- */
3946
- function templateIndex(basePath) {
3947
- if (basePath === void 0) return void 0;
3948
- const index = Number(basePath.slice(basePath.lastIndexOf("/") + 1));
3949
- return Number.isInteger(index) ? index : void 0;
3950
- }
3951
- /** The value of a ValidationResult where a boolean is expected. */
3952
- function coerce(value, keep) {
3953
- return !keep && (0, _copilotkit_shared.isValidationResult)(value) ? value.valid : value;
3954
- }
3955
- /**
3956
- * Resolves `value`. `keepValidation` keeps a ValidationResult as it is; by
3957
- * default it becomes its `valid` boolean, which is what every prop except
3958
- * a check condition wants.
3959
- */
3960
- function walk(value, state, keepValidation, scope = "outside") {
3961
- if (Array.isArray(value)) {
3962
- let changed = false;
3963
- const itemScope = scope === "list" ? "check" : "outside";
3964
- const items = value.map((item) => {
3965
- const next = walk(item, state, keepValidation, itemScope);
3966
- if (next !== item) changed = true;
3967
- return next;
3968
- });
3969
- return changed ? items : value;
3970
- }
3971
- if (!isRecord(value)) return value;
3972
- if ((0, _copilotkit_shared.isPathBinding)(value)) {
3973
- const path = resolvePath(value["@path"], state.context.basePath);
3974
- state.paths.add(path);
3975
- return state.context.data.get(path);
3976
- }
3977
- if ((0, _copilotkit_shared.isCallBinding)(value)) return call(value, state, keepValidation);
3978
- if ((0, _copilotkit_shared.isActionBinding)(value)) return value;
3979
- let changed = false;
3980
- const entries = Object.entries(value).map(([key, item]) => {
3981
- const next = walk(item, state, keepValidation || scope === "check" && key === "condition", key === "checks" ? "list" : "outside");
3982
- if (next !== item) changed = true;
3983
- return [key, next];
3984
- });
3985
- return changed ? Object.fromEntries(entries) : value;
3986
- }
3987
- function call(binding, state, keepValidation) {
3988
- const name = binding["@call"];
3989
- const rawArgs = binding.args ?? {};
3990
- if (!isRecord(rawArgs)) throw new ExpressionError(`the args of "${name}" must be an object`);
3991
- if (name === _copilotkit_shared.A2UI_INDEX_FUNCTION) {
3992
- const index = templateIndex(state.context.basePath);
3993
- if (index === void 0) return void 0;
3994
- const offset = walk(rawArgs.offset, state, false);
3995
- return index + (typeof offset === "number" ? offset : 0);
3996
- }
3997
- if (name === "formatString") {
3998
- const template = walk(rawArgs.value, state, false);
3999
- if (typeof template !== "string") throw new ExpressionError("formatString takes a string value");
4000
- return formatString(template, state);
4001
- }
4002
- const fn = Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name) ? BASIC_FUNCTIONS[name] : void 0;
4003
- if (!fn) throw new ExpressionError(`"${name}" is not a basic function`);
4004
- if (requiresUserActivation(name)) throw new ExpressionError(`"${name}" is not a value; bind it as the functionCall of an event`);
4005
- const result = fn(walk(rawArgs, state, false));
4006
- return givesValidationResult(name) ? coerce(result, keepValidation) : result;
4007
- }
4008
- function resolveDynamicValue(value, context, options = {}) {
4009
- const result = tryResolveDynamicValue(value, context, options);
4010
- if (!result.ok) throw result.error;
4011
- return result;
4012
- }
4013
- /**
4014
- * Like {@link resolveDynamicValue}, but a failure comes back as a result
4015
- * with the paths read so far, so the caller can keep watching them: a
4016
- * function that fails on an empty field works once the user fills it.
4017
- */
4018
- function tryResolveDynamicValue(value, context, options = {}) {
4019
- const state = {
4020
- context,
4021
- paths: /* @__PURE__ */ new Set()
4022
- };
4023
- try {
4024
- return {
4025
- ok: true,
4026
- value: walk(value, state, options.keepValidation ?? false, options.isChecks ? "list" : "outside"),
4027
- paths: state.paths
4028
- };
4029
- } catch (error) {
4030
- return {
4031
- ok: false,
4032
- error: error instanceof Error ? error : new Error(String(error)),
4033
- paths: state.paths
4034
- };
4035
- }
4036
- }
4037
- /** True when `value` holds a `{"@path"}` or `{"@call"}` at any depth. */
4038
- function containsDynamicValue(value) {
4039
- if (Array.isArray(value)) return value.some(containsDynamicValue);
4040
- if (!isRecord(value)) return false;
4041
- if ((0, _copilotkit_shared.isPathBinding)(value) || (0, _copilotkit_shared.isCallBinding)(value)) return true;
4042
- if ((0, _copilotkit_shared.isActionBinding)(value)) return false;
4043
- return Object.values(value).some(containsDynamicValue);
4044
- }
4045
- /**
4046
- * The `${...}` grammar of `formatString`:
4047
- *
4048
- * expression := path | literal | call
4049
- * path := "/" segments | identifier ("/" segments)*
4050
- * literal := 'text' | "text" | number | true | false | null
4051
- * call := identifier "(" [ name ":" expression ("," name ":" expression)* ] ")"
4052
- *
4053
- * A `\${` in the template is a literal `${`.
4054
- */
4055
- function formatString(template, state) {
4056
- let out = "";
4057
- let index = 0;
4058
- while (index < template.length) {
4059
- const start = template.indexOf("${", index);
4060
- if (start === -1) {
4061
- out += template.slice(index);
4062
- break;
4063
- }
4064
- if (start > 0 && template[start - 1] === "\\") {
4065
- out += `${template.slice(index, start - 1)}\${`;
4066
- index = start + 2;
4067
- continue;
4068
- }
4069
- out += template.slice(index, start);
4070
- const end = matchingBrace(template, start + 2);
4071
- if (end === -1) throw new ExpressionError("formatString: unclosed ${");
4072
- const value = new ExpressionParser(template.slice(start + 2, end).trim(), state).parse();
4073
- out += value === void 0 || value === null ? "" : String(value);
4074
- index = end + 1;
4075
- }
4076
- return out;
4077
- }
4078
- /** The index of the `}` that closes the block opened at `from`, or -1. */
4079
- function matchingBrace(template, from) {
4080
- let depth = 1;
4081
- let quote;
4082
- for (let i = from; i < template.length; i++) {
4083
- const char = template[i];
4084
- if (quote) {
4085
- if (char === "\\") i++;
4086
- else if (char === quote) quote = void 0;
4087
- continue;
4088
- }
4089
- if (char === "'" || char === "\"") quote = char;
4090
- else if (char === "{") depth++;
4091
- else if (char === "}" && --depth === 0) return i;
4092
- }
4093
- return -1;
4094
- }
4095
- const IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;
4096
- const NUMBER = /-?\d+(?:\.\d+)?/y;
4097
- const PATH_SEGMENT = /[^\s,():'"]+/y;
4098
- var ExpressionParser = class {
4099
- constructor(source, state) {
4100
- this.source = source;
4101
- this.state = state;
4102
- _defineProperty(this, "pos", 0);
4103
- }
4104
- parse() {
4105
- const value = this.expression();
4106
- this.skipSpace();
4107
- if (this.pos < this.source.length) throw new ExpressionError(`formatString: unexpected "${this.source.slice(this.pos)}" in \${${this.source}}`);
4108
- return value;
4109
- }
4110
- fail(what) {
4111
- throw new ExpressionError(`formatString: ${what} in \${${this.source}}`);
4112
- }
4113
- skipSpace() {
4114
- while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) this.pos++;
4115
- }
4116
- match(pattern) {
4117
- pattern.lastIndex = this.pos;
4118
- const found = pattern.exec(this.source);
4119
- if (!found) return void 0;
4120
- this.pos = pattern.lastIndex;
4121
- return found[0];
4122
- }
4123
- expression() {
4124
- this.skipSpace();
4125
- const char = this.source[this.pos];
4126
- if (char === void 0) this.fail("missing expression");
4127
- if (char === "'" || char === "\"") return this.quoted(char);
4128
- if (char === "/") return this.path(this.match(PATH_SEGMENT) ?? "/");
4129
- const number = this.match(NUMBER);
4130
- if (number !== void 0) return Number(number);
4131
- const name = this.match(IDENTIFIER);
4132
- if (name === void 0) this.fail(`unexpected "${char}"`);
4133
- if (name === "true") return true;
4134
- if (name === "false") return false;
4135
- if (name === "null") return null;
4136
- this.skipSpace();
4137
- if (this.source[this.pos] === "(") return this.call(name);
4138
- if (name.startsWith("@")) return call({ "@call": name }, this.state, false);
4139
- const rest = this.source[this.pos] === "/" ? this.match(PATH_SEGMENT) : "";
4140
- return this.path(`${name}${rest ?? ""}`);
4141
- }
4142
- quoted(quote) {
4143
- let value = "";
4144
- this.pos++;
4145
- while (this.pos < this.source.length) {
4146
- const char = this.source[this.pos++];
4147
- if (char === "\\" && this.pos < this.source.length) value += this.source[this.pos++];
4148
- else if (char === quote) return value;
4149
- else value += char;
4150
- }
4151
- return this.fail("unclosed string");
4152
- }
4153
- path(path) {
4154
- const absolute = resolvePath(path, this.state.context.basePath);
4155
- this.state.paths.add(absolute);
4156
- return this.state.context.data.get(absolute);
4157
- }
4158
- call(name) {
4159
- this.pos++;
4160
- const args = {};
4161
- this.skipSpace();
4162
- if (this.source[this.pos] === ")") {
4163
- this.pos++;
4164
- return call({
4165
- "@call": name,
4166
- args
4167
- }, this.state, false);
4168
- }
4169
- for (;;) {
4170
- this.skipSpace();
4171
- const key = this.match(IDENTIFIER);
4172
- if (key === void 0) this.fail("expected an argument name");
4173
- this.skipSpace();
4174
- if (this.source[this.pos] !== ":") this.fail(`expected ":" after ${key}`);
4175
- this.pos++;
4176
- args[key] = this.expression();
4177
- this.skipSpace();
4178
- const next = this.source[this.pos++];
4179
- if (next === ")") break;
4180
- if (next !== ",") this.fail(`expected "," or ")" after ${key}`);
4181
- }
4182
- return call({
4183
- "@call": name,
4184
- args
4185
- }, this.state, false);
4186
- }
4187
- };
4188
-
4189
- //#endregion
4190
- //#region src/generative-ui/schema.ts
4191
- const ASYNC_ISSUE = { message: "the schema validates asynchronously; component props and state need a schema that validates synchronously" };
4192
- function toResult(result) {
4193
- return result.issues ? {
4194
- success: false,
4195
- issues: result.issues
4196
- } : {
4197
- success: true,
4198
- data: result.value
4199
- };
4200
- }
4201
- /**
4202
- * Validates `value` with `schema`. The result comes back at once when the
4203
- * schema validates synchronously, else as a promise.
4204
- */
4205
- function validateSchema(schema, value) {
4206
- const result = schema["~standard"].validate(value);
4207
- return result instanceof Promise ? result.then(toResult) : toResult(result);
4208
- }
4209
- /**
4210
- * Validates `value` synchronously, for code that runs during render. A
4211
- * schema that validates asynchronously fails with an issue that says so.
4212
- */
4213
- function validateSchemaSync(schema, value) {
4214
- const result = validateSchema(schema, value);
4215
- if (!(result instanceof Promise)) return result;
4216
- result.catch(() => {});
4217
- return {
4218
- success: false,
4219
- issues: [ASYNC_ISSUE]
4220
- };
4221
- }
4222
- /** True for the issue that `validateSchemaSync` gives for an async schema. */
4223
- function isAsyncIssue(issue) {
4224
- return issue === ASYNC_ISSUE;
4225
- }
4226
- /** The first key of an issue path: the prop the issue is about. */
4227
- function issueKey(issue) {
4228
- const first = issue.path?.[0];
4229
- const key = typeof first === "object" ? first.key : first;
4230
- return key === void 0 ? void 0 : String(key);
4231
- }
4232
- /**
4233
- * `props` without the top-level props whose `null` the schema rejected, or
4234
- * `undefined` when there are none. A model writes `null` for "not set" (an
4235
- * empty selection, a value it has not filled yet), and A2UI deletes a data
4236
- * model key that is set to `null`, so a rejected `null` is read as an unset
4237
- * prop. A prop whose schema accepts `null` keeps it.
4238
- */
4239
- function withoutRejectedNulls(props, issues) {
4240
- const rejected = /* @__PURE__ */ new Set();
4241
- for (const issue of issues) {
4242
- const key = issueKey(issue);
4243
- if (key !== void 0 && issue.path?.length === 1 && props[key] === null) rejected.add(key);
4244
- }
4245
- if (rejected.size === 0) return void 0;
4246
- return Object.fromEntries(Object.entries(props).filter(([key]) => !rejected.has(key)));
4247
- }
4248
- /** `"a.b: message; c: message"`. A path-less issue gets `fallback`. */
4249
- function formatIssues(issues, fallback = "props") {
4250
- return issues.map((issue) => {
4251
- return `${(issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".") || fallback}: ${issue.message}`;
4252
- }).join("; ");
4253
- }
4254
-
4255
- //#endregion
4256
- //#region src/generative-ui/surface-manager.ts
4257
- function surfaceKey(threadId, surfaceId) {
4258
- return `${threadId}::${surfaceId}`;
4259
- }
4260
- let creationCounter = 0;
4261
- const FORBIDDEN_SEGMENTS = new Set([
4262
- "__proto__",
4263
- "constructor",
4264
- "prototype"
4265
- ]);
4266
- /** "/a/b/" to "/a/b". The root stays "/". */
4267
- function normalizePath(path) {
4268
- return (path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path) || "/";
4269
- }
4270
- /** True when `path` is `ancestor` or below it. */
4271
- function isAtOrBelow(path, ancestor) {
4272
- if (ancestor === "/") return true;
4273
- return path === ancestor || path.startsWith(`${ancestor}/`);
4274
- }
4275
- /**
4276
- * Rejections as `"operation <index>: <reason>"` lines, cut to the size that
4277
- * the envelope reader accepts.
4278
- */
4279
- function summarizeRejections(rejections) {
4280
- 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));
4281
- }
4282
- /**
4283
- * Framework-agnostic store of generated surfaces. One web_core SurfaceModel per
4284
- * (threadId, surfaceId), shared by every mount. Applies only newly committed
4285
- * operations, validates each before applying it, and owns app state and the
4286
- * data model paths that the user wrote, so agent updates cannot overwrite
4287
- * them. App state never goes into a surface's data model. Selectors read it
4288
- * with `getState()`.
4289
- */
4290
- var GenerativeUISurfaceManager = class {
4291
- constructor(ui, options = {}) {
4292
- this.ui = ui;
4293
- this.options = options;
4294
- _defineProperty(this, "surfaces", /* @__PURE__ */ new Map());
4295
- _defineProperty(this, "bookkeeping", /* @__PURE__ */ new Map());
4296
- _defineProperty(this, "listeners", /* @__PURE__ */ new Set());
4297
- _defineProperty(this, "targets", /* @__PURE__ */ new Map());
4298
- _defineProperty(this, "state", {});
4299
- _defineProperty(this, "owned", /* @__PURE__ */ new Map());
4300
- _defineProperty(this, "deletedKeys", /* @__PURE__ */ new Set());
4301
- _defineProperty(this, "linked", /* @__PURE__ */ new Map());
4302
- _defineProperty(this, "webCoreCatalog", void 0);
4303
- _defineProperty(this, "activeThreadId", void 0);
4304
- _defineProperty(this, "version", 0);
4305
- _defineProperty(this, "subscribe", (listener) => {
4306
- this.listeners.add(listener);
4307
- return () => {
4308
- this.listeners.delete(listener);
4309
- };
4310
- });
4311
- _defineProperty(this, "getVersion", () => this.version);
4312
- _defineProperty(
4313
- this,
4314
- /**
4315
- * The app state object. It is the same object until a key changes, so it
4316
- * can be a `useSyncExternalStore` snapshot.
4317
- */
4318
- "getState",
4319
- () => this.state
4320
- );
4321
- this.webCoreCatalog = new _a2ui_web_core_v0_9.Catalog(ui.id, [...ui.components.keys()].map((name) => ({
4322
- name,
4323
- schema: zod.any()
4324
- })), []);
4325
- }
4326
- notify() {
4327
- this.version++;
4328
- for (const listener of [...this.listeners]) listener();
4329
- }
4330
- setActiveThread(threadId) {
4331
- if (threadId === this.activeThreadId) return;
4332
- this.activeThreadId = threadId;
4333
- this.notify();
4334
- }
4335
- getActiveThread() {
4336
- return this.activeThreadId;
4337
- }
4338
- ingest(threadId, agentId, content) {
4339
- const key = surfaceKey(threadId, content.surfaceId);
4340
- const operations = content.operations ?? [];
4341
- let surface = this.surfaces.get(key);
4342
- let book = this.bookkeeping.get(key);
4343
- let changed = false;
4344
- if (surface && book && !this.extendsApplied(book, operations)) {
4345
- this.disposeSurface(key);
4346
- surface = void 0;
4347
- book = void 0;
4348
- }
4349
- if (!surface || !book) {
4350
- surface = this.createSurface(key, threadId, agentId, content);
4351
- this.restoreOwnedValues(surface);
4352
- book = {
4353
- appliedCount: 0,
4354
- lastFingerprint: void 0
4355
- };
4356
- this.surfaces.set(key, surface);
4357
- this.bookkeeping.set(key, book);
4358
- changed = true;
4359
- }
4360
- const serverRejected = content.rejected ?? [];
4361
- if (surface.clientRejected.length > 0 && (surface.status !== "streaming" && content.status === "streaming" || serverRejected.length < surface.serverRejected.length)) {
4362
- surface.clientRejected = [];
4363
- changed = true;
4364
- }
4365
- if (operations.length > 0) {
4366
- const lastFingerprint = JSON.stringify(operations[operations.length - 1]);
4367
- const isReplay = operations.some((op) => (0, _copilotkit_shared.getOperationKind)(op) === "deleteSurface");
4368
- for (let index = book.appliedCount; index < operations.length; index++) {
4369
- this.applyOperation(surface, operations[index], {
4370
- index,
4371
- isReplay
4372
- });
4373
- changed = true;
4374
- }
4375
- book.appliedCount = operations.length;
4376
- surface.operations = operations;
4377
- book.lastFingerprint = lastFingerprint;
4378
- }
4379
- if (surface.status !== content.status || surface.target !== content.target || surface.serverRejected.length !== serverRejected.length) {
4380
- surface.status = content.status;
4381
- surface.target = content.target;
4382
- surface.serverRejected = serverRejected;
4383
- changed = true;
4384
- }
4385
- if (changed) this.notify();
4386
- }
4387
- /** The surface of a `key` (see `surfaceKey`), unless it is deleted. */
4388
- getSurfaceByKey(key) {
4389
- const surface = this.surfaces.get(key);
4390
- return surface && !surface.deleted ? surface : void 0;
4391
- }
4392
- getSurface(threadId, surfaceId) {
4393
- const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
4394
- return surface && !surface.deleted ? surface : void 0;
4395
- }
4396
- getSurfaceForTarget(target, threadId = this.activeThreadId) {
4397
- if (!threadId) return void 0;
4398
- let latest;
4399
- for (const surface of this.surfaces.values()) {
4400
- if (surface.threadId !== threadId || surface.target !== target || surface.deleted) continue;
4401
- if (!latest || surface.createdAt > latest.createdAt) latest = surface;
4402
- }
4403
- return latest;
4404
- }
4405
- /**
4406
- * A surface whose first createSurface was rejected, so the chat can show
4407
- * the error where the surface would be. `undefined` for any other surface.
4408
- */
4409
- getFailedSurface(threadId, surfaceId) {
4410
- const surface = this.surfaces.get(surfaceKey(threadId, surfaceId));
4411
- return surface?.failed ? surface : void 0;
4412
- }
4413
- /**
4414
- * The surfaces of a thread, for the model. A surface with user-owned
4415
- * values lists them in `dataModel`, so the model can read what the user
4416
- * entered. A surface with dropped operations lists them in `rejected`, so
4417
- * the model can fix them on the next run. A deleted surface, or one that
4418
- * was never created, has a `status`, so the model knows that the id is
4419
- * not a live surface.
4420
- */
4421
- describeSurfaces(threadId) {
4422
- const described = {};
4423
- for (const surface of this.surfaces.values()) {
4424
- if (surface.threadId !== threadId) continue;
4425
- const owned = this.owned.get(surface.key);
4426
- const rejections = [...surface.serverRejected, ...surface.clientRejected];
4427
- const status = this.deletedKeys.has(surface.key) ? "deleted" : surface.failed ? "failed" : void 0;
4428
- described[surface.surfaceId] = {
4429
- target: surface.target,
4430
- ...owned && owned.size > 0 ? { dataModel: Object.fromEntries(owned) } : {},
4431
- ...rejections.length > 0 && status !== "deleted" ? { rejected: summarizeRejections(rejections) } : {},
4432
- ...status ? { status } : {}
4433
- };
4434
- }
4435
- return described;
4436
- }
4437
- /** Every surface that is not deleted, oldest first, for the inspector. */
4438
- debugSurfaces() {
4439
- return [...this.surfaces.values()].filter((surface) => !surface.deleted).sort((a, b) => a.createdAt - b.createdAt).map((surface) => ({
4440
- surfaceId: surface.surfaceId,
4441
- threadId: surface.threadId,
4442
- agentId: surface.agentId,
4443
- target: surface.target,
4444
- status: surface.status,
4445
- operations: surface.operations,
4446
- dataModel: surface.model.dataModel.get("/"),
4447
- userValues: Object.fromEntries(this.owned.get(surface.key) ?? []),
4448
- rejected: [...surface.serverRejected.map((r) => ({
4449
- ...r,
4450
- source: "runtime"
4451
- })), ...surface.clientRejected.map((r) => ({
4452
- ...r,
4453
- source: "browser"
4454
- }))]
4455
- }));
4456
- }
4457
- /**
4458
- * Marks a target as mounted. Returns the function that unmounts it. Calling
4459
- * that function more than once has no effect.
4460
- *
4461
- * @param id - The target id.
4462
- * @param options - The description and the allowed components of this mount.
4463
- */
4464
- registerTarget(id, options = {}) {
4465
- const registration = { ...options };
4466
- const registrations = this.targets.get(id) ?? /* @__PURE__ */ new Set();
4467
- registrations.add(registration);
4468
- this.targets.set(id, registrations);
4469
- this.notify();
4470
- let released = false;
4471
- return () => {
4472
- if (released) return;
4473
- released = true;
4474
- registrations.delete(registration);
4475
- if (registrations.size === 0) this.targets.delete(id);
4476
- this.notify();
4477
- };
4478
- }
4479
- /**
4480
- * The mounted targets. Each has the description and the component list of
4481
- * its earliest mount that has one.
4482
- */
4483
- getMountedTargets() {
4484
- const mounted = [];
4485
- for (const [id, registrations] of this.targets) {
4486
- const description = [...registrations].find((registration) => registration.description !== void 0)?.description;
4487
- const components = this.targetComponents(id);
4488
- mounted.push({
4489
- id,
4490
- ...description === void 0 ? {} : { description },
4491
- ...components === void 0 ? {} : { components: [...components] }
4492
- });
4493
- }
4494
- return mounted;
4495
- }
4496
- /**
4497
- * The component list of the earliest mount of `id` that has one.
4498
- * `undefined` when no mount of `id` limits its components.
4499
- */
4500
- targetComponents(id) {
4501
- return [...this.targets.get(id) ?? /* @__PURE__ */ new Set()].find((registration) => registration.components !== void 0)?.components;
4502
- }
4503
- /** The components that `validateOperation` allows on a surface. */
4504
- allowedComponentsFor(surface) {
4505
- const components = this.targetComponents(surface.target);
4506
- return components === void 0 ? void 0 : {
4507
- target: surface.target,
4508
- names: new Set(components)
4509
- };
4510
- }
4511
- /** Sets one state key. Notifies only when the value changed. */
4512
- setState(key, value) {
4513
- if (Object.hasOwn(this.state, key) && Object.is(this.state[key], value)) return;
4514
- this.state = {
4515
- ...this.state,
4516
- [key]: value
4517
- };
4518
- this.notify();
4519
- }
4520
- /** Removes one state key. Notifies only when the key was set. */
4521
- removeState(key) {
4522
- if (!Object.hasOwn(this.state, key)) return;
4523
- const { [key]: _removed, ...rest } = this.state;
4524
- this.state = rest;
4525
- this.notify();
4526
- }
4527
- /**
4528
- * Makes the surfaces of `surfaceIds` share their data model: a user write
4529
- * to one of them goes to all of them (see `setOwnedValue`). The markdown
4530
- * transport links the parts of a chat surface that the prose lift split.
4531
- * A later call for one of the surfaces replaces its group.
4532
- *
4533
- * @param threadId - The thread of the surfaces.
4534
- * @param surfaceIds - The surface ids of the group. One id clears a link.
4535
- */
4536
- linkSurfaces(threadId, surfaceIds) {
4537
- const keys = new Set(surfaceIds.map((id) => surfaceKey(threadId, id)));
4538
- for (const key of keys) if (keys.size > 1) this.linked.set(key, keys);
4539
- else this.linked.delete(key);
4540
- }
4541
- /**
4542
- * Writes a user value into the data model of a surface, and marks `path`
4543
- * as user-owned. Then agent writes to that path, or below it, are ignored.
4544
- * An agent write above it keeps the user value. Ownership ends when the
4545
- * surface is deleted. Does nothing for an unknown or deleted surface. The
4546
- * surfaces linked to it (see `linkSurfaces`) get the same write.
4547
- *
4548
- * @param key - The `key` of the surface.
4549
- * @param path - An absolute JSON pointer, for example "/form/email".
4550
- * @param value - The new value. It is copied.
4551
- * @throws Error when a path segment is "__proto__", "constructor" or
4552
- * "prototype", or when the path does not fit the data (for example, a
4553
- * segment above it holds a string).
4554
- */
4555
- setOwnedValue(key, path, value) {
4556
- const normalized = normalizePath(path);
4557
- const forbidden = normalized.split("/").find((segment) => FORBIDDEN_SEGMENTS.has(segment));
4558
- if (forbidden !== void 0) throw new Error(`[generativeUI] path segment "${forbidden}" is not allowed in "${path}".`);
4559
- for (const target of this.linked.get(key) ?? [key]) this.writeOwnedValue(target, normalized, value);
4560
- }
4561
- writeOwnedValue(key, path, value) {
4562
- const surface = this.surfaces.get(key);
4563
- if (!surface || surface.deleted) return;
4564
- surface.model.dataModel.set(path, structuredClone(value));
4565
- const owned = this.owned.get(key) ?? /* @__PURE__ */ new Map();
4566
- owned.set(path, structuredClone(value));
4567
- this.owned.set(key, owned);
4568
- }
4569
- /**
4570
- * Writes the user-owned values into the new, empty data model of a rebuilt
4571
- * surface. The agent operations are applied after it.
4572
- */
4573
- restoreOwnedValues(surface) {
4574
- const owned = this.owned.get(surface.key) ?? /* @__PURE__ */ new Map();
4575
- for (const [path, value] of owned) surface.model.dataModel.set(path, structuredClone(value));
4576
- }
4577
- /**
4578
- * The value that an agent write puts at `path`, with the user-owned values
4579
- * below `path` written back into it. `undefined` when `path` is user-owned
4580
- * or below a user-owned path, so the agent cannot write it. Throws when a
4581
- * user value does not fit the new value.
4582
- */
4583
- mergeOwnedValues(key, path, value) {
4584
- const merged = { value: structuredClone(value) };
4585
- const owned = this.owned.get(key);
4586
- if (!owned) return merged;
4587
- const ownedPaths = [...owned.keys()];
4588
- if (ownedPaths.some((ownedPath) => isAtOrBelow(path, ownedPath))) return void 0;
4589
- const below = ownedPaths.filter((ownedPath) => isAtOrBelow(ownedPath, path));
4590
- if (below.length === 0) return merged;
4591
- const scratch = new _a2ui_web_core_v0_9.DataModel({ value: merged.value });
4592
- const prefix = path === "/" ? "" : path;
4593
- for (const ownedPath of below) {
4594
- const relative = ownedPath.slice(prefix.length);
4595
- scratch.set(`/value${relative}`, structuredClone(owned.get(ownedPath)));
4596
- }
4597
- return { value: scratch.get("/value") };
4598
- }
4599
- extendsApplied(book, operations) {
4600
- if (operations.length < book.appliedCount) return false;
4601
- if (book.appliedCount === 0) return true;
4602
- return JSON.stringify(operations[book.appliedCount - 1]) === book.lastFingerprint;
4603
- }
4604
- createSurface(key, threadId, agentId, content) {
4605
- return {
4606
- key,
4607
- threadId,
4608
- surfaceId: content.surfaceId,
4609
- agentId,
4610
- model: new _a2ui_web_core_v0_9.SurfaceModel(content.surfaceId, this.webCoreCatalog),
4611
- createdAt: ++creationCounter,
4612
- target: content.target,
4613
- status: content.status,
4614
- deleted: false,
4615
- failed: false,
4616
- serverRejected: content.rejected ?? [],
4617
- clientRejected: [],
4618
- operations: []
4619
- };
4620
- }
4621
- disposeSurface(key) {
4622
- this.surfaces.get(key)?.model.dispose();
4623
- this.surfaces.delete(key);
4624
- this.bookkeeping.delete(key);
4625
- }
4626
- /**
4627
- * Marks a surface deleted and frees its components and data. The record
4628
- * stays, so the model is still told about the id and the bookkeeping does
4629
- * not rebuild the surface for content that was already applied.
4630
- */
4631
- closeSurface(surface) {
4632
- surface.deleted = true;
4633
- surface.model.dispose();
4634
- surface.model = new _a2ui_web_core_v0_9.SurfaceModel(surface.surfaceId, this.webCoreCatalog);
4635
- this.owned.delete(surface.key);
4636
- this.linked.delete(surface.key);
4637
- }
4638
- /** The surfaces of a thread that a part of `surfaceId` reads, for tests. */
4639
- getLinkedSurfaceIds(threadId, surfaceId) {
4640
- const keys = this.linked.get(surfaceKey(threadId, surfaceId));
4641
- if (!keys) return [surfaceId];
4642
- const prefix = `${threadId}::`;
4643
- return [...keys].map((key) => key.slice(prefix.length));
4644
- }
4645
- /**
4646
- * Drops the node keys that the app sets: bound props and matched events.
4647
- * The model does not see them, so a model value for one is ignored, not
4648
- * rejected. This runs before validation, because validation rejects keys
4649
- * that are not in the manifest. It never changes the given operation.
4650
- */
4651
- dropAppSetKeys(op) {
4652
- const kind = (0, _copilotkit_shared.getOperationKind)(op);
4653
- if (kind !== "updateComponents" && kind !== "createSurface") return op;
4654
- const record = op;
4655
- const payload = record[kind];
4656
- const nodes = payload?.components;
4657
- if (!Array.isArray(nodes)) return op;
4658
- return {
4659
- ...record,
4660
- [kind]: {
4661
- ...payload,
4662
- components: nodes.map((node) => this.dropAppSetNodeKeys(node))
4663
- }
4664
- };
4665
- }
4666
- dropAppSetNodeKeys(node) {
4667
- if (typeof node !== "object" || node === null || !("component" in node)) return node;
4668
- const { component } = node;
4669
- if (typeof component !== "string") return node;
4670
- const definition = this.ui.components.get(component);
4671
- if (!definition) return node;
4672
- return Object.fromEntries(Object.entries(node).filter(([key]) => !Object.hasOwn(definition.selectors, key) && !Object.hasOwn(definition.eventFunctions, key)));
4673
- }
4674
- /**
4675
- * The surfaces that `validateOperation` gets for one operation of the
4676
- * content of `surface`.
4677
- *
4678
- * - `knownSurfaces`: the surface, when it exists before the operation. It
4679
- * does not exist before its first createSurface, or after a delete.
4680
- * - `createdSurfaces`: the surface, when a createSurface at this position
4681
- * uses its id again. That is the case after the first operation, and for
4682
- * a surface that was deleted before, unless the content replays that
4683
- * delete.
4684
- */
4685
- surfacesFor(surface, kind, position) {
4686
- const isFirstCreate = kind === "createSurface" && position.index === 0;
4687
- const exists = !surface.deleted && !isFirstCreate;
4688
- const isRecreate = this.deletedKeys.has(surface.key) && !position.isReplay;
4689
- const isUsedAgain = position.index > 0 || isRecreate;
4690
- return {
4691
- knownSurfaces: new Set(exists ? [surface.surfaceId] : []),
4692
- createdSurfaces: new Set(isUsedAgain ? [surface.surfaceId] : [])
4693
- };
4694
- }
4695
- applyOperation(surface, received, position) {
4696
- const { index } = position;
4697
- const kind = (0, _copilotkit_shared.getOperationKind)(received);
4698
- if (kind === "callRendererFunction") return;
4699
- const reject = (reason) => {
4700
- if (kind === "createSurface" && index === 0) {
4701
- this.closeSurface(surface);
4702
- surface.failed = true;
2022
+ //#region src/generative-ui/markdown/context.ts
2023
+ /**
2024
+ * Registers the two context entries of the markdown transport: the compact
2025
+ * component schema and the fence guideline. Both go only to `agentIds`.
2026
+ *
2027
+ * The schema is built again at each run start and when a
2028
+ * `<GenerativeUISurface>` mounts, unmounts, or changes its description or
2029
+ * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
2030
+ *
2031
+ * @param copilotkit - The CopilotKit core of the provider.
2032
+ * @param runtime - The generative UI runtime parts, or null without one.
2033
+ * @param options - `enabled` and `agentIds`.
2034
+ *
2035
+ * @example
2036
+ * ```ts
2037
+ * useGenerativeUIMarkdownContext(copilotkit, core, {
2038
+ * enabled: config?.transport === "markdown" && config.sendContext !== false,
2039
+ * agentIds: config?.agentIds,
2040
+ * });
2041
+ * ```
2042
+ */
2043
+ function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
2044
+ const { enabled, agentIds } = options;
2045
+ const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
2046
+ (0, react.useEffect)(() => {
2047
+ if (!runtime || !enabled) return;
2048
+ const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
2049
+ const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
2050
+ let guidelineId;
2051
+ let guidelineValue;
2052
+ let schemaId;
2053
+ let schemaValue;
2054
+ const refreshSchema = (threadId) => {
2055
+ const manifest = (0, _copilotkit_core_generative_ui.buildGenerativeUIManifest)(runtime, threadId);
2056
+ const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
2057
+ if (guideline !== guidelineValue) {
2058
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
2059
+ guidelineValue = guideline;
2060
+ guidelineId = copilotkit.addContext({
2061
+ description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
2062
+ value: guideline,
2063
+ ...scope
2064
+ });
4703
2065
  }
4704
- surface.clientRejected.push({
4705
- index,
4706
- reason
4707
- });
4708
- this.options.onOperationRejected?.({
4709
- surfaceId: surface.surfaceId,
4710
- index,
4711
- reason
2066
+ const value = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
2067
+ if (value === schemaValue) return;
2068
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
2069
+ schemaValue = value;
2070
+ schemaId = copilotkit.addContext({
2071
+ description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
2072
+ value,
2073
+ ...scope
4712
2074
  });
4713
2075
  };
4714
- const targetId = (0, _copilotkit_shared.getOperationSurfaceId)(received);
4715
- if (targetId !== void 0 && targetId !== surface.surfaceId) return reject(`operation is for surface "${targetId}", not "${surface.surfaceId}"`);
4716
- const op = this.dropAppSetKeys(received);
4717
- const validation = (0, _copilotkit_shared.validateOperation)(op, {
4718
- manifest: {
4719
- catalogId: this.ui.id,
4720
- catalogIds: catalogIdsOf(this.ui),
4721
- components: this.ui.manifestComponents
4722
- },
4723
- ...this.surfacesFor(surface, kind, position),
4724
- allowedComponents: this.allowedComponentsFor(surface)
4725
- });
4726
- if (!validation.ok) return reject(validation.reason);
4727
- const typed = op;
4728
- if ("createSurface" in typed) {
4729
- const { dataModel, components = [] } = typed.createSurface;
4730
- const problem = this.nodesProblem(components);
4731
- if (problem) return reject(problem);
4732
- if (dataModel) {
4733
- const failure = this.writeAgentData(surface, "/", dataModel);
4734
- if (failure) return reject(failure);
4735
- }
4736
- for (const node of components) this.upsertNode(surface.model, node);
4737
- return;
4738
- }
4739
- if ("updateComponents" in typed) {
4740
- const nodes = typed.updateComponents.components;
4741
- const problem = this.nodesProblem(nodes);
4742
- if (problem) return reject(problem);
4743
- for (const node of nodes) this.upsertNode(surface.model, node);
4744
- return;
4745
- }
4746
- if ("updateDataModel" in typed) {
4747
- const { path = "/", value } = typed.updateDataModel;
4748
- const written = value === null ? void 0 : value;
4749
- const failure = this.writeAgentData(surface, normalizePath(path), written);
4750
- if (failure) return reject(failure);
4751
- return;
4752
- }
4753
- if ("deleteSurface" in typed) {
4754
- this.closeSurface(surface);
4755
- this.deletedKeys.add(surface.key);
4756
- }
4757
- }
4758
- /** The first node with props of the wrong type, as a reason. */
4759
- nodesProblem(nodes) {
4760
- for (const node of nodes) {
4761
- const problem = this.checkNodeProps(node);
4762
- if (problem) return `component "${node.id}": ${problem}`;
4763
- }
4764
- }
4765
- /**
4766
- * Writes an agent value at `path` and keeps the user-owned values. A write
4767
- * to a user-owned path is ignored, not rejected. Gives the reason when the
4768
- * value does not fit the data, else `undefined`.
4769
- */
4770
- writeAgentData(surface, path, value) {
4771
- try {
4772
- const merged = this.mergeOwnedValues(surface.key, path, value);
4773
- if (merged) surface.model.dataModel.set(path, merged.value);
4774
- return;
4775
- } catch (error) {
4776
- return error instanceof Error ? error.message : String(error);
4777
- }
4778
- }
4779
- checkNodeProps(node) {
4780
- const definition = this.ui.components.get(node.component);
4781
- if (!definition) return `unknown component "${node.component}"`;
4782
- const { id: _id, component: _component, ...rest } = node;
4783
- const dataProps = Object.fromEntries(Object.entries(rest).filter(([key]) => !definition.events?.[key] && !definition.slots?.[key] && !_copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS.has(key)));
4784
- if (!definition.props) return void 0;
4785
- const unknownNow = new Set(Object.keys(definition.selectors));
4786
- const literals = {};
4787
- for (const [key, value] of Object.entries(dataProps)) if (containsDynamicValue(value)) unknownNow.add(key);
4788
- else literals[key] = value;
4789
- let result = validateSchemaSync(definition.props, literals);
4790
- if (!result.success) {
4791
- const unset = withoutRejectedNulls(literals, result.issues);
4792
- if (unset) result = validateSchemaSync(definition.props, unset);
4793
- }
4794
- if (result.success) return void 0;
4795
- const issues = result.issues.filter((issue) => {
4796
- const key = issueKey(issue);
4797
- return key === void 0 ? isAsyncIssue(issue) : !unknownNow.has(key);
2076
+ refreshSchema(runtime.manager.getActiveThread());
2077
+ let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
2078
+ const unsubscribeManager = runtime.manager.subscribe(() => {
2079
+ const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
2080
+ if (nextKey === targetsKey) return;
2081
+ targetsKey = nextKey;
2082
+ refreshSchema(runtime.manager.getActiveThread());
4798
2083
  });
4799
- return issues.length > 0 ? formatIssues(issues) : void 0;
4800
- }
4801
- upsertNode(model, node) {
4802
- const { id, component, ...rest } = node;
4803
- const properties = structuredClone(rest);
4804
- const existing = model.componentsModel.get(id);
4805
- if (existing && existing.type === component) {
4806
- existing.properties = properties;
4807
- return;
4808
- }
4809
- if (existing) model.componentsModel.removeComponent(id);
4810
- model.componentsModel.addComponent(new _a2ui_web_core_v0_9.ComponentModel(id, component, properties));
4811
- }
4812
- };
2084
+ const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
2085
+ return () => {
2086
+ subscription.unsubscribe();
2087
+ unsubscribeManager();
2088
+ if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
2089
+ if (schemaId !== void 0) copilotkit.removeContext(schemaId);
2090
+ };
2091
+ }, [
2092
+ copilotkit,
2093
+ runtime,
2094
+ enabled,
2095
+ agentIdsKey
2096
+ ]);
2097
+ }
4813
2098
 
4814
2099
  //#endregion
4815
2100
  //#region src/generative-ui/use-generative-ui-root.ts
4816
2101
  const isDevelopment = () => process.env.NODE_ENV !== "production";
4817
- /** At most this many function follow-up runs for each user turn. */
4818
- const MAX_FUNCTION_FOLLOW_UPS = 5;
4819
2102
  function ingestMessages(manager, agent, messages) {
4820
2103
  if (!agent.threadId) return;
4821
2104
  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);
4822
2105
  }
4823
- /** What the envelope of a run says, from the provider config. */
4824
- function envelopeOptionsFor(config) {
4825
- if (config.transport === "markdown") return {
4826
- transport: "markdown",
4827
- includeCatalog: config.includeCatalog !== false,
4828
- contextSent: config.sendContext !== false
4829
- };
4830
- return {
4831
- transport: "tool",
4832
- includeCatalog: true,
4833
- contextSent: false
4834
- };
4835
- }
4836
- /**
4837
- * The components of a surface as one `updateComponents` operation, so that
4838
- * the label of the component that sent an event can be found.
4839
- */
4840
- function surfaceComponents(surface) {
4841
- const components = [...surface.model.componentsModel.entries].map(([id, model]) => ({
4842
- ...model.properties,
4843
- id,
4844
- component: model.type
4845
- }));
4846
- return [{
4847
- version: _copilotkit_shared.A2UI_VERSION,
4848
- updateComponents: {
4849
- surfaceId: surface.surfaceId,
4850
- components
4851
- }
4852
- }];
4853
- }
4854
- /** True when `value` names a `functionCallId`. */
4855
- function hasFunctionCallId(value) {
4856
- return typeof value === "object" && value !== null && "functionCallId" in value && typeof value.functionCallId === "string" && value.functionCallId !== "";
4857
- }
4858
- /** The `functionCallId` that a developer message answers, if any. */
4859
- function answeredCallId(content) {
4860
- if (!content.includes("rendererFunctionResponse")) return void 0;
4861
- try {
4862
- const parsed = JSON.parse(content);
4863
- const response = typeof parsed === "object" && parsed !== null && "rendererFunctionResponse" in parsed ? parsed.rendererFunctionResponse : void 0;
4864
- return hasFunctionCallId(response) ? response.functionCallId : void 0;
4865
- } catch {
4866
- return;
4867
- }
4868
- }
4869
- /** The function calls that a developer message in `messages` answers. */
4870
- function answeredCallIds(messages) {
4871
- const ids = /* @__PURE__ */ new Set();
4872
- for (const message of messages) {
4873
- if (message.role !== "developer") continue;
4874
- const id = answeredCallId(message.content);
4875
- if (id !== void 0) ids.add(id);
4876
- }
4877
- return ids;
4878
- }
4879
- /** The id of the last user message. A user turn starts with it. */
4880
- function lastUserMessageId(messages) {
4881
- for (let index = messages.length - 1; index >= 0; index--) {
4882
- const message = messages[index];
4883
- if (message?.role === "user") return message.id;
4884
- }
4885
- }
4886
- /** The function calls of the tool transport: its function-call activities. */
4887
- function activityFunctionCalls(messages) {
4888
- const requests = [];
4889
- for (const message of messages) {
4890
- if (!(message.role === "activity" && message.activityType === _copilotkit_shared.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE) || !hasFunctionCallId(message.content)) continue;
4891
- requests.push({
4892
- functionCallId: message.content.functionCallId,
4893
- operation: {
4894
- version: _copilotkit_shared.A2UI_VERSION,
4895
- callRendererFunction: message.content
4896
- }
4897
- });
4898
- }
4899
- return requests;
4900
- }
4901
- /** The function calls of the markdown transport: its fence lines. */
4902
- function markdownFunctionCalls(calls) {
4903
- const requests = [];
4904
- for (const { operation } of calls) {
4905
- const payload = operation.callRendererFunction;
4906
- if (!hasFunctionCallId(payload)) continue;
4907
- requests.push({
4908
- functionCallId: payload.functionCallId,
4909
- operation
4910
- });
4911
- }
4912
- return requests;
4913
- }
4914
- /** The text of a `rendererFunctionResponse` developer message. */
4915
- function responseContent(response) {
4916
- return JSON.stringify({
4917
- version: _copilotkit_shared.A2UI_VERSION,
4918
- rendererFunctionResponse: response
4919
- });
4920
- }
4921
- function errorAnswer(functionCallId, code, message) {
4922
- return {
4923
- content: responseContent({
4924
- functionCallId,
4925
- error: {
4926
- code,
4927
- message
4928
- }
4929
- }),
4930
- followUp: true
4931
- };
4932
- }
4933
- const overCapAnswer = (functionCallId) => ({
4934
- content: responseContent({
4935
- functionCallId,
4936
- error: {
4937
- code: "follow_up_limit",
4938
- 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.`
4939
- }
4940
- }),
4941
- followUp: false
4942
- });
4943
- /**
4944
- * Runs the functions that the agent calls with `callRendererFunction`, for
4945
- * both transports, and answers each call.
4946
- *
4947
- * - Each `functionCallId` runs once for each thread. A replay, a sync of
4948
- * the same messages again, or a call that already has an answer message
4949
- * does not run it again.
4950
- * - The answer is a hidden developer message with a `rendererFunctionResponse`.
4951
- * The answers go to the agent only when it is not running. Then one
4952
- * follow-up run starts for all of them.
4953
- * - A user turn has at most {@link MAX_FUNCTION_FOLLOW_UPS} follow-up runs.
4954
- * A call after that does not run. It gets a `follow_up_limit` error and
4955
- * starts no follow-up run.
4956
- */
4957
- function createFunctionCallRunner(options) {
4958
- const { copilotkit, dispatcher, manifest } = options;
4959
- const threads = /* @__PURE__ */ new Map();
4960
- const threadState = (threadId) => {
4961
- let state = threads.get(threadId);
4962
- if (!state) {
4963
- state = {
4964
- done: /* @__PURE__ */ new Set(),
4965
- pending: [],
4966
- turn: void 0,
4967
- followUps: 0,
4968
- flushing: false
4969
- };
4970
- threads.set(threadId, state);
4971
- }
4972
- return state;
4973
- };
4974
- const answer = async (request) => {
4975
- const { functionCallId } = request;
4976
- const validation = (0, _copilotkit_shared.validateOperation)(request.operation, {
4977
- manifest,
4978
- knownSurfaces: /* @__PURE__ */ new Set()
4979
- });
4980
- if (!validation.ok) return errorAnswer(functionCallId, "invalid_arguments", validation.reason);
4981
- const operation = request.operation;
4982
- if (!("callRendererFunction" in operation)) return errorAnswer(functionCallId, "invalid_arguments", "the operation is not a callRendererFunction");
4983
- const { callFunction } = operation.callRendererFunction;
4984
- const name = callFunction["@call"];
4985
- const result = await dispatcher.invoke(name, callFunction.args ?? {}, { functionCallId });
4986
- if (!result.ok) return errorAnswer(functionCallId, result.error.code, result.error.message);
4987
- try {
4988
- return {
4989
- content: responseContent({
4990
- functionCallId,
4991
- value: result.result ?? null
4992
- }),
4993
- followUp: true
4994
- };
4995
- } catch (cause) {
4996
- return errorAnswer(functionCallId, "handler_failed", `The result of "${name}" is not JSON: ${cause instanceof Error ? cause.message : String(cause)}`);
4997
- }
4998
- };
4999
- /**
5000
- * Adds the pending answers of a thread to the agent, then starts one
5001
- * follow-up run. It waits while the agent runs: the next read of the
5002
- * thread, at the end of the run, flushes again.
5003
- */
5004
- const flush = async (agent, threadId, state) => {
5005
- if (state.flushing) return;
5006
- state.flushing = true;
5007
- try {
5008
- while (state.pending.length > 0) {
5009
- const batch = [...state.pending];
5010
- const answers = await Promise.all(batch);
5011
- await copilotkit.waitForPendingFrameworkUpdates();
5012
- if (agent.isRunning || agent.threadId !== threadId) return;
5013
- if (state.pending.length > batch.length) continue;
5014
- state.pending = [];
5015
- for (const { content } of answers) agent.addMessage({
5016
- id: (0, _copilotkit_shared.randomUUID)(),
5017
- role: "developer",
5018
- content
5019
- });
5020
- if (!answers.some((item) => item.followUp)) continue;
5021
- state.followUps++;
5022
- await copilotkit.runAgent({ agent });
5023
- }
5024
- } catch (error) {
5025
- if (isDevelopment()) console.warn("[generativeUI] function follow-up run failed:", error);
5026
- } finally {
5027
- state.flushing = false;
5028
- }
5029
- };
5030
- return { run(agent, requests, messages, running) {
5031
- const { threadId } = agent;
5032
- if (!threadId) return;
5033
- const state = threadState(threadId);
5034
- const turn = lastUserMessageId(messages);
5035
- if (turn !== state.turn) {
5036
- state.turn = turn;
5037
- state.followUps = 0;
5038
- }
5039
- const isNew = (request) => !state.done.has(request.functionCallId);
5040
- const fresh = requests.filter(isNew);
5041
- const answered = fresh.length > 0 ? answeredCallIds(messages) : /* @__PURE__ */ new Set();
5042
- for (const request of fresh) {
5043
- const { functionCallId } = request;
5044
- if (state.done.has(functionCallId)) continue;
5045
- state.done.add(functionCallId);
5046
- if (answered.has(functionCallId)) continue;
5047
- const isOverCap = state.followUps >= MAX_FUNCTION_FOLLOW_UPS;
5048
- state.pending.push(isOverCap ? Promise.resolve(overCapAnswer(functionCallId)) : answer(request));
5049
- }
5050
- if (!running) flush(agent, threadId, state);
5051
- } };
5052
- }
5053
2106
  /** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */
5054
2107
  function useGenerativeUIRoot(copilotkit, config) {
5055
2108
  const configRef = (0, react.useRef)(config);
@@ -5067,12 +2120,12 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5067
2120
  }
5068
2121
  if (isDevelopment()) console.warn(`[generativeUI] ${info.kind} error in ${info.surfaceId}${info.componentId ? `/${info.componentId}` : ""}: ${info.error?.message}`);
5069
2122
  };
5070
- const manager = new GenerativeUISurfaceManager(ui, { onOperationRejected: ({ surfaceId, index, reason }) => reportError({
2123
+ const manager = new _copilotkit_core_generative_ui.GenerativeUISurfaceManager(ui, { onOperationRejected: ({ surfaceId, index, reason }) => reportError({
5071
2124
  kind: "operation",
5072
2125
  surfaceId,
5073
2126
  error: /* @__PURE__ */ new Error(`operation ${index} rejected: ${reason}`)
5074
2127
  }) });
5075
- const dispatcher = createGenerativeUIDispatcher({
2128
+ const dispatcher = (0, _copilotkit_core_generative_ui.createGenerativeUIDispatcher)({
5076
2129
  getDeclared: () => ui.functions,
5077
2130
  onError: ({ name, origin, error }) => {
5078
2131
  if ("functionCallId" in origin) {
@@ -5086,13 +2139,17 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5086
2139
  });
5087
2140
  }
5088
2141
  });
5089
- const functionCalls = createFunctionCallRunner({
5090
- copilotkit,
2142
+ const functionCalls = (0, _copilotkit_core_generative_ui.createFunctionCallRunner)({
2143
+ core: copilotkit,
5091
2144
  dispatcher,
5092
2145
  manifest: {
5093
2146
  catalogId: ui.id,
5094
- catalogIds: catalogIdsOf(ui),
2147
+ catalogIds: (0, _copilotkit_shared_generative_ui.catalogIdsOf)(ui),
5095
2148
  components: ui.manifestComponents
2149
+ },
2150
+ settle: () => copilotkit.waitForPendingFrameworkUpdates(),
2151
+ warn: (message, error) => {
2152
+ if (isDevelopment()) console.warn(message, error);
5096
2153
  }
5097
2154
  });
5098
2155
  const forwardingAgents = /* @__PURE__ */ new Set();
@@ -5121,12 +2178,12 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5121
2178
  actions.delete(agent);
5122
2179
  const latest = configRef.current;
5123
2180
  if (!latest) return;
5124
- const envelope = buildGenerativeUIEnvelope({
2181
+ const envelope = (0, _copilotkit_core_generative_ui.buildGenerativeUIEnvelope)({
5125
2182
  ui,
5126
2183
  manager,
5127
2184
  dispatcher
5128
2185
  }, agent.threadId, {
5129
- ...envelopeOptionsFor(latest),
2186
+ ...(0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest),
5130
2187
  action
5131
2188
  });
5132
2189
  const id = copilotkit.addScopedProperties({
@@ -5151,7 +2208,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5151
2208
  };
5152
2209
  const forwardEvent = async (event, agentId) => {
5153
2210
  const fail = (message) => {
5154
- const error = new GenerativeUIError("event_forward_failed", message);
2211
+ const error = new _copilotkit_shared_generative_ui.GenerativeUIError("event_forward_failed", message);
5155
2212
  reportError({
5156
2213
  kind: "event",
5157
2214
  surfaceId: event.surfaceId,
@@ -5167,16 +2224,16 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5167
2224
  if (!agent) return fail(`No agent "${agentId}" to receive "${event.name}"`);
5168
2225
  if (agent.isRunning || forwardingAgents.has(agent)) return {
5169
2226
  ok: false,
5170
- error: new GenerativeUIError("agent_busy", `"${event.name}" was not sent: the agent is running`)
2227
+ error: new _copilotkit_shared_generative_ui.GenerativeUIError("agent_busy", `"${event.name}" was not sent: the agent is running`)
5171
2228
  };
5172
2229
  forwardingAgents.add(agent);
5173
2230
  try {
5174
2231
  const surface = agent.threadId ? manager.getSurface(agent.threadId, event.surfaceId) : void 0;
5175
- const resolveLabel = surface ? createComponentLabelResolver(surfaceComponents(surface)) : void 0;
2232
+ const resolveLabel = surface ? (0, _copilotkit_core_generative_ui.surfaceLabelResolver)(surface) : void 0;
5176
2233
  agent.addMessage({
5177
2234
  id: (0, _copilotkit_shared.randomUUID)(),
5178
2235
  role: "user",
5179
- content: buildActionMessageText(event, resolveLabel)
2236
+ content: (0, _copilotkit_core_generative_ui.buildActionMessageText)(event, resolveLabel)
5180
2237
  });
5181
2238
  setAction(agent, (0, _copilotkit_shared.toA2UIActionMessage)(event));
5182
2239
  await copilotkit.runAgent({ agent });
@@ -5230,10 +2287,10 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5230
2287
  const watched = /* @__PURE__ */ new WeakSet();
5231
2288
  const agentSubscriptions = [];
5232
2289
  let envelopeId;
5233
- const debug = createGenerativeUIDebugSource(core, () => {
2290
+ const debug = (0, _copilotkit_core_generative_ui.createGenerativeUIDebugSource)(core, () => {
5234
2291
  const latest = configRef.current ?? { ui: core.ui };
5235
2292
  return {
5236
- options: envelopeOptionsFor(latest),
2293
+ options: (0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest),
5237
2294
  agentIds: latest.agentIds
5238
2295
  };
5239
2296
  });
@@ -5250,7 +2307,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5250
2307
  */
5251
2308
  const setEnvelope = (agent, latest) => {
5252
2309
  removeEnvelope();
5253
- const run = describeGenerativeUIRun(core, agent.threadId, envelopeOptionsFor(latest));
2310
+ const run = (0, _copilotkit_core_generative_ui.describeGenerativeUIRun)(core, agent.threadId, (0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest));
5254
2311
  envelopeId = copilotkit.addScopedProperties({
5255
2312
  properties: { [_copilotkit_shared.COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: run.envelope } },
5256
2313
  agentIds: latest.agentIds
@@ -5270,13 +2327,13 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5270
2327
  * Both give their function calls to the one runner.
5271
2328
  */
5272
2329
  const readMessages = (agent, messages, running) => {
5273
- const requests = activityFunctionCalls(messages);
2330
+ const requests = (0, _copilotkit_core_generative_ui.activityFunctionCalls)(messages);
5274
2331
  const { threadId } = agent;
5275
2332
  if (configRef.current?.transport !== "markdown") ingestMessages(core.manager, agent, messages);
5276
2333
  else if (threadId) {
5277
2334
  core.manager.setActiveThread(threadId);
5278
- const calls = getMarkdownSurfaceSource(core).sync(threadId, agent.agentId, messages, { running });
5279
- requests.push(...markdownFunctionCalls(calls));
2335
+ const calls = (0, _copilotkit_core_generative_ui.getMarkdownSurfaceSource)(core).sync(threadId, agent.agentId, messages, { running });
2336
+ requests.push(...(0, _copilotkit_core_generative_ui.markdownFunctionCalls)(calls));
5280
2337
  }
5281
2338
  core.functionCalls.run(agent, requests, messages, running);
5282
2339
  };
@@ -5320,16 +2377,6 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5320
2377
  if (!runtime) throw new Error("Generative UI components must be rendered inside <CopilotKitProvider generativeUI={{ ui }}>.");
5321
2378
  return runtime;
5322
2379
  }
5323
- /**
5324
- * Reports an error without ever throwing: `reportError` reaches host code
5325
- * (`onError`), and a throwing host callback must not break rendering or an
5326
- * event handler.
5327
- */
5328
- function reportErrorSafely(runtime, info) {
5329
- try {
5330
- runtime.reportError(info);
5331
- } catch {}
5332
- }
5333
2380
  const GenerativeUINodeContext = (0, react.createContext)(null);
5334
2381
 
5335
2382
  //#endregion
@@ -5399,7 +2446,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5399
2446
  }
5400
2447
  componentDidCatch(error) {
5401
2448
  const { runtime, surfaceId, componentId } = this.props;
5402
- reportErrorSafely(runtime, {
2449
+ (0, _copilotkit_core_generative_ui.reportErrorSafely)(runtime, {
5403
2450
  kind: "render",
5404
2451
  surfaceId,
5405
2452
  componentId,
@@ -5433,7 +2480,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5433
2480
  return { error };
5434
2481
  }
5435
2482
  componentDidCatch(error) {
5436
- reportErrorSafely(this.props.runtime, {
2483
+ (0, _copilotkit_core_generative_ui.reportErrorSafely)(this.props.runtime, {
5437
2484
  kind: "render",
5438
2485
  surfaceId: this.props.surfaceId,
5439
2486
  error
@@ -5448,287 +2495,6 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5448
2495
  }
5449
2496
  };
5450
2497
 
5451
- //#endregion
5452
- //#region src/generative-ui/accessibility.ts
5453
- const LIVE = new Set([
5454
- "off",
5455
- "polite",
5456
- "assertive"
5457
- ]);
5458
- /**
5459
- * The accessibility of a component from its resolved `accessibility`
5460
- * value. Fields of the wrong type are left out: a label that is still a
5461
- * binding, or a list, names nothing.
5462
- */
5463
- function readAccessibility(value) {
5464
- if (typeof value !== "object" || value === null || Array.isArray(value)) return;
5465
- const { label, description, live, hidden } = value;
5466
- const result = {};
5467
- if (typeof label === "string" && label !== "") result.label = label;
5468
- if (typeof description === "string" && description !== "") result.description = description;
5469
- if (typeof live === "string" && LIVE.has(live)) result.live = live;
5470
- if (typeof hidden === "boolean") result.hidden = hidden;
5471
- return Object.keys(result).length > 0 ? result : void 0;
5472
- }
5473
- /**
5474
- * The ARIA attributes for an `accessibility`. `live: "off"` is written out:
5475
- * a region inherits the live setting of its ancestors, and a `status` role
5476
- * is live on its own, so only the explicit value silences it.
5477
- *
5478
- * @example
5479
- * ```ts
5480
- * accessibilityAttributes({ label: "Totals", live: "polite" });
5481
- * // { "aria-label": "Totals", "aria-live": "polite" }
5482
- * ```
5483
- */
5484
- function accessibilityAttributes(accessibility) {
5485
- if (!accessibility) return {};
5486
- const { label, description, live, hidden } = accessibility;
5487
- return {
5488
- ...label === void 0 ? {} : { "aria-label": label },
5489
- ...description === void 0 ? {} : { "aria-description": description },
5490
- ...live === void 0 ? {} : { "aria-live": live },
5491
- ...hidden ? { "aria-hidden": true } : {}
5492
- };
5493
- }
5494
- /**
5495
- * The part of the attributes for the wrapper around a control: hidden and
5496
- * live cover the label and the control together.
5497
- */
5498
- function wrapperAria(aria) {
5499
- const { "aria-hidden": hidden, "aria-live": live } = aria;
5500
- return {
5501
- ...hidden === void 0 ? {} : { "aria-hidden": hidden },
5502
- ...live === void 0 ? {} : { "aria-live": live }
5503
- };
5504
- }
5505
-
5506
- //#endregion
5507
- //#region src/generative-ui/events.ts
5508
- /**
5509
- * The context of a running event binding: it reads the surface data model
5510
- * and resolves relative paths against the template item of the component.
5511
- * A function that needs a user gesture (openUrl) is not a value here
5512
- * either; it runs through the dispatcher as the binding's functionCall.
5513
- */
5514
- function eventContext(surface, basePath) {
5515
- return {
5516
- data: surface.model.dataModel,
5517
- basePath
5518
- };
5519
- }
5520
- /**
5521
- * A value of an event binding with its dynamic values resolved: `{"@path"}`
5522
- * bindings and function values, at any depth.
5523
- */
5524
- function resolveValue(surface, basePath, value) {
5525
- return resolveDynamicValue(value, eventContext(surface, basePath)).value;
5526
- }
5527
- /**
5528
- * The entries of an args or context record, each resolved on its own. The
5529
- * record is not resolved as a whole, because a record with one `event` or
5530
- * `functionCall` key would look like an action binding and stay as it is.
5531
- */
5532
- function resolveValues(surface, basePath, values) {
5533
- return Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [key, resolveValue(surface, basePath, value)]));
5534
- }
5535
- /**
5536
- * The `userMessage` of an event binding, as text. A `{"@path"}` or a
5537
- * function value is resolved. `undefined` when there is no message, or
5538
- * the value is not a string.
5539
- */
5540
- function resolveUserMessage(surface, basePath, userMessage) {
5541
- const value = resolveValue(surface, basePath, userMessage);
5542
- return typeof value === "string" ? value : void 0;
5543
- }
5544
- /**
5545
- * Validates the component's args with the event `parameters`, then runs
5546
- * `send` with them. Never throws: every failure is reported and becomes
5547
- * `{ ok: false, error }`.
5548
- */
5549
- async function runEvent(call, send) {
5550
- const { runtime, surface, componentId, name, parameters, args } = call;
5551
- const origin = {
5552
- surfaceId: surface.surfaceId,
5553
- componentId
5554
- };
5555
- try {
5556
- if (!parameters) return await send(args ?? {}, origin);
5557
- const result = validateSchema(parameters, args ?? {});
5558
- const parsed = result instanceof Promise ? await result : result;
5559
- if (!parsed.success) {
5560
- const error = new GenerativeUIError("invalid_event_args", `${name}: ${formatIssues(parsed.issues, "args")}`);
5561
- reportErrorSafely(runtime, {
5562
- kind: "event",
5563
- ...origin,
5564
- error
5565
- });
5566
- return {
5567
- ok: false,
5568
- error
5569
- };
5570
- }
5571
- return await send(parsed.data ?? {}, origin);
5572
- } catch (cause) {
5573
- const error = new GenerativeUIError("event_forward_failed", `${name}: ${cause instanceof Error ? cause.message : String(cause)}`);
5574
- reportErrorSafely(runtime, {
5575
- kind: "event",
5576
- ...origin,
5577
- error
5578
- });
5579
- return {
5580
- ok: false,
5581
- error
5582
- };
5583
- }
5584
- }
5585
- /**
5586
- * Runs one call of an event that the model bound: validates the component's
5587
- * args, merges them with the args from the binding (binding literals win),
5588
- * then calls a declared function or forwards an agent event. Never throws.
5589
- */
5590
- function invokeBoundEvent(params) {
5591
- const { runtime, surface, binding, basePath } = params;
5592
- return runEvent(params, (args, origin) => {
5593
- const componentArgs = args;
5594
- if ("functionCall" in binding) return runtime.dispatcher.invoke(binding.functionCall["@call"], {
5595
- ...componentArgs,
5596
- ...resolveValues(surface, basePath, binding.functionCall.args)
5597
- }, origin);
5598
- const { event } = binding;
5599
- const forwarded = {
5600
- name: event.name,
5601
- ...origin,
5602
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5603
- userMessage: resolveUserMessage(surface, basePath, event.userMessage),
5604
- context: {
5605
- ...componentArgs,
5606
- ...resolveValues(surface, basePath, event.context)
5607
- }
5608
- };
5609
- return runtime.forwardEvent(forwarded, surface.agentId);
5610
- });
5611
- }
5612
- /**
5613
- * Runs one call of an event that matches a declared function: validates the
5614
- * component's args with the event `parameters` (if any), then calls the
5615
- * function, which validates them with its own schema. Never throws.
5616
- */
5617
- function invokeMatchedEvent(params) {
5618
- const { runtime, functionName } = params;
5619
- return runEvent(params, (componentArgs, origin) => runtime.dispatcher.invoke(functionName, componentArgs, origin));
5620
- }
5621
-
5622
- //#endregion
5623
- //#region src/generative-ui/theme.ts
5624
- /**
5625
- * The built-in dark values. The light values are the fallbacks in the
5626
- * components, so a surface is light when no variable is set.
5627
- */
5628
- const DARK_THEME = {
5629
- "--a2ui-color-text-default": "#ececec",
5630
- "--a2ui-color-text-prose": "#ececec",
5631
- "--a2ui-color-text-primary": "#ececec",
5632
- "--a2ui-color-text-emphasis": "#fff",
5633
- "--a2ui-color-text-secondary": "#b4b4b4",
5634
- "--a2ui-color-text-tertiary": "#8e8e8e",
5635
- "--a2ui-color-text-success": "#4fd1a5",
5636
- "--a2ui-color-text-info": "#6cb6ff",
5637
- "--a2ui-color-text-warning": "#e3b341",
5638
- "--a2ui-color-text-caution": "#e3b341",
5639
- "--a2ui-color-text-danger": "#ff7b72",
5640
- "--a2ui-color-text-discovery": "#bc9cff",
5641
- "--a2ui-color-surface": "#1f1f1f",
5642
- "--a2ui-color-surface-secondary": "#2a2a2a",
5643
- "--a2ui-color-surface-tertiary": "#3a3a3a",
5644
- "--a2ui-color-surface-elevated": "#262626",
5645
- "--a2ui-color-surface-elevated-secondary": "#2f2f2f",
5646
- "--a2ui-color-surface-inverted": "#f2f2f2",
5647
- "--a2ui-color-surface-soft": "#232323",
5648
- "--a2ui-color-info": "rgba(80, 160, 255, 0.14)",
5649
- "--a2ui-color-warning": "rgba(240, 180, 60, 0.14)",
5650
- "--a2ui-color-caution": "rgba(240, 180, 60, 0.14)",
5651
- "--a2ui-color-success": "rgba(60, 200, 150, 0.14)",
5652
- "--a2ui-color-danger": "rgba(255, 110, 100, 0.14)",
5653
- "--a2ui-color-discovery": "rgba(170, 130, 255, 0.14)",
5654
- "--a2ui-color-info-soft": "rgba(80, 160, 255, 0.08)",
5655
- "--a2ui-color-warning-soft": "rgba(240, 180, 60, 0.08)",
5656
- "--a2ui-color-caution-soft": "rgba(240, 180, 60, 0.08)",
5657
- "--a2ui-color-success-soft": "rgba(60, 200, 150, 0.08)",
5658
- "--a2ui-color-danger-soft": "rgba(255, 110, 100, 0.08)",
5659
- "--a2ui-color-discovery-soft": "rgba(170, 130, 255, 0.08)",
5660
- "--a2ui-color-info-solid": "#3b8eea",
5661
- "--a2ui-color-warning-solid": "#c99a2e",
5662
- "--a2ui-color-caution-solid": "#c99a2e",
5663
- "--a2ui-color-success-solid": "#2fae86",
5664
- "--a2ui-color-danger-solid": "#e5534b",
5665
- "--a2ui-color-discovery-solid": "#9a6ff0",
5666
- "--a2ui-color-border-default": "rgba(255, 255, 255, 0.12)",
5667
- "--a2ui-color-border-subtle": "rgba(255, 255, 255, 0.06)",
5668
- "--a2ui-color-border-strong": "#4a4a4a",
5669
- "--a2ui-color-border-info": "#2f5f8f",
5670
- "--a2ui-color-border-warning": "#6b5420",
5671
- "--a2ui-color-border-caution": "#6b5420",
5672
- "--a2ui-color-border-success": "#1f5f4b",
5673
- "--a2ui-color-border-danger": "#7a2f2b",
5674
- "--a2ui-color-border-discovery": "#4f3a80",
5675
- "--a2ui-color-border-control": "rgba(255, 255, 255, 0.2)",
5676
- "--a2ui-color-accent": "#f2f2f2",
5677
- "--a2ui-color-on-accent": "#0d0d0d",
5678
- "--a2ui-color-panel": "#262626",
5679
- "--a2ui-color-control": "#2f2f2f",
5680
- "--a2ui-color-focus": "#3b9bff",
5681
- "--a2ui-color-shimmer": "rgba(255, 255, 255, 0.12)",
5682
- "--a2ui-color-chart-cursor": "rgba(255, 255, 255, 0.06)",
5683
- "--a2ui-color-slider-track": "rgba(255, 255, 255, 0.1)",
5684
- "--a2ui-color-badge-secondary": "rgba(255, 255, 255, 0.08)",
5685
- "--a2ui-color-highlight-green": "#1d4a37",
5686
- "--a2ui-color-highlight-orange": "#4d3418",
5687
- "--a2ui-color-highlight-pink": "#4d2338",
5688
- "--a2ui-shadow-xs": "0 1px 2px rgba(0, 0, 0, 0.5)",
5689
- "--a2ui-shadow-sm": "0 1px 3px rgba(0, 0, 0, 0.5)",
5690
- "--a2ui-shadow-soft": "0 1px 3px rgba(0, 0, 0, 0.3)",
5691
- "--a2ui-shadow-md": "0 4px 12px rgba(0, 0, 0, 0.4)"
5692
- };
5693
- const VARIABLE_NAME = /^--a2ui-[a-z0-9-]+$/;
5694
- const UNSAFE_VALUE = /[{};<>]/;
5695
- /** Matches the `dark` class on an ancestor of a surface, or on the surface. */
5696
- const DARK = ":where(.dark)";
5697
- /** The default dark values, as a rule that any theme rule beats. */
5698
- const DARK_THEME_CSS = `:where(.dark .a2ui-surface,.a2ui-surface.dark){${declarations(DARK_THEME)}}`;
5699
- function declarations(values) {
5700
- return Object.entries(values ?? {}).filter(([name, value]) => VARIABLE_NAME.test(name) && typeof value === "string" && !UNSAFE_VALUE.test(value)).map(([name, value]) => `${name}:${value}`).join(";");
5701
- }
5702
- /** A short, stable id for a stylesheet. */
5703
- function hashOf(text) {
5704
- let hash = 5381;
5705
- for (let index = 0; index < text.length; index++) hash = hash * 33 ^ text.charCodeAt(index);
5706
- return `t${(hash >>> 0).toString(36)}`;
5707
- }
5708
- /**
5709
- * The stylesheet of a theme: its values on the surfaces that carry its id,
5710
- * then its dark values in dark mode. `undefined` when the theme sets no
5711
- * variable. Values that could break out of the rule are left out.
5712
- *
5713
- * @example
5714
- * ```ts
5715
- * themeStyleSheet({ "--a2ui-color-accent": "red" });
5716
- * // { id: "t…", css: '.a2ui-surface[data-a2ui-theme="t…"]{--a2ui-color-accent:red}' }
5717
- * ```
5718
- */
5719
- function themeStyleSheet(theme) {
5720
- const { dark, ...base } = theme ?? {};
5721
- const both = declarations(base);
5722
- const darkOnly = declarations(dark);
5723
- if (!both && !darkOnly) return void 0;
5724
- const id = hashOf(`${both}|${darkOnly}`);
5725
- const self = `.a2ui-surface[data-a2ui-theme="${id}"]`;
5726
- return {
5727
- id,
5728
- css: [both && `${self}{${both}}`, darkOnly && `${DARK} ${self},${self}${DARK}{${darkOnly}}`].filter(Boolean).join("")
5729
- };
5730
- }
5731
-
5732
2498
  //#endregion
5733
2499
  //#region src/generative-ui/SurfaceView.tsx
5734
2500
  const NO_ANCESTORS = [];
@@ -5743,7 +2509,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5743
2509
  function SurfaceView({ surface }) {
5744
2510
  const runtime = useRequiredGenerativeUIRuntime();
5745
2511
  const { theme } = runtime;
5746
- const sheet = (0, react.useMemo)(() => themeStyleSheet(theme), [theme]);
2512
+ const sheet = (0, react.useMemo)(() => (0, _copilotkit_shared_generative_ui.themeStyleSheet)(theme), [theme]);
5747
2513
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
5748
2514
  className: "a2ui-surface",
5749
2515
  "data-generative-ui-root": surface.surfaceId,
@@ -5821,7 +2587,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5821
2587
  */
5822
2588
  function TemplateChildren({ surface, template, basePath, ancestors }) {
5823
2589
  const dataModel = surface.model.dataModel;
5824
- const listPath = resolvePath(template.path, basePath);
2590
+ const listPath = (0, _copilotkit_core_generative_ui.resolvePath)(template.path, basePath);
5825
2591
  const subscribe = (0, react.useCallback)((onChange) => {
5826
2592
  const subscription = dataModel.subscribe(listPath, onChange);
5827
2593
  return () => subscription.unsubscribe();
@@ -5834,7 +2600,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5834
2600
  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, {
5835
2601
  surface,
5836
2602
  componentId: template.componentId,
5837
- basePath: joinPath(listPath, String(index)),
2603
+ basePath: (0, _copilotkit_core_generative_ui.joinPath)(listPath, String(index)),
5838
2604
  ancestors
5839
2605
  }, index)) });
5840
2606
  }
@@ -5881,7 +2647,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5881
2647
  const cached = cache.current.get(key);
5882
2648
  const isFresh = cached !== void 0 && cached.raw === raw && cached.basePath === basePath && [...cached.reads].every(([path, value]) => Object.is(dataModel.get(path), value));
5883
2649
  const resolve = () => {
5884
- const resolved = tryResolveDynamicValue(raw, {
2650
+ const resolved = (0, _copilotkit_core_generative_ui.tryResolveDynamicValue)(raw, {
5885
2651
  data: dataModel,
5886
2652
  basePath
5887
2653
  }, { isChecks: key === "checks" });
@@ -5909,7 +2675,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
5909
2675
  for (const path of entry.reads.keys()) paths.add(path);
5910
2676
  }
5911
2677
  cache.current = next;
5912
- const accessibility = readAccessibility(a11yValues);
2678
+ const accessibility = (0, _copilotkit_core_generative_ui.readAccessibility)(a11yValues);
5913
2679
  for (const [key, value] of Object.entries(overrides)) if (!(0, _copilotkit_shared.isPathBinding)(properties[key])) values[key] = value;
5914
2680
  const rendered = (0, react.useRef)(next);
5915
2681
  rendered.current = next;
@@ -6009,22 +2775,22 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6009
2775
  values: {}
6010
2776
  };
6011
2777
  let values = modelData;
6012
- let result = validateSchemaSync(definition.props, values);
2778
+ let result = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, values);
6013
2779
  if (!result.success) {
6014
- const unset = withoutRejectedNulls(values, result.issues);
2780
+ const unset = (0, _copilotkit_shared_generative_ui.withoutRejectedNulls)(values, result.issues);
6015
2781
  if (unset) {
6016
2782
  values = unset;
6017
- result = validateSchemaSync(definition.props, values);
2783
+ result = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, values);
6018
2784
  }
6019
2785
  }
6020
2786
  if (!result.success) {
6021
2787
  const issues = result.issues.filter((issue) => {
6022
- const key = issueKey(issue);
6023
- return key === void 0 ? isAsyncIssue(issue) : !Object.hasOwn(definition.selectors, key);
2788
+ const key = (0, _copilotkit_shared_generative_ui.issueKey)(issue);
2789
+ return key === void 0 ? (0, _copilotkit_shared_generative_ui.isAsyncIssue)(issue) : !Object.hasOwn(definition.selectors, key);
6024
2790
  });
6025
2791
  if (issues.length > 0) return {
6026
2792
  ok: false,
6027
- problem: formatIssues(issues)
2793
+ problem: (0, _copilotkit_shared_generative_ui.formatIssues)(issues)
6028
2794
  };
6029
2795
  }
6030
2796
  return {
@@ -6054,14 +2820,14 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6054
2820
  ...modelCheck.values,
6055
2821
  ...selection.values
6056
2822
  };
6057
- let parsed = validateSchemaSync(definition.props, input);
2823
+ let parsed = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, input);
6058
2824
  if (!parsed.success) {
6059
- const unset = withoutRejectedNulls(input, parsed.issues);
6060
- if (unset) parsed = validateSchemaSync(definition.props, unset);
2825
+ const unset = (0, _copilotkit_shared_generative_ui.withoutRejectedNulls)(input, parsed.issues);
2826
+ if (unset) parsed = (0, _copilotkit_shared_generative_ui.validateSchemaSync)(definition.props, unset);
6061
2827
  }
6062
2828
  if (!parsed.success) return {
6063
2829
  ok: false,
6064
- problem: formatIssues(parsed.issues)
2830
+ problem: (0, _copilotkit_shared_generative_ui.formatIssues)(parsed.issues)
6065
2831
  };
6066
2832
  return {
6067
2833
  ok: true,
@@ -6096,12 +2862,12 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6096
2862
  parameters: definition.events?.[name]?.parameters
6097
2863
  };
6098
2864
  const functionName = Object.hasOwn(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
6099
- handlers[name] = functionName === void 0 ? (args) => invokeBoundEvent({
2865
+ handlers[name] = functionName === void 0 ? (args) => (0, _copilotkit_core_generative_ui.invokeBoundEvent)({
6100
2866
  ...call,
6101
2867
  binding: latest.current[name],
6102
2868
  basePath,
6103
2869
  args
6104
- }) : (args) => invokeMatchedEvent({
2870
+ }) : (args) => (0, _copilotkit_core_generative_ui.invokeMatchedEvent)({
6105
2871
  ...call,
6106
2872
  functionName,
6107
2873
  args
@@ -6132,7 +2898,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6132
2898
  setters: (0, react.useMemo)(() => {
6133
2899
  const result = {};
6134
2900
  const writable = definition.writable ?? [];
6135
- for (const key of writable) result[setterNameOf(key)] = (value) => {
2901
+ for (const key of writable) result[(0, _copilotkit_shared_generative_ui.setterNameOf)(key)] = (value) => {
6136
2902
  const binding = latest.current[key];
6137
2903
  if (!(0, _copilotkit_shared.isPathBinding)(binding)) {
6138
2904
  setOverrides((current) => ({
@@ -6142,14 +2908,14 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6142
2908
  return;
6143
2909
  }
6144
2910
  try {
6145
- runtime.manager.setOwnedValue(surface.key, resolvePath(binding["@path"], basePath), value);
2911
+ runtime.manager.setOwnedValue(surface.key, (0, _copilotkit_core_generative_ui.resolvePath)(binding["@path"], basePath), value);
6146
2912
  } catch (cause) {
6147
2913
  const message = cause instanceof Error ? cause.message : String(cause);
6148
- reportErrorSafely(runtime, {
2914
+ (0, _copilotkit_core_generative_ui.reportErrorSafely)(runtime, {
6149
2915
  kind: "props",
6150
2916
  surfaceId: surface.surfaceId,
6151
2917
  componentId,
6152
- error: /* @__PURE__ */ new Error(`${setterNameOf(key)}: ${message}`)
2918
+ error: /* @__PURE__ */ new Error(`${(0, _copilotkit_shared_generative_ui.setterNameOf)(key)}: ${message}`)
6153
2919
  });
6154
2920
  }
6155
2921
  };
@@ -6260,7 +3026,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6260
3026
  ]);
6261
3027
  const problem = dataProps.ok ? void 0 : dataProps.problem;
6262
3028
  (0, react.useEffect)(() => {
6263
- if (problem) reportErrorSafely(runtime, {
3029
+ if (problem) (0, _copilotkit_core_generative_ui.reportErrorSafely)(runtime, {
6264
3030
  kind: "props",
6265
3031
  surfaceId: surface.surfaceId,
6266
3032
  componentId,
@@ -6289,7 +3055,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
6289
3055
  children: hasEnvelope ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
6290
3056
  "data-a2ui-accessibility": "",
6291
3057
  style: ROOT_STYLE,
6292
- ...wrapperAria(accessibilityAttributes(accessibility)),
3058
+ ...(0, _copilotkit_core_generative_ui.wrapperAria)((0, _copilotkit_core_generative_ui.accessibilityAttributes)(accessibility)),
6293
3059
  children: rendered
6294
3060
  }) : rendered
6295
3061
  });
@@ -8749,7 +5515,7 @@ _radix_ui_react_popover = __toESM(_radix_ui_react_popover);
8749
5515
  useManagerVersion(runtime);
8750
5516
  const segments = (0, react.useMemo)(() => (0, _copilotkit_core.splitA2UIMarkdown)(content), [content]);
8751
5517
  const threadId = chatThreadId ?? runtime.manager.getActiveThread();
8752
- const source = getMarkdownSurfaceSource(runtime);
5518
+ const source = (0, _copilotkit_core_generative_ui.getMarkdownSurfaceSource)(runtime);
8753
5519
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: segments.map((segment, index) => {
8754
5520
  const isLast = index === segments.length - 1;
8755
5521
  if (segment.type === "markdown") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProviderMarkdown, {