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/README.md
CHANGED
|
@@ -23,6 +23,8 @@ Requires React 19. React is an optional peer dependency, so a server can use `ag
|
|
|
23
23
|
| ---------------------------- | ------------------------------------------------------------------------------ |
|
|
24
24
|
| `agentic-ui-kit` | React components and hooks |
|
|
25
25
|
| `agentic-ui-kit/core` | Types, stream events, the message reducer, SSE helpers. No React, no DOM. |
|
|
26
|
+
| `agentic-ui-kit/visuals` | Optional: inline visuals (model-drawn UI), turned on with `<VisualsProvider>` |
|
|
27
|
+
| `agentic-ui-kit/visuals/core`| Tools, guides, checks and specs for inline visuals. No React, for servers. |
|
|
26
28
|
| `agentic-ui-kit/styles.css` | Precompiled styles, for apps without Tailwind |
|
|
27
29
|
| `agentic-ui-kit/tailwind.css`| The same styles as Tailwind v4 source, for apps that use Tailwind |
|
|
28
30
|
|
|
@@ -189,10 +191,12 @@ chosen links in replies your way, e.g. a job link as a job row.
|
|
|
189
191
|
|
|
190
192
|
The model can draw something interactive in its reply, and it fills in while the model writes. The kit is
|
|
191
193
|
only the UI: your harness names the tools and writes the prompt; the kit suggests both and draws the result.
|
|
192
|
-
|
|
194
|
+
Inline visuals are opt-in: import them from `agentic-ui-kit/visuals` (React) and `agentic-ui-kit/visuals/core`
|
|
195
|
+
(servers), and wrap the chat in `<VisualsProvider>`. Upgrading from 0.8: see
|
|
196
|
+
https://bushshrub.github.io/agentic-ui-kit/get-started/upgrading-to-0-9/. Full guide: https://bushshrub.github.io/agentic-ui-kit/custom-harness/connecting-your-agent/
|
|
193
197
|
|
|
194
198
|
**Your components (recommended).** Register components with a JSON Schema for their props (with zod:
|
|
195
|
-
`z.toJSONSchema`). Give the model `showUiTool(specs)` from `agentic-ui-kit/core`: it passes JSX as a string,
|
|
199
|
+
`z.toJSONSchema`). Give the model `showUiTool(specs)` from `agentic-ui-kit/visuals/core`: it passes JSX as a string,
|
|
196
200
|
which the chat draws element by element as it streams. Answer each call with
|
|
197
201
|
`checkUiMarkupCode(markup, specs).feedback`, so the model learns what to fix (line, component, allowed props).
|
|
198
202
|
|
|
@@ -202,11 +206,10 @@ const components: UiComponent[] = [
|
|
|
202
206
|
{ name: "Stack", description: "Children in a column.", children: true, render: Stack },
|
|
203
207
|
];
|
|
204
208
|
// server: tools: [showUiTool(components.map(({ render, ...spec }) => spec)), ...]
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
</UiComponentsProvider>;
|
|
209
|
+
// import { VisualsProvider } from "agentic-ui-kit/visuals"
|
|
210
|
+
<VisualsProvider components={components} persist={store}>
|
|
211
|
+
<ChatView {...chat} />
|
|
212
|
+
</VisualsProvider>;
|
|
210
213
|
```
|
|
211
214
|
|
|
212
215
|
Inside a component, `useUiAction()` runs an action from its props (`uiActionSchema`: set a state key, send
|
|
@@ -215,21 +218,22 @@ widget's state across reloads. Also available: ` ```ui ` blocks in reply text (`
|
|
|
215
218
|
`checkUiMarkup`) and JSON trees in a tool call (`renderUiTool`, `uiTreeToolView`, `checkUiTree`).
|
|
216
219
|
|
|
217
220
|
**Sandboxed HTML.** For maps, charts and anything free-form: give the model `visualizeTool` and put
|
|
218
|
-
`visualizeGuide` in its instructions,
|
|
221
|
+
`visualizeGuide` in its instructions, and answer calls with
|
|
219
222
|
`checkWidgetCode(code, allow).feedback`. Widgets render in a `WidgetFrame`: an iframe with
|
|
220
223
|
`sandbox="allow-scripts"` only and a CSP that blocks every request, themed with your `--chat-*` variables.
|
|
221
224
|
The same frame hosts MCP App UIs (MCP Apps spec 2026-01-26: `ui/initialize`, tool input and result,
|
|
222
225
|
`tools/call`); the kit never fetches anything itself, your `readResource` does.
|
|
223
226
|
|
|
224
227
|
```tsx
|
|
225
|
-
<
|
|
226
|
-
{
|
|
227
|
-
widgets={{
|
|
228
|
+
<VisualsProvider
|
|
229
|
+
host={{
|
|
228
230
|
allow: { resourceDomains: ["https://unpkg.com", "https://tile.openstreetmap.org"] }, // the most any widget may load
|
|
229
231
|
onCallTool: (name, args) => mcp.callTool(name, args), // MCP App UIs; leave out to turn it off
|
|
230
232
|
onWidgetError: ({ partId, message }) => report(partId, message), // script errors, to send back to the model
|
|
231
233
|
}}
|
|
232
|
-
|
|
234
|
+
>
|
|
235
|
+
<ChatView {...chat} />
|
|
236
|
+
</VisualsProvider>
|
|
233
237
|
```
|
|
234
238
|
|
|
235
239
|
A widget's `sendPrompt(text)` sends through `onSend`, and its links open in a new tab; set either callback to
|
|
@@ -288,7 +292,7 @@ The React package has four layers, each built only from the ones before it:
|
|
|
288
292
|
| ---------- | --------------------------------------------------------------------------------------------- |
|
|
289
293
|
| Primitives | `Button`, `IconButton`, `Menu`, `ContextMenu`, `Modal`, `Drawer`, `Panel`, `Tooltip`, `CodeBlock`, `ChatTheme` |
|
|
290
294
|
| Hooks | `useChat`, `sseTransport`, `AgentProvider`, `useAgentTool`, `useAgentContext`, `useSmoothText` |
|
|
291
|
-
| Components | `Composer`, `ModelPicker`, `MessageList`, `ActivityGroup`, `ApprovalCard`, `Markdown`, `ChatHeader`, `ChatList`, `ContextPanel
|
|
295
|
+
| Components | `Composer`, `ModelPicker`, `MessageList`, `ActivityGroup`, `ApprovalCard`, `Markdown`, `ChatHeader`, `ChatList`, `ContextPanel` |
|
|
292
296
|
| Views | `ChatView`, `AppShell`, `Sidebar` |
|
|
293
297
|
|
|
294
298
|
Use `ChatView` for the whole thing, or build your own layout from the components.
|
|
@@ -311,8 +315,8 @@ your brand and of the space it sits in.
|
|
|
311
315
|
- Wording and locale: `ChatTheme labels`, see Theming. Icons: `ChatTheme icons`, Lucide by default.
|
|
312
316
|
- Content: the `header`, `footer`, `notice`, `emptyState` and `disclaimer` slots, custom parts through
|
|
313
317
|
`renderPart`, and tool views through `useChatTool`.
|
|
314
|
-
- Inline visuals: which domains widgets may load and which of their abilities are
|
|
315
|
-
components the model may compose (`
|
|
318
|
+
- Inline visuals (`agentic-ui-kit/visuals`): which domains widgets may load and which of their abilities are
|
|
319
|
+
on (`VisualsProvider host`), and the components the model may compose (`VisualsProvider components`).
|
|
316
320
|
|
|
317
321
|
**Fixed on purpose**
|
|
318
322
|
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import { t as parsePartialJson } from "./partial-json-w_oXePqJ.js";
|
|
2
|
+
// ../core/src/reduce.ts
|
|
3
|
+
/**
|
|
4
|
+
* Applies one stream event to the message it builds. Pure and immutable: returns the same object when the
|
|
5
|
+
* event changes nothing, so React can skip renders.
|
|
6
|
+
*
|
|
7
|
+
* Events with a seq at or below `message.lastSeq` are dropped, so replaying from an earlier seq after a
|
|
8
|
+
* reconnect is safe. Events other than run.start need the message to exist; without it they are dropped.
|
|
9
|
+
*/
|
|
10
|
+
function applyEvent(message, event) {
|
|
11
|
+
if (event.type === "run.start") {
|
|
12
|
+
if (message?.runId === event.runId && (message.lastSeq ?? -1) >= event.seq) return message;
|
|
13
|
+
if (message?.id === event.messageId) return {
|
|
14
|
+
...message,
|
|
15
|
+
status: "streaming",
|
|
16
|
+
runId: event.runId,
|
|
17
|
+
lastSeq: event.seq
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
id: event.messageId,
|
|
21
|
+
parentId: event.parentId,
|
|
22
|
+
role: "assistant",
|
|
23
|
+
status: "streaming",
|
|
24
|
+
parts: [],
|
|
25
|
+
createdAt: event.createdAt,
|
|
26
|
+
runId: event.runId,
|
|
27
|
+
lastSeq: event.seq,
|
|
28
|
+
...event.model !== void 0 && { model: event.model },
|
|
29
|
+
...event.effort !== void 0 && { effort: event.effort }
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
if (!message || message.runId !== event.runId) return message;
|
|
33
|
+
if ((message.lastSeq ?? -1) >= event.seq) return message;
|
|
34
|
+
const seen = {
|
|
35
|
+
...message,
|
|
36
|
+
lastSeq: event.seq
|
|
37
|
+
};
|
|
38
|
+
switch (event.type) {
|
|
39
|
+
case "part.start":
|
|
40
|
+
if (message.parts.some((p) => p.id === event.part.id)) return seen;
|
|
41
|
+
return {
|
|
42
|
+
...seen,
|
|
43
|
+
parts: [...message.parts, event.part]
|
|
44
|
+
};
|
|
45
|
+
case "part.delta": return updatePart(seen, event.partId, (part) => appendDelta(part, event.text, event.inputJson));
|
|
46
|
+
case "part.update": return updatePart(seen, event.partId, (part) => applyFields(part, event));
|
|
47
|
+
case "part.end": return updatePart(seen, event.partId, (part) => closePart(applyFields(part, event)));
|
|
48
|
+
case "run.usage": return {
|
|
49
|
+
...seen,
|
|
50
|
+
usage: event.usage
|
|
51
|
+
};
|
|
52
|
+
case "run.end": return {
|
|
53
|
+
...seen,
|
|
54
|
+
status: event.status,
|
|
55
|
+
parts: message.parts.map((p) => closeOpenPart(p, event.status)),
|
|
56
|
+
...event.usage !== void 0 && { usage: event.usage },
|
|
57
|
+
...event.error !== void 0 && { error: event.error }
|
|
58
|
+
};
|
|
59
|
+
case "title": return seen;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** Builds a message from a full event list, e.g. a stored run or a test fixture. */
|
|
63
|
+
function reduceEvents(events, initial) {
|
|
64
|
+
let message = initial;
|
|
65
|
+
for (const event of events) message = applyEvent(message, event);
|
|
66
|
+
return message;
|
|
67
|
+
}
|
|
68
|
+
function updatePart(message, partId, update) {
|
|
69
|
+
const index = message.parts.findIndex((p) => p.id === partId);
|
|
70
|
+
if (index === -1) return message;
|
|
71
|
+
const parts = message.parts.slice();
|
|
72
|
+
parts[index] = update(parts[index]);
|
|
73
|
+
return {
|
|
74
|
+
...message,
|
|
75
|
+
parts
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function appendDelta(part, text = "", inputJson = "") {
|
|
79
|
+
switch (part.type) {
|
|
80
|
+
case "text":
|
|
81
|
+
case "thinking": return text ? {
|
|
82
|
+
...part,
|
|
83
|
+
text: part.text + text
|
|
84
|
+
} : part;
|
|
85
|
+
case "custom": return text ? {
|
|
86
|
+
...part,
|
|
87
|
+
text: (part.text ?? "") + text
|
|
88
|
+
} : part;
|
|
89
|
+
case "widget": return text ? {
|
|
90
|
+
...part,
|
|
91
|
+
html: (part.html ?? "") + text
|
|
92
|
+
} : part;
|
|
93
|
+
case "tool_call":
|
|
94
|
+
if (!inputJson) return part;
|
|
95
|
+
return {
|
|
96
|
+
...part,
|
|
97
|
+
inputJson: part.inputJson + inputJson,
|
|
98
|
+
partialInput: parsePartialJson(part.inputJson + inputJson)
|
|
99
|
+
};
|
|
100
|
+
case "attachment": return part;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** Copies the fields from `fields` that are valid for the part's type. */
|
|
104
|
+
function applyFields(part, fields) {
|
|
105
|
+
const pick = (...keys) => {
|
|
106
|
+
const out = {};
|
|
107
|
+
for (const key of keys) if (fields[key] !== void 0) out[key] = fields[key];
|
|
108
|
+
return out;
|
|
109
|
+
};
|
|
110
|
+
const status = pick("status");
|
|
111
|
+
switch (part.type) {
|
|
112
|
+
case "text": return {
|
|
113
|
+
...part,
|
|
114
|
+
...status
|
|
115
|
+
};
|
|
116
|
+
case "thinking": return {
|
|
117
|
+
...part,
|
|
118
|
+
...status,
|
|
119
|
+
...pick("title", "durationMs")
|
|
120
|
+
};
|
|
121
|
+
case "tool_call": {
|
|
122
|
+
const next = {
|
|
123
|
+
...part,
|
|
124
|
+
...status,
|
|
125
|
+
...pick("title", "subtitle", "durationMs", "input", "result", "data", "error", "needsApproval")
|
|
126
|
+
};
|
|
127
|
+
return next.status === "input" || next.status === "streaming" ? next : withParsedInput(next);
|
|
128
|
+
}
|
|
129
|
+
case "attachment": return {
|
|
130
|
+
...part,
|
|
131
|
+
...status,
|
|
132
|
+
...pick("url")
|
|
133
|
+
};
|
|
134
|
+
case "widget": return {
|
|
135
|
+
...part,
|
|
136
|
+
...status,
|
|
137
|
+
...pick("title", "resourceUri")
|
|
138
|
+
};
|
|
139
|
+
case "custom": return {
|
|
140
|
+
...part,
|
|
141
|
+
...status,
|
|
142
|
+
...pick("data")
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function closePart(part) {
|
|
147
|
+
return withParsedInput(part.status === "error" ? part : {
|
|
148
|
+
...part,
|
|
149
|
+
status: "done"
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
/** Parses a tool call's streamed input if it is complete JSON and not parsed yet. */
|
|
153
|
+
function withParsedInput(part) {
|
|
154
|
+
if (part.type !== "tool_call") return part;
|
|
155
|
+
const { partialInput: _, ...rest } = part;
|
|
156
|
+
if (part.input !== void 0 || !part.inputJson) return "partialInput" in part ? rest : part;
|
|
157
|
+
const input = parseJson(part.inputJson);
|
|
158
|
+
if (input !== void 0) return {
|
|
159
|
+
...rest,
|
|
160
|
+
input
|
|
161
|
+
};
|
|
162
|
+
return part.status === "error" ? rest : {
|
|
163
|
+
...rest,
|
|
164
|
+
status: "error",
|
|
165
|
+
error: part.error ?? "The tool input was cut off or is not valid JSON"
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/** At the end of a run, parts still open are closed. A tool call cut off by a stop or an error is an error. */
|
|
169
|
+
function closeOpenPart(part, runStatus) {
|
|
170
|
+
if (part.status === "done" || part.status === "error") return part;
|
|
171
|
+
if (part.type === "tool_call" && part.status === "awaiting" && runStatus === "done") return withParsedInput(part);
|
|
172
|
+
if (part.type === "tool_call" && runStatus !== "done") {
|
|
173
|
+
const error = part.error ?? (runStatus === "stopped" ? "Stopped" : "Failed");
|
|
174
|
+
return withParsedInput({
|
|
175
|
+
...part,
|
|
176
|
+
status: "error",
|
|
177
|
+
error
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
return closePart(part);
|
|
181
|
+
}
|
|
182
|
+
function parseJson(text) {
|
|
183
|
+
try {
|
|
184
|
+
return JSON.parse(text);
|
|
185
|
+
} catch {
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Rough token count of text, about four characters per token. For live counters, not billing. */
|
|
190
|
+
function estimateTokens(text) {
|
|
191
|
+
return Math.ceil(text.length / 4);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Tokens the model spent inside an activity group: its reasoning and the tool inputs it wrote. Tool
|
|
195
|
+
* results are not model output, so they do not count. An estimate; per-step counts are not reported.
|
|
196
|
+
*/
|
|
197
|
+
function activityTokens(parts) {
|
|
198
|
+
let chars = 0;
|
|
199
|
+
for (const part of parts) if (part.type === "thinking") chars += part.text.length;
|
|
200
|
+
else if (part.type === "tool_call") chars += part.inputJson.length;
|
|
201
|
+
return Math.ceil(chars / 4);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Output tokens of a message so far: the backend's count when it has sent one, else an estimate from
|
|
205
|
+
* everything the model has written (text, thinking, tool input, widget html).
|
|
206
|
+
*/
|
|
207
|
+
function outputTokens(message) {
|
|
208
|
+
if (message.usage?.outputTokens !== void 0) return message.usage.outputTokens;
|
|
209
|
+
let chars = 0;
|
|
210
|
+
for (const part of message.parts) if (part.type === "text" || part.type === "thinking") chars += part.text.length;
|
|
211
|
+
else if (part.type === "tool_call") chars += part.inputJson.length;
|
|
212
|
+
else if (part.type === "widget") chars += part.html?.length ?? 0;
|
|
213
|
+
else if (part.type === "custom") chars += part.text?.length ?? 0;
|
|
214
|
+
return Math.ceil(chars / 4);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* The effort to send with a model: the chosen one if the model offers it, else the model's default, else
|
|
218
|
+
* none. Models without effort levels never get one.
|
|
219
|
+
*/
|
|
220
|
+
function resolveEffort(model, effort) {
|
|
221
|
+
const levels = model?.efforts;
|
|
222
|
+
if (!levels?.length) return void 0;
|
|
223
|
+
if (effort && levels.some((e) => e.id === effort)) return effort;
|
|
224
|
+
return model?.defaultEffort ?? levels[0].id;
|
|
225
|
+
}
|
|
226
|
+
/** Tool calls the client has to act on: run them (client tools) or ask the user (approvals). */
|
|
227
|
+
function awaitingToolCalls(message) {
|
|
228
|
+
return message.parts.filter((p) => p.type === "tool_call" && p.status === "awaiting");
|
|
229
|
+
}
|
|
230
|
+
/** Sets fields on one tool call locally, e.g. a client tool's result or the user's approval. */
|
|
231
|
+
function settleToolCall(message, partId, fields) {
|
|
232
|
+
return {
|
|
233
|
+
...message,
|
|
234
|
+
parts: message.parts.map((p) => p.id === partId && p.type === "tool_call" ? {
|
|
235
|
+
...p,
|
|
236
|
+
...fields
|
|
237
|
+
} : p)
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
// ../core/src/blocks.ts
|
|
241
|
+
function isActivityPart(part) {
|
|
242
|
+
return part.type === "thinking" || part.type === "tool_call";
|
|
243
|
+
}
|
|
244
|
+
function toBlocks(parts, standalone) {
|
|
245
|
+
const blocks = [];
|
|
246
|
+
for (const part of parts) {
|
|
247
|
+
if (part.type === "tool_call" && standalone?.(part)) {
|
|
248
|
+
blocks.push({
|
|
249
|
+
kind: "tool",
|
|
250
|
+
id: part.id,
|
|
251
|
+
part
|
|
252
|
+
});
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (!isActivityPart(part)) {
|
|
256
|
+
blocks.push({
|
|
257
|
+
kind: "part",
|
|
258
|
+
id: part.id,
|
|
259
|
+
part
|
|
260
|
+
});
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const last = blocks.at(-1);
|
|
264
|
+
if (last?.kind === "activity") last.parts.push(part);
|
|
265
|
+
else blocks.push({
|
|
266
|
+
kind: "activity",
|
|
267
|
+
id: part.id,
|
|
268
|
+
parts: [part]
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
return blocks;
|
|
272
|
+
}
|
|
273
|
+
// ../core/src/sse.ts
|
|
274
|
+
/**
|
|
275
|
+
* Reads a server-sent event stream of `StreamEvent`s. Each SSE message carries one JSON event in `data`;
|
|
276
|
+
* comments and messages without data (keep-alives) are skipped.
|
|
277
|
+
*/
|
|
278
|
+
async function* readEventStream(body) {
|
|
279
|
+
const reader = body.getReader();
|
|
280
|
+
const decoder = new TextDecoder();
|
|
281
|
+
let buffer = "";
|
|
282
|
+
try {
|
|
283
|
+
for (;;) {
|
|
284
|
+
const { value, done } = await reader.read();
|
|
285
|
+
if (done) break;
|
|
286
|
+
buffer += decoder.decode(value, { stream: true });
|
|
287
|
+
let end;
|
|
288
|
+
while ((end = messageEnd(buffer)) !== -1) {
|
|
289
|
+
const event = parseMessage(buffer.slice(0, end));
|
|
290
|
+
buffer = buffer.slice(end).replace(BLANK_LINE_START, "");
|
|
291
|
+
if (event) yield event;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
const event = parseMessage(buffer + decoder.decode());
|
|
295
|
+
if (event) yield event;
|
|
296
|
+
} finally {
|
|
297
|
+
reader.releaseLock();
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/** Formats one event as an SSE message, for servers written in TS. */
|
|
301
|
+
function formatEvent(event) {
|
|
302
|
+
return `id: ${event.seq}\ndata: ${JSON.stringify(event)}\n\n`;
|
|
303
|
+
}
|
|
304
|
+
const BLANK_LINE = /\r\n\r\n|\n\n|\r\r/;
|
|
305
|
+
const BLANK_LINE_START = /^(\r\n\r\n|\n\n|\r\r)/;
|
|
306
|
+
function messageEnd(buffer) {
|
|
307
|
+
const match = BLANK_LINE.exec(buffer);
|
|
308
|
+
return match ? match.index : -1;
|
|
309
|
+
}
|
|
310
|
+
function parseMessage(text) {
|
|
311
|
+
const data = [];
|
|
312
|
+
for (const line of text.split(/\r\n|\r|\n/)) if (line.startsWith("data:")) data.push(line.slice(line.startsWith("data: ") ? 6 : 5));
|
|
313
|
+
if (data.length === 0) return void 0;
|
|
314
|
+
return JSON.parse(data.join("\n"));
|
|
315
|
+
}
|
|
316
|
+
// ../core/src/ask-user.ts
|
|
317
|
+
/** The tool definition to give the model. Same shape as a page tool's `ToolSpec`. */
|
|
318
|
+
const askUserTool = {
|
|
319
|
+
name: "ask_user",
|
|
320
|
+
description: "Ask the user one to four short multiple-choice questions when you need their preference or a decision before going on, instead of guessing. Each question is single (pick one), multiple (pick any) or rank (put the options in order). The user can also type their own answer, skip a question or decline. The result lists every question with the user's answer, or skipped.",
|
|
321
|
+
inputSchema: {
|
|
322
|
+
type: "object",
|
|
323
|
+
properties: { questions: {
|
|
324
|
+
type: "array",
|
|
325
|
+
minItems: 1,
|
|
326
|
+
maxItems: 4,
|
|
327
|
+
items: {
|
|
328
|
+
type: "object",
|
|
329
|
+
properties: {
|
|
330
|
+
question: {
|
|
331
|
+
type: "string",
|
|
332
|
+
description: "The question, one sentence."
|
|
333
|
+
},
|
|
334
|
+
kind: {
|
|
335
|
+
type: "string",
|
|
336
|
+
enum: [
|
|
337
|
+
"single",
|
|
338
|
+
"multiple",
|
|
339
|
+
"rank"
|
|
340
|
+
],
|
|
341
|
+
description: "Defaults to single."
|
|
342
|
+
},
|
|
343
|
+
options: {
|
|
344
|
+
type: "array",
|
|
345
|
+
items: { type: "string" },
|
|
346
|
+
minItems: 2,
|
|
347
|
+
maxItems: 8,
|
|
348
|
+
description: "Short option texts. Do not add a catch-all: the user can always type their own answer."
|
|
349
|
+
}
|
|
350
|
+
},
|
|
351
|
+
required: ["question", "options"]
|
|
352
|
+
}
|
|
353
|
+
} },
|
|
354
|
+
required: ["questions"]
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
const kinds = [
|
|
358
|
+
"single",
|
|
359
|
+
"multiple",
|
|
360
|
+
"rank"
|
|
361
|
+
];
|
|
362
|
+
/** The questions in a tool call's input, dropping malformed ones; `kind` defaults to "single". Empty while the input is incomplete. */
|
|
363
|
+
function readAskUserInput(input) {
|
|
364
|
+
const list = input?.questions;
|
|
365
|
+
if (!Array.isArray(list)) return [];
|
|
366
|
+
const out = [];
|
|
367
|
+
for (const q of list) {
|
|
368
|
+
if (!q || typeof q !== "object") continue;
|
|
369
|
+
const { question, kind = "single", options } = q;
|
|
370
|
+
if (typeof question !== "string" || !question.trim() || !kinds.includes(kind)) continue;
|
|
371
|
+
if (!Array.isArray(options)) continue;
|
|
372
|
+
const texts = options.filter((o) => typeof o === "string" && o.trim() !== "");
|
|
373
|
+
if (texts.length === 0) continue;
|
|
374
|
+
out.push({
|
|
375
|
+
question,
|
|
376
|
+
kind,
|
|
377
|
+
options: texts
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
return out;
|
|
381
|
+
}
|
|
382
|
+
/** The answers in a tool call's result, or undefined when it is not an ask_user result. */
|
|
383
|
+
function readAskUserResult(result) {
|
|
384
|
+
const list = result?.answers;
|
|
385
|
+
if (!Array.isArray(list)) return void 0;
|
|
386
|
+
return list.filter((a) => !!a && typeof a === "object" && typeof a.question === "string" && kinds.includes(a.kind));
|
|
387
|
+
}
|
|
388
|
+
export { readEventStream as a, activityTokens as c, estimateTokens as d, outputTokens as f, settleToolCall as h, formatEvent as i, applyEvent as l, resolveEffort as m, readAskUserInput as n, isActivityPart as o, reduceEvents as p, readAskUserResult as r, toBlocks as s, askUserTool as t, awaitingToolCalls as u };
|
package/dist/core.js
CHANGED
|
@@ -1,103 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* The visualize preset: a tool the model calls to draw an interactive visual inline (similar to claude.ai's
|
|
5
|
-
* visualize tool), and the design guide to put in the system prompt. The kit's `show_widget` tool view feeds
|
|
6
|
-
* the streaming `widget_code` into a sandboxed WidgetFrame. The backend runs the tool as a no-op ("shown").
|
|
7
|
-
*/
|
|
8
|
-
/** The tool definition to give the model. Same shape as a page tool's `ToolSpec`. */
|
|
9
|
-
const visualizeTool = {
|
|
10
|
-
name: "show_widget",
|
|
11
|
-
description: "Draw an interactive visual inline in your reply: a chart, diagram, map, calendar, calculator, planner. Write an HTML fragment or an <svg> in widget_code; it runs in a sandboxed frame that matches the chat's theme. Follow the visual design guide in your instructions.",
|
|
12
|
-
inputSchema: {
|
|
13
|
-
type: "object",
|
|
14
|
-
properties: {
|
|
15
|
-
widget_code: {
|
|
16
|
-
type: "string",
|
|
17
|
-
description: "An HTML fragment (no <html>, <head> or <body>) or an <svg>. Inline <style> and <script> are allowed."
|
|
18
|
-
},
|
|
19
|
-
title: {
|
|
20
|
-
type: "string",
|
|
21
|
-
description: "Short snake_case name for the visual, e.g. gym_week."
|
|
22
|
-
},
|
|
23
|
-
loading_messages: {
|
|
24
|
-
type: "array",
|
|
25
|
-
items: { type: "string" },
|
|
26
|
-
minItems: 1,
|
|
27
|
-
maxItems: 4,
|
|
28
|
-
description: "1-4 short lines shown while you write it, e.g. \"Finding free slots\"."
|
|
29
|
-
},
|
|
30
|
-
replaces: replacesProperty
|
|
31
|
-
},
|
|
32
|
-
required: ["widget_code"]
|
|
33
|
-
}
|
|
34
|
-
};
|
|
35
|
-
/** Design guide for the system prompt when the visualize tool is on. */
|
|
36
|
-
const visualizeGuide = `## Visuals (show_widget)
|
|
37
|
-
Use show_widget when a visual says it better than text: data to compare, a plan to adjust, a place to see, a
|
|
38
|
-
process to step through. Keep explaining in text around it; the widget is not the whole answer.
|
|
39
|
-
|
|
40
|
-
How the frame works
|
|
41
|
-
- widget_code is a fragment: no <!doctype>, <html>, <head> or <body>. Put <style> first, then markup, then <script>.
|
|
42
|
-
- It renders while you write it; scripts run once it is complete, in order. Put scripts last.
|
|
43
|
-
- No network unless the host allows it: no fetch, no external images or fonts. Inline your data.
|
|
44
|
-
- The background is transparent and the frame sizes itself to your content. Add no outer margin or padding,
|
|
45
|
-
no outer border or card around the whole widget, and no fixed height on the root.
|
|
46
|
-
- Two globals: sendPrompt(text) sends a message as the user (for "Add these to my calendar", "Explain this"),
|
|
47
|
-
openLink(url) opens an http(s) link. Prefer local state (JavaScript in the widget) over round trips: filter,
|
|
48
|
-
toggle, recalculate and animate in place; use sendPrompt only for what needs you.
|
|
49
|
-
- ${replacesGuide}
|
|
50
|
-
|
|
51
|
-
Look
|
|
52
|
-
- Use the chat's theme variables, never hard-coded colors or fonts: var(--chat-fg) text, var(--chat-muted) and
|
|
53
|
-
var(--chat-subtle) secondary text, var(--chat-surface) and var(--chat-raised) fills, var(--chat-border) and
|
|
54
|
-
var(--chat-divider) lines, var(--chat-hover) hover, var(--chat-accent) with var(--chat-accent-fg) for the one
|
|
55
|
-
thing that matters most, var(--chat-check) good, var(--chat-warning), var(--chat-danger) bad;
|
|
56
|
-
var(--chat-font-sans), var(--chat-font-mono); var(--chat-ui-font-size), var(--chat-ui-font-size-sm);
|
|
57
|
-
var(--chat-radius-sm), var(--chat-radius-md), var(--chat-radius-lg).
|
|
58
|
-
- Quiet by default: thin borders, few fills, one accent. Readable labels, aligned numbers, no decoration.
|
|
59
|
-
- Set apart what you added or changed from what was already there: your proposals in the accent with a small
|
|
60
|
-
"New" (or "Changed") tag, existing data quiet. The user must see at a glance what is yours.
|
|
61
|
-
- Make it work on a narrow screen (down to 320px wide) and with a keyboard: real <button>s, visible focus.`;
|
|
62
|
-
const originOf = (url) => {
|
|
63
|
-
try {
|
|
64
|
-
return new URL(url).origin.toLowerCase();
|
|
65
|
-
} catch {
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
};
|
|
69
|
-
/**
|
|
70
|
-
* Checks widget code before it reaches the user, so a harness can send problems back to the model as the
|
|
71
|
-
* tool result. `allow` is what the host lets widgets load (the same `allow` as the chat's `widgets`).
|
|
72
|
-
*/
|
|
73
|
-
function checkWidgetCode(html, allow = {}, toolName = visualizeTool.name) {
|
|
74
|
-
const errors = [];
|
|
75
|
-
const warnings = [];
|
|
76
|
-
if (typeof html !== "string" || !html.trim()) errors.push("widget_code: required, an HTML fragment or an <svg>");
|
|
77
|
-
else {
|
|
78
|
-
if (/<!doctype|<html[\s>]|<head[\s>]|<body[\s>]/i.test(html)) errors.push("Send a fragment: no <!doctype>, <html>, <head> or <body>.");
|
|
79
|
-
const allowed = (allow.resourceDomains ?? []).map((d) => d.toLowerCase().replace(/\/$/, ""));
|
|
80
|
-
const fits = (origin) => allowed.some((a) => a === origin || a.includes("*.") && origin.endsWith(a.slice(a.indexOf("*.") + 1)) && origin.startsWith(a.slice(0, a.indexOf("*."))));
|
|
81
|
-
const blocked = /* @__PURE__ */ new Set();
|
|
82
|
-
for (const m of html.matchAll(/(?:src|href)\s*=\s*["']?(https?:\/\/[^"'\s>]+)|url\(\s*["']?(https?:\/\/[^"')\s]+)|@import\s+["'](https?:\/\/[^"']+)/gi)) {
|
|
83
|
-
const origin = originOf(m[1] ?? m[2] ?? m[3] ?? "");
|
|
84
|
-
if (origin && !fits(origin) && !/<a\s[^>]*$/i.test(html.slice(0, m.index))) blocked.add(origin);
|
|
85
|
-
}
|
|
86
|
-
if (blocked.size) errors.push(`Blocked by the sandbox: ${[...blocked].join(", ")}. ${allowed.length ? `Only ${allowed.join(", ")} may be loaded.` : "Nothing external may be loaded."} Inline it instead.`);
|
|
87
|
-
if (!(allow.connectDomains ?? []).length && /\bfetch\s*\(|XMLHttpRequest|new\s+WebSocket|EventSource\s*\(/.test(html)) errors.push("Network calls (fetch, XHR, WebSocket) are blocked: inline the data.");
|
|
88
|
-
if (/\b(localStorage|sessionStorage|document\.cookie|indexedDB)\b/.test(html)) errors.push("Storage (localStorage, cookies, indexedDB) is not available in the sandbox: keep state in variables.");
|
|
89
|
-
if (/\b(alert|confirm|prompt)\s*\(/.test(html)) errors.push("alert/confirm/prompt are blocked: show it in the widget, or use sendPrompt(text).");
|
|
90
|
-
if (/<form[\s>]/i.test(html) && /type\s*=\s*["']?submit/i.test(html)) warnings.push("Form submits are blocked: handle the button's click in a script.");
|
|
91
|
-
const colors = new Set([...html.matchAll(/(?<![\w-])(#[0-9a-f]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\))/gi)].map((m) => m[1].toLowerCase()));
|
|
92
|
-
if (colors.size) warnings.push(`Hard-coded colors (${[...colors].slice(0, 5).join(", ")}${colors.size > 5 ? ", ..." : ""}): use var(--chat-*) so it matches the theme.`);
|
|
93
|
-
}
|
|
94
|
-
const ok = errors.length === 0;
|
|
95
|
-
const lines = [...errors, ...warnings].map((e) => `- ${e}`).join("\n");
|
|
96
|
-
return {
|
|
97
|
-
ok,
|
|
98
|
-
errors,
|
|
99
|
-
warnings,
|
|
100
|
-
feedback: ok && !warnings.length ? "Shown to the user." : ok ? `Shown to the user, and it works: do not draw it again now. Next time, to fit the chat better:\n${lines}` : `Shown, but it will not work as written. Fix these and call ${toolName} again with "replaces" set to this call's id, without remarking on the fix to the user:\n${lines}`
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
export { activityTokens, applyEvent, askUserTool, awaitingToolCalls, checkUiMarkup, checkUiMarkupCode, checkUiTree, checkWidgetCode, estimateTokens, findUiBlocks, formatEvent, isActivityPart, isStateRef, matchesSchema, outputTokens, parsePartialJson, parseUiMarkup, readAskUserInput, readAskUserResult, readEventStream, readUiValue, reduceEvents, renderUiTool, renderUiToolName, replacedId, replacesGuide, replacesProperty, resolveEffort, resolveReplaces, salvageJson, schemaErrors, settleToolCall, showUiTool, showUiToolName, toBlocks, uiActionSchema, uiComponentSpecs, uiMarkupGuide, uiMarkupLanguage, uiSpecGroups, uiSpecSet, uiSpecs, visualizeGuide, visualizeTool, widgetFrameLoader, widgetLoaderMessages, withCallId };
|
|
1
|
+
import { n as salvageJson, t as parsePartialJson } from "./partial-json-w_oXePqJ.js";
|
|
2
|
+
import { a as readEventStream, c as activityTokens, d as estimateTokens, f as outputTokens, h as settleToolCall, i as formatEvent, l as applyEvent, m as resolveEffort, n as readAskUserInput, o as isActivityPart, p as reduceEvents, r as readAskUserResult, s as toBlocks, t as askUserTool, u as awaitingToolCalls } from "./ask-user-CwDYhXX4.js";
|
|
3
|
+
export { activityTokens, applyEvent, askUserTool, awaitingToolCalls, estimateTokens, formatEvent, isActivityPart, outputTokens, parsePartialJson, readAskUserInput, readAskUserResult, readEventStream, reduceEvents, resolveEffort, salvageJson, settleToolCall, toBlocks };
|