@dudko.dev/agent-web-react 0.0.29 → 0.0.30

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.
@@ -0,0 +1,1535 @@
1
+ import { McpAppCsp, McpAppResource, McpAppToolResult, AppSamplingView, AppToolCallRequest, AppSamplingRequest, AppSamplingResult, AgentToolSet, IPlan, IPlanStep, ModelTier, TierReason, EscalationReason, DecisionPoint, DecisionFallbackReason, McpSkillConsentView, IUsage, ReplanMode, AgentEvent } from '@dudko.dev/agent-web';
2
+
3
+ /**
4
+ * MCP Apps, the host's side: the security core of `<McpAppFrame>`, as pure code - no React, no
5
+ * DOM - so every guard is unit-tested (`tests/apps.test.ts`) and proved in a real browser
6
+ * (`e2e/apps.spec.ts`).
7
+ *
8
+ * The frame: an app is third-party HTML WITH scripts that must talk to the page, so it gets the
9
+ * HTML preview's boundary (`html-preview.ts`) and one addition, a relay:
10
+ *
11
+ * 1. The outer `<iframe sandbox="allow-scripts">` (never `allow-same-origin`): an opaque origin,
12
+ * no access to the page's DOM, storage, IndexedDB (the key vault) or cookies; no top
13
+ * navigation, popups, forms, modals, downloads. No `allow` attribute: no camera, microphone,
14
+ * geolocation or clipboard, whatever the app asked for.
15
+ * 2. It holds a SHELL of ours (`buildMcpAppDocument`): the policy built from the resource's
16
+ * declared origins and nothing else (`mcpAppCsp`), one inner frame - the app, also
17
+ * `sandbox="allow-scripts"`, with the same policy first in its own document - and a relay
18
+ * script. The shell's `frame-src 'none'` is what stops the app navigating itself (a frame
19
+ * may always navigate itself; only the EMBEDDING document's policy decides where to).
20
+ * 3. The relay forwards messages between the page and the app, and nothing else: from the
21
+ * app's window to the page, from the page to the app's window, never the
22
+ * `ui/notifications/sandbox-*` messages the specification reserves. The app talks to
23
+ * `window.parent` as the extension's SDK does; the page accepts messages only from the outer
24
+ * frame (`event.source`), so the app writing to `window.top` directly is ignored.
25
+ * 4. The bridge (`McpAppBridge`) answers the app: a method allow-list, checked parameters, a
26
+ * cap on requests in flight, and every request that DOES something (a tool call, a link, a
27
+ * message) handed to the host, which asks the user.
28
+ *
29
+ * That is the default. Opt-in, the app runs on an origin of its own instead, behind a sandbox
30
+ * page the host serves on another origin (the specification's "sandbox proxy"): 1 - 3 change
31
+ * (see "An app on an origin of its own" below and `mcp-app-policy.ts`), 4 does not.
32
+ */
33
+ /** The revision of the extension this host speaks. */
34
+ declare const MCP_APP_PROTOCOL_VERSION = "2026-01-26";
35
+ /** An app's frame height, before it says how tall it is. */
36
+ declare const APP_DEFAULT_HEIGHT = 360;
37
+ /** The frame's height is the host's: the app's wish, clamped to these. */
38
+ declare const APP_MIN_HEIGHT = 120;
39
+ declare const APP_MAX_HEIGHT = 800;
40
+ /** At most this many requests of one app wait at once (tool calls, links, messages). */
41
+ declare const MCP_APP_MAX_IN_FLIGHT = 3;
42
+ /** A message an app puts in the chat: at most this many characters. */
43
+ declare const MCP_APP_MAX_MESSAGE_CHARS = 4000;
44
+ /** A link an app asks to open: at most this many characters. */
45
+ declare const MCP_APP_MAX_URL_CHARS = 2048;
46
+ /** The arguments of a tool call an app makes: at most this many characters as JSON. */
47
+ declare const MCP_APP_MAX_ARGS_CHARS = 64000;
48
+ declare const clampAppHeight: (height: number) => number;
49
+ /**
50
+ * The policy of an app's document: scripts and styles inline, `data:` / `blob:` media, and the
51
+ * network ONLY where the resource declared it - `connectDomains` for `fetch` / XHR / WebSocket,
52
+ * `resourceDomains` for scripts, styles, images, fonts and media. Nothing declared, nothing
53
+ * reached. Nested frames, workers, plugins, forms and `<base>` are refused whatever was declared
54
+ * (`frameDomains` / `baseUriDomains` are not granted: a frame the app may embed would also be a
55
+ * place it may navigate itself to). Each entry is checked again with the core's `mcpAppOrigin`.
56
+ */
57
+ declare const mcpAppCsp: (csp?: Partial<McpAppCsp>) => string;
58
+ /** The origins the policy actually grants: what the app is told in `hostCapabilities.sandbox`. */
59
+ declare const grantedAppCsp: (csp?: Partial<McpAppCsp>) => {
60
+ connectDomains: string[];
61
+ resourceDomains: string[];
62
+ };
63
+ /**
64
+ * The relay of the shell: the app's messages to the page, the page's to the app - matched by
65
+ * `event.source`, never by anything the message says - and not the reserved
66
+ * `ui/notifications/sandbox-*` ones. It reads nothing else and runs nothing it is sent.
67
+ */
68
+ declare const MCP_APP_RELAY: string;
69
+ /**
70
+ * What goes into the OUTER frame's `srcdoc`: the shell (the app's policy first, one inner frame
71
+ * that fills it, the relay) carrying the app, escaped, as the inner frame's `srcdoc` - with the
72
+ * same policy first in it. Give the outer `<iframe>` `sandbox="allow-scripts"` and nothing else.
73
+ */
74
+ declare const buildMcpAppDocument: (html: string, csp?: Partial<McpAppCsp>) => string;
75
+ /** A link an app asks to open, taken apart for the prompt: the host is what the user checks. */
76
+ interface AppLink {
77
+ /** The normalised URL (what is opened). */
78
+ href: string;
79
+ /** `https://` */
80
+ scheme: string;
81
+ /** The host (and port), as the browser will go there - an internationalised name in punycode. */
82
+ host: string;
83
+ /** Everything after the host. */
84
+ rest: string;
85
+ }
86
+ /** An `http(s)` URL with a host and no credentials, at most `MCP_APP_MAX_URL_CHARS`; else none. */
87
+ declare const appLinkOf: (value: unknown) => AppLink | undefined;
88
+ /**
89
+ * The text of a `ui/message` an app sends: text blocks only (one, or a list of at most 20),
90
+ * joined, without invisible characters, at most `MCP_APP_MAX_MESSAGE_CHARS`. Anything else -
91
+ * an image, a resource, an empty or a longer text - is refused (`undefined`).
92
+ */
93
+ declare const appMessageTextOf: (content: unknown) => string | undefined;
94
+ /** A JSON-RPC message as the bridge sends it. */
95
+ type McpAppRpcMessage = {
96
+ jsonrpc: '2.0';
97
+ id: string | number;
98
+ method: string;
99
+ params?: unknown;
100
+ } | {
101
+ jsonrpc: '2.0';
102
+ method: string;
103
+ params?: unknown;
104
+ } | {
105
+ jsonrpc: '2.0';
106
+ id: string | number;
107
+ result: unknown;
108
+ } | {
109
+ jsonrpc: '2.0';
110
+ id: string | number;
111
+ error: {
112
+ code: number;
113
+ message: string;
114
+ };
115
+ };
116
+ /** The requests an app may make of this host. Any other is answered "method not found". */
117
+ declare const MCP_APP_REQUESTS: readonly ["ui/initialize", "ping", "tools/call", "ui/open-link", "ui/message", "ui/request-display-mode"];
118
+ /**
119
+ * Requests answered only when the host turned the feature on (`downloadFile` / `sampling` in
120
+ * `hostCapabilities`, a handler given to the bridge); otherwise "method not found", as before.
121
+ */
122
+ declare const MCP_APP_OPTIONAL_REQUESTS: readonly ["ui/download-file", "sampling/createMessage"];
123
+ /** The notifications this host reads. Any other is dropped. */
124
+ declare const MCP_APP_NOTIFICATIONS: readonly ["ui/notifications/initialized", "ui/notifications/size-changed"];
125
+ /** An error the bridge answers with: a JSON-RPC code and a message for the app. */
126
+ declare class McpAppRpcError extends Error {
127
+ readonly code: number;
128
+ constructor(code: number, message: string);
129
+ }
130
+ /** The host refused: the user said no, too many requests, not initialized. */
131
+ declare const MCP_APP_REFUSED = -32000;
132
+ /** How an app is shown (`hostContext.displayMode`). This host offers `inline` and `fullscreen`. */
133
+ type McpAppDisplayMode = 'inline' | 'fullscreen' | 'pip';
134
+ /** The modes the extension names (a request for any other is invalid). */
135
+ declare const MCP_APP_DISPLAY_MODES: readonly McpAppDisplayMode[];
136
+ /** A file an app asks the host to save (`ui/download-file`), as checked by `appDownloadOf`. */
137
+ type AppDownload = {
138
+ kind: 'embedded';
139
+ /** The file name, sanitized (`appFileNameOf`): what it is saved as. */
140
+ name: string;
141
+ /** The type the app declared, if it is a MIME type at all. */
142
+ mimeType?: string;
143
+ bytes: Uint8Array;
144
+ } | {
145
+ /** A `resource_link`: read with `resources/read` on the app's own server, never fetched. */
146
+ kind: 'link';
147
+ uri: string;
148
+ name: string;
149
+ mimeType?: string;
150
+ };
151
+ /** What the host does for an app (the user is asked inside these, never by the bridge). */
152
+ interface McpAppBridgeHandlers {
153
+ /** A `tools/call`: resolves with the result the app is given; throws when refused. */
154
+ callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>;
155
+ /** A link (already checked): resolves true when it was opened, false when the user said no. */
156
+ openLink: (link: AppLink) => Promise<boolean>;
157
+ /** A message (already cleaned): resolves true when it was accepted, false when not. */
158
+ message: (text: string) => Promise<boolean>;
159
+ /** The app's wish for a height (the caller clamps it). */
160
+ resize: (height: number) => void;
161
+ /**
162
+ * `ui/request-display-mode` for a mode the host offers and the app declared (or `inline`):
163
+ * the mode the app is in afterwards - the host may say no and answer the current one.
164
+ * Without it, an app stays where it is.
165
+ */
166
+ displayMode?: (mode: McpAppDisplayMode) => McpAppDisplayMode | Promise<McpAppDisplayMode>;
167
+ /**
168
+ * `ui/download-file` (already checked): true once the file was saved, false when the user said
169
+ * no. Without it the method is not offered (`hostCapabilities.downloadFile` absent).
170
+ */
171
+ downloadFile?: (file: AppDownload) => Promise<boolean>;
172
+ /**
173
+ * `sampling/createMessage`: the result for the app; throws (an `McpAppRpcError`) when refused.
174
+ * Without it the method is not offered (`hostCapabilities.sampling` absent).
175
+ */
176
+ sample?: (params: Record<string, unknown>) => Promise<unknown>;
177
+ }
178
+ interface McpAppBridgeOptions {
179
+ /** Send a message to the app (the page posts it to the outer frame). */
180
+ post: (message: McpAppRpcMessage) => void;
181
+ handlers: McpAppBridgeHandlers;
182
+ hostInfo: {
183
+ name: string;
184
+ version: string;
185
+ };
186
+ hostCapabilities: Record<string, unknown>;
187
+ hostContext: Record<string, unknown>;
188
+ /** The tool call's arguments: sent once the app says it is initialized. */
189
+ toolInput: Record<string, unknown>;
190
+ /** Its result; `undefined` = the app is told the call was cancelled (`reason`). */
191
+ toolResult?: unknown;
192
+ cancelledReason?: string;
193
+ maxInFlight?: number;
194
+ }
195
+ /**
196
+ * One app's conversation with the host (the extension's JSON-RPC over `postMessage`). It never
197
+ * touches the DOM: `receive` is given what arrived - from the right frame, the caller checked
198
+ * `event.source` - and `post` sends. Requests outside the allow-list get "method not found";
199
+ * before `ui/initialize`, only `ping` is answered; parameters are checked before a handler sees
200
+ * them; at most `maxInFlight` requests run at once. The tool's input and result are sent once,
201
+ * after the app's `ui/notifications/initialized`, as the specification requires.
202
+ */
203
+ declare class McpAppBridge {
204
+ private readonly o;
205
+ private initializeSeen;
206
+ private delivered;
207
+ private inFlight;
208
+ private closed;
209
+ private seq;
210
+ private appModes;
211
+ constructor(options: McpAppBridgeOptions);
212
+ /** The app said it is ready, and was given the tool's input and result. */
213
+ get initialized(): boolean;
214
+ /** Stop answering: the frame is gone or was reloaded. */
215
+ close(): void;
216
+ /** Tell the app it is being torn down (not waited for: the frame goes anyway). */
217
+ teardown(reason: string): void;
218
+ /** How the app is shown now (`hostContext.displayMode`). */
219
+ get displayMode(): McpAppDisplayMode;
220
+ /** Tell an initialized app that part of the host context changed (the theme). */
221
+ updateContext(patch: Record<string, unknown>): void;
222
+ /** One message from the app's frame. */
223
+ receive(data: unknown): void;
224
+ private send;
225
+ private error;
226
+ private notification;
227
+ private request;
228
+ }
229
+ /**
230
+ * What this host tells an app it can do (`hostCapabilities` of `ui/initialize`): only what it
231
+ * does. `downloadFile` and `sampling` (never `sampling.tools`) only when the host turned them on.
232
+ */
233
+ declare const mcpAppHostCapabilities: (csp?: Partial<McpAppCsp>, features?: {
234
+ downloadFile?: boolean;
235
+ sampling?: boolean;
236
+ }) => Record<string, unknown>;
237
+ /**
238
+ * Whether a display mode an app asks for may be given: `inline` always (the way back needs no
239
+ * permission); any other only when the host offers it AND the app declared it in
240
+ * `appCapabilities.availableDisplayModes` - an app that declared nothing stays inline (the
241
+ * specification lets a host decline it).
242
+ */
243
+ declare const appDisplayModeAllowed: (o: {
244
+ requested: McpAppDisplayMode;
245
+ current: McpAppDisplayMode;
246
+ host: readonly McpAppDisplayMode[];
247
+ app: readonly McpAppDisplayMode[] | undefined;
248
+ }) => boolean;
249
+ /**
250
+ * Whether the user just acted INSIDE the app's frame: the page's frame element has the focus
251
+ * (a click or a key in a frame focuses it) and the page has transient user activation (an
252
+ * activation in a frame reaches every page above it, for a few seconds). Where the browser has
253
+ * no `navigator.userActivation`, the focus alone.
254
+ */
255
+ declare const appGestureOf: (o: {
256
+ focused: boolean;
257
+ activation: boolean | undefined;
258
+ }) => boolean;
259
+ /** A file an app asks to save: at most this many bytes. */
260
+ declare const MCP_APP_MAX_DOWNLOAD_BYTES: number;
261
+ /** A saved file's name: at most this many characters (the extension kept). */
262
+ declare const MCP_APP_MAX_FILE_NAME_CHARS = 100;
263
+ /**
264
+ * Extensions this host never saves: programs, scripts, installers, shortcuts, disk images - and
265
+ * documents a browser runs scripts in when they are opened (HTML, SVG, XML).
266
+ */
267
+ declare const MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS: readonly string[];
268
+ /** Types this host never saves (the same kinds), and any `…+xml`. */
269
+ declare const MCP_APP_REFUSED_DOWNLOAD_TYPES: readonly string[];
270
+ /** A declared type as a bare MIME type (`text/plain`), or undefined when it is not one. */
271
+ declare const appMimeTypeOf: (value: unknown) => string | undefined;
272
+ /**
273
+ * The name a file is saved under: the last segment of a path or URI (`file:///x/report.json` →
274
+ * `report.json`; percent-encoding decoded, and split again), without what cannot be seen or
275
+ * reserved characters (`<>:"/\|?*`, controls), no leading dots (a hidden file) or trailing dots
276
+ * and spaces, not a Windows device name, at most `MCP_APP_MAX_FILE_NAME_CHARS` with the extension
277
+ * kept; `download` when nothing is left.
278
+ */
279
+ declare const appFileNameOf: (value: unknown) => string;
280
+ /** The extension of a (sanitized) file name, lowercased, without the dot; '' when none. */
281
+ declare const appFileExtensionOf: (name: string) => string;
282
+ /**
283
+ * Why a file may not be saved, or undefined when it may: an extension or a type of the refused
284
+ * lists (a program, a script, a page a browser would run), checked on the sanitized name and
285
+ * the declared type both.
286
+ */
287
+ declare const appDownloadRefusal: (name: string, mimeType?: string) => string | undefined;
288
+ /**
289
+ * What `ui/download-file` asks for, checked - or why not (a message for the app): ONE item of
290
+ * `contents` (one file per request, one prompt); an `EmbeddedResource` (`resource.uri` names
291
+ * it, `text` as UTF-8 or base64 `blob`, at most `maxBytes`) or a `ResourceLink` (a one-line URI,
292
+ * read later from the app's own server: the name is its last segment, else its `name`); the
293
+ * name sanitized and the name and type not refused (`appDownloadRefusal`).
294
+ */
295
+ declare const appDownloadOf: (params: unknown, maxBytes?: number) => AppDownload | string;
296
+ /** A file ready to be put to the user: its name, type, bytes, and where the bytes came from. */
297
+ interface AppReadyDownload {
298
+ name: string;
299
+ mimeType?: string;
300
+ bytes: Uint8Array;
301
+ source: 'embedded' | 'link';
302
+ }
303
+ /** How a linked file is read: `resources/read` on the app's OWN server (the connection's). */
304
+ type AppResourceReader = (server: string, uri: string, options: {
305
+ signal?: AbortSignal;
306
+ maxBytes: number;
307
+ }) => Promise<{
308
+ mimeType?: string;
309
+ bytes: Uint8Array;
310
+ }>;
311
+ /**
312
+ * The bytes of a checked file: an embedded one as it came; a linked one read from `server` -
313
+ * the app's own - through `read` (never a fetch of its URI), at most `maxBytes`, and the type the
314
+ * SERVER gives it judged again (an app cannot pass a page off as a text file through a link).
315
+ * Throws an `McpAppRpcError` for the app: no reader, a failed read, a refused type, too large.
316
+ */
317
+ declare const resolveAppDownload: (file: AppDownload, server: string, read: AppResourceReader | undefined, signal?: AbortSignal, maxBytes?: number) => Promise<AppReadyDownload>;
318
+ /**
319
+ * The error an app is told when the agent did not answer its sampling request: the core's
320
+ * `AppSamplingError` carries its JSON-RPC code (`-1`: the user said no, `-32602`: not a request
321
+ * this host takes, `-32000`: too many); anything else is a refusal.
322
+ */
323
+ declare const appSamplingErrorOf: (err: unknown) => McpAppRpcError;
324
+ /** What `saveAppFile` uses of the page (passed in: this module touches no DOM by itself). */
325
+ interface AppFileSaverEnv {
326
+ document: {
327
+ createElement: (tag: 'a') => HTMLAnchorElement;
328
+ body: {
329
+ append: (n: Node) => void;
330
+ };
331
+ };
332
+ URL: {
333
+ createObjectURL: (blob: Blob) => string;
334
+ revokeObjectURL: (url: string) => void;
335
+ };
336
+ setTimeout: (fn: () => void, ms: number) => unknown;
337
+ }
338
+ /**
339
+ * Save a checked file the user agreed to: a `Blob` of type `application/octet-stream` (the
340
+ * browser never renders or sniffs it as a page), a `blob:` URL of THIS page, an `<a download>`
341
+ * made here and clicked once. No navigation, no `data:` or `javascript:` URL, nothing of the app
342
+ * in the page; the URL is revoked a minute later.
343
+ */
344
+ declare const saveAppFile: (file: {
345
+ name: string;
346
+ bytes: Uint8Array;
347
+ }, env: AppFileSaverEnv) => void;
348
+ /** `<AgentChat appSandbox>` / `useMcpAppHost({ sandbox })`. */
349
+ interface McpAppSandboxOptions {
350
+ /**
351
+ * The sandbox page's base URL on another origin you serve (`mcpAppSandboxResponse` of the
352
+ * `./mcp-app-sandbox` entry), e.g. `https://apps.example.com/sandbox/v1`; an app's frame loads
353
+ * `<url>/<policy>`. `{server}` in the host name gives each server an origin of its own
354
+ * (`https://{server}.apps.example.com/sandbox/v1`; the server's name must be a DNS label - it
355
+ * needs a wildcard certificate). `https://` only; `http://` on `localhost` / `127.0.0.1`.
356
+ */
357
+ url: string;
358
+ /** How long a frame waits for the page's handshake before it falls back (default 5000 ms). */
359
+ timeoutMs?: number;
360
+ }
361
+ /** Why an app runs in the opaque frame although a sandbox URL is set. */
362
+ type McpAppSandboxReason = 'invalid' | 'insecure' | 'same-origin' | 'no-page-origin' | 'server-name' | 'too-many-origins' | 'no-answer';
363
+ type McpAppSandboxTarget = {
364
+ ok: true;
365
+ origin: string;
366
+ base: string;
367
+ } | {
368
+ ok: false;
369
+ reason: McpAppSandboxReason;
370
+ };
371
+ /** The placeholder for the server's name in `McpAppSandboxOptions.url`. */
372
+ declare const MCP_APP_SANDBOX_SERVER = "{server}";
373
+ declare const MCP_APP_SANDBOX_TIMEOUT_MS = 5000;
374
+ /** After the shell has loaded (the proxy loaded or failed), the handshake gets this much longer. */
375
+ declare const MCP_APP_SANDBOX_GRACE_MS = 1000;
376
+ /**
377
+ * The sandbox flags of the shell's frame and of the proxy's: scripts and an origin - the shell
378
+ * must keep YOUR origin (else the proxy below it would get an opaque one) and runs no script; the
379
+ * proxy is on the sandbox origin. Nothing else: no navigation, popup, form, modal, download.
380
+ */
381
+ declare const MCP_APP_SANDBOX_FRAME_TOKENS = "allow-scripts allow-same-origin";
382
+ /**
383
+ * Where an app of `server` runs, for a page on `pageOrigin`: the sandbox's origin and base URL,
384
+ * or why not. Refused: not a URL; credentials, a query or a fragment; not `https://` (`http://`
385
+ * only on `localhost` / `127.0.0.1`); a path a policy cannot name; `{server}` anywhere but the
386
+ * host name, more than once, or a server name that is not a lowercase DNS label; a page without
387
+ * an origin; and the sandbox on the PAGE'S OWN origin - `allow-same-origin` there would hand the
388
+ * app your storage and the key vault.
389
+ */
390
+ declare const mcpAppSandboxTarget: (options: McpAppSandboxOptions | undefined, server: string, pageOrigin: string | undefined) => McpAppSandboxTarget;
391
+ /** The proxy page's URL for an app's declared origins (`<base>/<policy>`), or none if too long. */
392
+ declare const mcpAppSandboxProxyUrl: (base: string, csp?: Partial<McpAppCsp>) => string | undefined;
393
+ /**
394
+ * The policy of the shell: no script at all, and frames from the proxy's exact URL only - a
395
+ * `frame-src` with a path matches that path and nothing else (the query is not part of the
396
+ * match), so the proxy's frame can never be navigated anywhere else.
397
+ */
398
+ declare const mcpAppSandboxShellCsp: (proxyUrl: string) => string;
399
+ /**
400
+ * What goes into the OUTER frame's `srcdoc` in sandbox mode: the shell - its policy first, one
401
+ * frame of the proxy page, no script, nothing of the app. Give the outer `<iframe>`
402
+ * `sandbox={MCP_APP_SANDBOX_FRAME_TOKENS}` and nothing else. Throws on a URL that is not a proxy
403
+ * URL this package builds (`mcpAppSandboxProxyUrl`).
404
+ */
405
+ declare const buildMcpAppSandboxShell: (proxyUrl: string) => string;
406
+ /** What one message from the proxy's frame is, for the page (`McpAppSandboxLink.receive`). */
407
+ type McpAppSandboxInput = 'drop' | 'ready' | 'broken' | 'app';
408
+ interface McpAppSandboxLinkOptions {
409
+ /** The sandbox origin (`mcpAppSandboxTarget(…).origin`). */
410
+ origin: string;
411
+ /** The app, as read from its server: sent once, on the proxy's first ready. */
412
+ html: string;
413
+ csp?: Partial<McpAppCsp>;
414
+ /** Post to the proxy's window. Always called with the sandbox origin as the target - never `*`. */
415
+ post: (message: unknown, targetOrigin: string) => void;
416
+ }
417
+ /**
418
+ * The page's side of the sandbox proxy, without the DOM: which messages are the proxy's, the
419
+ * handshake, and every post to the sandbox origin. A message is the proxy's only when it comes
420
+ * from the proxy's window (`event.source`) AND from the sandbox origin (`event.origin`). The
421
+ * first `sandbox-proxy-ready` is answered with the app (`sandbox-resource-ready`); another one
422
+ * means the proxy page was loaded again - by the app - and the link breaks (`'broken'`: stop the
423
+ * app). Every other `ui/notifications/sandbox-*` message is dropped; nothing reaches the bridge
424
+ * (`'app'`) before the app was handed over.
425
+ */
426
+ declare class McpAppSandboxLink {
427
+ private readonly o;
428
+ private state;
429
+ constructor(options: McpAppSandboxLinkOptions);
430
+ /** The proxy answered and was given the app. */
431
+ get ready(): boolean;
432
+ /** The proxy page was loaded a second time: the app must be stopped. */
433
+ get broken(): boolean;
434
+ /** Whether a message event is the proxy's: its window, and the sandbox origin. */
435
+ accepts(event: {
436
+ source: unknown;
437
+ origin: string;
438
+ }, proxy: unknown): boolean;
439
+ receive(event: {
440
+ source: unknown;
441
+ origin: string;
442
+ data: unknown;
443
+ }, proxy: unknown): McpAppSandboxInput;
444
+ /** Send a message to the app, through the proxy, to the sandbox origin. Nothing once broken. */
445
+ post(message: unknown): void;
446
+ close(): void;
447
+ }
448
+
449
+ /**
450
+ * The connection's side of MCP Apps, structurally: the core's `ConnectedMcp.apps` (`./mcp`,
451
+ * `apps: true`), or the one `useMcp` / `useMcpServers` return. Every method names the server,
452
+ * and the host always passes the app's OWN server: an app reads and calls only what its server
453
+ * declared.
454
+ */
455
+ interface McpAppsConnectionLike {
456
+ readUiResource: (server: string, uri: string, options?: {
457
+ signal?: AbortSignal;
458
+ }) => Promise<McpAppResource>;
459
+ appTool: (server: string, name: string) => {
460
+ key: string;
461
+ readOnly: boolean;
462
+ description?: string;
463
+ inputSchema?: unknown;
464
+ } | undefined;
465
+ callAppTool: (server: string, name: string, args: Record<string, unknown>, options?: {
466
+ signal?: AbortSignal;
467
+ }) => Promise<McpAppToolResult>;
468
+ /**
469
+ * A resource of that server for a file its app asks to save (a `resource_link`): the core's
470
+ * `ConnectedMcp.apps.readResource` - `resources/read` on that server, never a fetch. Older
471
+ * cores have none: a linked file is then refused.
472
+ */
473
+ readResource?: (server: string, uri: string, options?: {
474
+ signal?: AbortSignal;
475
+ maxBytes?: number;
476
+ }) => Promise<{
477
+ uri: string;
478
+ mimeType?: string;
479
+ bytes: Uint8Array;
480
+ }>;
481
+ }
482
+ /** A file an app asks to save, as the prompt shows it (the bytes stay with the host). */
483
+ interface AppDownloadView {
484
+ /** What it will be saved as (sanitized). */
485
+ name: string;
486
+ /** The declared type, if any (the server's, for a linked file). */
487
+ mimeType?: string;
488
+ /** Bytes. */
489
+ size: number;
490
+ /** In the request (`embedded`), or read from the app's server (`link`). */
491
+ source: 'embedded' | 'link';
492
+ }
493
+ /** What an app asks for besides a tool call, waiting for the user (`<AppRequestPrompt>`). */
494
+ interface AppRequestView {
495
+ id: string;
496
+ /** The app (`AppView.id`) that asks. */
497
+ appId: string;
498
+ server: string;
499
+ kind: 'link' | 'message' | 'download' | 'sampling';
500
+ /** `kind: 'link'`: the link, taken apart (the host is what the user checks). */
501
+ link?: AppLink;
502
+ /** `kind: 'message'`: the app's text, cleaned. */
503
+ text?: string;
504
+ /** `kind: 'download'`: the file. */
505
+ download?: AppDownloadView;
506
+ /** `kind: 'sampling'`: exactly what the model would get (the core checked and cleaned it). */
507
+ sampling?: AppSamplingView;
508
+ }
509
+ /** How the user answered (`answer(id, accept, options)`). */
510
+ interface AppRequestAnswerOptions {
511
+ /** A sampling request: allow this app's requests until the page is reloaded. */
512
+ always?: boolean;
513
+ }
514
+ /** What `<McpAppFrame>` asks of the host, and what the host shows the user. */
515
+ interface McpAppHost {
516
+ /** No connection (apps are off, or the server is gone): frames say so. */
517
+ connected: boolean;
518
+ read: (app: AppView, signal?: AbortSignal) => Promise<McpAppResource>;
519
+ /** The tool an app's tool-info names (for its host context); undefined when unknown. */
520
+ tool: (app: AppView) => {
521
+ description?: string;
522
+ inputSchema?: unknown;
523
+ } | undefined;
524
+ /** An app's `tools/call`: the agent's consent gate first, then the call. Throws when refused. */
525
+ callTool: (app: AppView, name: string, args: Record<string, unknown>, signal?: AbortSignal) => Promise<McpAppToolResult>;
526
+ /** An app's `ui/open-link`: true once the user opened it, false when they did not. */
527
+ openLink: (app: AppView, link: AppLink, signal?: AbortSignal) => Promise<boolean>;
528
+ /** An app's `ui/message`: true once the user put it in the message box. */
529
+ message: (app: AppView, text: string, signal?: AbortSignal) => Promise<boolean>;
530
+ /**
531
+ * An app's `ui/download-file` (checked by the bridge): true once the user saved it, false when
532
+ * they did not. Present only with `downloads` on: absent, the method is not offered.
533
+ */
534
+ downloadFile?: (app: AppView, file: AppDownload, signal?: AbortSignal) => Promise<boolean>;
535
+ /**
536
+ * An app's `sampling/createMessage`: the agent's model answers it (the core's
537
+ * `Agent.sampleForApp`), after the user said yes. Present only with `sampling` on and a
538
+ * `sample` given: absent, the method is not offered.
539
+ */
540
+ sample?: (app: AppView, params: Record<string, unknown>, signal?: AbortSignal) => Promise<unknown>;
541
+ /** Links, messages, files and sampling requests waiting for the user. */
542
+ requests: AppRequestView[];
543
+ /**
544
+ * The user's answer to a request. Call it from the click: an accepted link is opened right
545
+ * there (`window.open`, `noopener,noreferrer`) and an accepted file saved right there
546
+ * (`saveAppFile`), nowhere else. `always` (a sampling request): this app's next requests are
547
+ * not asked about until the page is reloaded.
548
+ */
549
+ answer: (id: string, accept: boolean, options?: AppRequestAnswerOptions) => void;
550
+ /** The last message the user accepted: the composer appends it as a draft (never sends it). */
551
+ draft?: {
552
+ id: string;
553
+ text: string;
554
+ };
555
+ /** Whether the app has something waiting for the user (a link, a message, a tool call). */
556
+ isWaiting: (app: AppView) => boolean;
557
+ /**
558
+ * Where apps run: on an origin of their own, through the sandbox page at this URL - or, when
559
+ * absent (the default), in an opaque frame. See `McpAppSandboxOptions`.
560
+ */
561
+ sandbox?: McpAppSandboxOptions;
562
+ }
563
+ interface UseMcpAppHostOptions {
564
+ /** The connection(s) the apps came from; without one, frames say their server is not connected. */
565
+ connection?: McpAppsConnectionLike;
566
+ /** The agent's consent gate for an app's calls: `useAgent().approveAppToolCall`. */
567
+ approve?: (call: AppToolCallRequest, signal?: AbortSignal) => Promise<void>;
568
+ /** The pending consent requests (`useAgent().pendingApprovals`): an app's are its "waiting". */
569
+ approvals?: ApprovalView[];
570
+ /**
571
+ * Run apps on an origin of their own: the URL of a sandbox page you serve on ANOTHER origin
572
+ * (`./mcp-app-sandbox`). Without it, apps run in an opaque frame (no storage of their own).
573
+ */
574
+ sandbox?: McpAppSandboxOptions;
575
+ /**
576
+ * Let apps hand the user a file to save (`ui/download-file`, `hostCapabilities.downloadFile`).
577
+ * Each file is put to the user (name, type, size) and saved only on their click. Default false.
578
+ */
579
+ downloads?: boolean;
580
+ /**
581
+ * Let apps ask the agent's model for a completion (`sampling/createMessage`,
582
+ * `hostCapabilities.sampling` - never `sampling.tools`). Needs `sample`. Default false.
583
+ */
584
+ sampling?: boolean;
585
+ /** The agent's seam for it: `useAgent().sampleForApp`. */
586
+ sample?: (request: AppSamplingRequest, approve: (view: AppSamplingView) => Promise<boolean>, signal?: AbortSignal) => Promise<AppSamplingResult>;
587
+ }
588
+ /**
589
+ * The host's side of MCP Apps for a chat: reads an app from its own server, puts each tool call
590
+ * an app asks for through the agent's consent gate, and holds the link and message requests until
591
+ * the user answers. `<AgentChat mcpApps={…}>` uses it; use it yourself with `<McpAppFrame>` and
592
+ * `<AppRequestPrompt>` in your own UI.
593
+ */
594
+ declare const useMcpAppHost: ({ connection, approve, approvals, sandbox, downloads, sampling, sample: sampleFn, }: UseMcpAppHostOptions) => McpAppHost;
595
+
596
+ /**
597
+ * Structural types for the core's OPTIONAL `@dudko.dev/agent-web/mcp` subpath.
598
+ *
599
+ * The subpath is loaded with a dynamic import and typed here rather than
600
+ * imported, for two reasons: it drags in `@modelcontextprotocol/client` (an
601
+ * optional peer of the core, which apps without MCP must not have to install),
602
+ * and the OAuth half only exists in newer cores while this package supports
603
+ * `@dudko.dev/agent-web >= 0.0.6`. `useMcp` feature-detects at runtime and
604
+ * reports `oauthSupported: false` on an older core instead of crashing.
605
+ */
606
+ interface McpCatalogEntry {
607
+ name: string;
608
+ description: string;
609
+ server: string;
610
+ /** The server marked the tool read-only (newer cores). */
611
+ readOnly?: boolean;
612
+ /** With `apps: true`: the MCP App (`ui://…`) the tool declares (newer cores). */
613
+ app?: string;
614
+ }
615
+ interface McpServerResult {
616
+ name: string;
617
+ connected: boolean;
618
+ error?: string;
619
+ needsAuthorization?: boolean;
620
+ }
621
+ /** The `instructions` one connected server returned in its `initialize` result. */
622
+ interface McpServerInstructions {
623
+ /** The server's name: its key in the configuration. */
624
+ server: string;
625
+ instructions: string;
626
+ }
627
+ /**
628
+ * Which revisions of the MCP protocol a connection may use (the core's per-server `protocol`):
629
+ * `'legacy'` (default) the 2025 revisions, `'auto'` 2026-07-28 when the server offers it and the
630
+ * 2025 ones otherwise, `'modern'` 2026-07-28 only.
631
+ */
632
+ type McpProtocolMode = 'legacy' | 'auto' | 'modern';
633
+ /** What a connection negotiated with one server. */
634
+ interface McpServerProtocol {
635
+ /** The server's name: its key in the configuration. */
636
+ server: string;
637
+ /** The protocol revision in use, e.g. `2025-11-25` or `2026-07-28`. */
638
+ version: string;
639
+ era: 'legacy' | 'modern';
640
+ }
641
+ interface ConnectedMcp {
642
+ tools: AgentToolSet;
643
+ catalog: McpCatalogEntry[];
644
+ results: McpServerResult[];
645
+ /**
646
+ * What each connected server told the agent in its handshake (newer cores; absent on older
647
+ * ones). THIRD-PARTY text: the core puts it in the system prompt of an agent that uses the
648
+ * server's tools, so a host should let the user see it.
649
+ */
650
+ instructions?: McpServerInstructions[];
651
+ /** The protocol revision negotiated with each connected server (cores with `protocol`). */
652
+ protocols?: McpServerProtocol[];
653
+ refreshServer?: (name: string) => Promise<void>;
654
+ close: () => Promise<void>;
655
+ /** MCP Apps, on a connection made with `apps: true` (newer cores; absent otherwise). */
656
+ apps?: McpAppsConnectionLike;
657
+ }
658
+ interface McpHttpServerConfig {
659
+ url: string;
660
+ headers?: Record<string, string>;
661
+ authProvider?: unknown;
662
+ /** Per-server connect deadline (newer cores; ignored by older ones). */
663
+ connectTimeoutMs?: number;
664
+ /**
665
+ * The MCP protocol revisions this connection may use (newer cores; an older one ignores the
666
+ * field and speaks the 2025 revisions). The hooks set it only for a server that was given a
667
+ * `protocol`. From a page, `'auto'` and `'modern'` need `Mcp-Method` and `Mcp-Name` in the
668
+ * server's `Access-Control-Allow-Headers`.
669
+ */
670
+ protocol?: McpProtocolMode;
671
+ /**
672
+ * EXPERIMENTAL: load the server's skills (the `io.modelcontextprotocol/skills` extension) into
673
+ * the agent's catalog, as `<server>/<skill>` (cores with MCP skills; an older one ignores the
674
+ * field). Needs `protocol: 'auto'` or `'modern'`. The hooks set it only for a server that was
675
+ * given `skills` (`true`, or `{ consent }` - a core with skill consent; an older one reads any
676
+ * object as off).
677
+ */
678
+ skills?: true | {
679
+ consent?: 'ask' | 'once-per-skill' | 'never';
680
+ };
681
+ /**
682
+ * MCP Apps for this server alone, over the connection's `apps` (cores with per-server apps;
683
+ * an older one ignores it). `false`: its apps are not shown - nothing declared, no app read,
684
+ * its app-only tools not mounted. The hooks set it only for a server that was given `apps`.
685
+ */
686
+ apps?: boolean;
687
+ }
688
+ /**
689
+ * One field of a form a server asks the user to fill in (MCP elicitation): the flat subset of
690
+ * JSON Schema the specification allows. The core has already checked, cleaned and capped it.
691
+ */
692
+ interface McpElicitationFieldSchema {
693
+ type: 'string' | 'number' | 'integer' | 'boolean' | 'array';
694
+ title?: string;
695
+ description?: string;
696
+ default?: string | number | boolean | string[];
697
+ minLength?: number;
698
+ maxLength?: number;
699
+ format?: 'email' | 'uri' | 'date' | 'date-time';
700
+ /** Single-select, plain (`enumNames`: the older titled form). */
701
+ enum?: string[];
702
+ enumNames?: string[];
703
+ /** Single-select with titles. */
704
+ oneOf?: {
705
+ const: string;
706
+ title: string;
707
+ }[];
708
+ minimum?: number;
709
+ maximum?: number;
710
+ /** Multi-select. */
711
+ minItems?: number;
712
+ maxItems?: number;
713
+ items?: {
714
+ type?: 'string';
715
+ enum?: string[];
716
+ anyOf?: {
717
+ const: string;
718
+ title: string;
719
+ }[];
720
+ };
721
+ }
722
+ /** The form of an elicitation, as the core hands it to a host. */
723
+ interface McpElicitationSchema {
724
+ type: 'object';
725
+ properties: Record<string, McpElicitationFieldSchema>;
726
+ required?: string[];
727
+ }
728
+ /**
729
+ * What the core's `onElicitation` callback is given: an MCP server asks the user for input in
730
+ * the middle of a tool call. Every string in it is the SERVER's text, never instructions.
731
+ */
732
+ interface McpElicitationRequest {
733
+ /** Unique per question; the `mcp.elicitation-*` events carry the same id. */
734
+ id: string;
735
+ server: string;
736
+ /** The tool call during which the server asks: the tool's name as the model called it. */
737
+ tool: string;
738
+ mode: 'form' | 'url';
739
+ message: string;
740
+ /** Form mode: the fields to fill in. */
741
+ requestedSchema?: McpElicitationSchema;
742
+ /** URL mode: a link the server wants the user to open. The core never opens it. */
743
+ url?: string;
744
+ elicitationId?: string;
745
+ runId?: string;
746
+ /** Set when a helper (a subagent) is the one whose call asks. */
747
+ subagent?: {
748
+ id: string;
749
+ depth: number;
750
+ };
751
+ }
752
+ /** The answer to an elicitation. `accept` carries the form's values (form mode only). */
753
+ type McpElicitationResult = {
754
+ action: 'accept';
755
+ content?: Record<string, string | number | boolean | string[]>;
756
+ } | {
757
+ action: 'decline';
758
+ } | {
759
+ action: 'cancel';
760
+ };
761
+ /** The core's `onElicitation`. `ctx.signal` aborts when the answer is no longer wanted. */
762
+ type McpElicitationHandler = (request: McpElicitationRequest, ctx: {
763
+ signal: AbortSignal;
764
+ }) => McpElicitationResult | Promise<McpElicitationResult>;
765
+ /** The core's `elicitation` settings (all optional; see the core's README). */
766
+ interface McpElicitationOptions {
767
+ timeoutMs?: number;
768
+ maxPerToolCall?: number;
769
+ maxPerRun?: number;
770
+ /** Also accept URL mode. Default false. */
771
+ url?: boolean;
772
+ /** Let a subagent's call ask the user too. Default false. */
773
+ subagents?: boolean;
774
+ }
775
+ interface McpOAuthCallback {
776
+ code?: string;
777
+ state?: string;
778
+ /** The `iss` parameter of the response (RFC 9207); the core checks it. */
779
+ iss?: string;
780
+ error?: string;
781
+ errorDescription?: string;
782
+ }
783
+ /**
784
+ * How a server's OAuth client is registered (the core's `McpOAuthRegistration`): `'auto'` the
785
+ * client ID metadata document (CIMD) where the authorization server supports it and dynamic
786
+ * registration (DCR) otherwise, `'cimd'` the document only, `'dcr'` dynamic registration only.
787
+ */
788
+ type McpOAuthRegistration = 'auto' | 'cimd' | 'dcr';
789
+ /** How a stored OAuth client was registered (the core's `McpOAuthRegistrationKind`). */
790
+ type McpOAuthRegistrationKind = 'cimd' | 'dcr';
791
+ interface BrowserOAuthProvider {
792
+ serverUrl: string;
793
+ authorizationUrl?: URL;
794
+ /** The provider's `registration`. Absent on cores older than the option. */
795
+ readonly registration?: McpOAuthRegistration;
796
+ /** How the stored client was registered. Absent on cores older than the option. */
797
+ registrationKind?(): Promise<McpOAuthRegistrationKind | undefined>;
798
+ isAuthorized(): Promise<boolean>;
799
+ reset(): Promise<void>;
800
+ }
801
+ interface BrowserOAuthProviderOptions {
802
+ serverUrl: string;
803
+ redirectUrl: string;
804
+ clientName?: string;
805
+ scope?: string;
806
+ /** Client ID metadata document URL (CIMD). Cores without it ignore the field. */
807
+ clientMetadataUrl?: string;
808
+ /**
809
+ * How the client is registered. Cores without it ignore the field - which is why the hooks
810
+ * refuse a `'cimd'` / `'dcr'` such a core did not take (`newMcpOAuthProvider`).
811
+ */
812
+ registration?: McpOAuthRegistration;
813
+ }
814
+ /** The shape of the subpath module, as far as this package uses it. */
815
+ interface McpModule {
816
+ connectMcpHttp: (servers: Record<string, McpHttpServerConfig>, opts?: {
817
+ clientName?: string;
818
+ onLog?: (level: string, message: string) => void;
819
+ connectTimeoutMs?: number;
820
+ /**
821
+ * Answer a server's question to the user (cores with MCP elicitation; an older core
822
+ * ignores both fields and declares no capability). The hooks set them only when their
823
+ * `elicitation` option is on.
824
+ */
825
+ onElicitation?: McpElicitationHandler;
826
+ elicitation?: McpElicitationOptions;
827
+ /** MCP Apps (cores with the extension; an older core ignores it and declares nothing). */
828
+ apps?: boolean;
829
+ }) => Promise<ConnectedMcp>;
830
+ BrowserOAuthProvider?: new (opts: BrowserOAuthProviderOptions) => BrowserOAuthProvider;
831
+ readOAuthCallback?: (input?: string | URL) => McpOAuthCallback | undefined;
832
+ finishMcpOAuth?: (provider: BrowserOAuthProvider, callback: McpOAuthCallback) => Promise<void>;
833
+ /**
834
+ * The SDK's error class, re-exported by the core so an authorization failure
835
+ * can be recognised by identity (`@modelcontextprotocol/client` on a core on
836
+ * the 2.x MCP SDK, `@modelcontextprotocol/sdk` before). Absent on cores older
837
+ * than 0.0.12.
838
+ */
839
+ UnauthorizedError?: new (message?: string) => Error;
840
+ }
841
+
842
+ /** Why a run stopped early (a `budget.exceeded` event). */
843
+ interface BudgetView {
844
+ kind: 'input' | 'output' | 'reasoning' | 'total' | 'tool-calls';
845
+ tokens: number;
846
+ cap: number;
847
+ }
848
+ /**
849
+ * Lifecycle of the agent instance the hook owns.
850
+ * - `idle` — no config yet, nothing built.
851
+ * - `initializing` — building the agent (dynamic provider imports, vault key
852
+ * fetch, and — for WebLLM — weight download).
853
+ * - `ready` — the agent is built and can run.
854
+ * - `running` — a run is in flight.
855
+ * - `error` — the agent failed to build (a run error keeps it `ready`).
856
+ */
857
+ type AgentStatus = 'idle' | 'initializing' | 'ready' | 'running' | 'error';
858
+ /** A file or image shown with a message (and, for images, sent to the model). */
859
+ interface ChatAttachment {
860
+ name: string;
861
+ mediaType: string;
862
+ /** A data URL (images: thumbnail + full view) — kept so a saved chat can show it again. */
863
+ dataUrl?: string;
864
+ /** Where it was stored in the virtual file system, if it was. */
865
+ path?: string;
866
+ size?: number;
867
+ }
868
+ /** One turn of the chat transcript that a chat UI renders. */
869
+ interface ChatMessage {
870
+ id: string;
871
+ role: 'user' | 'assistant';
872
+ content: string;
873
+ /** An assistant message that is still streaming (no final/stopped/error yet). */
874
+ pending: boolean;
875
+ /** User turn: what was attached (images, files). */
876
+ attachments?: ChatAttachment[];
877
+ /** Assistant turn: the run's steps — tool calls, thoughts, subagents — as they happened. */
878
+ steps?: StepView[];
879
+ /** Assistant turn: consent decisions of the run. */
880
+ approvals?: ApprovalView[];
881
+ /** Assistant turn: subagent delegations of the run. */
882
+ subagents?: SubagentView[];
883
+ /** Assistant turn: what the user said while the run was going, and where it reached the agent. */
884
+ notes?: UserNoteView[];
885
+ /** Assistant turn: the synthesizer's thoughts. */
886
+ reasoning?: string;
887
+ /** Assistant turn: tokens the run spent, by kind. */
888
+ usage?: IUsage;
889
+ /** Assistant turn: wall-clock duration of the run (needs timestamps from the hook). */
890
+ durationMs?: number;
891
+ /** Assistant turn: skills the run used. */
892
+ skills?: string[];
893
+ /** Assistant turn: lessons the agent wrote down during the run (names). */
894
+ learned?: string[];
895
+ /** Assistant turn: what the model fetched from the web during the run. */
896
+ fetches?: FetchView[];
897
+ /** Assistant turn: the images and audio the run generated (`config.media`); absent when none. */
898
+ media?: MediaView[];
899
+ /** Assistant turn: the audio the run transcribed (`config.media`); absent when none. */
900
+ transcripts?: TranscriptView[];
901
+ /**
902
+ * Assistant turn: the files the run wrote to the workspace and did not delete again (the file
903
+ * tools and the sandbox; a subagent's are here too). Absent until the first one.
904
+ */
905
+ writtenFiles?: WrittenFileView[];
906
+ /**
907
+ * Assistant turn: the MCP Apps its tool calls came with (the core's `mcp.app`, on a
908
+ * connection made with `apps: true`). Absent until the first one. Holds the call's input and
909
+ * result for the app - never the app's HTML, which is read from its server when it is shown.
910
+ */
911
+ apps?: AppView[];
912
+ /** Assistant turn ended with an error. */
913
+ error?: boolean;
914
+ }
915
+ /** A single tool call as it appears in a step, streamed then finalized. */
916
+ interface ToolCallView {
917
+ name: string;
918
+ input: unknown;
919
+ output?: unknown;
920
+ ok?: boolean;
921
+ status: 'calling' | 'done';
922
+ /** When the call started (ms epoch; set when the hook stamps events). */
923
+ startedAt?: number;
924
+ /** How long the call took. */
925
+ durationMs?: number;
926
+ /** ≈ tokens of the arguments the model wrote (chars / 4). */
927
+ inputTokens?: number;
928
+ /** ≈ tokens of the result fed back to the model (chars / 4). */
929
+ outputTokens?: number;
930
+ /**
931
+ * Set on a call of an attempt that was escalated (model tiers): the attempt it belongs to,
932
+ * 1 for the step's first. A call of the attempt the step is on now (or finished on) has none.
933
+ */
934
+ attempt?: number;
935
+ /**
936
+ * The core did NOT run this call again: the same write already succeeded in an earlier attempt
937
+ * at the step, and the model was handed that result (`output` carries the core's note).
938
+ */
939
+ replayed?: boolean;
940
+ /** The call came with an MCP App (an `mcp.app` event): the `AppView` id. */
941
+ app?: string;
942
+ }
943
+ /**
944
+ * An MCP App that came with a tool call (the core's `mcp.app` event): which server, which tool,
945
+ * which `ui://` resource, and the call's input and result - what the app is shown. Never the
946
+ * app itself: `<McpAppFrame>` reads it from the server that declared it when it is drawn.
947
+ */
948
+ interface AppView {
949
+ /** The core's event id: unique per call. */
950
+ id: string;
951
+ server: string;
952
+ /** The tool as the model called it (`server__tool`). */
953
+ tool: string;
954
+ /** The server's own name for it. */
955
+ toolName: string;
956
+ resourceUri: string;
957
+ input: Record<string, unknown>;
958
+ /** What the app is given; absent when the result was too large to hand to it. */
959
+ result?: McpAppToolResult;
960
+ stepId?: string;
961
+ /** A subagent's (or helper's) call: who made it. */
962
+ by?: {
963
+ id: string;
964
+ name: string;
965
+ role?: string;
966
+ };
967
+ }
968
+ /**
969
+ * One escalation of a step (a `step.escalated` event): the attempt on tier `from` failed for
970
+ * `reason` and the step was retried on the stronger tier `to`.
971
+ */
972
+ interface StepEscalationView {
973
+ from: ModelTier;
974
+ to: ModelTier;
975
+ reason: EscalationReason;
976
+ /** The model id of `to` (absent only when the escalation is known from the step's result alone). */
977
+ model?: string;
978
+ /** What the failed attempt had written when it was escalated (its streamed text), if anything. */
979
+ text?: string;
980
+ }
981
+ /**
982
+ * A lesson in the agent's notebook (`config.learning`): a skill the agent wrote down itself.
983
+ * `revision` goes up each time it rewrites the lesson.
984
+ */
985
+ interface LessonView {
986
+ name: string;
987
+ /** WHEN the lesson applies - the line the planner sees. */
988
+ description: string;
989
+ revision: number;
990
+ /** Size of the instructions, in characters. */
991
+ chars: number;
992
+ /** What it consulted: the sources it named, then the pages `web_fetch` read in that run. */
993
+ sources: string[];
994
+ }
995
+ /** One request the model made through `web_fetch` (an `egress.request` event). */
996
+ interface FetchView {
997
+ /** Origin and path only - the core never reports the query string. */
998
+ url: string;
999
+ allowed: boolean;
1000
+ status?: number;
1001
+ /** Why it was refused. */
1002
+ reason?: string;
1003
+ }
1004
+ /**
1005
+ * A file a media tool wrote (a `media.generated` event). The bytes are in the virtual file system
1006
+ * at `path` - never in the state.
1007
+ */
1008
+ interface MediaView {
1009
+ kind: 'image' | 'speech';
1010
+ path: string;
1011
+ mediaType: string;
1012
+ /** Size of the file. */
1013
+ bytes: number;
1014
+ /** The media model that made it. */
1015
+ model: string;
1016
+ /** The step whose tool call made it, when the event named one. */
1017
+ stepId?: string;
1018
+ }
1019
+ /**
1020
+ * A file the run wrote to the virtual file system (the core's `file.written` event: `fs_write`,
1021
+ * or the sandbox's `fs.writeFile`). One entry per path however many times it was written; a
1022
+ * `file.deleted` takes it away. The content is in the file system at `path` - never in the state.
1023
+ */
1024
+ interface WrittenFileView {
1025
+ path: string;
1026
+ /** The MIME type the file system gave it. */
1027
+ mediaType: string;
1028
+ /** Size after the last write. */
1029
+ bytes: number;
1030
+ /** How many times the run wrote it. */
1031
+ writes: number;
1032
+ /** The step whose tool call wrote it last, when the event named one (never a subagent's step). */
1033
+ stepId?: string;
1034
+ /** The subagent that wrote it last; absent when the agent itself did. */
1035
+ by?: {
1036
+ id: string;
1037
+ name: string;
1038
+ role?: string;
1039
+ };
1040
+ }
1041
+ /**
1042
+ * An audio file that was transcribed (a `media.transcribed` event): one the user attached
1043
+ * (`attachment`) or one the model asked about (`tool`). `text` is the content of that file -
1044
+ * third-party text, never instructions.
1045
+ */
1046
+ interface TranscriptView {
1047
+ source: 'attachment' | 'tool';
1048
+ /** The file's name. */
1049
+ name: string;
1050
+ text: string;
1051
+ language?: string;
1052
+ durationInSeconds?: number;
1053
+ model: string;
1054
+ }
1055
+ /**
1056
+ * One question put to `config.decisionModel` (a `decision` event): its answer was used
1057
+ * (`accepted`), or the ordinary model call ran and `reason` says why.
1058
+ */
1059
+ interface DecisionView {
1060
+ point: DecisionPoint;
1061
+ accepted: boolean;
1062
+ choice?: string;
1063
+ /** The probability the decision model gave its choice, 0..1. */
1064
+ confidence?: number;
1065
+ threshold: number;
1066
+ reason?: DecisionFallbackReason;
1067
+ durationMs: number;
1068
+ model?: string;
1069
+ }
1070
+ /** A tool call waiting for (or decided by) the user's consent. */
1071
+ interface ApprovalView {
1072
+ id: string;
1073
+ name: string;
1074
+ input: unknown;
1075
+ readOnly: boolean;
1076
+ /** The step the call belongs to, when known. */
1077
+ stepId?: string;
1078
+ /**
1079
+ * Set when a helper the model started is asking, not the run itself: its id (a node of
1080
+ * `subagents`), its depth, and - when its `subagent.start` was seen - its name and role.
1081
+ */
1082
+ subagent?: {
1083
+ id: string;
1084
+ depth: number;
1085
+ name?: string;
1086
+ role?: string;
1087
+ };
1088
+ status: 'pending' | 'approved' | 'denied';
1089
+ reason?: string;
1090
+ /** Decided by policy (rule / read-only mode), not by a person. */
1091
+ automatic?: boolean;
1092
+ /**
1093
+ * Set when an MCP App asks, not the model (`useAgent().approveAppToolCall`): its server, the
1094
+ * tool's own name there and the app's resource. `name` is then the key the consent rules
1095
+ * match. Such a request outlives a run (it is the user's, not the run's) and is never kept on
1096
+ * a message.
1097
+ */
1098
+ app?: {
1099
+ server: string;
1100
+ tool: string;
1101
+ resourceUri: string;
1102
+ };
1103
+ /**
1104
+ * Set when the request is about an MCP server's skill about to enter the model's context, not
1105
+ * a tool call (the core's `ToolApprovalRequest.skill`): the server, the skill, its description,
1106
+ * size and files, and - while the request is pending - `body`, the very text the model would
1107
+ * read. All of it is the SERVER's text: show it as plain text. `body` is dropped once the
1108
+ * request is decided, so a saved conversation does not keep a server's instructions.
1109
+ */
1110
+ skill?: SkillConsentView;
1111
+ }
1112
+ /** What a person is shown of an MCP server's skill (the core's `McpSkillConsentView`). */
1113
+ type SkillConsentView = Omit<McpSkillConsentView, 'body'> & {
1114
+ body?: string;
1115
+ };
1116
+ /**
1117
+ * A question an MCP server put to the user in the middle of a tool call (MCP elicitation; the
1118
+ * core's `mcp.elicitation-*` events). `message`, `requestedSchema` and `url` are the SERVER's
1119
+ * text - show them as such, never as the application's own. The view never holds what the user
1120
+ * answered: `fields` are the names of the fields an accepted form was answered with.
1121
+ */
1122
+ interface ElicitationView {
1123
+ /** The question's id: the same as `McpElicitationRequest.id` handed to `onElicitation`. */
1124
+ id: string;
1125
+ server: string;
1126
+ /** The tool call during which the server asked. */
1127
+ tool: string;
1128
+ /** Absent only for a question that was refused before it could be shown. */
1129
+ mode?: 'form' | 'url';
1130
+ message: string;
1131
+ /** Form mode: the fields to fill in. */
1132
+ requestedSchema?: McpElicitationSchema;
1133
+ /** URL mode: the link the server wants opened. Nothing opens it for the user. */
1134
+ url?: string;
1135
+ /** The step the tool call belongs to, when known. */
1136
+ stepId?: string;
1137
+ /** Set when a helper (a subagent) is the one whose call asks. */
1138
+ subagent?: {
1139
+ id: string;
1140
+ depth: number;
1141
+ name?: string;
1142
+ role?: string;
1143
+ };
1144
+ status: 'pending' | 'accepted' | 'declined' | 'cancelled';
1145
+ /** Answered without anybody deciding (a guard, a cap, a timeout, a stopped run). */
1146
+ automatic?: boolean;
1147
+ /** Why it was answered automatically (the core's reason, or `stopped`). */
1148
+ reason?: string;
1149
+ /** The names of the fields an accepted form was answered with. */
1150
+ fields?: string[];
1151
+ }
1152
+ /** A message sent to the agent while it works, still waiting for a boundary to be shown to the model. */
1153
+ interface QueuedMessageView {
1154
+ id: string;
1155
+ text: string;
1156
+ }
1157
+ /**
1158
+ * A message the user sent while the run was going, after it reached the agent.
1159
+ * `at` says where: `round` = between tool calls inside a step, `step` = at the end
1160
+ * of a step (the replanner then re-checked the plan), `final` = just before the
1161
+ * answer was written.
1162
+ */
1163
+ interface UserNoteView {
1164
+ id: string;
1165
+ text: string;
1166
+ at: 'round' | 'step' | 'final';
1167
+ /** The step it was delivered in (`round`) or after (`step`); none for `final`. */
1168
+ stepId?: string;
1169
+ }
1170
+ /**
1171
+ * A delegated task running in a subagent: one the host defined (`createSubagentTool`, in-process
1172
+ * or a Web Worker) or a helper the model started (`spawn_subagent`). Each is a NODE OF A TREE:
1173
+ * `parentId` / `depth` say where, and {@link subagentTree} nests the flat list.
1174
+ */
1175
+ interface SubagentView {
1176
+ id: string;
1177
+ /** The subagent's name (`spawn_subagent` for a helper the model started). */
1178
+ name: string;
1179
+ /** Empty when only its events were seen (its `subagent.start` never arrived). */
1180
+ task: string;
1181
+ /**
1182
+ * The subagent that started this one; absent for the run's own subagents (depth 1). A parent
1183
+ * that is not in the list (its start was never seen) leaves the node at the top of the tree.
1184
+ */
1185
+ parentId?: string;
1186
+ /** 1 for the run's own subagents, 2 for theirs, ... */
1187
+ depth: number;
1188
+ /** A helper the model started itself (`subagents.dynamic`). */
1189
+ dynamic?: true;
1190
+ /** What the model wrote for a helper it started. Model-written text. */
1191
+ role?: string;
1192
+ /** The tool names a helper was given. */
1193
+ tools?: string[];
1194
+ /** The model and tier its latest step ran on - known only when the child uses model tiers. */
1195
+ model?: string;
1196
+ tier?: ModelTier;
1197
+ /** When it started (ms epoch; set when the hook stamps events). */
1198
+ startedAt?: number;
1199
+ /** How long it ran, once it ended. */
1200
+ durationMs?: number;
1201
+ /** `stopped`: the user stopped this subagent; the run went on without it. */
1202
+ status: 'running' | 'done' | 'error' | 'stopped';
1203
+ /** The profile the parent model chose for this delegation, when there are profiles. */
1204
+ profile?: string;
1205
+ /** The step that delegated it, when known. */
1206
+ stepId?: string;
1207
+ /** What the child is doing right now ("step 2: …", "→ tool"). */
1208
+ activity: string;
1209
+ /** Steps the child started. */
1210
+ steps: number;
1211
+ /** Tool calls the child made. */
1212
+ toolCalls: number;
1213
+ /** The child's answer (streamed, then final). */
1214
+ text: string;
1215
+ /**
1216
+ * Tokens spent under this node, its own subagents included: counted live from its `usage`
1217
+ * events, then replaced by the total its end reports.
1218
+ */
1219
+ usage: IUsage;
1220
+ error?: string;
1221
+ }
1222
+ /** A {@link SubagentView} with the subagents it started (see {@link subagentTree}). */
1223
+ interface SubagentNode extends SubagentView {
1224
+ children: SubagentNode[];
1225
+ }
1226
+ /** One compaction of the context (a `context.compacted` event). */
1227
+ interface CompactionView {
1228
+ scope: 'history' | 'trace' | 'tool-results';
1229
+ beforeTokens: number;
1230
+ afterTokens: number;
1231
+ }
1232
+ /** An execution step with its accumulated text and tool calls. */
1233
+ interface StepView {
1234
+ id: string;
1235
+ index: number;
1236
+ total: number;
1237
+ step: IPlanStep;
1238
+ /** Streamed executor text for this step (step.text-delta). */
1239
+ text: string;
1240
+ /** Streamed executor thoughts for this step (step.reasoning-delta). */
1241
+ reasoning: string;
1242
+ toolCalls: ToolCallView[];
1243
+ status: 'running' | 'done';
1244
+ summary?: string;
1245
+ blocked: boolean;
1246
+ /**
1247
+ * Model tiers (`config.executorTiers`) - all four are absent when tiers are off.
1248
+ * `tier` / `model`: the tier the step is on NOW (where it started, then where an escalation
1249
+ * took it, then where it finished) and that tier's model id.
1250
+ */
1251
+ tier?: ModelTier;
1252
+ model?: string;
1253
+ /** Why the step STARTED on its tier: the planner's rating, the default, or a fallback. */
1254
+ tierReason?: TierReason;
1255
+ /**
1256
+ * The step's escalations, in order. `text` / `reasoning` above hold the current attempt only;
1257
+ * the calls of the attempts before it stay in `toolCalls`, marked with their `attempt`.
1258
+ */
1259
+ escalations?: StepEscalationView[];
1260
+ /**
1261
+ * The replanner call that followed this step failed (the provider's error): the run went on
1262
+ * with the plan it had. A warning, not a failed step.
1263
+ */
1264
+ replanFailed?: string;
1265
+ /** What `config.decisionModel` was asked after this step; absent without a decision model. */
1266
+ decisions?: DecisionView[];
1267
+ /** The files this step's media tools wrote (also in the turn's `media`); absent when none. */
1268
+ media?: MediaView[];
1269
+ }
1270
+ /** WebLLM weight-download / engine-init progress (model.load events). */
1271
+ interface ModelLoadState {
1272
+ progress: number;
1273
+ text: string;
1274
+ }
1275
+ interface ReplanState {
1276
+ mode: ReplanMode;
1277
+ reason: string;
1278
+ /** The replanner ran because the user sent a message, not because a step failed. */
1279
+ byUser?: boolean;
1280
+ /**
1281
+ * The replanner call itself failed and `continue` is the fallback, not the model's decision.
1282
+ * `error` is the failure (the `error` event of phase `replan` that came just before).
1283
+ */
1284
+ failed?: true;
1285
+ error?: string;
1286
+ /** `config.decisionModel` made this decision: the probability it gave its choice. */
1287
+ confidence?: number;
1288
+ }
1289
+ /**
1290
+ * The whole UI-facing view of an agent run, rebuilt purely from the stream of
1291
+ * `AgentEvent`s by {@link agentStateReducer}. `status` is owned by the hook
1292
+ * (build/run lifecycle) and layered on top; everything else here is derived
1293
+ * only from events, so the reducer is deterministic and testable without React.
1294
+ */
1295
+ interface AgentUiState {
1296
+ status: AgentStatus;
1297
+ /** The goal of the current / most recent run. */
1298
+ goal?: string;
1299
+ /** The last plan the agent produced (created or revised). */
1300
+ plan?: IPlan;
1301
+ /** Streamed planner "thinking" text (plan.thought-delta). */
1302
+ planThought: string;
1303
+ /** Execution steps, in order, with their tool calls. */
1304
+ steps: StepView[];
1305
+ /** The final answer (streamed via final.text-delta, finalized on final). */
1306
+ finalText: string;
1307
+ /** The synthesizer's streamed thoughts (final.reasoning-delta). */
1308
+ finalReasoning: string;
1309
+ /** Tool calls that asked for consent in this run, pending first-come. */
1310
+ approvals: ApprovalView[];
1311
+ /**
1312
+ * Subagent delegations of this run - static subagents and the helpers the model started, at
1313
+ * every depth, in the order they started. A tree: see `SubagentView.parentId` / `subagentTree`.
1314
+ */
1315
+ subagents: SubagentView[];
1316
+ /**
1317
+ * Questions MCP servers put to the user in this run (MCP elicitation), in the order they
1318
+ * arrived; absent until the first one. Per-run view only: they are not copied into the
1319
+ * transcript, so a saved conversation never holds a server's form.
1320
+ */
1321
+ elicitations?: ElicitationView[];
1322
+ /** Messages sent while the run goes that have not yet been shown to the model. */
1323
+ queued: QueuedMessageView[];
1324
+ /** What the user said during this run and when it reached the agent. */
1325
+ notes: UserNoteView[];
1326
+ /**
1327
+ * Messages the run ended without showing the model (sent while the answer was being
1328
+ * written, or still queued when the run was stopped). The hook sends them as a
1329
+ * follow-up unless the run was stopped; see `useAgent`'s `followUp`.
1330
+ */
1331
+ undelivered: string[];
1332
+ /** Skills activated in this run. */
1333
+ skills: string[];
1334
+ /**
1335
+ * The agent's notebook: the lessons it wrote down (`config.learning`). It belongs to the
1336
+ * agent, not to a conversation - it survives `reset` and a chat switch, and the hook
1337
+ * re-reads it whenever the agent is rebuilt.
1338
+ */
1339
+ learned: LessonView[];
1340
+ /** Names of the lessons written in this run. */
1341
+ learnedNow: string[];
1342
+ /** What the model fetched from the web in this run (`config.egress`). */
1343
+ fetches: FetchView[];
1344
+ /** Images and audio generated in this run (`config.media`). Absent until the first one. */
1345
+ media?: MediaView[];
1346
+ /** Audio transcribed in this run (`config.media`). Absent until the first one. */
1347
+ transcripts?: TranscriptView[];
1348
+ /** Files written in this run and still there (`file.written` / `file.deleted`). Absent until the first one. */
1349
+ writtenFiles?: WrittenFileView[];
1350
+ /** MCP Apps this run's tool calls came with (`mcp.app`). Absent until the first one. */
1351
+ apps?: AppView[];
1352
+ /**
1353
+ * Questions put to `config.decisionModel` before any step existed (a decision that follows a
1354
+ * step is on that step). Absent until the first one.
1355
+ */
1356
+ decisions?: DecisionView[];
1357
+ /** Tools activated by find_tools in this run. */
1358
+ discoveredTools: string[];
1359
+ /** Compactions in this run. */
1360
+ compactions: CompactionView[];
1361
+ /** Set when a run-level limit stopped the run early. */
1362
+ budget?: BudgetView;
1363
+ /** Running token total across the current run. */
1364
+ usage: IUsage;
1365
+ /** Token total across the whole conversation (every run since the last reset). */
1366
+ totalUsage: IUsage;
1367
+ /** When the current run started (ms epoch; set when the hook stamps events). */
1368
+ runStartedAt?: number;
1369
+ /** The id of the assistant message the current run streams into. */
1370
+ runMessageId?: string;
1371
+ /** WebLLM progress, present only while a local model is loading. */
1372
+ modelLoad?: ModelLoadState;
1373
+ /** The most recent replan decision, if any. */
1374
+ replan?: ReplanState;
1375
+ /**
1376
+ * Error message from the last run error / build failure. A non-fatal `plan` / `execute` /
1377
+ * `synthesize` error is kept here too while the run goes on; a replanner failure is not (see
1378
+ * `replan.failed` and `StepView.replanFailed`).
1379
+ */
1380
+ error?: string;
1381
+ /** True when the last run was aborted via stop(). */
1382
+ stopped: boolean;
1383
+ /** A chat-style transcript built from every run, for chat UIs. */
1384
+ messages: ChatMessage[];
1385
+ /** The raw event log (most recent last), capped by `maxEvents`. */
1386
+ events: AgentEvent[];
1387
+ /** Monotonic counter; mints stable message ids without Date/Math.random. */
1388
+ seq: number;
1389
+ }
1390
+
1391
+ /**
1392
+ * MCP elicitation, the part of it that is not React: what a field of a server's form is drawn
1393
+ * as, what the user typed turned into the answer, the checks an answer must pass before it is
1394
+ * sent (the core's own rules, so the form says what is wrong instead of the tool call failing),
1395
+ * what a link may be opened as, and the queue of questions waiting for the user.
1396
+ *
1397
+ * Pure, and free of the MCP SDK and of the core's `./mcp` subpath: the prompt is in the main
1398
+ * entry of this package, the hooks that fill the queue are in `./mcp`.
1399
+ *
1400
+ * Nothing here keeps, logs or returns a value the user entered except to the one caller that
1401
+ * hands it to the server: an issue names the field and the rule, never the value.
1402
+ */
1403
+ /**
1404
+ * A question waiting for the user: the core's request (every string in it is the SERVER's
1405
+ * text), and when the core will stop waiting for the answer.
1406
+ */
1407
+ interface PendingElicitation extends McpElicitationRequest {
1408
+ /** Epoch ms after which the core cancels the question by itself; absent when it has no limit. */
1409
+ expiresAt?: number;
1410
+ }
1411
+ /**
1412
+ * The hooks' `elicitation` option as the core's settings, or `undefined` when it is off - and
1413
+ * then NOTHING is passed to the core: no capability is declared and the wire is what it was.
1414
+ */
1415
+ declare const elicitationSettings: (option: boolean | McpElicitationOptions | undefined | null) => McpElicitationOptions | undefined;
1416
+ /**
1417
+ * What the hooks add to the options of the core's `connectMcpHttp`: the handler and the
1418
+ * settings when elicitation is on, and NOTHING - not even the keys - when it is off.
1419
+ */
1420
+ declare const elicitationConnectOptions: (option: boolean | McpElicitationOptions | undefined | null, handler: McpElicitationHandler) => {
1421
+ onElicitation?: McpElicitationHandler;
1422
+ elicitation?: McpElicitationOptions;
1423
+ };
1424
+ /**
1425
+ * How long the core waits for an answer with these settings; `undefined` = no limit of its own
1426
+ * (`0`, `Infinity`, more than a timer holds - the core's own rules).
1427
+ */
1428
+ declare const elicitationTimeoutOf: (settings: McpElicitationOptions) => number | undefined;
1429
+ interface ElicitationQueueOptions {
1430
+ /**
1431
+ * How long the core waits (ms), for `expiresAt`; `undefined` = no limit. A function is read
1432
+ * when a question arrives (the settings of the connection that is open then).
1433
+ */
1434
+ timeoutMs?: number | (() => number | undefined);
1435
+ /** Called whenever the list of pending questions changed. */
1436
+ onChange?: (pending: PendingElicitation[]) => void;
1437
+ /** The clock (tests). */
1438
+ now?: () => number;
1439
+ }
1440
+ interface ElicitationQueue {
1441
+ /** The core's `onElicitation`: resolves when the user answers, or as `cancel`. */
1442
+ handler: McpElicitationHandler;
1443
+ /** The questions waiting, oldest first. */
1444
+ pending: () => PendingElicitation[];
1445
+ /** Answer one. False when no such question is waiting (answered, expired, cancelled). */
1446
+ answer: (id: string, result: McpElicitationResult) => boolean;
1447
+ /** Cancel the waiting questions - all of them, or those `match` picks (one server's). */
1448
+ cancel: (match?: (request: PendingElicitation) => boolean) => void;
1449
+ /** Cancel everything and stop reporting: the owner is gone. A later question is cancelled at once. */
1450
+ dispose: () => void;
1451
+ }
1452
+ /**
1453
+ * The questions MCP servers are waiting on: `request.id → resolver`. A question leaves the queue
1454
+ * exactly once - answered by the user, cancelled because the core no longer wants the answer
1455
+ * (`ctx.signal`: its time ran out, the run stopped), or cancelled by its owner (a disconnect, an
1456
+ * unmount) - and the queue never holds an answer: `answer` passes it straight to the resolver.
1457
+ */
1458
+ declare const createElicitationQueue: (options?: ElicitationQueueOptions) => ElicitationQueue;
1459
+ /** What a field is drawn as. */
1460
+ type ElicitationControl = 'text' | 'email' | 'url' | 'date' | 'datetime' | 'number' | 'checkbox' | 'select' | 'multiselect';
1461
+ interface ElicitationOption {
1462
+ /** What goes back to the server, verbatim. */
1463
+ value: string;
1464
+ /** What the user reads (the option's title, or the value). */
1465
+ label: string;
1466
+ }
1467
+ /** One field of a form, ready to draw. `label`, `description` and option labels are the server's text. */
1468
+ interface ElicitationField {
1469
+ name: string;
1470
+ label: string;
1471
+ description?: string;
1472
+ required: boolean;
1473
+ control: ElicitationControl;
1474
+ /** `select` / `multiselect`. */
1475
+ options?: ElicitationOption[];
1476
+ schema: McpElicitationFieldSchema;
1477
+ }
1478
+ /** What the form holds while it is being filled in: text as typed, a tick, the ticked options. */
1479
+ type ElicitationDraftValue = string | boolean | string[];
1480
+ type ElicitationDraft = Record<string, ElicitationDraftValue>;
1481
+ /**
1482
+ * The fields of a form in the order the server listed them - exactly the set the core's schema
1483
+ * guard lets through: a text (plain, email, uri, date, date-time), a number / integer, a
1484
+ * boolean, a single select (`enum`, `enum` + `enumNames`, `oneOf`) and a multi-select (an array
1485
+ * of `enum` or `anyOf` options).
1486
+ */
1487
+ declare const elicitationFields: (schema: McpElicitationSchema | undefined) => ElicitationField[];
1488
+ /** What the form starts with: the schema's defaults (the core dropped the ones that do not fit). */
1489
+ declare const elicitationInitialDraft: (schema: McpElicitationSchema | undefined) => ElicitationDraft;
1490
+ /** The rules an answer can break. An issue never carries the value. */
1491
+ type ElicitationIssueKind = 'required' | 'tooShort' | 'tooLong' | 'email' | 'uri' | 'date' | 'dateTime' | 'notNumber' | 'notInteger' | 'belowMinimum' | 'aboveMaximum' | 'notAnOption' | 'tooFew' | 'tooMany';
1492
+ interface ElicitationIssue {
1493
+ kind: ElicitationIssueKind;
1494
+ /** The limit the rule states (a length, a bound, a count), when it has one. */
1495
+ limit?: number;
1496
+ }
1497
+ type ElicitationFormOutcome = {
1498
+ ok: true;
1499
+ content: Record<string, string | number | boolean | string[]>;
1500
+ } | {
1501
+ ok: false;
1502
+ issues: Record<string, ElicitationIssue>;
1503
+ };
1504
+ /**
1505
+ * A filled-in form as the answer the core will accept, or what is wrong with it, per field. The
1506
+ * rules are the core's (`validateMcpElicitationContent`): a required field is there, every
1507
+ * value is of its field's type and within its limits, and nothing the form did not ask for is
1508
+ * sent. A field left empty is left out, not sent as an empty text.
1509
+ */
1510
+ declare const elicitationFormAnswer: (schema: McpElicitationSchema | undefined, draft: ElicitationDraft) => ElicitationFormOutcome;
1511
+ interface ElicitationLink {
1512
+ /** The host the link leads to (with its port), as the browser will resolve it; '' if unparseable. */
1513
+ host: string;
1514
+ /** The whole link as text: the parsed form when it parses, what the server sent otherwise. */
1515
+ href: string;
1516
+ /** Whether an "Open" action may exist for it: https, or http on a loopback host, no credentials. */
1517
+ openable: boolean;
1518
+ }
1519
+ /**
1520
+ * A link a server wants the user to open, as the prompt may show it. The core already refuses
1521
+ * anything but https (http on loopback); this is the same rule applied again where the link is
1522
+ * about to be opened, because a host may hand the prompt a request the core never checked.
1523
+ */
1524
+ declare const elicitationLink: (raw: unknown) => ElicitationLink;
1525
+ /**
1526
+ * Why a question was answered without anybody deciding: the core's reasons
1527
+ * (`mcp.elicitation-answered` with `automatic: true`), and `stopped`, which the reducer sets on
1528
+ * whatever was still waiting when the run stopped.
1529
+ */
1530
+ type ElicitationOutcomeReason = 'timeout' | 'step-timeout' | 'aborted' | 'stopped' | 'cap-per-call' | 'cap-per-run' | 'unsupported-schema' | 'unsupported-mode' | 'insecure-url' | 'invalid-request' | 'subagent' | 'handler-error' | 'invalid-answer' | 'after-failure' | 'no-tool-call';
1531
+ /** "4:05" - what is left of a question's time. */
1532
+ declare const formatCountdown: (ms: number) => string;
1533
+
1534
+ export { MCP_APP_MAX_MESSAGE_CHARS as $, MCP_APP_DISPLAY_MODES as V, MCP_APP_MAX_ARGS_CHARS as X, MCP_APP_MAX_DOWNLOAD_BYTES as Y, MCP_APP_MAX_FILE_NAME_CHARS as Z, MCP_APP_MAX_IN_FLIGHT as _, MCP_APP_MAX_URL_CHARS as a0, MCP_APP_NOTIFICATIONS as a1, MCP_APP_OPTIONAL_REQUESTS as a2, MCP_APP_PROTOCOL_VERSION as a3, MCP_APP_REFUSED as a4, MCP_APP_REFUSED_DOWNLOAD_EXTENSIONS as a5, MCP_APP_REFUSED_DOWNLOAD_TYPES as a6, MCP_APP_RELAY as a7, MCP_APP_REQUESTS as a8, MCP_APP_SANDBOX_FRAME_TOKENS as a9, appGestureOf as aA, appLinkOf as aB, appMessageTextOf as aC, appMimeTypeOf as aD, appSamplingErrorOf as aE, buildMcpAppDocument as aF, buildMcpAppSandboxShell as aG, clampAppHeight as aH, elicitationFields as aI, elicitationFormAnswer as aJ, elicitationInitialDraft as aK, elicitationLink as aL, formatCountdown as aM, grantedAppCsp as aN, mcpAppCsp as aO, mcpAppHostCapabilities as aP, mcpAppSandboxProxyUrl as aQ, mcpAppSandboxShellCsp as aR, mcpAppSandboxTarget as aS, resolveAppDownload as aT, saveAppFile as aU, useMcpAppHost as aV, MCP_APP_SANDBOX_GRACE_MS as aa, MCP_APP_SANDBOX_SERVER as ab, MCP_APP_SANDBOX_TIMEOUT_MS as ac, McpAppBridge as ad, McpAppRpcError as ah, McpAppSandboxLink as ak, appDisplayModeAllowed as av, appDownloadOf as aw, appDownloadRefusal as ax, appFileExtensionOf as ay, appFileNameOf as az, createElicitationQueue as ba, elicitationConnectOptions as bb, elicitationSettings as bc, elicitationTimeoutOf as bd, APP_DEFAULT_HEIGHT as s, APP_MAX_HEIGHT as t, APP_MIN_HEIGHT as u };
1535
+ export type { AgentUiState as A, BudgetView as B, ChatAttachment as C, DecisionView as D, ElicitationIssueKind as E, AppResourceReader as F, ElicitationControl as G, ElicitationDraft as H, ElicitationDraftValue as I, ElicitationField as J, ElicitationFormOutcome as K, LessonView as L, McpAppSandboxReason as M, ElicitationIssue as N, ElicitationLink as O, PendingElicitation as P, ElicitationOption as Q, FetchView as R, SubagentView as S, ToolCallView as T, UserNoteView as U, WrittenFileView as W, ApprovalView as a, McpOAuthRegistrationKind as a$, McpOAuthRegistration as aW, McpProtocolMode as aX, McpElicitationOptions as aY, McpCatalogEntry as aZ, McpServerProtocol as a_, McpAppBridgeHandlers as ae, McpAppBridgeOptions as af, McpAppDisplayMode as ag, McpAppRpcMessage as ai, McpAppSandboxInput as aj, McpAppSandboxLinkOptions as al, McpAppSandboxTarget as am, McpElicitationFieldSchema as an, McpElicitationRequest as ao, McpElicitationSchema as ap, QueuedMessageView as aq, ReplanState as ar, SkillConsentView as as, StepEscalationView as at, UseMcpAppHostOptions as au, ChatMessage as b, McpOAuthCallback as b0, McpServerResult as b1, McpModule as b2, ConnectedMcp as b3, BrowserOAuthProviderOptions as b4, BrowserOAuthProvider as b5, ElicitationQueue as b6, ElicitationQueueOptions as b7, McpElicitationHandler as b8, McpServerInstructions as b9, AgentStatus as c, ElicitationOutcomeReason as d, SubagentNode as e, McpElicitationResult as f, ElicitationView as g, StepView as h, MediaView as i, AppView as j, McpAppsConnectionLike as k, McpAppSandboxOptions as l, AppRequestView as m, TranscriptView as n, CompactionView as o, ModelLoadState as p, McpAppHost as q, AppRequestAnswerOptions as r, AppDownload as v, AppDownloadView as w, AppFileSaverEnv as x, AppLink as y, AppReadyDownload as z };