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