@copilotkit/react-core 2.0.0-rc.4 → 2.0.0-rc.41
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/MarkdownRendererContext-BL8ct_3U.d.mts +34 -0
- package/dist/MarkdownRendererContext-BL8ct_3U.d.mts.map +1 -0
- package/dist/MarkdownRendererContext-C2J_lgqF.d.cts +34 -0
- package/dist/MarkdownRendererContext-C2J_lgqF.d.cts.map +1 -0
- package/dist/MarkdownSurfaces-Byz821bg.mjs +324 -0
- package/dist/MarkdownSurfaces-Byz821bg.mjs.map +1 -0
- package/dist/MarkdownSurfaces-D2Ck-cbb.cjs +378 -0
- package/dist/MarkdownSurfaces-D2Ck-cbb.cjs.map +1 -0
- package/dist/chat-Bf0vVdo7.mjs +1600 -0
- package/dist/chat-Bf0vVdo7.mjs.map +1 -0
- package/dist/chat-D3fxo6Ah.cjs +1784 -0
- package/dist/chat-D3fxo6Ah.cjs.map +1 -0
- package/dist/chat-DgP2N7bD.d.mts +233 -0
- package/dist/chat-DgP2N7bD.d.mts.map +1 -0
- package/dist/chat-DtHs4alO.d.cts +233 -0
- package/dist/chat-DtHs4alO.d.cts.map +1 -0
- package/dist/context.cjs +75 -63
- package/dist/context.cjs.map +1 -1
- package/dist/context.d.cts +62 -107
- package/dist/context.d.cts.map +1 -1
- package/dist/context.d.mts +62 -107
- package/dist/context.d.mts.map +1 -1
- package/dist/context.mjs +76 -64
- package/dist/context.mjs.map +1 -1
- package/dist/generative-ui/native.cjs +66 -0
- package/dist/generative-ui/native.cjs.map +1 -0
- package/dist/generative-ui/native.d.cts +155 -0
- package/dist/generative-ui/native.d.cts.map +1 -0
- package/dist/generative-ui/native.d.mts +155 -0
- package/dist/generative-ui/native.d.mts.map +1 -0
- package/dist/generative-ui/native.mjs +24 -0
- package/dist/generative-ui/native.mjs.map +1 -0
- package/dist/generative-ui.cjs +757 -3056
- package/dist/generative-ui.cjs.map +1 -1
- package/dist/generative-ui.d.cts +2470 -4788
- package/dist/generative-ui.d.cts.map +1 -1
- package/dist/generative-ui.d.mts +2470 -4788
- package/dist/generative-ui.d.mts.map +1 -1
- package/dist/generative-ui.mjs +327 -2636
- package/dist/generative-ui.mjs.map +1 -1
- package/dist/headless.cjs +289 -1054
- package/dist/headless.cjs.map +1 -1
- package/dist/headless.d.cts +146 -371
- package/dist/headless.d.cts.map +1 -1
- package/dist/headless.d.mts +120 -236
- package/dist/headless.d.mts.map +1 -1
- package/dist/headless.mjs +283 -1054
- package/dist/headless.mjs.map +1 -1
- package/dist/hooks-2Ur8NQhj.d.cts +84 -0
- package/dist/hooks-2Ur8NQhj.d.cts.map +1 -0
- package/dist/hooks-BRYonCVu.d.mts +84 -0
- package/dist/hooks-BRYonCVu.d.mts.map +1 -0
- package/dist/index.cjs +9003 -13047
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +352 -834
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +349 -831
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1904 -7583
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +10629 -15765
- package/dist/index.umd.js.map +1 -1
- package/dist/refs-BIUfn1wb.cjs +43 -0
- package/dist/refs-BIUfn1wb.cjs.map +1 -0
- package/dist/refs-CMrRm3ta.mjs +31 -0
- package/dist/refs-CMrRm3ta.mjs.map +1 -0
- package/dist/use-generative-ui-root-C12htqbK.cjs +390 -0
- package/dist/use-generative-ui-root-C12htqbK.cjs.map +1 -0
- package/dist/use-generative-ui-root-CVgsDy1f.mjs +385 -0
- package/dist/use-generative-ui-root-CVgsDy1f.mjs.map +1 -0
- package/package.json +45 -23
- package/dist/MarkdownRendererContext-B4Us6mwL.d.cts +0 -954
- package/dist/MarkdownRendererContext-B4Us6mwL.d.cts.map +0 -1
- package/dist/MarkdownRendererContext-CRKFzsEB.d.mts +0 -954
- package/dist/MarkdownRendererContext-CRKFzsEB.d.mts.map +0 -1
- package/dist/MarkdownSurfaces-Bd--93O1.mjs +0 -3676
- package/dist/MarkdownSurfaces-Bd--93O1.mjs.map +0 -1
- package/dist/MarkdownSurfaces-S4wfUl3J.cjs +0 -3991
- package/dist/MarkdownSurfaces-S4wfUl3J.cjs.map +0 -1
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const require_chat = require('./chat-D3fxo6Ah.cjs');
|
|
2
|
+
let _copilotkit_shared_generative_ui = require("@copilotkit/shared/generative-ui");
|
|
3
|
+
|
|
4
|
+
//#region src/generative-ui/refs.ts
|
|
5
|
+
/**
|
|
6
|
+
* One component id. The component receives the rendered child. Pass the
|
|
7
|
+
* description here, not with `.describe()`, which would replace the mark.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* const tabsSchema = z.object({
|
|
12
|
+
* tabs: z.array(z.object({ title: z.string(), child: child() })),
|
|
13
|
+
* });
|
|
14
|
+
* // The component gets `tabs: { title: string; child: ReactNode }[]`.
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
function child(description) {
|
|
18
|
+
return (0, _copilotkit_shared_generative_ui.child)(description);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A list of component ids, or a template `{ componentId, path }` that
|
|
22
|
+
* repeats one component for each item of the list at `path`. The
|
|
23
|
+
* component receives the rendered children. Pass the description here,
|
|
24
|
+
* not with `.describe()`.
|
|
25
|
+
*/
|
|
26
|
+
function childList(description) {
|
|
27
|
+
return (0, _copilotkit_shared_generative_ui.childList)(description);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
//#endregion
|
|
31
|
+
Object.defineProperty(exports, 'child', {
|
|
32
|
+
enumerable: true,
|
|
33
|
+
get: function () {
|
|
34
|
+
return child;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
Object.defineProperty(exports, 'childList', {
|
|
38
|
+
enumerable: true,
|
|
39
|
+
get: function () {
|
|
40
|
+
return childList;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
//# sourceMappingURL=refs-BIUfn1wb.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refs-BIUfn1wb.cjs","names":[],"sources":["../src/generative-ui/refs.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport {\n child as sharedChild,\n childList as sharedChildList,\n} from \"@copilotkit/shared/generative-ui\";\n\n/**\n * One component id. The component receives the rendered child. Pass the\n * description here, not with `.describe()`, which would replace the mark.\n *\n * @example\n * ```ts\n * const tabsSchema = z.object({\n * tabs: z.array(z.object({ title: z.string(), child: child() })),\n * });\n * // The component gets `tabs: { title: string; child: ReactNode }[]`.\n * ```\n */\nexport function child(description?: string) {\n return sharedChild<ReactNode>(description);\n}\n\n/**\n * A list of component ids, or a template `{ componentId, path }` that\n * repeats one component for each item of the list at `path`. The\n * component receives the rendered children. Pass the description here,\n * not with `.describe()`.\n */\nexport function childList(description?: string) {\n return sharedChildList<ReactNode>(description);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,SAAgB,MAAM,aAAsB;AAC1C,oDAA8B,YAAY;;;;;;;;AAS5C,SAAgB,UAAU,aAAsB;AAC9C,wDAAkC,YAAY"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { child, childList } from "@copilotkit/shared/generative-ui";
|
|
2
|
+
|
|
3
|
+
//#region src/generative-ui/refs.ts
|
|
4
|
+
/**
|
|
5
|
+
* One component id. The component receives the rendered child. Pass the
|
|
6
|
+
* description here, not with `.describe()`, which would replace the mark.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* const tabsSchema = z.object({
|
|
11
|
+
* tabs: z.array(z.object({ title: z.string(), child: child() })),
|
|
12
|
+
* });
|
|
13
|
+
* // The component gets `tabs: { title: string; child: ReactNode }[]`.
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
function child$1(description) {
|
|
17
|
+
return child(description);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* A list of component ids, or a template `{ componentId, path }` that
|
|
21
|
+
* repeats one component for each item of the list at `path`. The
|
|
22
|
+
* component receives the rendered children. Pass the description here,
|
|
23
|
+
* not with `.describe()`.
|
|
24
|
+
*/
|
|
25
|
+
function childList$1(description) {
|
|
26
|
+
return childList(description);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
//#endregion
|
|
30
|
+
export { childList$1 as n, child$1 as t };
|
|
31
|
+
//# sourceMappingURL=refs-CMrRm3ta.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refs-CMrRm3ta.mjs","names":["child","sharedChild","childList","sharedChildList"],"sources":["../src/generative-ui/refs.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport {\n child as sharedChild,\n childList as sharedChildList,\n} from \"@copilotkit/shared/generative-ui\";\n\n/**\n * One component id. The component receives the rendered child. Pass the\n * description here, not with `.describe()`, which would replace the mark.\n *\n * @example\n * ```ts\n * const tabsSchema = z.object({\n * tabs: z.array(z.object({ title: z.string(), child: child() })),\n * });\n * // The component gets `tabs: { title: string; child: ReactNode }[]`.\n * ```\n */\nexport function child(description?: string) {\n return sharedChild<ReactNode>(description);\n}\n\n/**\n * A list of component ids, or a template `{ componentId, path }` that\n * repeats one component for each item of the list at `path`. The\n * component receives the rendered children. Pass the description here,\n * not with `.describe()`.\n */\nexport function childList(description?: string) {\n return sharedChildList<ReactNode>(description);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,SAAgBA,QAAM,aAAsB;AAC1C,QAAOC,MAAuB,YAAY;;;;;;;;AAS5C,SAAgBC,YAAU,aAAsB;AAC9C,QAAOC,UAA2B,YAAY"}
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
const require_chat = require('./chat-D3fxo6Ah.cjs');
|
|
2
|
+
let react = require("react");
|
|
3
|
+
let _copilotkit_shared = require("@copilotkit/shared");
|
|
4
|
+
let _copilotkit_core_generative_ui = require("@copilotkit/core/generative-ui");
|
|
5
|
+
let _copilotkit_shared_generative_ui = require("@copilotkit/shared/generative-ui");
|
|
6
|
+
|
|
7
|
+
//#region src/generative-ui/markdown/context.ts
|
|
8
|
+
/**
|
|
9
|
+
* Registers the two context entries of the markdown transport: the compact
|
|
10
|
+
* component schema and the fence guideline. Both go only to `agentIds`.
|
|
11
|
+
*
|
|
12
|
+
* The schema is built again at each run start and when a
|
|
13
|
+
* `<GenerativeUISurface>` mounts, unmounts, or changes its description or
|
|
14
|
+
* its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.
|
|
15
|
+
*
|
|
16
|
+
* @param copilotkit - The CopilotKit core of the provider.
|
|
17
|
+
* @param runtime - The generative UI runtime parts, or null without one.
|
|
18
|
+
* @param options - `enabled` and `agentIds`.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* useGenerativeUIMarkdownContext(copilotkit, core, {
|
|
23
|
+
* enabled: config?.transport === "markdown" && config.sendContext !== false,
|
|
24
|
+
* agentIds: config?.agentIds,
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
function useGenerativeUIMarkdownContext(copilotkit, runtime, options) {
|
|
29
|
+
const { enabled, agentIds } = options;
|
|
30
|
+
const agentIdsKey = agentIds === void 0 ? "" : JSON.stringify(agentIds);
|
|
31
|
+
(0, react.useEffect)(() => {
|
|
32
|
+
if (!runtime || !enabled) return;
|
|
33
|
+
const scopedAgentIds = agentIdsKey ? JSON.parse(agentIdsKey) : void 0;
|
|
34
|
+
const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};
|
|
35
|
+
let guidelineId;
|
|
36
|
+
let guidelineValue;
|
|
37
|
+
let schemaId;
|
|
38
|
+
let schemaValue;
|
|
39
|
+
const refreshSchema = (threadId) => {
|
|
40
|
+
const manifest = (0, _copilotkit_core_generative_ui.buildGenerativeUIManifest)(runtime, threadId);
|
|
41
|
+
const guideline = (0, _copilotkit_shared.buildGenerativeUIMarkdownGuidelines)((0, _copilotkit_shared.generativeUIGuideFeatures)(manifest));
|
|
42
|
+
if (guideline !== guidelineValue) {
|
|
43
|
+
if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
|
|
44
|
+
guidelineValue = guideline;
|
|
45
|
+
guidelineId = copilotkit.addContext({
|
|
46
|
+
description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,
|
|
47
|
+
value: guideline,
|
|
48
|
+
...scope
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const value = (0, _copilotkit_shared.renderGenerativeUISchema)(manifest, (0, _copilotkit_shared.defaultGenerativeUIPromptSpec)().schema.markdown);
|
|
52
|
+
if (value === schemaValue) return;
|
|
53
|
+
if (schemaId !== void 0) copilotkit.removeContext(schemaId);
|
|
54
|
+
schemaValue = value;
|
|
55
|
+
schemaId = copilotkit.addContext({
|
|
56
|
+
description: _copilotkit_shared.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
|
|
57
|
+
value,
|
|
58
|
+
...scope
|
|
59
|
+
});
|
|
60
|
+
};
|
|
61
|
+
refreshSchema(runtime.manager.getActiveThread());
|
|
62
|
+
let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());
|
|
63
|
+
const unsubscribeManager = runtime.manager.subscribe(() => {
|
|
64
|
+
const nextKey = JSON.stringify(runtime.manager.getMountedTargets());
|
|
65
|
+
if (nextKey === targetsKey) return;
|
|
66
|
+
targetsKey = nextKey;
|
|
67
|
+
refreshSchema(runtime.manager.getActiveThread());
|
|
68
|
+
});
|
|
69
|
+
const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId) });
|
|
70
|
+
return () => {
|
|
71
|
+
subscription.unsubscribe();
|
|
72
|
+
unsubscribeManager();
|
|
73
|
+
if (guidelineId !== void 0) copilotkit.removeContext(guidelineId);
|
|
74
|
+
if (schemaId !== void 0) copilotkit.removeContext(schemaId);
|
|
75
|
+
};
|
|
76
|
+
}, [
|
|
77
|
+
copilotkit,
|
|
78
|
+
runtime,
|
|
79
|
+
enabled,
|
|
80
|
+
agentIdsKey
|
|
81
|
+
]);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region src/generative-ui/use-generative-ui-root.ts
|
|
86
|
+
const isDevelopment = () => process.env.NODE_ENV !== "production";
|
|
87
|
+
/**
|
|
88
|
+
* The malformed-content warnings already printed, by manager, so each
|
|
89
|
+
* distinct issue warns once while the manager lives.
|
|
90
|
+
*/
|
|
91
|
+
const warnedMalformed = /* @__PURE__ */ new WeakMap();
|
|
92
|
+
/**
|
|
93
|
+
* Ingests the surface activity messages of `messages`. A message whose
|
|
94
|
+
* content is malformed (for example `null`) is skipped, in development with a
|
|
95
|
+
* warning once for each distinct issue, so it cannot throw inside the
|
|
96
|
+
* agent's run; the messages after it are still ingested.
|
|
97
|
+
*/
|
|
98
|
+
function ingestMessages(manager, agent, messages) {
|
|
99
|
+
const { threadId } = agent;
|
|
100
|
+
if (!threadId) return;
|
|
101
|
+
for (const message of messages) {
|
|
102
|
+
if (message.role !== "activity" || message.activityType !== _copilotkit_shared.GENERATIVE_UI_ACTIVITY_TYPE) continue;
|
|
103
|
+
const parsed = (0, _copilotkit_core_generative_ui.parseGenerativeUISurfaceContent)(message.content);
|
|
104
|
+
if (parsed.content) {
|
|
105
|
+
manager.ingest(threadId, agent.agentId, parsed.content);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (!isDevelopment()) continue;
|
|
109
|
+
const warning = `[generativeUI] skipped an activity message of thread ${JSON.stringify(threadId)}: its content is malformed: ${parsed.issues.join("; ")}.`;
|
|
110
|
+
let warned = warnedMalformed.get(manager);
|
|
111
|
+
if (!warned) {
|
|
112
|
+
warned = /* @__PURE__ */ new Set();
|
|
113
|
+
warnedMalformed.set(manager, warned);
|
|
114
|
+
}
|
|
115
|
+
if (warned.has(warning)) continue;
|
|
116
|
+
warned.add(warning);
|
|
117
|
+
console.warn(warning);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */
|
|
121
|
+
function useGenerativeUIRoot(copilotkit, config) {
|
|
122
|
+
const configRef = (0, react.useRef)(config);
|
|
123
|
+
configRef.current = config;
|
|
124
|
+
const ui = config?.ui;
|
|
125
|
+
const transport = config?.transport ?? "tool";
|
|
126
|
+
const theme = require_chat.useShallowStableRef(config?.theme);
|
|
127
|
+
const core = (0, react.useMemo)(() => {
|
|
128
|
+
if (!ui) return null;
|
|
129
|
+
const reportError = (info) => {
|
|
130
|
+
try {
|
|
131
|
+
configRef.current?.errorBoundary?.onError?.(info);
|
|
132
|
+
} catch (hostError) {
|
|
133
|
+
if (isDevelopment()) console.error("[generativeUI] errorBoundary.onError threw:", hostError);
|
|
134
|
+
}
|
|
135
|
+
if (isDevelopment()) console.warn(`[generativeUI] ${info.kind} error in ${info.surfaceId}${info.componentId ? `/${info.componentId}` : ""}: ${info.error?.message}`);
|
|
136
|
+
};
|
|
137
|
+
const manager = new _copilotkit_core_generative_ui.GenerativeUISurfaceManager(ui, { onOperationRejected: ({ surfaceId, index, reason }) => reportError({
|
|
138
|
+
kind: "operation",
|
|
139
|
+
surfaceId,
|
|
140
|
+
error: /* @__PURE__ */ new Error(`operation ${index} rejected: ${reason}`)
|
|
141
|
+
}) });
|
|
142
|
+
const dispatcher = (0, _copilotkit_core_generative_ui.createGenerativeUIDispatcher)({
|
|
143
|
+
getDeclared: () => ui.functions,
|
|
144
|
+
onError: ({ name, origin, error }) => {
|
|
145
|
+
if ("functionCallId" in origin) {
|
|
146
|
+
if (isDevelopment()) console.warn(`[generativeUI] function call ${origin.functionCallId} to "${name}" failed: ${error.message}`);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
reportError({
|
|
150
|
+
kind: "function",
|
|
151
|
+
...origin,
|
|
152
|
+
error
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
const functionCalls = (0, _copilotkit_core_generative_ui.createFunctionCallRunner)({
|
|
157
|
+
core: copilotkit,
|
|
158
|
+
dispatcher,
|
|
159
|
+
manifest: {
|
|
160
|
+
catalogId: ui.id,
|
|
161
|
+
catalogIds: (0, _copilotkit_shared_generative_ui.catalogIdsOf)(ui),
|
|
162
|
+
components: ui.manifestComponents
|
|
163
|
+
},
|
|
164
|
+
settle: () => copilotkit.waitForPendingFrameworkUpdates(),
|
|
165
|
+
warn: (message, error) => {
|
|
166
|
+
if (isDevelopment()) console.warn(message, error);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
const forwardingAgents = /* @__PURE__ */ new Set();
|
|
170
|
+
/**
|
|
171
|
+
* The action of a user event, as an envelope entry scoped to the agent
|
|
172
|
+
* the user acted on, for the run that the event starts: the structured
|
|
173
|
+
* form of the user message. It is set before the run starts and dropped
|
|
174
|
+
* when the run is over, so a suggestion request or a follow-up run
|
|
175
|
+
* (both read the properties with no run start) does not carry the same
|
|
176
|
+
* action again, and another agent never gets a click meant for this one.
|
|
177
|
+
* The entry comes after the shared envelope, so it wins for its agent;
|
|
178
|
+
* `refreshActions` keeps it last when the shared envelope is set again.
|
|
179
|
+
*/
|
|
180
|
+
const actions = /* @__PURE__ */ new Map();
|
|
181
|
+
const dropAction = (agent) => {
|
|
182
|
+
const entry = actions.get(agent);
|
|
183
|
+
if (!entry) return;
|
|
184
|
+
entry.subscription.unsubscribe();
|
|
185
|
+
copilotkit.removeScopedProperties(entry.id);
|
|
186
|
+
actions.delete(agent);
|
|
187
|
+
};
|
|
188
|
+
const setAction = (agent, action) => {
|
|
189
|
+
const previous = actions.get(agent);
|
|
190
|
+
previous?.subscription.unsubscribe();
|
|
191
|
+
if (previous) copilotkit.removeScopedProperties(previous.id);
|
|
192
|
+
actions.delete(agent);
|
|
193
|
+
const latest = configRef.current;
|
|
194
|
+
if (!latest) return;
|
|
195
|
+
const envelope = (0, _copilotkit_core_generative_ui.buildGenerativeUIEnvelope)({
|
|
196
|
+
ui,
|
|
197
|
+
manager,
|
|
198
|
+
dispatcher
|
|
199
|
+
}, agent.threadId, {
|
|
200
|
+
...(0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest),
|
|
201
|
+
action
|
|
202
|
+
});
|
|
203
|
+
const id = copilotkit.addScopedProperties({
|
|
204
|
+
properties: { [_copilotkit_shared.COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: envelope } },
|
|
205
|
+
agentIds: agent.agentId === void 0 ? latest.agentIds : [agent.agentId]
|
|
206
|
+
});
|
|
207
|
+
const subscription = agent.subscribe({
|
|
208
|
+
onRunFinalized: () => dropAction(agent),
|
|
209
|
+
onRunFailed: () => dropAction(agent)
|
|
210
|
+
});
|
|
211
|
+
actions.set(agent, {
|
|
212
|
+
id,
|
|
213
|
+
action,
|
|
214
|
+
subscription
|
|
215
|
+
});
|
|
216
|
+
};
|
|
217
|
+
const refreshActions = () => {
|
|
218
|
+
for (const [agent, { action }] of [...actions]) setAction(agent, action);
|
|
219
|
+
};
|
|
220
|
+
const dropAllActions = () => {
|
|
221
|
+
for (const agent of [...actions.keys()]) dropAction(agent);
|
|
222
|
+
};
|
|
223
|
+
const forwardEvent = async (event, agentId) => {
|
|
224
|
+
const fail = (message) => {
|
|
225
|
+
const error = new _copilotkit_shared_generative_ui.GenerativeUIError("event_forward_failed", message);
|
|
226
|
+
reportError({
|
|
227
|
+
kind: "event",
|
|
228
|
+
surfaceId: event.surfaceId,
|
|
229
|
+
componentId: event.componentId,
|
|
230
|
+
error
|
|
231
|
+
});
|
|
232
|
+
return {
|
|
233
|
+
ok: false,
|
|
234
|
+
error
|
|
235
|
+
};
|
|
236
|
+
};
|
|
237
|
+
const agent = copilotkit.getAgent(agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID);
|
|
238
|
+
if (!agent) return fail(`No agent "${agentId}" to receive "${event.name}"`);
|
|
239
|
+
if (agent.isRunning || forwardingAgents.has(agent)) return {
|
|
240
|
+
ok: false,
|
|
241
|
+
error: new _copilotkit_shared_generative_ui.GenerativeUIError("agent_busy", `"${event.name}" was not sent: the agent is running`)
|
|
242
|
+
};
|
|
243
|
+
forwardingAgents.add(agent);
|
|
244
|
+
try {
|
|
245
|
+
const surface = agent.threadId ? manager.getSurface(agent.threadId, event.surfaceId) : void 0;
|
|
246
|
+
const resolveLabel = surface ? (0, _copilotkit_core_generative_ui.surfaceLabelResolver)(surface) : void 0;
|
|
247
|
+
agent.addMessage({
|
|
248
|
+
id: (0, _copilotkit_shared.randomUUID)(),
|
|
249
|
+
role: "user",
|
|
250
|
+
content: (0, _copilotkit_core_generative_ui.buildActionMessageText)(event, resolveLabel)
|
|
251
|
+
});
|
|
252
|
+
setAction(agent, (0, _copilotkit_shared.toA2UIActionMessage)(event));
|
|
253
|
+
await copilotkit.runAgent({ agent });
|
|
254
|
+
return {
|
|
255
|
+
ok: true,
|
|
256
|
+
result: void 0
|
|
257
|
+
};
|
|
258
|
+
} catch (cause) {
|
|
259
|
+
return fail(`Forwarding "${event.name}" failed: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
260
|
+
} finally {
|
|
261
|
+
forwardingAgents.delete(agent);
|
|
262
|
+
dropAction(agent);
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
return {
|
|
266
|
+
manager,
|
|
267
|
+
dispatcher,
|
|
268
|
+
ui,
|
|
269
|
+
forwardEvent,
|
|
270
|
+
reportError,
|
|
271
|
+
functionCalls,
|
|
272
|
+
refreshActions,
|
|
273
|
+
dropAllActions
|
|
274
|
+
};
|
|
275
|
+
}, [ui, copilotkit]);
|
|
276
|
+
const runtime = (0, react.useMemo)(() => {
|
|
277
|
+
if (!core) return null;
|
|
278
|
+
const { manager, dispatcher, forwardEvent, reportError } = core;
|
|
279
|
+
return {
|
|
280
|
+
manager,
|
|
281
|
+
dispatcher,
|
|
282
|
+
ui: core.ui,
|
|
283
|
+
forwardEvent,
|
|
284
|
+
reportError,
|
|
285
|
+
transport,
|
|
286
|
+
theme,
|
|
287
|
+
get config() {
|
|
288
|
+
return configRef.current ?? { ui: core.ui };
|
|
289
|
+
},
|
|
290
|
+
get errorFallback() {
|
|
291
|
+
return configRef.current?.errorBoundary?.fallback;
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
}, [
|
|
295
|
+
core,
|
|
296
|
+
transport,
|
|
297
|
+
theme
|
|
298
|
+
]);
|
|
299
|
+
(0, react.useEffect)(() => {
|
|
300
|
+
if (!core) return;
|
|
301
|
+
const watched = /* @__PURE__ */ new WeakSet();
|
|
302
|
+
const agentSubscriptions = [];
|
|
303
|
+
let envelopeId;
|
|
304
|
+
const debug = (0, _copilotkit_core_generative_ui.createGenerativeUIDebugSource)(core, () => {
|
|
305
|
+
const latest = configRef.current ?? { ui: core.ui };
|
|
306
|
+
return {
|
|
307
|
+
options: (0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest),
|
|
308
|
+
agentIds: latest.agentIds
|
|
309
|
+
};
|
|
310
|
+
});
|
|
311
|
+
copilotkit.ɵsetGenerativeUIDebugSource(debug.source);
|
|
312
|
+
const removeEnvelope = () => {
|
|
313
|
+
if (envelopeId === void 0) return;
|
|
314
|
+
copilotkit.removeScopedProperties(envelopeId);
|
|
315
|
+
envelopeId = void 0;
|
|
316
|
+
};
|
|
317
|
+
/**
|
|
318
|
+
* Sets the shared envelope of the run. The action entries of the agents
|
|
319
|
+
* with a user event under way (see `forwardEvent`) are set again after
|
|
320
|
+
* it, so they stay the last entries and win for their agents.
|
|
321
|
+
*/
|
|
322
|
+
const setEnvelope = (agent, latest) => {
|
|
323
|
+
removeEnvelope();
|
|
324
|
+
const run = (0, _copilotkit_core_generative_ui.describeGenerativeUIRun)(core, agent.threadId, (0, _copilotkit_core_generative_ui.envelopeOptionsFor)(latest));
|
|
325
|
+
envelopeId = copilotkit.addScopedProperties({
|
|
326
|
+
properties: { [_copilotkit_shared.COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: run.envelope } },
|
|
327
|
+
agentIds: latest.agentIds
|
|
328
|
+
});
|
|
329
|
+
core.refreshActions();
|
|
330
|
+
if (!latest.agentIds || latest.agentIds.includes(agent.agentId ?? "")) debug.recordRun({
|
|
331
|
+
...run,
|
|
332
|
+
agentId: agent.agentId,
|
|
333
|
+
threadId: agent.threadId,
|
|
334
|
+
startedAt: Date.now()
|
|
335
|
+
});
|
|
336
|
+
};
|
|
337
|
+
/**
|
|
338
|
+
* The tool transport reads the surface activity messages. The markdown
|
|
339
|
+
* transport reads the ```a2ui fences of the assistant messages, and
|
|
340
|
+
* builds the surfaces of the thread from them again on each change.
|
|
341
|
+
* Both give their function calls to the one runner.
|
|
342
|
+
*/
|
|
343
|
+
const readMessages = (agent, messages, running) => {
|
|
344
|
+
const requests = (0, _copilotkit_core_generative_ui.activityFunctionCalls)(messages);
|
|
345
|
+
const { threadId } = agent;
|
|
346
|
+
if (configRef.current?.transport !== "markdown") ingestMessages(core.manager, agent, messages);
|
|
347
|
+
else if (threadId) {
|
|
348
|
+
core.manager.setActiveThread(threadId);
|
|
349
|
+
const calls = (0, _copilotkit_core_generative_ui.getMarkdownSurfaceSource)(core).sync(threadId, agent.agentId, messages, { running });
|
|
350
|
+
requests.push(...(0, _copilotkit_core_generative_ui.markdownFunctionCalls)(calls));
|
|
351
|
+
}
|
|
352
|
+
core.functionCalls.run(agent, requests, messages, running);
|
|
353
|
+
};
|
|
354
|
+
const subscription = copilotkit.subscribe({ onAgentRunStarted: ({ agent }) => {
|
|
355
|
+
core.manager.setActiveThread(agent.threadId);
|
|
356
|
+
const latest = configRef.current;
|
|
357
|
+
if (latest) setEnvelope(agent, latest);
|
|
358
|
+
if (!watched.has(agent)) {
|
|
359
|
+
watched.add(agent);
|
|
360
|
+
agentSubscriptions.push(agent.subscribe({
|
|
361
|
+
onMessagesChanged: ({ messages }) => readMessages(agent, messages, agent.isRunning),
|
|
362
|
+
onRunFinalized: () => readMessages(agent, agent.messages, false),
|
|
363
|
+
onRunFailed: () => readMessages(agent, agent.messages, false)
|
|
364
|
+
}));
|
|
365
|
+
}
|
|
366
|
+
readMessages(agent, agent.messages, true);
|
|
367
|
+
} });
|
|
368
|
+
return () => {
|
|
369
|
+
subscription.unsubscribe();
|
|
370
|
+
for (const s of agentSubscriptions) s.unsubscribe();
|
|
371
|
+
core.dropAllActions();
|
|
372
|
+
removeEnvelope();
|
|
373
|
+
if (copilotkit.ɵgenerativeUIDebugSource === debug.source) copilotkit.ɵsetGenerativeUIDebugSource(void 0);
|
|
374
|
+
};
|
|
375
|
+
}, [core, copilotkit]);
|
|
376
|
+
useGenerativeUIMarkdownContext(copilotkit, core, {
|
|
377
|
+
enabled: config?.transport === "markdown" && config.sendContext !== false,
|
|
378
|
+
agentIds: config?.agentIds
|
|
379
|
+
});
|
|
380
|
+
return runtime;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
//#endregion
|
|
384
|
+
Object.defineProperty(exports, 'useGenerativeUIRoot', {
|
|
385
|
+
enumerable: true,
|
|
386
|
+
get: function () {
|
|
387
|
+
return useGenerativeUIRoot;
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
//# sourceMappingURL=use-generative-ui-root-C12htqbK.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-generative-ui-root-C12htqbK.cjs","names":["GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION","GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION","GENERATIVE_UI_ACTIVITY_TYPE","useShallowStableRef","GenerativeUISurfaceManager","COPILOTKIT_FORWARDED_PROPS_KEY","GenerativeUIError","DEFAULT_AGENT_ID"],"sources":["../src/generative-ui/markdown/context.ts","../src/generative-ui/use-generative-ui-root.ts"],"sourcesContent":["import { useEffect } from \"react\";\nimport {\n buildCompactGenerativeUISchema,\n buildGenerativeUIMarkdownGuidelines,\n generativeUIGuideFeatures,\n GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,\n GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,\n defaultGenerativeUIPromptSpec,\n renderGenerativeUISchema,\n} from \"@copilotkit/shared\";\nimport { buildGenerativeUIManifest } from \"@copilotkit/core/generative-ui\";\nimport type { CopilotKitCoreReact } from \"../../lib/react-core\";\nimport type { GenerativeUIRuntime } from \"../runtime-context\";\n\n/** The compact schema lives in shared, so tools outside React build the same text. */\nexport { buildCompactGenerativeUISchema };\n\n/** What the markdown context of the generative UI needs. */\nexport interface GenerativeUIMarkdownContextOptions {\n /** Register the entries. False for the tool transport or `sendContext: false`. */\n enabled: boolean;\n /** The agents that get the entries. All agents when left out. */\n agentIds: string[] | undefined;\n}\n\n/**\n * Registers the two context entries of the markdown transport: the compact\n * component schema and the fence guideline. Both go only to `agentIds`.\n *\n * The schema is built again at each run start and when a\n * `<GenerativeUISurface>` mounts, unmounts, or changes its description or\n * its components, so its targets, functions, and surfaces stay current. The surfaces are those of the running thread.\n *\n * @param copilotkit - The CopilotKit core of the provider.\n * @param runtime - The generative UI runtime parts, or null without one.\n * @param options - `enabled` and `agentIds`.\n *\n * @example\n * ```ts\n * useGenerativeUIMarkdownContext(copilotkit, core, {\n * enabled: config?.transport === \"markdown\" && config.sendContext !== false,\n * agentIds: config?.agentIds,\n * });\n * ```\n */\nexport function useGenerativeUIMarkdownContext(\n copilotkit: CopilotKitCoreReact,\n runtime: Pick<GenerativeUIRuntime, \"ui\" | \"manager\" | \"dispatcher\"> | null,\n options: GenerativeUIMarkdownContextOptions,\n) {\n const { enabled, agentIds } = options;\n // A new array with the same ids must not register the entries again.\n const agentIdsKey = agentIds === undefined ? \"\" : JSON.stringify(agentIds);\n\n useEffect(() => {\n if (!runtime || !enabled) return;\n const scopedAgentIds: string[] | undefined = agentIdsKey\n ? JSON.parse(agentIdsKey)\n : undefined;\n const scope = scopedAgentIds ? { agentIds: scopedAgentIds } : {};\n // The guideline has only the rule groups that the manifest uses, and the\n // mounted functions can change, so it is built again with the schema.\n let guidelineId: string | undefined;\n let guidelineValue: string | undefined;\n let schemaId: string | undefined;\n let schemaValue: string | undefined;\n const refreshSchema = (threadId: string | undefined) => {\n const manifest = buildGenerativeUIManifest(runtime, threadId);\n const guideline = buildGenerativeUIMarkdownGuidelines(\n generativeUIGuideFeatures(manifest),\n );\n if (guideline !== guidelineValue) {\n if (guidelineId !== undefined) copilotkit.removeContext(guidelineId);\n guidelineValue = guideline;\n guidelineId = copilotkit.addContext({\n description: GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION,\n value: guideline,\n ...scope,\n });\n }\n const value = renderGenerativeUISchema(\n manifest,\n defaultGenerativeUIPromptSpec().schema.markdown,\n );\n if (value === schemaValue) return;\n if (schemaId !== undefined) copilotkit.removeContext(schemaId);\n schemaValue = value;\n schemaId = copilotkit.addContext({\n description: GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,\n value,\n ...scope,\n });\n };\n refreshSchema(runtime.manager.getActiveThread());\n\n // The manager notifies on every operation. Build the schema again only\n // when the mounted targets, their descriptions, or their component lists\n // change.\n let targetsKey = JSON.stringify(runtime.manager.getMountedTargets());\n const unsubscribeManager = runtime.manager.subscribe(() => {\n const nextKey = JSON.stringify(runtime.manager.getMountedTargets());\n if (nextKey === targetsKey) return;\n targetsKey = nextKey;\n refreshSchema(runtime.manager.getActiveThread());\n });\n // Function handlers can mount at any time. Core reads the context after\n // this callback, so the run gets the current functions and the surfaces\n // of its thread.\n const subscription = copilotkit.subscribe({\n onAgentRunStarted: ({ agent }) => refreshSchema(agent.threadId),\n });\n\n return () => {\n subscription.unsubscribe();\n unsubscribeManager();\n if (guidelineId !== undefined) copilotkit.removeContext(guidelineId);\n if (schemaId !== undefined) copilotkit.removeContext(schemaId);\n };\n }, [copilotkit, runtime, enabled, agentIdsKey]);\n}\n","import { useEffect, useMemo, useRef } from \"react\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport {\n COPILOTKIT_FORWARDED_PROPS_KEY,\n DEFAULT_AGENT_ID,\n GENERATIVE_UI_ACTIVITY_TYPE,\n randomUUID,\n toA2UIActionMessage,\n} from \"@copilotkit/shared\";\nimport type { A2UIActionMessage } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreReact } from \"../lib/react-core\";\nimport { useShallowStableRef } from \"../lib/shallow-stable-ref\";\nimport {\n buildActionMessageText,\n envelopeOptionsFor,\n surfaceLabelResolver,\n} from \"@copilotkit/core/generative-ui\";\nimport {\n createGenerativeUIDebugSource,\n describeGenerativeUIRun,\n} from \"@copilotkit/core/generative-ui\";\nimport { createGenerativeUIDispatcher } from \"@copilotkit/core/generative-ui\";\nimport { GenerativeUIError } from \"@copilotkit/shared/generative-ui\";\nimport type { GenerativeUIErrorInfo } from \"@copilotkit/shared/generative-ui\";\nimport { parseGenerativeUISurfaceContent } from \"./activity\";\nimport { catalogIdsOf } from \"./catalog\";\nimport { buildGenerativeUIEnvelope } from \"@copilotkit/core/generative-ui\";\nimport type {\n GenerativeUIConfig,\n GenerativeUIRuntime,\n} from \"./runtime-context\";\nimport { useGenerativeUIMarkdownContext } from \"./markdown/context\";\nimport { getMarkdownSurfaceSource } from \"@copilotkit/core/generative-ui\";\nimport {\n activityFunctionCalls,\n createFunctionCallRunner,\n markdownFunctionCalls,\n} from \"@copilotkit/core/generative-ui\";\nimport type { ReadonlyMessages } from \"@copilotkit/core/generative-ui\";\nimport { GenerativeUISurfaceManager } from \"@copilotkit/core/generative-ui\";\n\nconst isDevelopment = () => process.env.NODE_ENV !== \"production\";\n\n/**\n * The malformed-content warnings already printed, by manager, so each\n * distinct issue warns once while the manager lives.\n */\nconst warnedMalformed = new WeakMap<GenerativeUISurfaceManager, Set<string>>();\n\n/**\n * Ingests the surface activity messages of `messages`. A message whose\n * content is malformed (for example `null`) is skipped, in development with a\n * warning once for each distinct issue, so it cannot throw inside the\n * agent's run; the messages after it are still ingested.\n */\nfunction ingestMessages(\n manager: GenerativeUISurfaceManager,\n agent: AbstractAgent,\n messages: ReadonlyMessages,\n) {\n const { threadId } = agent;\n if (!threadId) return;\n for (const message of messages) {\n if (\n message.role !== \"activity\" ||\n message.activityType !== GENERATIVE_UI_ACTIVITY_TYPE\n ) {\n continue;\n }\n const parsed = parseGenerativeUISurfaceContent(message.content);\n if (parsed.content) {\n manager.ingest(threadId, agent.agentId, parsed.content);\n continue;\n }\n if (!isDevelopment()) continue;\n const warning = `[generativeUI] skipped an activity message of thread ${JSON.stringify(threadId)}: its content is malformed: ${parsed.issues.join(\"; \")}.`;\n let warned = warnedMalformed.get(manager);\n if (!warned) {\n warned = new Set();\n warnedMalformed.set(manager, warned);\n }\n if (warned.has(warning)) continue;\n warned.add(warning);\n console.warn(warning);\n }\n}\n\n/** Provider-side wiring: manager, dispatcher, agent subscriptions, envelope. */\nexport function useGenerativeUIRoot(\n copilotkit: CopilotKitCoreReact,\n config: GenerativeUIConfig | undefined,\n): GenerativeUIRuntime | null {\n const configRef = useRef(config);\n configRef.current = config;\n const ui = config?.ui;\n const transport = config?.transport ?? \"tool\";\n const theme = useShallowStableRef(config?.theme);\n\n // The parts that live as long as `ui`. The surfaces are in the manager, so\n // a new theme or transport does not remount them.\n const core = useMemo(() => {\n if (!ui) return null;\n // Never throws: it is called from rendering, ingestion and event handlers,\n // and a throwing host `onError` must not break any of them.\n const reportError = (info: GenerativeUIErrorInfo) => {\n try {\n configRef.current?.errorBoundary?.onError?.(info);\n } catch (hostError) {\n if (isDevelopment()) {\n console.error(\n \"[generativeUI] errorBoundary.onError threw:\",\n hostError,\n );\n }\n }\n if (isDevelopment()) {\n console.warn(\n `[generativeUI] ${info.kind} error in ${info.surfaceId}${info.componentId ? `/${info.componentId}` : \"\"}: ${info.error?.message}`,\n );\n }\n };\n const manager = new GenerativeUISurfaceManager(ui, {\n onOperationRejected: ({ surfaceId, index, reason }) =>\n reportError({\n kind: \"operation\",\n surfaceId,\n error: new Error(`operation ${index} rejected: ${reason}`),\n }),\n });\n const dispatcher = createGenerativeUIDispatcher({\n getDeclared: () => ui.functions,\n onError: ({ name, origin, error }) => {\n if (\"functionCallId\" in origin) {\n // The model gets this error in the answer of the call. The error\n // info of `onError` needs a surface, and this call has none.\n if (isDevelopment()) {\n console.warn(\n `[generativeUI] function call ${origin.functionCallId} to \"${name}\" failed: ${error.message}`,\n );\n }\n return;\n }\n reportError({ kind: \"function\", ...origin, error });\n },\n });\n const functionCalls = createFunctionCallRunner({\n core: copilotkit,\n dispatcher,\n manifest: {\n catalogId: ui.id,\n catalogIds: catalogIdsOf(ui),\n components: ui.manifestComponents,\n },\n // As for a frontend-tool follow-up: let React commit the state that\n // the handlers set, so that the follow-up run reads it.\n settle: () => copilotkit.waitForPendingFrameworkUpdates(),\n warn: (message, error) => {\n if (isDevelopment()) console.warn(message, error);\n },\n });\n // The agents with an event on its way to a run. Set before the run\n // starts, so a repeat click in the same tick is caught too.\n const forwardingAgents = new Set<AbstractAgent>();\n /**\n * The action of a user event, as an envelope entry scoped to the agent\n * the user acted on, for the run that the event starts: the structured\n * form of the user message. It is set before the run starts and dropped\n * when the run is over, so a suggestion request or a follow-up run\n * (both read the properties with no run start) does not carry the same\n * action again, and another agent never gets a click meant for this one.\n * The entry comes after the shared envelope, so it wins for its agent;\n * `refreshActions` keeps it last when the shared envelope is set again.\n */\n const actions = new Map<\n AbstractAgent,\n {\n id: string;\n action: A2UIActionMessage;\n /** Drops the action when the run ends, before any follow-up run. */\n subscription: { unsubscribe(): void };\n }\n >();\n const dropAction = (agent: AbstractAgent) => {\n const entry = actions.get(agent);\n if (!entry) return;\n entry.subscription.unsubscribe();\n copilotkit.removeScopedProperties(entry.id);\n actions.delete(agent);\n };\n const setAction = (agent: AbstractAgent, action: A2UIActionMessage) => {\n const previous = actions.get(agent);\n previous?.subscription.unsubscribe();\n if (previous) copilotkit.removeScopedProperties(previous.id);\n actions.delete(agent);\n const latest = configRef.current;\n if (!latest) return;\n const envelope = buildGenerativeUIEnvelope(\n { ui, manager, dispatcher },\n agent.threadId,\n { ...envelopeOptionsFor(latest), action },\n );\n const id = copilotkit.addScopedProperties({\n properties: { [COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: envelope } },\n agentIds:\n agent.agentId === undefined ? latest.agentIds : [agent.agentId],\n });\n // The run ends before `runAgent` resolves: a frontend tool makes a\n // follow-up run first, and that run must not carry the action again.\n // The agent itself says when its run is over.\n const subscription = agent.subscribe({\n onRunFinalized: () => dropAction(agent),\n onRunFailed: () => dropAction(agent),\n });\n actions.set(agent, { id, action, subscription });\n };\n const refreshActions = () => {\n for (const [agent, { action }] of [...actions]) setAction(agent, action);\n };\n const dropAllActions = () => {\n for (const agent of [...actions.keys()]) dropAction(agent);\n };\n const forwardEvent: GenerativeUIRuntime[\"forwardEvent\"] = async (\n event,\n agentId,\n ) => {\n const fail = (message: string) => {\n const error = new GenerativeUIError(\"event_forward_failed\", message);\n reportError({\n kind: \"event\",\n surfaceId: event.surfaceId,\n componentId: event.componentId,\n error,\n });\n return { ok: false as const, error };\n };\n const agent = copilotkit.getAgent(agentId ?? DEFAULT_AGENT_ID);\n if (!agent) {\n return fail(`No agent \"${agentId}\" to receive \"${event.name}\"`);\n }\n // An event is a one-click send. While the agent runs, or another event\n // is on its way, a second one is almost always a repeat: a double\n // click, or a click while the reply streams. Sending it would start a\n // second run and derail the chat, so it is dropped. The component gets\n // `agent_busy`; it is not an error of the UI, so nothing is reported.\n if (agent.isRunning || forwardingAgents.has(agent)) {\n return {\n ok: false as const,\n error: new GenerativeUIError(\n \"agent_busy\",\n `\"${event.name}\" was not sent: the agent is running`,\n ),\n };\n }\n forwardingAgents.add(agent);\n try {\n // A visible user message: the user and the model both see the event.\n const surface = agent.threadId\n ? manager.getSurface(agent.threadId, event.surfaceId)\n : undefined;\n const resolveLabel = surface\n ? surfaceLabelResolver(surface)\n : undefined;\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: buildActionMessageText(event, resolveLabel),\n });\n // Set now, not at the run start: while another agent runs, this\n // run starts with no run-start notification.\n setAction(agent, toA2UIActionMessage(event));\n await copilotkit.runAgent({ agent });\n return { ok: true, result: undefined };\n } catch (cause) {\n return fail(\n `Forwarding \"${event.name}\" failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n } finally {\n forwardingAgents.delete(agent);\n dropAction(agent);\n }\n };\n return {\n manager,\n dispatcher,\n ui,\n forwardEvent,\n reportError,\n functionCalls,\n refreshActions,\n dropAllActions,\n };\n }, [ui, copilotkit]);\n\n // A new object when the theme or the transport changes, so that the\n // components that read them render again.\n const runtime = useMemo<GenerativeUIRuntime | null>(() => {\n if (!core) return null;\n const { manager, dispatcher, forwardEvent, reportError } = core;\n return {\n manager,\n dispatcher,\n ui: core.ui,\n forwardEvent,\n reportError,\n transport,\n theme,\n get config() {\n // `core` exists only while the provider has a config. After the\n // config is removed, nothing reads this runtime again.\n return configRef.current ?? { ui: core.ui };\n },\n get errorFallback() {\n return configRef.current?.errorBoundary?.fallback;\n },\n };\n }, [core, transport, theme]);\n\n useEffect(() => {\n if (!core) return;\n const watched = new WeakSet<AbstractAgent>();\n const agentSubscriptions: Array<{ unsubscribe(): void }> = [];\n let envelopeId: string | undefined;\n // The inspector reads the catalog, the surfaces, and the runs from it.\n const debug = createGenerativeUIDebugSource(core, () => {\n const latest = configRef.current ?? { ui: core.ui };\n return {\n options: envelopeOptionsFor(latest),\n agentIds: latest.agentIds,\n };\n });\n copilotkit.ɵsetGenerativeUIDebugSource(debug.source);\n const removeEnvelope = () => {\n if (envelopeId === undefined) return;\n copilotkit.removeScopedProperties(envelopeId);\n envelopeId = undefined;\n };\n /**\n * Sets the shared envelope of the run. The action entries of the agents\n * with a user event under way (see `forwardEvent`) are set again after\n * it, so they stay the last entries and win for their agents.\n */\n const setEnvelope = (agent: AbstractAgent, latest: GenerativeUIConfig) => {\n removeEnvelope();\n const run = describeGenerativeUIRun(\n core,\n agent.threadId,\n envelopeOptionsFor(latest),\n );\n envelopeId = copilotkit.addScopedProperties({\n properties: {\n [COPILOTKIT_FORWARDED_PROPS_KEY]: { ui: run.envelope },\n },\n agentIds: latest.agentIds,\n });\n core.refreshActions();\n const isForAgent =\n !latest.agentIds || latest.agentIds.includes(agent.agentId ?? \"\");\n if (isForAgent) {\n debug.recordRun({\n ...run,\n agentId: agent.agentId,\n threadId: agent.threadId,\n startedAt: Date.now(),\n });\n }\n };\n /**\n * The tool transport reads the surface activity messages. The markdown\n * transport reads the ```a2ui fences of the assistant messages, and\n * builds the surfaces of the thread from them again on each change.\n * Both give their function calls to the one runner.\n */\n const readMessages = (\n agent: AbstractAgent,\n messages: ReadonlyMessages,\n running: boolean,\n ) => {\n const requests = activityFunctionCalls(messages);\n const { threadId } = agent;\n if (configRef.current?.transport !== \"markdown\") {\n ingestMessages(core.manager, agent, messages);\n } else if (threadId) {\n // A thread switch can happen with no run start. The named targets\n // must show the surfaces of the thread that the messages belong to.\n core.manager.setActiveThread(threadId);\n const calls = getMarkdownSurfaceSource(core).sync(\n threadId,\n agent.agentId,\n messages,\n { running },\n );\n requests.push(...markdownFunctionCalls(calls));\n }\n core.functionCalls.run(agent, requests, messages, running);\n };\n const subscription = copilotkit.subscribe({\n // Core awaits this before it reads the properties for the run, so the\n // envelope set here goes with this run. Tool-call follow-up runs do not\n // fire it. The scoped entry stays until the next run start replaces it,\n // so the follow-up runs send the same envelope.\n onAgentRunStarted: ({ agent }) => {\n core.manager.setActiveThread(agent.threadId);\n const latest = configRef.current;\n if (latest) setEnvelope(agent, latest);\n if (!watched.has(agent)) {\n watched.add(agent);\n agentSubscriptions.push(\n agent.subscribe({\n onMessagesChanged: ({ messages }) =>\n readMessages(agent, messages, agent.isRunning),\n // The last message is final now. An open fence in it is final\n // too, so its surface is no longer \"streaming\". The function\n // calls of the run get their answers now.\n onRunFinalized: () => readMessages(agent, agent.messages, false),\n onRunFailed: () => readMessages(agent, agent.messages, false),\n }),\n );\n }\n // The run starts now, but the agent is not marked as running yet.\n readMessages(agent, agent.messages, true);\n },\n });\n return () => {\n subscription.unsubscribe();\n for (const s of agentSubscriptions) s.unsubscribe();\n // Stop advertising a generative UI that is no longer mounted.\n core.dropAllActions();\n removeEnvelope();\n if (copilotkit.ɵgenerativeUIDebugSource === debug.source) {\n copilotkit.ɵsetGenerativeUIDebugSource(undefined);\n }\n };\n }, [core, copilotkit]);\n\n useGenerativeUIMarkdownContext(copilotkit, core, {\n enabled: config?.transport === \"markdown\" && config.sendContext !== false,\n agentIds: config?.agentIds,\n });\n\n return runtime;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,+BACd,YACA,SACA,SACA;CACA,MAAM,EAAE,SAAS,aAAa;CAE9B,MAAM,cAAc,aAAa,SAAY,KAAK,KAAK,UAAU,SAAS;AAE1E,4BAAgB;AACd,MAAI,CAAC,WAAW,CAAC,QAAS;EAC1B,MAAM,iBAAuC,cACzC,KAAK,MAAM,YAAY,GACvB;EACJ,MAAM,QAAQ,iBAAiB,EAAE,UAAU,gBAAgB,GAAG,EAAE;EAGhE,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,MAAM,iBAAiB,aAAiC;GACtD,MAAM,yEAAqC,SAAS,SAAS;GAC7D,MAAM,0HACsB,SAAS,CACpC;AACD,OAAI,cAAc,gBAAgB;AAChC,QAAI,gBAAgB,OAAW,YAAW,cAAc,YAAY;AACpE,qBAAiB;AACjB,kBAAc,WAAW,WAAW;KAClC,aAAaA;KACb,OAAO;KACP,GAAG;KACJ,CAAC;;GAEJ,MAAM,yDACJ,iEAC+B,CAAC,OAAO,SACxC;AACD,OAAI,UAAU,YAAa;AAC3B,OAAI,aAAa,OAAW,YAAW,cAAc,SAAS;AAC9D,iBAAc;AACd,cAAW,WAAW,WAAW;IAC/B,aAAaC;IACb;IACA,GAAG;IACJ,CAAC;;AAEJ,gBAAc,QAAQ,QAAQ,iBAAiB,CAAC;EAKhD,IAAI,aAAa,KAAK,UAAU,QAAQ,QAAQ,mBAAmB,CAAC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