agentic-ui-kit 0.8.0 → 0.9.1
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 +19 -15
- package/dist/ask-user-CwDYhXX4.js +388 -0
- package/dist/core.js +3 -103
- package/dist/extensions-CJ4Asuxk.js +329 -0
- package/dist/index.js +43 -1394
- package/dist/partial-json-w_oXePqJ.js +111 -0
- package/dist/types/core/src/blocks.d.ts +1 -1
- package/dist/types/core/src/events.d.ts +1 -1
- package/dist/types/core/src/index.d.ts +9 -20
- package/dist/types/core/src/reduce.d.ts +2 -2
- package/dist/types/core/src/sse.d.ts +1 -1
- package/dist/types/core/src/ui-components.d.ts +1 -1
- package/dist/types/core/src/ui-markup.d.ts +1 -1
- package/dist/types/core/src/visuals.d.ts +11 -0
- package/dist/types/react/src/components/approval-card.d.ts +1 -1
- package/dist/types/react/src/components/ask-user.d.ts +1 -1
- package/dist/types/react/src/components/chat-list.d.ts +1 -1
- package/dist/types/react/src/components/composer.d.ts +1 -1
- package/dist/types/react/src/components/extensions.d.ts +50 -0
- package/dist/types/react/src/components/message-list.d.ts +1 -1
- package/dist/types/react/src/components/messages.d.ts +1 -1
- package/dist/types/react/src/components/tool-prompt.d.ts +1 -1
- package/dist/types/react/src/components/tools.d.ts +2 -2
- package/dist/types/react/src/hooks/sse-transport.d.ts +1 -1
- package/dist/types/react/src/hooks/use-chat.d.ts +1 -1
- package/dist/types/react/src/index.d.ts +86 -90
- package/dist/types/react/src/primitives/chat-theme.d.ts +3 -3
- package/dist/types/react/src/views/chat-transcript.d.ts +2 -5
- package/dist/types/react/src/views/chat-view.d.ts +4 -11
- package/dist/types/react/src/views/sidebar.d.ts +1 -1
- package/dist/types/react/src/visuals/core.d.ts +1 -0
- package/dist/types/react/src/visuals/index.d.ts +8 -0
- package/dist/types/react/src/visuals/provider.d.ts +26 -0
- package/dist/types/react/src/{components → visuals}/ui-components.d.ts +2 -2
- package/dist/types/react/src/{components → visuals}/ui-tree.d.ts +2 -1
- package/dist/types/react/src/{components → visuals}/widget-frame.d.ts +2 -1
- package/dist/{src-BrPYkHdt.js → visuals-CxCXnEob.js} +96 -490
- package/dist/visuals-core.js +1 -0
- package/dist/visuals.js +1134 -0
- package/package.json +9 -1
- /package/dist/types/react/src/{components → visuals}/replacements.d.ts +0 -0
package/dist/visuals.js
ADDED
|
@@ -0,0 +1,1134 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { A as widgetLoaderMessages, C as visualizeTool, D as resolveReplaces, b as uiActionSchema, c as parseUiMarkup, d as showUiToolName, g as matchesSchema, h as isStateRef, r as uiSpecSet, v as renderUiToolName, w as replacedId } from "./visuals-CxCXnEob.js";
|
|
3
|
+
import { c as Button, i as useChatInteraction, s as useLabels, t as ChatExtensionsProvider } from "./extensions-CJ4Asuxk.js";
|
|
4
|
+
import { n as salvageJson } from "./partial-json-w_oXePqJ.js";
|
|
5
|
+
import { Component, createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
6
|
+
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
7
|
+
// src/visuals/replacements.tsx
|
|
8
|
+
/**
|
|
9
|
+
* In-place updates of drawn visuals: a tool call whose input has `replaces: <id>` takes the place of that
|
|
10
|
+
* earlier call. In the same reply the newest finished call is drawn where the first one was, and the old one
|
|
11
|
+
* stays (dimmed) until the new one's input is complete. A call replaced from a later reply folds into a link.
|
|
12
|
+
*/
|
|
13
|
+
/** Ready to take the old one's place: its input is complete and it didn't fail. */
|
|
14
|
+
const isReady = (p) => p.status !== "streaming" && p.status !== "input" && p.status !== "error";
|
|
15
|
+
const callsOf = (m) => m.parts.filter((p) => p.type === "tool_call");
|
|
16
|
+
const replaces = (p) => replacedId(p.input ?? p.partialInput);
|
|
17
|
+
const titleOf = (p) => {
|
|
18
|
+
const t = (p.input ?? p.partialInput)?.title;
|
|
19
|
+
return typeof t === "string" && t ? t : void 0;
|
|
20
|
+
};
|
|
21
|
+
/** Ids and titles of the calls seen so far, to resolve `replaces` (an id, or a title as a fallback). */
|
|
22
|
+
function seen() {
|
|
23
|
+
const ids = /* @__PURE__ */ new Set();
|
|
24
|
+
const titles = /* @__PURE__ */ new Map();
|
|
25
|
+
return {
|
|
26
|
+
resolve: (call) => {
|
|
27
|
+
const r = replaces(call);
|
|
28
|
+
return r === void 0 ? void 0 : resolveReplaces(r, ids, titles);
|
|
29
|
+
},
|
|
30
|
+
add: (call) => {
|
|
31
|
+
ids.add(call.id);
|
|
32
|
+
const t = titleOf(call);
|
|
33
|
+
if (t) titles.set(t, call.id);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** One reply's chains: each call's first call (where the chain is drawn) and each first call's chain, in order. */
|
|
38
|
+
function chainsOf(message) {
|
|
39
|
+
const first = /* @__PURE__ */ new Map();
|
|
40
|
+
const chains = /* @__PURE__ */ new Map();
|
|
41
|
+
const known = seen();
|
|
42
|
+
for (const call of callsOf(message)) {
|
|
43
|
+
const r = known.resolve(call);
|
|
44
|
+
known.add(call);
|
|
45
|
+
const root = r !== void 0 && first.has(r) ? first.get(r) : call.id;
|
|
46
|
+
first.set(call.id, root);
|
|
47
|
+
chains.set(root, [...chains.get(root) ?? [], call]);
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
first,
|
|
51
|
+
chains
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** Calls replaced by a finished call in a later reply: replaced id → the newest such call. */
|
|
55
|
+
function laterReplacements(messages) {
|
|
56
|
+
const later = /* @__PURE__ */ new Map();
|
|
57
|
+
const known = seen();
|
|
58
|
+
for (const m of messages) {
|
|
59
|
+
if (m.role !== "assistant") continue;
|
|
60
|
+
const calls = callsOf(m);
|
|
61
|
+
const own = new Set(calls.map((c) => c.id));
|
|
62
|
+
for (const call of calls) {
|
|
63
|
+
const r = known.resolve(call);
|
|
64
|
+
if (r !== void 0 && !own.has(r) && isReady(call)) later.set(r, call);
|
|
65
|
+
}
|
|
66
|
+
calls.forEach(known.add);
|
|
67
|
+
}
|
|
68
|
+
return later;
|
|
69
|
+
}
|
|
70
|
+
const LaterContext = createContext(/* @__PURE__ */ new Map());
|
|
71
|
+
function LaterReplacements({ value, children }) {
|
|
72
|
+
return /* @__PURE__ */ jsx(LaterContext.Provider, {
|
|
73
|
+
value,
|
|
74
|
+
children
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
/** The call in a later reply that replaces any call of this chain, if there is one. */
|
|
78
|
+
function useLaterReplacement(chain) {
|
|
79
|
+
const later = useContext(LaterContext);
|
|
80
|
+
for (let i = chain.length - 1; i >= 0; i--) {
|
|
81
|
+
const by = later.get(chain[i].id);
|
|
82
|
+
if (by) return by;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** The DOM id of a drawn tool call, for the "Updated below" link. */
|
|
86
|
+
const toolAnchor = (id) => `chat-tool-${id}`;
|
|
87
|
+
/** Draws a chain: the newest finished call (dimmed while a newer one streams), or a link to its later update. */
|
|
88
|
+
function ToolChain({ chain, draw }) {
|
|
89
|
+
const labels = useLabels();
|
|
90
|
+
const later = useLaterReplacement(chain);
|
|
91
|
+
const shown = chain.findLast(isReady) ?? chain[0];
|
|
92
|
+
const updating = chain.indexOf(shown) < chain.length - 1 && chain.at(-1).status !== "error";
|
|
93
|
+
if (later) return /* @__PURE__ */ jsx(Button, {
|
|
94
|
+
variant: "ghost",
|
|
95
|
+
size: "sm",
|
|
96
|
+
className: "self-start text-chat-muted data-hovered:text-chat-fg",
|
|
97
|
+
onPress: () => document.getElementById(toolAnchor(later.id))?.scrollIntoView({
|
|
98
|
+
behavior: "smooth",
|
|
99
|
+
block: "center"
|
|
100
|
+
}),
|
|
101
|
+
children: labels.visualUpdated
|
|
102
|
+
});
|
|
103
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
104
|
+
id: toolAnchor(chain[0].id),
|
|
105
|
+
"aria-busy": updating || void 0,
|
|
106
|
+
className: updating ? "opacity-60 transition-opacity" : "transition-opacity",
|
|
107
|
+
children: [/* @__PURE__ */ jsx("div", { children: draw(shown) }, shown.id), updating && /* @__PURE__ */ jsx("p", {
|
|
108
|
+
className: "chat-shimmer mt-1 font-chat-sans text-(length:--chat-ui-font-size-sm) text-chat-muted",
|
|
109
|
+
children: labels.visualUpdating
|
|
110
|
+
})]
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
// src/visuals/widget-frame.tsx
|
|
114
|
+
const WidgetHostContext = createContext({});
|
|
115
|
+
/** Sets what widgets below may do. `VisualsProvider` sets it from its `host` prop. */
|
|
116
|
+
function WidgetHostProvider({ host, children }) {
|
|
117
|
+
return /* @__PURE__ */ jsx(WidgetHostContext.Provider, {
|
|
118
|
+
value: host,
|
|
119
|
+
children
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
/** The host's abilities. Inside a ChatView, `onPrompt` sends through its `onSend`; a ChatTranscript has no `onPrompt` or `onCallTool`. */
|
|
123
|
+
function useWidgetHost() {
|
|
124
|
+
const host = useContext(WidgetHostContext);
|
|
125
|
+
const { send, readOnly } = useChatInteraction();
|
|
126
|
+
return useMemo(() => {
|
|
127
|
+
if (readOnly) {
|
|
128
|
+
const { onPrompt: _prompt, onCallTool: _call, ...rest } = host;
|
|
129
|
+
return rest;
|
|
130
|
+
}
|
|
131
|
+
return send ? {
|
|
132
|
+
onPrompt: send,
|
|
133
|
+
...host
|
|
134
|
+
} : host;
|
|
135
|
+
}, [
|
|
136
|
+
host,
|
|
137
|
+
send,
|
|
138
|
+
readOnly
|
|
139
|
+
]);
|
|
140
|
+
}
|
|
141
|
+
/** The tallest a widget may grow, in px. */
|
|
142
|
+
const WIDGET_MAX_HEIGHT = 2e3;
|
|
143
|
+
const PROTOCOL_VERSION = "2026-01-26";
|
|
144
|
+
const THEME_VARS = [
|
|
145
|
+
"bg",
|
|
146
|
+
"fg",
|
|
147
|
+
"muted",
|
|
148
|
+
"subtle",
|
|
149
|
+
"surface",
|
|
150
|
+
"raised",
|
|
151
|
+
"hover",
|
|
152
|
+
"selected",
|
|
153
|
+
"border",
|
|
154
|
+
"border-strong",
|
|
155
|
+
"divider",
|
|
156
|
+
"accent",
|
|
157
|
+
"accent-fg",
|
|
158
|
+
"check",
|
|
159
|
+
"warning",
|
|
160
|
+
"danger",
|
|
161
|
+
"code-bg",
|
|
162
|
+
"font-sans",
|
|
163
|
+
"font-serif",
|
|
164
|
+
"font-mono",
|
|
165
|
+
"radius-sm",
|
|
166
|
+
"radius-md",
|
|
167
|
+
"radius-lg",
|
|
168
|
+
"ui-font-size",
|
|
169
|
+
"ui-font-size-sm",
|
|
170
|
+
"message-font-size"
|
|
171
|
+
];
|
|
172
|
+
const ORIGIN = /^(https?|wss?):\/\/(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*(:\d{1,5})?$/;
|
|
173
|
+
function origins(list) {
|
|
174
|
+
return (list ?? []).map((d) => d.trim().toLowerCase().replace(/\/$/, "")).filter((d) => ORIGIN.test(d));
|
|
175
|
+
}
|
|
176
|
+
/** Whether `origin` is covered by `allowed`, which may be a wildcard like "https://*.example.com". */
|
|
177
|
+
function covers(allowed, origin) {
|
|
178
|
+
if (allowed === origin) return true;
|
|
179
|
+
const wild = /^([a-z]+:\/\/)\*\.(.+)$/.exec(allowed);
|
|
180
|
+
return !!wild && origin.startsWith(wild[1]) && origin.slice(wild[1].length).endsWith("." + wild[2]) && !origin.includes("*");
|
|
181
|
+
}
|
|
182
|
+
/** The part of a widget's request that the host allows. */
|
|
183
|
+
function intersectAllow(request, allow = {}) {
|
|
184
|
+
const keep = (asked, max) => origins(asked).filter((o) => origins(max).some((m) => covers(m, o)));
|
|
185
|
+
return {
|
|
186
|
+
resourceDomains: keep(request.resourceDomains, allow.resourceDomains),
|
|
187
|
+
connectDomains: keep(request.connectDomains, allow.connectDomains)
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
/** The Content-Security-Policy of a widget's document. */
|
|
191
|
+
function widgetCsp(allow = {}) {
|
|
192
|
+
const res = origins(allow.resourceDomains).join(" ");
|
|
193
|
+
const conn = origins(allow.connectDomains).join(" ");
|
|
194
|
+
const with_ = (base) => res ? `${base} ${res}` : base;
|
|
195
|
+
return [
|
|
196
|
+
"default-src 'none'",
|
|
197
|
+
with_("script-src 'unsafe-inline'"),
|
|
198
|
+
with_("style-src 'unsafe-inline'"),
|
|
199
|
+
with_("img-src data: blob:"),
|
|
200
|
+
with_("font-src data:"),
|
|
201
|
+
with_("media-src data: blob:"),
|
|
202
|
+
`connect-src ${conn || "'none'"}`,
|
|
203
|
+
"frame-src 'none'",
|
|
204
|
+
"base-uri 'none'",
|
|
205
|
+
"form-action 'none'"
|
|
206
|
+
].join("; ");
|
|
207
|
+
}
|
|
208
|
+
/** Runs inside a fragment's frame: renders the markup, reports its height, offers sendPrompt and openLink. */
|
|
209
|
+
const BOOT = `(() => {
|
|
210
|
+
const root = document.getElementById("widget");
|
|
211
|
+
let id = 0;
|
|
212
|
+
const post = (method, params, request) => parent.postMessage(request ? { jsonrpc: "2.0", id: ++id, method, params } : { jsonrpc: "2.0", method, params }, "*");
|
|
213
|
+
window.sendPrompt = (text) => post("ui/message", { role: "user", content: [{ type: "text", text: String(text) }] }, true);
|
|
214
|
+
window.openLink = (url) => post("ui/open-link", { url: String(url) }, true);
|
|
215
|
+
let done = false;
|
|
216
|
+
const runScripts = async () => {
|
|
217
|
+
for (const old of [...root.querySelectorAll("script")]) {
|
|
218
|
+
const s = document.createElement("script");
|
|
219
|
+
for (const a of old.attributes) s.setAttribute(a.name, a.value);
|
|
220
|
+
s.textContent = old.textContent;
|
|
221
|
+
const loaded = s.src ? new Promise((ok) => { s.onload = s.onerror = ok; }) : null;
|
|
222
|
+
old.replaceWith(s);
|
|
223
|
+
if (loaded) await loaded;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
const theme = (ctx) => {
|
|
227
|
+
const vars = (ctx && ctx.styles && ctx.styles.variables) || {};
|
|
228
|
+
for (const k in vars) if (k.startsWith("--chat-")) document.documentElement.style.setProperty(k, vars[k]);
|
|
229
|
+
if (ctx && ctx.theme) document.documentElement.style.colorScheme = ctx.theme;
|
|
230
|
+
};
|
|
231
|
+
addEventListener("message", (e) => {
|
|
232
|
+
if (e.source !== parent) return;
|
|
233
|
+
const m = e.data || {};
|
|
234
|
+
if (m.method === "ui/notifications/host-context-changed") return theme(m.params);
|
|
235
|
+
const code = m.params && m.params.arguments && m.params.arguments.widget_code;
|
|
236
|
+
if (typeof code !== "string" || done) return;
|
|
237
|
+
if (m.method === "ui/notifications/tool-input-partial") root.innerHTML = code;
|
|
238
|
+
if (m.method === "ui/notifications/tool-input") { done = true; root.innerHTML = code; runScripts(); }
|
|
239
|
+
});
|
|
240
|
+
let last = -1;
|
|
241
|
+
new ResizeObserver(() => {
|
|
242
|
+
const h = Math.ceil(root.getBoundingClientRect().height);
|
|
243
|
+
if (h !== last) { last = h; post("ui/notifications/size-changed", { height: h }); }
|
|
244
|
+
// The frame grows to fit, a moment behind; only content past the cap gets a scrollbar.
|
|
245
|
+
document.documentElement.style.overflowY = h > ${WIDGET_MAX_HEIGHT} ? "auto" : "hidden";
|
|
246
|
+
}).observe(root);
|
|
247
|
+
const seen = new Set();
|
|
248
|
+
const report = (text) => { if (!seen.has(text) && seen.size < 10) { seen.add(text); post("notifications/message", { level: "error", logger: "widget", data: text }); } };
|
|
249
|
+
addEventListener("error", (e) => report(String(e.message) + (e.lineno ? " (line " + e.lineno + ")" : "")));
|
|
250
|
+
addEventListener("unhandledrejection", (e) => report("Unhandled promise rejection: " + String(e.reason && e.reason.message || e.reason)));
|
|
251
|
+
post("ui/notifications/initialized", {});
|
|
252
|
+
})();`;
|
|
253
|
+
function fragmentDoc(csp, theme) {
|
|
254
|
+
return `<!doctype html><html><head><meta charset="utf-8">
|
|
255
|
+
<meta http-equiv="Content-Security-Policy" content="${csp}">
|
|
256
|
+
<style>
|
|
257
|
+
:root { ${Object.entries(theme.vars).map(([k, v]) => `${k}: ${v};`).join(" ")} color-scheme: ${theme.scheme}; }
|
|
258
|
+
html { overflow: hidden; }
|
|
259
|
+
html, body { margin: 0; background: transparent; color: var(--chat-fg); font-family: var(--chat-font-sans);
|
|
260
|
+
font-size: var(--chat-ui-font-size); line-height: 1.5; }
|
|
261
|
+
#widget { display: flow-root; }
|
|
262
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
263
|
+
button, input, select, textarea { font: inherit; color: inherit; }
|
|
264
|
+
</style></head><body><div id="widget"></div><script>${BOOT}<\/script></body></html>`;
|
|
265
|
+
}
|
|
266
|
+
/** An app's own document with the host's CSP put first in its head (a second policy can only narrow it). */
|
|
267
|
+
function appDoc(csp, html) {
|
|
268
|
+
const meta = `<meta http-equiv="Content-Security-Policy" content="${csp}">`;
|
|
269
|
+
const head = /<head(\s[^>]*)?>/i.exec(html);
|
|
270
|
+
if (head) return html.slice(0, head.index + head[0].length) + meta + html.slice(head.index + head[0].length);
|
|
271
|
+
const root = /<html(\s[^>]*)?>/i.exec(html);
|
|
272
|
+
if (root) return html.slice(0, root.index + root[0].length) + `<head>${meta}</head>` + html.slice(root.index + root[0].length);
|
|
273
|
+
return `<!doctype html><html><head>${meta}</head><body>${html}</body></html>`;
|
|
274
|
+
}
|
|
275
|
+
function readTheme(el) {
|
|
276
|
+
const style = getComputedStyle(el);
|
|
277
|
+
return {
|
|
278
|
+
vars: Object.fromEntries(THEME_VARS.map((v) => [`--chat-${v}`, style.getPropertyValue(`--chat-${v}`).trim()])),
|
|
279
|
+
scheme: /light/.test(style.colorScheme) && !/dark/.test(style.colorScheme) ? "light" : "dark"
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/** Calls `onChange` when anything above `el` changes attributes (a theme switch) or the OS scheme flips. */
|
|
283
|
+
function watchTheme(el, onChange) {
|
|
284
|
+
const observer = new MutationObserver(onChange);
|
|
285
|
+
for (let node = el; node; node = node.parentElement) observer.observe(node, {
|
|
286
|
+
attributes: true,
|
|
287
|
+
attributeFilter: [
|
|
288
|
+
"class",
|
|
289
|
+
"style",
|
|
290
|
+
"data-chat-theme"
|
|
291
|
+
]
|
|
292
|
+
});
|
|
293
|
+
const media = typeof matchMedia === "function" ? matchMedia("(prefers-color-scheme: dark)") : void 0;
|
|
294
|
+
media?.addEventListener?.("change", onChange);
|
|
295
|
+
return () => {
|
|
296
|
+
observer.disconnect();
|
|
297
|
+
media?.removeEventListener?.("change", onChange);
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
function WidgetFrame({ html, document: isDocument = false, streaming = false, title, loadingMessages, allow, csp: request, onPrompt, onOpenLink, onCallTool, onError, toolInput, toolResult, cancelled, frameUrl: ownFrameUrl, className }) {
|
|
301
|
+
const labels = useLabels();
|
|
302
|
+
const hostFrameUrl = useWidgetHost().frameUrl;
|
|
303
|
+
const frameUrl = ownFrameUrl ?? hostFrameUrl;
|
|
304
|
+
const frame = useRef(null);
|
|
305
|
+
const host = useRef(null);
|
|
306
|
+
const [ready, setReady] = useState(false);
|
|
307
|
+
const [height, setHeight] = useState(0);
|
|
308
|
+
const [initial, setInitial] = useState();
|
|
309
|
+
const theme = useRef(void 0);
|
|
310
|
+
const [tick, setTick] = useState(0);
|
|
311
|
+
const effective = request ? intersectAllow(request, allow) : isDocument ? {} : allow ?? {};
|
|
312
|
+
const policy = widgetCsp(effective);
|
|
313
|
+
const doc = useMemo(() => initial && (isDocument ? appDoc(policy, html) : fragmentDoc(policy, initial)), [
|
|
314
|
+
initial,
|
|
315
|
+
policy,
|
|
316
|
+
isDocument,
|
|
317
|
+
isDocument && html
|
|
318
|
+
]);
|
|
319
|
+
const latest = useRef({
|
|
320
|
+
onPrompt,
|
|
321
|
+
onOpenLink,
|
|
322
|
+
onCallTool,
|
|
323
|
+
onError,
|
|
324
|
+
policy,
|
|
325
|
+
effective,
|
|
326
|
+
doc
|
|
327
|
+
});
|
|
328
|
+
latest.current = {
|
|
329
|
+
onPrompt,
|
|
330
|
+
onOpenLink,
|
|
331
|
+
onCallTool,
|
|
332
|
+
onError,
|
|
333
|
+
policy,
|
|
334
|
+
effective,
|
|
335
|
+
doc
|
|
336
|
+
};
|
|
337
|
+
const generation = useRef({
|
|
338
|
+
doc,
|
|
339
|
+
n: 0
|
|
340
|
+
});
|
|
341
|
+
if (generation.current.doc !== doc) generation.current = {
|
|
342
|
+
doc,
|
|
343
|
+
n: generation.current.n + 1
|
|
344
|
+
};
|
|
345
|
+
const send = (message) => frame.current?.contentWindow?.postMessage({
|
|
346
|
+
jsonrpc: "2.0",
|
|
347
|
+
...message
|
|
348
|
+
}, "*");
|
|
349
|
+
const context = () => ({
|
|
350
|
+
theme: theme.current?.scheme,
|
|
351
|
+
styles: { variables: theme.current?.vars },
|
|
352
|
+
displayMode: "inline",
|
|
353
|
+
availableDisplayModes: ["inline"],
|
|
354
|
+
containerDimensions: {
|
|
355
|
+
maxHeight: WIDGET_MAX_HEIGHT,
|
|
356
|
+
...host.current && { width: host.current.clientWidth }
|
|
357
|
+
},
|
|
358
|
+
platform: "web",
|
|
359
|
+
...labels.locale && { locale: labels.locale }
|
|
360
|
+
});
|
|
361
|
+
useEffect(() => {
|
|
362
|
+
const el = host.current;
|
|
363
|
+
theme.current = readTheme(el);
|
|
364
|
+
setInitial(theme.current);
|
|
365
|
+
return watchTheme(el, () => {
|
|
366
|
+
const next = readTheme(el);
|
|
367
|
+
if (JSON.stringify(next) === JSON.stringify(theme.current)) return;
|
|
368
|
+
theme.current = next;
|
|
369
|
+
send({
|
|
370
|
+
method: "ui/notifications/host-context-changed",
|
|
371
|
+
params: {
|
|
372
|
+
theme: next.scheme,
|
|
373
|
+
styles: { variables: next.vars }
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
});
|
|
377
|
+
}, []);
|
|
378
|
+
useEffect(() => setReady(false), [doc]);
|
|
379
|
+
useEffect(() => {
|
|
380
|
+
const reply = (id, result) => id !== void 0 && send({
|
|
381
|
+
id,
|
|
382
|
+
result
|
|
383
|
+
});
|
|
384
|
+
const fail = (id, code, message) => id !== void 0 && send({
|
|
385
|
+
id,
|
|
386
|
+
error: {
|
|
387
|
+
code,
|
|
388
|
+
message
|
|
389
|
+
}
|
|
390
|
+
});
|
|
391
|
+
const onMessage = async (e) => {
|
|
392
|
+
if (!frame.current || e.source !== frame.current.contentWindow) return;
|
|
393
|
+
if (e.data?.type === widgetLoaderMessages.ready) {
|
|
394
|
+
const html = latest.current.doc;
|
|
395
|
+
if (html) frame.current.contentWindow?.postMessage({
|
|
396
|
+
type: widgetLoaderMessages.document,
|
|
397
|
+
html
|
|
398
|
+
}, "*");
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
const m = e.data ?? {};
|
|
402
|
+
if (typeof m !== "object" || typeof m.method !== "string") return;
|
|
403
|
+
const { onPrompt, onOpenLink, onCallTool, effective } = latest.current;
|
|
404
|
+
switch (m.method) {
|
|
405
|
+
case "ui/initialize": return reply(m.id, {
|
|
406
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
407
|
+
hostInfo: {
|
|
408
|
+
name: "agentic-ui-kit",
|
|
409
|
+
version: "1"
|
|
410
|
+
},
|
|
411
|
+
hostCapabilities: {
|
|
412
|
+
...onOpenLink && { openLinks: {} },
|
|
413
|
+
...onCallTool && { serverTools: {} },
|
|
414
|
+
logging: {},
|
|
415
|
+
sandbox: { csp: effective }
|
|
416
|
+
},
|
|
417
|
+
hostContext: context()
|
|
418
|
+
});
|
|
419
|
+
case "ui/notifications/initialized": return setReady(true);
|
|
420
|
+
case "ui/notifications/size-changed": return setHeight(Math.min(Math.max(0, Number(m.params?.height) || 0), WIDGET_MAX_HEIGHT));
|
|
421
|
+
case "ui/message": {
|
|
422
|
+
const text = (Array.isArray(m.params?.content) ? m.params.content : []).find((c) => c?.type === "text")?.text;
|
|
423
|
+
if (!onPrompt) return fail(m.id, -32e3, "Sending messages is off");
|
|
424
|
+
if (typeof text !== "string" || !text.trim()) return fail(m.id, -32602, "Empty message");
|
|
425
|
+
onPrompt(text.slice(0, 4e3));
|
|
426
|
+
return reply(m.id, {});
|
|
427
|
+
}
|
|
428
|
+
case "ui/open-link": {
|
|
429
|
+
const url = String(m.params?.url ?? "");
|
|
430
|
+
if (!onOpenLink) return fail(m.id, -32e3, "Opening links is off");
|
|
431
|
+
if (!/^https?:\/\//i.test(url)) return fail(m.id, -32602, "Only http(s) links");
|
|
432
|
+
onOpenLink(url);
|
|
433
|
+
return reply(m.id, {});
|
|
434
|
+
}
|
|
435
|
+
case "tools/call": {
|
|
436
|
+
if (!onCallTool) return fail(m.id, -32e3, "Calling tools is off");
|
|
437
|
+
const name = String(m.params?.name ?? "");
|
|
438
|
+
const args = m.params?.arguments ?? {};
|
|
439
|
+
try {
|
|
440
|
+
return reply(m.id, await onCallTool(name, args));
|
|
441
|
+
} catch (error) {
|
|
442
|
+
return fail(m.id, -32e3, error instanceof Error ? error.message : String(error));
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
case "ping": return reply(m.id, {});
|
|
446
|
+
case "notifications/message": {
|
|
447
|
+
const data = typeof m.params?.data === "string" ? m.params.data : JSON.stringify(m.params?.data);
|
|
448
|
+
if (m.params?.level === "error" && data) latest.current.onError?.(data.slice(0, 1e3));
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
default: return fail(m.id, -32601, "Method not found");
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
window.addEventListener("message", onMessage);
|
|
455
|
+
return () => window.removeEventListener("message", onMessage);
|
|
456
|
+
}, []);
|
|
457
|
+
useEffect(() => {
|
|
458
|
+
if (!ready || isDocument) return;
|
|
459
|
+
send({
|
|
460
|
+
method: streaming ? "ui/notifications/tool-input-partial" : "ui/notifications/tool-input",
|
|
461
|
+
params: { arguments: { widget_code: html } }
|
|
462
|
+
});
|
|
463
|
+
}, [
|
|
464
|
+
ready,
|
|
465
|
+
isDocument,
|
|
466
|
+
html,
|
|
467
|
+
streaming
|
|
468
|
+
]);
|
|
469
|
+
const inputKey = isDocument && toolInput !== void 0 ? JSON.stringify(toolInput) : void 0;
|
|
470
|
+
useEffect(() => {
|
|
471
|
+
if (!ready || inputKey === void 0) return;
|
|
472
|
+
send({
|
|
473
|
+
method: streaming ? "ui/notifications/tool-input-partial" : "ui/notifications/tool-input",
|
|
474
|
+
params: { arguments: JSON.parse(inputKey) }
|
|
475
|
+
});
|
|
476
|
+
}, [
|
|
477
|
+
ready,
|
|
478
|
+
inputKey,
|
|
479
|
+
streaming
|
|
480
|
+
]);
|
|
481
|
+
useEffect(() => {
|
|
482
|
+
if (ready && isDocument && toolResult !== void 0) send({
|
|
483
|
+
method: "ui/notifications/tool-result",
|
|
484
|
+
params: toolResult
|
|
485
|
+
});
|
|
486
|
+
}, [
|
|
487
|
+
ready,
|
|
488
|
+
isDocument,
|
|
489
|
+
toolResult
|
|
490
|
+
]);
|
|
491
|
+
useEffect(() => {
|
|
492
|
+
if (ready && isDocument && cancelled !== void 0) send({
|
|
493
|
+
method: "ui/notifications/tool-cancelled",
|
|
494
|
+
params: { reason: cancelled }
|
|
495
|
+
});
|
|
496
|
+
}, [
|
|
497
|
+
ready,
|
|
498
|
+
isDocument,
|
|
499
|
+
cancelled
|
|
500
|
+
]);
|
|
501
|
+
const lines = loadingMessages?.length ? loadingMessages : [labels.drawingWidget];
|
|
502
|
+
useEffect(() => {
|
|
503
|
+
if (!streaming || lines.length < 2) return;
|
|
504
|
+
const id = setInterval(() => setTick((t) => t + 1), 1800);
|
|
505
|
+
return () => clearInterval(id);
|
|
506
|
+
}, [streaming, lines.length]);
|
|
507
|
+
return /* @__PURE__ */ jsxs("figure", {
|
|
508
|
+
ref: host,
|
|
509
|
+
className: className ?? "my-2",
|
|
510
|
+
"aria-label": title ?? labels.widget,
|
|
511
|
+
"aria-busy": streaming || void 0,
|
|
512
|
+
children: [streaming && /* @__PURE__ */ jsx("div", {
|
|
513
|
+
className: "mb-2 animate-pulse font-chat-sans text-(length:--chat-ui-font-size) text-chat-muted motion-reduce:animate-none",
|
|
514
|
+
children: lines[tick % lines.length]
|
|
515
|
+
}), doc && /* @__PURE__ */ jsx("iframe", {
|
|
516
|
+
ref: frame,
|
|
517
|
+
title: title ?? labels.widget,
|
|
518
|
+
sandbox: "allow-scripts",
|
|
519
|
+
...frameUrl ? { src: frameUrl } : { srcDoc: doc },
|
|
520
|
+
style: {
|
|
521
|
+
height: height || (streaming ? 120 : 0),
|
|
522
|
+
transition: "height 150ms ease-out"
|
|
523
|
+
},
|
|
524
|
+
className: "block w-full border-0 bg-transparent"
|
|
525
|
+
}, frameUrl ? generation.current.n : "srcdoc")]
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
/** Pulls the host's abilities from context into frame props. */
|
|
529
|
+
function useHostProps(partId) {
|
|
530
|
+
const { allow, onPrompt, onOpenLink, onCallTool, onWidgetError } = useWidgetHost();
|
|
531
|
+
return {
|
|
532
|
+
...allow && { allow },
|
|
533
|
+
...onPrompt && { onPrompt },
|
|
534
|
+
...onOpenLink && { onOpenLink },
|
|
535
|
+
...onCallTool && { onCallTool },
|
|
536
|
+
...onWidgetError && { onError: (message) => onWidgetError({
|
|
537
|
+
partId,
|
|
538
|
+
message
|
|
539
|
+
}) }
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
/** The default look of a `widget` part: inline html, or an app UI the host reads from `resourceUri`. */
|
|
543
|
+
function WidgetPartView({ part }) {
|
|
544
|
+
const host = useWidgetHost();
|
|
545
|
+
const props = useHostProps(part.id);
|
|
546
|
+
const [resource, setResource] = useState();
|
|
547
|
+
const uri = part.html === void 0 ? part.resourceUri : void 0;
|
|
548
|
+
useEffect(() => {
|
|
549
|
+
if (!uri || !host.readResource) return;
|
|
550
|
+
let live = true;
|
|
551
|
+
host.readResource(uri).then((r) => live && setResource(r), (e) => console.warn("widget:", e));
|
|
552
|
+
return () => {
|
|
553
|
+
live = false;
|
|
554
|
+
};
|
|
555
|
+
}, [uri, host.readResource]);
|
|
556
|
+
if (part.html !== void 0) return /* @__PURE__ */ jsx(WidgetFrame, {
|
|
557
|
+
html: part.html,
|
|
558
|
+
streaming: part.status === "streaming",
|
|
559
|
+
...part.title && { title: part.title },
|
|
560
|
+
...props
|
|
561
|
+
});
|
|
562
|
+
if (!resource) return null;
|
|
563
|
+
return /* @__PURE__ */ jsx(WidgetFrame, {
|
|
564
|
+
document: true,
|
|
565
|
+
html: resource.html,
|
|
566
|
+
...resource.csp && { csp: resource.csp },
|
|
567
|
+
...part.title && { title: part.title },
|
|
568
|
+
...props
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
const str = (v) => typeof v === "string" ? v : void 0;
|
|
572
|
+
/** Reads the fields of the suggested `visualizeTool` (widget_code, title, loading_messages). */
|
|
573
|
+
function readVisualizeInput(input) {
|
|
574
|
+
const i = input ?? {};
|
|
575
|
+
const loading = Array.isArray(i.loading_messages) ? i.loading_messages.filter((l) => typeof l === "string" && l !== "") : [];
|
|
576
|
+
return {
|
|
577
|
+
...str(i.widget_code) !== void 0 && { html: str(i.widget_code) },
|
|
578
|
+
...str(i.title) && { title: str(i.title) },
|
|
579
|
+
...loading.length && { loadingMessages: loading.slice(0, 4) }
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* A tool view that draws a call's (streaming) input in a WidgetFrame, for whatever tool your harness uses
|
|
584
|
+
* to write HTML. Register it under your tool's name: `{ show_widget: widgetToolView() }`. `read` maps your
|
|
585
|
+
* tool's input (possibly cut short while it streams) to the frame's fields; the default reads the suggested
|
|
586
|
+
* `visualizeTool`'s fields.
|
|
587
|
+
*/
|
|
588
|
+
function widgetToolView(read = readVisualizeInput) {
|
|
589
|
+
function WidgetToolBlock({ part }) {
|
|
590
|
+
const props = useHostProps(part.id);
|
|
591
|
+
const { html = "", title, loadingMessages } = read(part.input ?? part.partialInput);
|
|
592
|
+
if (part.status === "error" && !html) return null;
|
|
593
|
+
return /* @__PURE__ */ jsx(WidgetFrame, {
|
|
594
|
+
html,
|
|
595
|
+
streaming: part.status === "streaming" || part.status === "input",
|
|
596
|
+
...title && { title },
|
|
597
|
+
...loadingMessages?.length && { loadingMessages },
|
|
598
|
+
...props
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
return { Block: WidgetToolBlock };
|
|
602
|
+
}
|
|
603
|
+
/** The default `onOpenLink` of ChatView and ChatTranscript: a new tab with no opener. */
|
|
604
|
+
function openInNewTab(url) {
|
|
605
|
+
window.open(url, "_blank", "noopener,noreferrer");
|
|
606
|
+
}
|
|
607
|
+
// src/visuals/ui-tree.tsx
|
|
608
|
+
const RegistryContext = createContext(void 0);
|
|
609
|
+
/**
|
|
610
|
+
* The components the model may use: in ```ui blocks of its replies (see `uiMarkupGuide` in
|
|
611
|
+
* agentic-ui-kit/core) and in tool calls drawn with `uiTreeToolView`. `persist` keeps each widget's state.
|
|
612
|
+
*/
|
|
613
|
+
function UiComponentsProvider({ components, persist, markup = "ui", children }) {
|
|
614
|
+
const value = useMemo(() => ({
|
|
615
|
+
components: new Map(components.map((c) => [c.name, c])),
|
|
616
|
+
persist,
|
|
617
|
+
markup
|
|
618
|
+
}), [
|
|
619
|
+
components,
|
|
620
|
+
persist,
|
|
621
|
+
markup
|
|
622
|
+
]);
|
|
623
|
+
return /* @__PURE__ */ jsx(RegistryContext.Provider, {
|
|
624
|
+
value,
|
|
625
|
+
children
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
const TreeContext = createContext({
|
|
629
|
+
state: {},
|
|
630
|
+
run: () => {},
|
|
631
|
+
streaming: false
|
|
632
|
+
});
|
|
633
|
+
/** Inside a registered component: runs an action from its props, e.g. `run(props.onPress)`. Bad actions do nothing. */
|
|
634
|
+
function useUiAction() {
|
|
635
|
+
const { run } = useContext(TreeContext);
|
|
636
|
+
return useCallback((action) => matchesSchema(uiActionSchema, action) && run(action), [run]);
|
|
637
|
+
}
|
|
638
|
+
/** Inside a registered component: the widget's state and a setter, for inputs that write to it. */
|
|
639
|
+
function useUiState() {
|
|
640
|
+
const { state, run } = useContext(TreeContext);
|
|
641
|
+
return [state, useCallback((key, value) => run({
|
|
642
|
+
action: "set",
|
|
643
|
+
key,
|
|
644
|
+
value
|
|
645
|
+
}), [run])];
|
|
646
|
+
}
|
|
647
|
+
/** Replaces `{ "$state": key }` anywhere in the props with the state's value. */
|
|
648
|
+
function resolve(value, state) {
|
|
649
|
+
if (isStateRef(value)) return state[value.$state];
|
|
650
|
+
if (Array.isArray(value)) return value.map((v) => resolve(v, state));
|
|
651
|
+
if (typeof value === "object" && value !== null) {
|
|
652
|
+
const out = {};
|
|
653
|
+
for (const [k, v] of Object.entries(value)) {
|
|
654
|
+
const r = resolve(v, state);
|
|
655
|
+
if (r !== void 0) out[k] = r;
|
|
656
|
+
}
|
|
657
|
+
return out;
|
|
658
|
+
}
|
|
659
|
+
return value;
|
|
660
|
+
}
|
|
661
|
+
/** A component that throws renders nothing instead of taking the message down. */
|
|
662
|
+
var Contain = class extends Component {
|
|
663
|
+
state = { failed: false };
|
|
664
|
+
static getDerivedStateFromError() {
|
|
665
|
+
return { failed: true };
|
|
666
|
+
}
|
|
667
|
+
componentDidCatch(error) {
|
|
668
|
+
console.warn("render_ui:", error);
|
|
669
|
+
}
|
|
670
|
+
render() {
|
|
671
|
+
return this.state.failed ? null : this.props.children;
|
|
672
|
+
}
|
|
673
|
+
};
|
|
674
|
+
function Node({ node, registry }) {
|
|
675
|
+
const { state } = useContext(TreeContext);
|
|
676
|
+
if (Array.isArray(node)) return node.map((child, i) => /* @__PURE__ */ jsx(Node, {
|
|
677
|
+
node: child,
|
|
678
|
+
registry
|
|
679
|
+
}, i));
|
|
680
|
+
if (typeof node !== "object" || node === null) return null;
|
|
681
|
+
const { component, props = {}, children } = node;
|
|
682
|
+
const spec = typeof component === "string" ? registry.components.get(component) : void 0;
|
|
683
|
+
if (!spec || typeof props !== "object") return null;
|
|
684
|
+
const resolved = resolve(props, state);
|
|
685
|
+
if (!matchesSchema(spec.props ?? { type: "object" }, resolved)) return null;
|
|
686
|
+
const Render = spec.render;
|
|
687
|
+
const kids = spec.children && Array.isArray(children) ? children.map((child, i) => /* @__PURE__ */ jsx(Node, {
|
|
688
|
+
node: child,
|
|
689
|
+
registry
|
|
690
|
+
}, i)) : void 0;
|
|
691
|
+
return /* @__PURE__ */ jsx(Contain, { children: /* @__PURE__ */ jsx(Render, {
|
|
692
|
+
...resolved,
|
|
693
|
+
children: kids
|
|
694
|
+
}) });
|
|
695
|
+
}
|
|
696
|
+
/** Draws a `render_ui` tree with the registered components. Unknown components and bad props render nothing. */
|
|
697
|
+
function UiTree({ id, stateKey, root, state: initial, streaming = false }) {
|
|
698
|
+
const storeKey = stateKey ?? id;
|
|
699
|
+
const registry = useContext(RegistryContext);
|
|
700
|
+
const host = useWidgetHost();
|
|
701
|
+
const [local, setLocal] = useState(() => registry?.persist?.load(storeKey) ?? {});
|
|
702
|
+
const changed = useRef(false);
|
|
703
|
+
const latest = useRef(host);
|
|
704
|
+
latest.current = host;
|
|
705
|
+
useEffect(() => {
|
|
706
|
+
if (changed.current) registry?.persist?.save(storeKey, local);
|
|
707
|
+
}, [
|
|
708
|
+
storeKey,
|
|
709
|
+
local,
|
|
710
|
+
registry
|
|
711
|
+
]);
|
|
712
|
+
const run = useCallback((action) => {
|
|
713
|
+
switch (action.action) {
|
|
714
|
+
case "set":
|
|
715
|
+
changed.current = true;
|
|
716
|
+
return setLocal((s) => ({
|
|
717
|
+
...s,
|
|
718
|
+
[action.key]: action.value
|
|
719
|
+
}));
|
|
720
|
+
case "send": return latest.current.onPrompt?.(action.text);
|
|
721
|
+
case "open": return /^https?:\/\//i.test(action.url) && latest.current.onOpenLink?.(action.url);
|
|
722
|
+
case "copy":
|
|
723
|
+
navigator.clipboard?.writeText(action.text).catch(() => {});
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
}, []);
|
|
727
|
+
const state = useMemo(() => ({
|
|
728
|
+
...typeof initial === "object" && initial ? initial : {},
|
|
729
|
+
...local
|
|
730
|
+
}), [initial, local]);
|
|
731
|
+
const context = useMemo(() => ({
|
|
732
|
+
state,
|
|
733
|
+
run,
|
|
734
|
+
streaming
|
|
735
|
+
}), [
|
|
736
|
+
state,
|
|
737
|
+
run,
|
|
738
|
+
streaming
|
|
739
|
+
]);
|
|
740
|
+
if (!registry) return null;
|
|
741
|
+
return /* @__PURE__ */ jsx(TreeContext.Provider, {
|
|
742
|
+
value: context,
|
|
743
|
+
children: /* @__PURE__ */ jsx("div", {
|
|
744
|
+
className: "chat-ui-tree my-2",
|
|
745
|
+
"aria-busy": streaming || void 0,
|
|
746
|
+
children: /* @__PURE__ */ jsx(Node, {
|
|
747
|
+
node: root,
|
|
748
|
+
registry
|
|
749
|
+
})
|
|
750
|
+
})
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
/** The fence language drawn as UI here, or undefined outside a `UiComponentsProvider`. */
|
|
754
|
+
function useUiMarkupLanguage() {
|
|
755
|
+
const registry = useContext(RegistryContext);
|
|
756
|
+
return registry && registry.markup !== false ? registry.markup : void 0;
|
|
757
|
+
}
|
|
758
|
+
/** A ```ui block from a reply, drawn with the registered components. Safe on a block that is still streaming. */
|
|
759
|
+
function UiMarkupBlock({ id, stateKey, source, streaming = false }) {
|
|
760
|
+
const { nodes, state } = useMemo(() => parseUiMarkup(source), [source]);
|
|
761
|
+
return /* @__PURE__ */ jsx(UiTree, {
|
|
762
|
+
id,
|
|
763
|
+
...stateKey && { stateKey },
|
|
764
|
+
root: nodes,
|
|
765
|
+
state,
|
|
766
|
+
streaming
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
function stateKeyOf(options, part) {
|
|
770
|
+
const stateKey = options.stateKey?.(part);
|
|
771
|
+
return stateKey ? { stateKey } : {};
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* A tool view that draws a call's (streaming) JSX markup with your registered components, for whatever tool
|
|
775
|
+
* your harness uses; the suggested one is core's `showUiTool`. Register it under your tool's name:
|
|
776
|
+
* `{ show_ui: uiMarkupToolView() }`. `read` maps your tool's input to the markup; the default reads `markup`.
|
|
777
|
+
*/
|
|
778
|
+
function uiMarkupToolView(read = (input) => {
|
|
779
|
+
const markup = input?.markup;
|
|
780
|
+
return typeof markup === "string" ? markup : void 0;
|
|
781
|
+
}, options = {}) {
|
|
782
|
+
function UiMarkupToolBlock({ part }) {
|
|
783
|
+
const markup = read(part.input ?? part.partialInput);
|
|
784
|
+
if (!markup) return null;
|
|
785
|
+
return /* @__PURE__ */ jsx(UiMarkupBlock, {
|
|
786
|
+
id: part.id,
|
|
787
|
+
...stateKeyOf(options, part),
|
|
788
|
+
source: markup,
|
|
789
|
+
streaming: part.status === "streaming" || part.status === "input"
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
return { Block: UiMarkupToolBlock };
|
|
793
|
+
}
|
|
794
|
+
/** Reads `{ root, state }`. Models sometimes send `root` or `state` as a JSON string; those are parsed too. */
|
|
795
|
+
function readTreeInput(input) {
|
|
796
|
+
const i = input ?? {};
|
|
797
|
+
const unwrap = (v) => typeof v === "string" ? salvageJson(v).value : v;
|
|
798
|
+
const root = unwrap(i.root);
|
|
799
|
+
const state = unwrap(i.state);
|
|
800
|
+
return {
|
|
801
|
+
...root !== void 0 && { root },
|
|
802
|
+
...typeof state === "object" && state !== null && { state }
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* A tool view that draws a call's (streaming) input as a tree of your registered components, for whatever
|
|
807
|
+
* tool your harness uses. Register it under your tool's name: `{ render_ui: uiTreeToolView() }`. `read` maps
|
|
808
|
+
* your tool's input to the tree and its starting state; the default reads `{ root, state }`, the shape of
|
|
809
|
+
* the suggested `renderUiTool`.
|
|
810
|
+
*/
|
|
811
|
+
function uiTreeToolView(read = readTreeInput, options = {}) {
|
|
812
|
+
function UiTreeToolBlock({ part }) {
|
|
813
|
+
const { root, state } = read(part.input ?? part.partialInput);
|
|
814
|
+
if (!root) return null;
|
|
815
|
+
const ok = typeof state === "object" && state !== null;
|
|
816
|
+
return /* @__PURE__ */ jsx(UiTree, {
|
|
817
|
+
id: part.id,
|
|
818
|
+
...stateKeyOf(options, part),
|
|
819
|
+
root,
|
|
820
|
+
...ok && { state },
|
|
821
|
+
streaming: part.status === "streaming" || part.status === "input"
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
return { Block: UiTreeToolBlock };
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* The escape hatch: raw HTML or SVG in a sandboxed WidgetFrame, as a node of the tree. Register it only if
|
|
828
|
+
* the model may write HTML; it gets what the chat's `widgets` host allows.
|
|
829
|
+
*/
|
|
830
|
+
const htmlComponent = {
|
|
831
|
+
name: "Html",
|
|
832
|
+
description: "Raw HTML or <svg> in a sandboxed frame, only for what the other components cannot show. Follow the visual design guide.",
|
|
833
|
+
props: {
|
|
834
|
+
type: "object",
|
|
835
|
+
properties: {
|
|
836
|
+
html: { type: "string" },
|
|
837
|
+
title: { type: "string" }
|
|
838
|
+
},
|
|
839
|
+
required: ["html"]
|
|
840
|
+
},
|
|
841
|
+
render: function Html({ html, title }) {
|
|
842
|
+
const { streaming } = useContext(TreeContext);
|
|
843
|
+
const { allow, onPrompt, onOpenLink } = useWidgetHost();
|
|
844
|
+
return /* @__PURE__ */ jsx(WidgetFrame, {
|
|
845
|
+
html,
|
|
846
|
+
streaming,
|
|
847
|
+
...title && { title },
|
|
848
|
+
...allow && { allow },
|
|
849
|
+
...onPrompt && { onPrompt },
|
|
850
|
+
...onOpenLink && { onOpenLink }
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
// src/visuals/provider.tsx
|
|
855
|
+
/** Views for the suggested tools: `visualizeTool`, `renderUiTool` and `showUiTool`, under their names. */
|
|
856
|
+
const visualToolViews = {
|
|
857
|
+
[visualizeTool.name]: widgetToolView(),
|
|
858
|
+
[renderUiToolName]: uiTreeToolView(),
|
|
859
|
+
[showUiToolName]: uiMarkupToolView()
|
|
860
|
+
};
|
|
861
|
+
function LaterScope({ messages, children }) {
|
|
862
|
+
const later = useMemo(() => laterReplacements(messages), [messages]);
|
|
863
|
+
return /* @__PURE__ */ jsx(LaterReplacements, {
|
|
864
|
+
value: later,
|
|
865
|
+
children
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
const extensions = {
|
|
869
|
+
toolViews: visualToolViews,
|
|
870
|
+
renderPart: (part) => part.type === "widget" ? /* @__PURE__ */ jsx(WidgetPartView, { part }) : void 0,
|
|
871
|
+
messageScope: LaterScope,
|
|
872
|
+
toolChains: {
|
|
873
|
+
group: chainsOf,
|
|
874
|
+
Chain: ToolChain
|
|
875
|
+
}
|
|
876
|
+
};
|
|
877
|
+
/**
|
|
878
|
+
* Turns on inline visuals for the chats below it: views for the suggested tools, `widget` parts, ```ui
|
|
879
|
+
* blocks, and in-place updates (`replaces`). One line: `<VisualsProvider components={uiComponents}>`.
|
|
880
|
+
*/
|
|
881
|
+
function VisualsProvider({ components = [], persist, markup = "ui", host, children }) {
|
|
882
|
+
const hostValue = useMemo(() => ({
|
|
883
|
+
onOpenLink: openInNewTab,
|
|
884
|
+
...host
|
|
885
|
+
}), [host]);
|
|
886
|
+
const own = useMemo(() => ({
|
|
887
|
+
...extensions,
|
|
888
|
+
...markup !== false && { codeBlocks: { [markup]: UiMarkupCode } }
|
|
889
|
+
}), [markup]);
|
|
890
|
+
return /* @__PURE__ */ jsx(ChatExtensionsProvider, {
|
|
891
|
+
extensions: own,
|
|
892
|
+
children: /* @__PURE__ */ jsx(WidgetHostProvider, {
|
|
893
|
+
host: hostValue,
|
|
894
|
+
children: /* @__PURE__ */ jsx(UiComponentsProvider, {
|
|
895
|
+
components,
|
|
896
|
+
...persist && { persist },
|
|
897
|
+
markup,
|
|
898
|
+
children
|
|
899
|
+
})
|
|
900
|
+
})
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
function UiMarkupCode({ id, code, streaming }) {
|
|
904
|
+
return /* @__PURE__ */ jsx(UiMarkupBlock, {
|
|
905
|
+
id,
|
|
906
|
+
source: code,
|
|
907
|
+
streaming
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
// src/visuals/ui-components.tsx
|
|
911
|
+
const toneClass = {
|
|
912
|
+
default: "text-chat-fg",
|
|
913
|
+
accent: "text-chat-accent",
|
|
914
|
+
good: "text-chat-check",
|
|
915
|
+
warning: "text-chat-warning",
|
|
916
|
+
bad: "text-chat-danger"
|
|
917
|
+
};
|
|
918
|
+
const fillClass = {
|
|
919
|
+
default: "bg-chat-fg",
|
|
920
|
+
accent: "bg-chat-accent",
|
|
921
|
+
good: "bg-chat-check",
|
|
922
|
+
warning: "bg-chat-warning",
|
|
923
|
+
bad: "bg-chat-danger"
|
|
924
|
+
};
|
|
925
|
+
/** "New" / "Changed": what the model added stands out in the accent. */
|
|
926
|
+
function Tag({ children, quiet = false }) {
|
|
927
|
+
return /* @__PURE__ */ jsx("span", {
|
|
928
|
+
className: `rounded-chat-sm px-1.5 text-(length:--chat-ui-font-size-sm) font-medium ${quiet ? "border border-chat-border-strong text-chat-muted" : "bg-chat-accent text-chat-accent-fg"}`,
|
|
929
|
+
children
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
const Stack = ({ direction = "column", gap = "md", children }) => /* @__PURE__ */ jsx("div", {
|
|
933
|
+
className: `flex ${direction === "row" ? "flex-row flex-wrap" : "flex-col"} ${{
|
|
934
|
+
sm: "gap-1.5",
|
|
935
|
+
md: "gap-3",
|
|
936
|
+
lg: "gap-5"
|
|
937
|
+
}[gap]}`,
|
|
938
|
+
children
|
|
939
|
+
});
|
|
940
|
+
const Grid = ({ columns = 2, children }) => /* @__PURE__ */ jsx("div", {
|
|
941
|
+
className: "grid gap-3",
|
|
942
|
+
style: { gridTemplateColumns: `repeat(auto-fit, minmax(min(100%, ${Math.floor(36 / columns)}rem), 1fr))` },
|
|
943
|
+
children
|
|
944
|
+
});
|
|
945
|
+
const Card = ({ title, subtitle, tag, tone = "default", children }) => /* @__PURE__ */ jsxs("section", {
|
|
946
|
+
className: `rounded-chat-lg border p-3 ${tone === "accent" ? "border-chat-accent" : "border-chat-border"}`,
|
|
947
|
+
children: [
|
|
948
|
+
(title || tag) && /* @__PURE__ */ jsxs("header", {
|
|
949
|
+
className: "mb-1 flex items-center gap-2",
|
|
950
|
+
children: [title && /* @__PURE__ */ jsx("h3", {
|
|
951
|
+
className: "font-chat-sans text-(length:--chat-ui-font-size) font-semibold",
|
|
952
|
+
children: title
|
|
953
|
+
}), tag && /* @__PURE__ */ jsx(Tag, {
|
|
954
|
+
quiet: tone !== "accent",
|
|
955
|
+
children: tag
|
|
956
|
+
})]
|
|
957
|
+
}),
|
|
958
|
+
subtitle && /* @__PURE__ */ jsx("p", {
|
|
959
|
+
className: "mb-2 text-(length:--chat-ui-font-size-sm) text-chat-muted",
|
|
960
|
+
children: subtitle
|
|
961
|
+
}),
|
|
962
|
+
children
|
|
963
|
+
]
|
|
964
|
+
});
|
|
965
|
+
const Heading = ({ text }) => /* @__PURE__ */ jsx("h2", {
|
|
966
|
+
className: "font-chat-sans text-(length:--chat-ui-font-size) font-semibold",
|
|
967
|
+
children: text
|
|
968
|
+
});
|
|
969
|
+
const Text = ({ text, tone = "default" }) => /* @__PURE__ */ jsx("p", {
|
|
970
|
+
className: `font-chat-sans text-(length:--chat-ui-font-size) leading-relaxed ${tone === "muted" ? "text-chat-muted" : ""}`,
|
|
971
|
+
children: text
|
|
972
|
+
});
|
|
973
|
+
const Metric = ({ label, value, note, tone = "default" }) => /* @__PURE__ */ jsxs("div", {
|
|
974
|
+
className: "min-w-24",
|
|
975
|
+
children: [
|
|
976
|
+
/* @__PURE__ */ jsx("div", {
|
|
977
|
+
className: "text-(length:--chat-ui-font-size-sm) text-chat-muted",
|
|
978
|
+
children: label
|
|
979
|
+
}),
|
|
980
|
+
/* @__PURE__ */ jsx("div", {
|
|
981
|
+
className: `font-chat-sans text-xl font-semibold tabular-nums ${toneClass[tone]}`,
|
|
982
|
+
children: value
|
|
983
|
+
}),
|
|
984
|
+
note && /* @__PURE__ */ jsx("div", {
|
|
985
|
+
className: "text-(length:--chat-ui-font-size-sm) text-chat-subtle",
|
|
986
|
+
children: note
|
|
987
|
+
})
|
|
988
|
+
]
|
|
989
|
+
});
|
|
990
|
+
const List = ({ items }) => /* @__PURE__ */ jsx("ul", {
|
|
991
|
+
className: "divide-y divide-chat-divider",
|
|
992
|
+
children: items.map((item, i) => /* @__PURE__ */ jsxs("li", {
|
|
993
|
+
className: "flex items-baseline gap-2 py-1.5 font-chat-sans text-(length:--chat-ui-font-size)",
|
|
994
|
+
children: [
|
|
995
|
+
/* @__PURE__ */ jsx("span", {
|
|
996
|
+
className: item.tag ? "text-chat-accent" : "",
|
|
997
|
+
children: item.label
|
|
998
|
+
}),
|
|
999
|
+
item.tag && /* @__PURE__ */ jsx(Tag, { children: item.tag }),
|
|
1000
|
+
item.detail && /* @__PURE__ */ jsx("span", {
|
|
1001
|
+
className: "ml-auto text-chat-muted tabular-nums",
|
|
1002
|
+
children: item.detail
|
|
1003
|
+
})
|
|
1004
|
+
]
|
|
1005
|
+
}, i))
|
|
1006
|
+
});
|
|
1007
|
+
const Table = ({ columns, rows }) => /* @__PURE__ */ jsx("div", {
|
|
1008
|
+
className: "max-w-full overflow-x-auto",
|
|
1009
|
+
children: /* @__PURE__ */ jsxs("table", {
|
|
1010
|
+
className: "w-full border-collapse text-left font-chat-sans text-(length:--chat-ui-font-size)",
|
|
1011
|
+
children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", {
|
|
1012
|
+
className: "border-b border-chat-border-strong",
|
|
1013
|
+
children: columns.map((c, i) => /* @__PURE__ */ jsx("th", {
|
|
1014
|
+
scope: "col",
|
|
1015
|
+
className: "px-2 py-1.5 font-medium text-chat-muted",
|
|
1016
|
+
children: c
|
|
1017
|
+
}, i))
|
|
1018
|
+
}) }), /* @__PURE__ */ jsx("tbody", {
|
|
1019
|
+
className: "divide-y divide-chat-divider",
|
|
1020
|
+
children: rows.map((row, r) => /* @__PURE__ */ jsx("tr", { children: columns.map((_, c) => /* @__PURE__ */ jsx("td", {
|
|
1021
|
+
className: `px-2 py-1.5 ${typeof row[c] === "number" ? "tabular-nums" : ""}`,
|
|
1022
|
+
children: row[c]
|
|
1023
|
+
}, c)) }, r))
|
|
1024
|
+
})]
|
|
1025
|
+
})
|
|
1026
|
+
});
|
|
1027
|
+
const Badge = ({ label, tone = "default" }) => /* @__PURE__ */ jsx("span", {
|
|
1028
|
+
className: `inline-block self-start rounded-chat-sm border border-current px-1.5 font-chat-sans text-(length:--chat-ui-font-size-sm) font-medium ${toneClass[tone]}`,
|
|
1029
|
+
children: label
|
|
1030
|
+
});
|
|
1031
|
+
const Progress = ({ label, value, max = 100, tone = "accent" }) => {
|
|
1032
|
+
const share = Math.min(1, Math.max(0, value / max));
|
|
1033
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
1034
|
+
className: "flex flex-col gap-1",
|
|
1035
|
+
children: [label && /* @__PURE__ */ jsxs("div", {
|
|
1036
|
+
className: "flex justify-between text-(length:--chat-ui-font-size-sm) text-chat-muted",
|
|
1037
|
+
children: [/* @__PURE__ */ jsx("span", { children: label }), /* @__PURE__ */ jsxs("span", {
|
|
1038
|
+
className: "tabular-nums",
|
|
1039
|
+
children: [Math.round(share * 100), "%"]
|
|
1040
|
+
})]
|
|
1041
|
+
}), /* @__PURE__ */ jsx("div", {
|
|
1042
|
+
role: "progressbar",
|
|
1043
|
+
"aria-label": label ?? "Progress",
|
|
1044
|
+
"aria-valuemin": 0,
|
|
1045
|
+
"aria-valuemax": max,
|
|
1046
|
+
"aria-valuenow": Math.min(value, max),
|
|
1047
|
+
className: "h-1.5 overflow-hidden rounded-full bg-chat-border",
|
|
1048
|
+
children: /* @__PURE__ */ jsx("div", {
|
|
1049
|
+
className: `h-full rounded-full ${fillClass[tone]}`,
|
|
1050
|
+
style: { width: `${share * 100}%` }
|
|
1051
|
+
})
|
|
1052
|
+
})]
|
|
1053
|
+
});
|
|
1054
|
+
};
|
|
1055
|
+
const Checklist = function Checklist({ stateKey, items }) {
|
|
1056
|
+
const [state, set] = useUiState();
|
|
1057
|
+
const done = state[stateKey] ?? [];
|
|
1058
|
+
return /* @__PURE__ */ jsx("ul", {
|
|
1059
|
+
className: "flex flex-col gap-1",
|
|
1060
|
+
children: items.map((item) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs("label", {
|
|
1061
|
+
className: "flex items-center gap-2 font-chat-sans text-(length:--chat-ui-font-size)",
|
|
1062
|
+
children: [/* @__PURE__ */ jsx("input", {
|
|
1063
|
+
type: "checkbox",
|
|
1064
|
+
className: "accent-(--chat-accent)",
|
|
1065
|
+
checked: done.includes(item),
|
|
1066
|
+
onChange: (e) => set(stateKey, e.target.checked ? [...done, item] : done.filter((d) => d !== item))
|
|
1067
|
+
}), /* @__PURE__ */ jsx("span", {
|
|
1068
|
+
className: done.includes(item) ? "text-chat-subtle line-through" : "",
|
|
1069
|
+
children: item
|
|
1070
|
+
})]
|
|
1071
|
+
}) }, item))
|
|
1072
|
+
});
|
|
1073
|
+
};
|
|
1074
|
+
const Tabs = function Tabs({ stateKey, value, options }) {
|
|
1075
|
+
const [, set] = useUiState();
|
|
1076
|
+
const current = value ?? options[0].id;
|
|
1077
|
+
return /* @__PURE__ */ jsx("div", {
|
|
1078
|
+
role: "tablist",
|
|
1079
|
+
className: "inline-flex max-w-full flex-wrap gap-1 self-start rounded-chat-md border border-chat-border p-0.5",
|
|
1080
|
+
children: options.map((o) => /* @__PURE__ */ jsx(Button, {
|
|
1081
|
+
size: "sm",
|
|
1082
|
+
variant: o.id === current ? "subtle" : "ghost",
|
|
1083
|
+
onPress: () => set(stateKey, o.id),
|
|
1084
|
+
"aria-selected": o.id === current,
|
|
1085
|
+
children: o.label
|
|
1086
|
+
}, o.id))
|
|
1087
|
+
});
|
|
1088
|
+
};
|
|
1089
|
+
const Show = ({ value, equals, fallback, children }) => value === equals || value === void 0 && fallback ? /* @__PURE__ */ jsx(Fragment$1, { children }) : null;
|
|
1090
|
+
/**
|
|
1091
|
+
* The drawing of each component, by name and apart from its spec. Take one to reuse in your own
|
|
1092
|
+
* component: `{ ...uiSpecs.Card, render: uiRenders.Card }`.
|
|
1093
|
+
*/
|
|
1094
|
+
const uiRenders = {
|
|
1095
|
+
Stack,
|
|
1096
|
+
Grid,
|
|
1097
|
+
Card,
|
|
1098
|
+
Heading,
|
|
1099
|
+
Text,
|
|
1100
|
+
Metric,
|
|
1101
|
+
List,
|
|
1102
|
+
Table,
|
|
1103
|
+
Badge,
|
|
1104
|
+
Progress,
|
|
1105
|
+
Checklist,
|
|
1106
|
+
Tabs,
|
|
1107
|
+
Show,
|
|
1108
|
+
Button: function UiButton({ label, variant = "secondary", onPress }) {
|
|
1109
|
+
const run = useUiAction();
|
|
1110
|
+
return /* @__PURE__ */ jsx(Button, {
|
|
1111
|
+
size: "sm",
|
|
1112
|
+
className: "self-start",
|
|
1113
|
+
variant: variant === "primary" ? "primary" : "subtle",
|
|
1114
|
+
onPress: () => run(onPress),
|
|
1115
|
+
children: label
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
};
|
|
1119
|
+
/**
|
|
1120
|
+
* The ready components for `UiComponentsProvider`, in the order of `uiComponentSpecs`. Everything by default;
|
|
1121
|
+
* `include` and `exclude` take component names or the groups `"display"` (Stack, Grid, Card, Heading, Text,
|
|
1122
|
+
* Metric, List, Table, Badge, Progress) and `"interactive"` (Checklist, Tabs, Show, Button). `renders` swaps the
|
|
1123
|
+
* drawing of single components. Build the model's tool from the same picks so it only hears of what you
|
|
1124
|
+
* registered: `uiSpecSet({ include })` in `agentic-ui-kit/core`, or strip the renders from this list.
|
|
1125
|
+
*/
|
|
1126
|
+
function uiComponentSet({ renders = {}, ...selection } = {}) {
|
|
1127
|
+
return uiSpecSet(selection).map((spec) => ({
|
|
1128
|
+
...spec,
|
|
1129
|
+
render: renders[spec.name] ?? uiRenders[spec.name]
|
|
1130
|
+
}));
|
|
1131
|
+
}
|
|
1132
|
+
/** The whole set: `uiComponentSet()`. */
|
|
1133
|
+
const uiComponents = uiComponentSet();
|
|
1134
|
+
export { UiComponentsProvider, UiMarkupBlock, UiTree, VisualsProvider, WIDGET_MAX_HEIGHT, WidgetFrame, WidgetHostProvider, WidgetPartView, htmlComponent, intersectAllow, openInNewTab, readTreeInput, readVisualizeInput, uiComponentSet, uiComponents, uiMarkupToolView, uiRenders, uiTreeToolView, useUiAction, useUiMarkupLanguage, useUiState, useWidgetHost, visualToolViews, widgetCsp, widgetToolView };
|