@dudko.dev/agent-web
v0.0.60
Published
Headless, configurable in-browser LLM agent on the Vercel AI SDK: multi-provider bring-your-own-key (OpenAI, Anthropic, Google, xAI, DeepSeek, gateway, openai-compatible) AND local WebGPU/WebLLM, native + prompted tool-calling, structured output, an encry
Maintainers
Readme
@dudko.dev/agent-web
agent.dudko.dev · docs · live demo · source
Headless, universal, configurable in-browser LLM agent built on the Vercel AI SDK. One package drives any model from the browser:
- ☁️ Cloud providers, bring-your-own-key — OpenAI, Anthropic, Google, xAI, DeepSeek, any OpenAI-compatible server, and the Vercel AI Gateway.
- 🖥️ Local WebGPU models — via WebLLM
(
@browser-ai/web-llm); no server, no key, data never leaves the device. - 🔌 Any AI SDK
LanguageModel— e.g. Chrome/Edge built-in AI.
It gives you simple text generation, streaming, native tool-calling, and structured output, plus a high-level plan → execute → replan → synthesize agent — with host-defined tools, optional MCP, system prompts, IndexedDB storage, and an encrypted token vault. UI-agnostic: it streams typed events; you render them however you like.
The agent loop also has thinking (portable reasoning levels or exact
budgets), token limits (input / output / thinking / total per run),
context compaction (automatic and agent.compact()), prompt caching,
skills (SKILL.md bundles), tool consent modes with an autopilot switch,
tool search for catalogues of hundreds of MCP tools, subagents in
Web Workers, image / PDF / file / URL input (with a clear error for models
that can't take them),
a virtual file system in IndexedDB with fs_* tools (fs_read by line range too), usage counted live
across a session (agent.usage), steering a run while it goes (RunControl),
resuming an interrupted run, egress you switch on and bound (the model's
web_fetch), and learning — the agent writes its own lessons down as skills
— see docs/capabilities.md.
Browser sibling of the Node package
@dudko.dev/agent.
Using React?
@dudko.dev/agent-web-reactwraps this core in auseAgenthook, an<AgentProvider>context and drop-in UI components — try the live demo (source).
The family
One planning loop: two agents, and the layers that put its chat on a page. Every package has its page at agent.dudko.dev/docs. The live demo and the app are built on them.
| Package | What it is |
| --- | --- |
| @dudko.dev/agent | The agent in Node: stdio and HTTP MCP servers, OAuth 2.1, a REPL CLI, persistence and resume |
| @dudko.dev/agent-web (this package) | The same agent in a browser tab, with no backend: your own key or a local WebGPU model |
| @dudko.dev/agent-web-ui | Its chat with no framework: the state, a controller, labels in 33 languages, Markdown |
| @dudko.dev/agent-web-react | React: the useAgent hook and a ready chat panel |
| @dudko.dev/agent-web-element | <dd-agent-chat>: the whole chat as a web component, for a page on any stack |
| @dudko.dev/agent-web-vue | Vue 3: the useAgent() composable |
| @dudko.dev/agent-web-angular | Angular: injectAgent(), the chat state as signals |
| @dudko.dev/agent-web-svelte | Svelte 4 and 5: createAgent(), the chat state as a store |
Install
npm install @dudko.dev/agent-webai, zod and idb are its dependencies and come with it. Add zod to your own package only
when your code imports it, as the tool examples below do.
Then add only the providers you use (all optional peers, dynamically imported):
# cloud, pick what you need
npm install @ai-sdk/openai # or @ai-sdk/anthropic, @ai-sdk/google, @ai-sdk/xai, @ai-sdk/deepseek, @ai-sdk/openai-compatible
# local WebGPU models
npm install @browser-ai/web-llm @mlc-ai/web-llm
# optional: HTTP MCP (the official 2.x client SDK; see "Upgrading to the 2.x MCP SDK")
npm install @modelcontextprotocol/clientCDN / standalone bundle (no build step)
dist/agent-web.js is a self-contained ESM bundle of the core — ai,
zod and idb are baked in. It ships in the npm package (so it's on every
CDN) and is attached to each
GitHub release as
agent-web-<version>.min.js:
<script type="module">
import { createAgent, defineTool } from 'https://cdn.jsdelivr.net/npm/@dudko.dev/agent-web/dist/agent-web.js'
// or: https://unpkg.com/@dudko.dev/agent-web/dist/agent-web.js
</script>Bundler users can also opt into it via the @dudko.dev/agent-web/bundle
subpath. Optional provider peers stay external even in the bundle; in a
bundler-less page, map the ones you use with an import map (the runtime
import() respects it) — direct LanguageModels and gateway specs need no
import map at all:
<script type="importmap">
{
"imports": {
"@ai-sdk/openai": "https://cdn.jsdelivr.net/npm/@ai-sdk/openai/+esm"
}
}
</script>Quick start — cloud model, bring-your-own-key
Keys are stored encrypted at rest (WebCrypto, IndexedDB) and referenced by id — never inlined into config. See security.
import {
createAgent,
defineTool,
VaultCredentialStore,
} from '@dudko.dev/agent-web'
import { z } from 'zod'
// 1. Store the user's key once (e.g. from a settings form). Encrypted at rest. (A settings page
// that only stores keys can import it from '@dudko.dev/agent-web/secrets': no agent loaded.)
const credentials = new VaultCredentialStore()
await credentials.setApiKey('openai', userProvidedKey)
// 2. Tools = your app's actions.
const tools = {
add_text: defineTool({
description: 'Add a text block to the page.',
inputSchema: z.object({ text: z.string(), x: z.number().optional() }),
execute: async ({ text, x }) => addTextBlock(text, x), // your code
}),
}
// 3. Create the agent. The key is fetched from the vault at build time.
const agent = await createAgent({
model: { providerType: 'openai', model: 'gpt-4o-mini', credentialRef: 'openai' },
credentials,
tools,
describeState: () => serializeMyCanvas(), // optional grounding
})
// 4. Run. Every step is a typed event.
const result = await agent.run('Add a centered title and a totals line', {
onEvent: (e) => {
if (e.type === 'plan.created') console.log('plan:', e.plan.steps)
if (e.type === 'step.tool-call') console.log('tool:', e.name, e.input)
if (e.type === 'final') console.log('done:', e.text)
},
})
console.log(result.final, `— ${result.applied} changes`)Direct browser calls & CORS: as of October 2026 Google, OpenAI, xAI and DeepSeek send CORS headers, so a user's own key works straight from the page; Anthropic works too (a required header is injected for you). Kimi, Groq, Mistral and OpenRouter do as well (build their AI SDK models yourself and pass them as
model). Your own server (Ollama, LM Studio, vLLM...) or model: see "Your own model" there. See docs/providers.md.
Quick start — local WebGPU model (no key, offline)
import { createAgent, createWebLLMModel, isWebGPUAvailable } from '@dudko.dev/agent-web'
if (!isWebGPUAvailable()) throw new Error('WebGPU required for local models')
const model = await createWebLLMModel('Llama-3.2-3B-Instruct-q4f16_1-MLC', {
initProgressCallback: (r) => console.log('loading', Math.round(r.progress * 100), '%'),
contextWindowTokens: 8192, // WebLLM loads with 4096 unless told otherwise
})
// Local models default to the robust "prompted" tool-mode automatically, and
// the agent sizes compaction and tool lists from the model's own window.
const agent = await createAgent({ model, tools /* ...same as above */ })
await agent.run('Summarize the current page and add a heading')A local vision model (Phi-3.5-vision-instruct-q4f16_1-MLC) takes images
like a cloud one. See docs/capabilities.md
for the window: WebLLM's default is 4096 tokens, raised per model at load.
You can also pass a model by spec: { providerType: 'web-llm', model: '…' }.
Simple generation & tool-calling (no agent loop)
import { generate, stream, generateStructured, runToolLoop } from '@dudko.dev/agent-web'
import { z } from 'zod'
const { text } = await generate(model, { prompt: 'Write a haiku about WebGPU' })
const { textStream } = stream(model, { prompt: 'Explain IndexedDB' })
for await (const chunk of textStream) process.stdout.write(chunk)
const { object } = await generateStructured(
model,
z.object({ title: z.string(), tags: z.array(z.string()) }),
{ prompt: 'Suggest a title and tags for this article: …' },
)
// Tool-calling with feedback (native or prompted), normalized result. In both
// modes the model sees its tool results and can keep going, up to `maxSteps`
// rounds (default 4; prompted models get the results as a TOOL RESULTS turn):
const { text: reply, toolCalls } = await runToolLoop(model, {
mode: 'native',
prompt: 'Add a title',
tools,
})Optional: MCP tools over HTTP
import { connectMcpHttp } from '@dudko.dev/agent-web/mcp'
const mcp = await connectMcpHttp({
docs: { url: 'https://my-mcp-server.example/mcp', headers: { Authorization: `Bearer ${t}` } },
})
const agent = await createAgent({ model, tools: { ...tools, ...mcp.tools } })
// ... later: await mcp.close()Browsers can only speak the HTTP (StreamableHTTP) transport — stdio MCP is
Node-only. The connector lives in the ./mcp subpath so the MCP SDK never
enters your core bundle.
The MCP client is the official 2.x SDK, @modelcontextprotocol/client (an
optional peer: install it when you import ./mcp; @modelcontextprotocol/sdk
1.x is no longer used — what to change). By
default it negotiates the 2025 protocol revisions with the unchanged
initialize handshake, so servers see the same requests and the same headers
as before; a server that speaks only the 2026-07-28 revision then fails to
connect, at once, with Unsupported protocol version: 2025-11-25 in
results[].error.
The 2026-07-28 revision is a per-server opt-in, protocol:
const mcp = await connectMcpHttp({
docs: { url: 'https://docs.example.com/mcp' }, // 'legacy', the default
crm: { url: 'https://crm.example.com/mcp', protocol: 'auto' },
files: { url: 'https://files.example.com/mcp', protocol: 'modern' },
})
mcp.protocols // [{ server: 'docs', version: '2025-11-25', era: 'legacy' }, { server: 'crm', version: '2026-07-28', era: 'modern' }, …]| protocol | What is spoken | Against a server of the other kind |
| --- | --- | --- |
| 'legacy' (default, same as leaving it out) | The 2025 revisions: exactly the requests and the request headers sent before the option existed (a test compares them with a recording made before it). | Only 2026-07-28: Unsupported protocol version: 2025-11-25, at once. |
| 'auto' | The server is asked first (server/discover). One that answers with 2026-07-28 is spoken to that way; any other gets the 2025 handshake. | Works with both. An HTTP 5xx, an answer that is not JSON-RPC or no answer fails the connect: an outage is not read as "an old server". |
| 'modern' | 2026-07-28 only. | A 2025 server: the server did not offer pinned protocol version 2026-07-28 …, at once. |
The revision is decided once, at connect; no tool call is ever sent again in
another revision. protocols says what each connected server negotiated, and
for a server with protocol set an info line goes to onLog
([mcp] crm: protocol 2026-07-28 (modern: …; configured 'auto')).
On 2026-07-28: there is no session (mcp-session-id), no GET stream and no
initialize; instructions, isError, structuredContent and the
outputSchema note work as before; OAuth is unchanged. Three things differ:
- CORS. Every request carries
Mcp-MethodandMcp-Name, andMCP-Protocol-Versionfrom the first one on: the server must allow them (below). A server that does not cannot be reached that way from a page.'modern'then fails, and the error names the missing headers.'auto'cannot tell a blocked probe from an old server (the browser says nothing), so it falls back to the 2025 revisions and logs awarnline that names the headers - or, when the server speaks only 2026-07-28, fails with that same explanation. - Tool list changes arrive over a
subscriptions/listenstream, which the connector opens at connect when you passonToolsChangedand the server advertisestools.listChanged. When that stream ends while the connection is open - dropped, or closed by the server with its result - it is opened again, with backoff (at most 1 s, 2 s, 4 s, ... up to 60 s, less a random share of up to half; the count starts over after a stream that stayed up a minute), and once it is backonToolsChanged(name)fires once, exactly as for a notice: a change made in the gap was announced to nobody. After 10 attempts in a row it gives up; a 401 / 403 / 404 / 405 (or-32601) stops it at once. Onewarnper loss with the attempt and the delay, oneinfowhen it is back, onewarnon giving up.close()takes down a pending retry and an attempt in flight.refreshServer(name)always works. No setting: see docs/design.md. input_requiredneedsonElicitation. Without it, a tool that asks the user something (elicitation), or asks for the call to be sent again with a state, fails withMCP tool "x" did not finish: the server asked for more input …; the call is not repeated. With it, see Elicitation.
Pass several servers at once — they connect concurrently, each with its own
deadline (connectTimeoutMs, default 30 s), every page of a paginated
tools/list is read, and tools a server marks readOnlyHint are treated as
read-only by the consent gate. A failing server is reported in results; the
others still mount. With hundreds of tools the agent switches to tool search
automatically (see docs/capabilities.md).
A server's instructions (from its initialize result) reach the planner's and
the executor's system prompts, marked as third-party text and capped; a tool's
structuredContent reaches the model once, as JSON, and a result that breaks
its outputSchema is passed on with a note instead of failing the call. See
docs/capabilities.md;
the instructions are a prompt-injection surface
(docs/security.md) —
mcpInstructions: false switches them off.
A tool the server refuses with a JSON-RPC error (what a 2.x server answers for
an unknown tool, -32602) is a failed call like an isError result; its
message is the server's own, without the MCP error <code>: prefix the 1.x
SDK added — read error.code for the number. A paginated tools/list is
followed for up to 100 pages (a repeated cursor ends the walk; past the cap a
warn line says the rest is not mounted).
connectMcpHttp returns { tools, catalog, listed, results, instructions, protocols, refreshServer, close }.
listed is EVERY tool each server listed, for a host's settings: the ones offered to the model
and the ones that are not (for its app only, or skipped), each with the key the consent rules
match (server__tool; one not mounted gets a key of its own after the mounted ones - …_2 when
its name sanitizes to a mounted tool's -, so no two tools of a connection share one), mounted,
title, readOnly, destructive (MCP's reading of destructiveHint, which means something only
for a tool that is not read-only: there, true unless the server says false; never for a read-only
tool), the app it declares in _meta.ui whatever the apps mode (described only), and
appCallable. It changes nothing of what is mounted or sent. tools, catalog and listed are mutated in place by refreshServer(name), so an
agent built from them picks up a server's new tool list (react to it via the
onToolsChanged option) without being rebuilt. Filtering is plain object work:
delete the keys you don't want before merging.
MCP skills (experimental): a server's instructions as skills
A server may serve skills (the Skills extension,
io.modelcontextprotocol/skills, Beta, written against 2026-07-28): SKILL.md instruction files
and the files they bundle. Opt in per server - they come with its tools:
const mcp = await connectMcpHttp({
docs: { url: 'https://docs.example.com/mcp', protocol: 'auto', skills: true },
// a server you vetted: its skills load without a question
ours: { url: 'https://mcp.internal.example/mcp', protocol: 'auto', skills: { consent: 'never' } },
// a server you trust with its GENERATED skills (no checksums): read whole, that copy approved
gen: { url: 'https://gen.example.com/mcp', protocol: 'auto', skills: { dynamic: true } },
})
const agent = await createAgent({
model,
tools: { ...mcp.tools },
toolApproval: { onRequest: askThePerson }, // a request with `skill`: show it, then answer
})
agent.skills // [{ name: 'docs/pdf-processing', description: '… [from the MCP server "docs" - third-party]', server: 'docs' }, …]| | |
| --- | --- |
| Off by default | Without skills (true, or { consent, dynamic }) the extension is not declared and nothing of it is sent. It is declared only where 2026-07-28 may be spoken (protocol: 'auto' / 'modern'); 'legacy' (or none) logs a warn and asks nothing, an 'auto' connection that ends on 2025 lists nothing. No agent-wide switch. |
| One catalog, namespaced | The server's skills join your skills and the agent's lessons as <server>/<skill> (the server by its key in connectMcpHttp, never its serverInfo). No other skill name can hold a /: a server cannot shadow yours, a lesson or another server's - your git-workflow keeps its name and the clash is logged. Same-named skills of one server are kept by their paths. |
| On demand, verified | The prompts carry the name, the description (one line, ≤ 300 characters) and the origin. Nothing is read at connect; SKILL.md is read when load_skill or the planner asks, a file when read_skill_file asks - each checked against the server's entry (size, SHA-256, and for SKILL.md the frontmatter): a mismatch is refused, nothing of it used. A file only from the skill's own server, only if its entry lists it, as text. |
| Knowledge, never policy | Loaded under a preamble saying it is third-party text that cannot grant permissions, approve a call or change the approval mode, widen egress or the sandbox, or make the agent run anything. Nothing of its frontmatter beyond name / description is read (allowed-tools grants nothing). While a run acts on an MCP skill, a tool that runs code (run_js, or yours marked with markCodeExecution) is always asked - whatever the mode or a rule say; with no onRequest it is refused. |
| Caps | 32 skills per server, 64 in all; 16 000 characters of instructions, 32 000 of a file - every cut said. Entries over the extension's limits (512 files, 16 MiB), "dynamic" ones (unless the server has skills: { dynamic: true }) and ones whose URI and frontmatter name disagree are refused with a warn. |
| Changes | Announced as a resource list change: onToolsChanged(name) fires (also for that notice), and refreshServer(name) lists the skills again. An agent built afterwards has the new ones. |
| Directories | read_skill_file with a directory of a skill (templates/, . for the root) lists it - { name, directory, files, directories, more?, notServed?, note? }, the direct children by path, at most 64 - from the entry the skill was loaded and approved with, after the same consent as a file. When the server declared directoryRead, resources/directory/read goes to THAT server too (skill://<path>/<dir>, no trailing slash), only to see whether the skill changed there: what it lists beyond the entry is never shown - a fixed note says how many, a warn is logged (counts only) and onToolsChanged(name) fires once for that loaded skill; what the entry holds and the server no longer lists is kept and named in notServed. A failed directory read: the listing from the entry alone, and a log line. Without directoryRead the method is never called. A generated skill's directories are listed from its snapshot (below), the same way. |
| Generated skills (opt-in) | A "dynamic" entry - the server generates the skill and publishes no checksums - is declined unless THAT server has skills: { dynamic: true } (no agent-wide switch: you trust servers with this one by one). It joins the catalog like any other, its line ending [from the MCP server "x" - third-party, no checksums]. When it would enter the context - BEFORE anyone is asked - the agent reads all of it once: SKILL.md (frontmatter compared with the entry's) and, if the server declared directoryRead, its directory tree (direct children each time, only inode/directory children inside the skill, never twice) and every file found. Bounds: 512 files and 16 MiB read per skill (the extension's limits, counted on what is read), 64 directories, 8 levels deep, and 64 MiB held by all of one agent's copies (MCP_SKILL_SNAPSHOTS_MAX_BYTES) - past any of them it is declined: nobody is asked, the model is told why, a warn says it. The agent computes each file's size and SHA-256 itself; that copy (its "snapshot") is the skill's entry from then on: the consent request carries dynamic: true and the copy's size, files and text, a yes binds to the copy's digests (another copy that differs in one byte - after a refresh, in a new agent - is asked about again under 'once-per-skill'; the same bytes are not), and the model gets that copy only: its body, and every file served from memory, never read from the server again. Without directoryRead the copy is SKILL.md alone (noFileListing: true; no other file can be read). Nothing of a copy is written to IndexedDB, a checkpoint, an event or a log: a resumed run in a new agent reads a new one. 'never' works too (a vetted server). |
| A person sees it first | Before a server's skill enters the model's context (load_skill, the planner's pick, a resumed run, read_skill_file), its verified SKILL.md is put to toolApproval.onRequest: a request with toolName: 'load_skill' and skill (McpSkillConsentView: server, name, description, size, files, byUri, nestedIn, consent, and body - the very text the model would read). Yes lets it in; remember: true = "Always for this server" (nested skills excepted); no keeps all of it out and the model is told. Asked whatever the approval mode says - autopilot too; without onRequest it is not loaded. When: skills: { consent } per server, else mcpSkills: { consent } on the agent, else 'once-per-skill' (the first time per skill in the agent's life, again if its files change); 'ask' (every run); 'never' (a vetted server). A nested skill is asked about on its own. |
| By URI | A skill the listing leaves out, named by URI in a server's text: load_skill({ server, uri }) (its description says so). A skill://…/SKILL.md URI and a server whose skills are on - checked before any request - and room under the per-server cap; then skills/get to THAT server only (its -32602 reaches the model), the same entry rules, verification, consent (byUri) and preamble. It stays in the catalog, under a name no other skill has. |
A server's skills come with its tools, like its instructions: a server whose tools are all filtered out (or that has none) offers none. Details: docs/capabilities.md, what a server's skill can and cannot do: docs/security.md.
Elicitation: a server asks the user
A tool may need something only the user has - a name to confirm, a choice, a page to visit - and ask for it in the middle of the call. Off until you give the connection a callback:
const pending = new Map<string, (r: McpElicitationResult) => void>()
const mcp = await connectMcpHttp(servers, {
// The HOST decides, never the model. `request` is the SERVER's text: show it as such.
onElicitation: (request, { signal }) =>
new Promise((resolve) => {
pending.set(request.id, resolve) // your UI resolves it: accept / decline / cancel
signal.addEventListener('abort', () => pending.delete(request.id)) // no longer wanted
}),
elicitation: { timeoutMs: 300_000, maxPerToolCall: 5, maxPerRun: 20 }, // the defaults
})
// later, from the form the user filled in:
pending.get(id)?.({ action: 'accept', content: { name: 'Ada' } })- Off = nothing changes. Without
onElicitationno capability is declared, a server cannot ask, and every request is byte for byte what it was (no new request header either: a server's CORS list needs nothing for this). - The request (
McpElicitationRequest):id,server,tool(the call that asks),mode: 'form' | 'url',message, andrequestedSchema(a flat form: strings, numbers, booleans, selects) orurl. All of it is third-party text, cleaned and capped; none of it reaches a prompt. A form that is not flat, or too large, is declined without the callback being called. - The answer is checked against the form before it is sent (types, limits, required fields, no field the form did not ask for) and goes only to the server that asked: not into the model's context, an event, a log or a run checkpoint.
- URL mode is opt-in (
elicitation: { url: true }). The link is only handed to your callback: this package never fetches it and never callswindow.open. Onlyhttps:(or loopbackhttp:) links get that far. Open it from a user gesture, in a new tab, showing the host name first. - Nobody decided = the call fails. A callback that throws or does not answer
within
timeoutMs, an answer that does not fit, a cap: the question is cancelled, the tool call fails with one sentence that says why, and nothing is retried. - Subagents do not ask unless the connection says so
(
elicitation: { subagents: true }): a helper the model started, and a subagent tool's child that was handed these tools, have their questions cancelled without the callback being called. - Time. A question waits
timeoutMs(5 minutes) at most;0orInfinityremoves that limit (the question waits until the run is stopped), and so does a value above 2^31 - 1 ms (about 24.8 days, the longest delay a timer holds). A negative number orNaNfails the connect. The step it belongs to does not run out of time meanwhile:chatTimeoutMs(default 120 s) is stopped while a question waits - like thetimeoutMsof a subagent the question holds up - and goes on with the time it had left. The same holds while a person decides a tool approval (whose own bound istoolApproval.timeoutMs, also 5 minutes by default). Stopping the run ends a wait at once. - Events inside a run:
mcp.elicitation-requestedandmcp.elicitation-answered(field names, never a value).
The whole of it, with every guard: docs/capabilities.md and docs/security.md.
MCP Apps: a server's own interface for a tool
With MCP Apps (the stable extension
io.modelcontextprotocol/ui, revision 2026-01-26) a tool declares an HTML app
(_meta.ui.resourceUri: 'ui://…') that shows its result - a flight list, a chart, a form. This
package is the host's data side: it reads the declaration, tells the run when such a tool
returned, reads the app from its server, and makes the calls the app asks for. Drawing the
app is the UI's job: the React package's <AgentChat mcpApps> does it in a sandboxed frame.
Off until you ask:
const mcp = await connectMcpHttp(servers, { apps: true })
const agent = await createAgent({ model, tools: mcp.tools })
agent.run(goal, {
onEvent: async (e) => {
if (e.type !== 'mcp.app') return
// e.server, e.tool / e.toolName, e.resourceUri, e.input, e.result: what the app is shown
const app = await mcp.apps!.readUiResource(e.server, e.resourceUri) // { html, csp, permissions, … }
// ... frame app.html with a policy built from app.csp (connectDomains / resourceDomains only)
},
})
// The app asks to call a tool of ITS server: consent first, then the call.
const tool = mcp.apps!.appTool('travel', 'flights.book') // undefined: not one an app may call
await agent.approveAppToolCall({ tool: tool!.key, toolName: 'flights.book', server: 'travel',
resourceUri, input: args, readOnly: tool!.readOnly }) // throws ToolDeniedError when refused
const result = await mcp.apps!.callAppTool('travel', 'flights.book', args)Off = nothing changes. Without
appsno extension is declared,_metais not read, every tool is mounted as before and the wire is byte for byte what it was. On, the only difference on the wire is the extension in the handshake (capabilities.extensions).The HTML never reaches the model: it is in no tool result, event, log or checkpoint. The model's tool result is what it would be without apps.
mcp.appcarries the call's arguments and the result for the app (content,structuredContent,isError,_meta; left out aboveMCP_APP_MAX_RESULT_CHARS, 512 000).An app is read only from the server that declared it, and only a
ui://URI that a tool of THAT server declares in its current listing - nothing is asked of a server otherwise; checked (the exact URI, the MIME typetext/html;profile=mcp-app, at most 2 000 000 characters,textor base64blob) and cached per connection; a refused read is not kept. Its declared CSP is cleaned to origins (https://host,wss://…,https://*.example.com, loopbackhttp): a keyword, a scheme, a path,*or a;never gets through. The permissions it asks for (camera, microphone, …) are reported, never granted here. Each read logs the policy (onLog).Who may call what (
_meta.ui.visibility): a tool for its app only (['app']) is not mounted for the model;appTool/callAppToolrefuse a tool whose visibility leaves out'app', or that the server does not list - before anything is sent.Consent for an app's calls -
agent.approveAppToolCall(call, onEvent?, signal?, options?)- is the agent's own gate (
toolApproval: its mode, rules, handler and timeout), the same as for the model's calls:'autopilot'asks nothing - writes and destructive tools included -, an explicit rule still wins ('ask'asks,'deny'refuses),'ask-writes'asks before a write. "Always allow" given to an app is remembered for apps only and for THAT app:appGrantKey- the server's identity on its connection (call.serverId, fromMcpAppTool.serverId: opaque, new for every connection, so a server removed and another added under the same name inherits nothing), the tool and the app's resource - inoptions.rememberedwhen the host passes a set (it then outlives the agent: the React package keeps one for the page's life), else in the agent's own. It never answers a rule nor outranks a refusal: a'deny'rule,'read-only'and an'ask'rule are decided before it (the gate's one order, as for the model's calls - an'ask'rule asks every time, and its request carriesrule). The request carriesapp: { server, tool, resourceUri }.callAppToolitself does not ask: call it after the consent.
- is the agent's own gate (
One server's apps off:
McpHttpServerConfig.apps: false(over the connection'sapps) - that server is not told of apps, none of its apps is read, nomcp.appis told for it, and a tool it marks for its app only is mounted for nobody; its other tools are plain tools.apps: trueturns them on for that server alone (mcpAppsModeOf:'on' | 'declined' | 'off').A file an app links to (
ui/download-filewith aresource_link):mcp.apps.readResource(server, uri, { maxBytes })-resources/readon that server only, never a fetch of the URI; its bytes, at mostMCP_APP_MAX_DOWNLOAD_BYTES(20 MB), not cached. It neither asks the user nor judges the type: the UI does both before it saves anything.A completion an app asks for (
sampling/createMessage) -agent.sampleForApp({ server, resourceUri, params }, { approve, signal?, onEvent?, sessionId? }): checked (text; images only for a model known to read them; no tools; 16 000 characters;maxTokenslowered to 1024), rate limited per app (5 a minute, 30 in all), put toapprovewith exactly what the model will get, then answered by the synthesizer's model with nothing of the agent's context. Its tokens count inagent.usage(ausageevent of phase'app'); the answer goes to the caller only - never into memory, an event or a run. Caps:config.appSampling(falserefuses every request).
const answer = await agent.sampleForApp(
{ server: 'demo', resourceUri: 'ui://demo/trip-board.html', params: request.params },
{ approve: (view) => askTheUser(view) }, // view: { messages, systemPrompt?, maxTokens, … }
) // { role: 'assistant', content: { type: 'text', text }, model, stopReason } - or AppSamplingErrorEverything else an app may ask for - opening a link, putting a message in the chat, full screen, saving a file - is the UI's to ask the user about. The whole of it: docs/capabilities.md and docs/security.md.
OAuth 2.1 + Dynamic Client Registration
A server behind OAuth needs more than a header: access tokens expire mid-run.
Pass an authProvider and the MCP SDK discovers the authorization server
(RFC 9728), registers this app — dynamically (RFC 7591) or by its client ID
metadata document (CIMD), automatically or one of them only (registration):
no client_id to pre-provision — runs PKCE, and refreshes the access token on
any 401 and retries the request.
import { BrowserOAuthProvider, connectMcpHttp, finishMcpOAuth, readOAuthCallback }
from '@dudko.dev/agent-web/mcp'
const provider = new BrowserOAuthProvider({
serverUrl: 'https://my-mcp-server.example/mcp',
redirectUrl: `${location.origin}/callback`, // must match on the way back
})
// 1. On the callback page: finish the flow before anything else.
const callback = readOAuthCallback()
if (callback) await finishMcpOAuth(provider, callback)
// 2. Connect. `needsAuthorization` means "send the user to authorize".
const mcp = await connectMcpHttp({ docs: { url: provider.serverUrl, authProvider: provider } })
if (mcp.results[0]?.needsAuthorization) {
location.href = String(provider.authorizationUrl) // a button, a popup — your call
}Tokens, the registration, the PKCE verifier and what discovery found are stored in the same
encrypted IndexedDB vault as provider API keys (VaultOAuthStorage; swap in
MemoryOAuthStorage or your own via storage). redirectToAuthorization never
navigates on its own — the SDK can demand authorization from inside a running
tool call, and evicting the user then would discard the run. The URL is recorded
on provider.authorizationUrl and the app decides when to use it.
iss(RFC 9207).readOAuthCallbackreads theissparameter of the redirect andfinishMcpOAuthchecks it against the authorization server the flow was started with, afterstateand before the code is exchanged. A different issuer is refused (a mix-up attack), and so is a missingisswhen the server's metadata saysauthorization_response_iss_parameter_supported: true. The comparison is exact. If you parse the callback yourself, passissalong;checkAuthorizationResponseIssueris the rule on its own.clientMetadataUrl(CIMD). Host a client ID metadata document and pass its URL: an authorization server that advertisesclient_id_metadata_document_supportedtakes the URL as theclient_idand no registration request is made. Other servers get dynamic registration as before, and a registration already in storage wins over both. The URL must be https with a path (anything else throws in the constructor), and the document must list the sameredirect_urisasredirectUrl.registration: how the client is registered —'auto'(the default),'cimd'or'dcr'; the Node package has the same option.| value | the client | an authorization server without CIMD support | |---|---|---| |
'auto'| the document where the server advertisesclient_id_metadata_document_supported(andclientMetadataUrlis set), a dynamic registration elsewhere; a stored client is used as it is | dynamic registration | |'cimd'| the document only; needsclientMetadataUrl(the constructor throws without one) | refused before anything is sent to its registration endpoint: the connect fails with… does not support client ID metadata documents (CIMD), which this connection requires (registration: 'cimd') - nothing was sent to its registration endpoint, and what discovery found is dropped, so the next attempt reads the server's metadata again | |'dcr'| a dynamic registration only, even with aclientMetadataUrl(the provider'sclientMetadataUrlis thenundefined: the SDK never sees the URL) | dynamic registration |await provider.registrationKind()says how the stored client was made —'cimd','dcr'(also a client you saved yourself), orundefinedwhen there is none this provider would use;provider.registrationis the setting. Under'cimd'/'dcr'a stored client of the other kind is not reused: it is forgotten together with the tokens issued to it (a token belongs to its client) before either is read, and the user signs in again. The kind is stamped on the stored record when it is saved, so a later change ofclientMetadataUrldoes not make an old document client look like a dynamic one; a record saved before the stamp existed is CIMD when itsclient_idis the document configured now.Registration describes a public PKCE client.
application_typefollows the redirect URL:'web'for an https page,'native'for a loopback one (local development). Change any field throughclientMetadata.provider.reset()forgets tokens, registration and discovery - use it when a server moved to another authorization server.Discovery is stored next to the tokens (the authorization server and its metadata), so later calls skip it and the issuer check has something to compare with. A code is exchanged only when that record is still there: a flow whose discovery state is gone (started by a version that did not keep it, or storage was cleared in between) is refused by
finishMcpOAuthwithAuthorization cannot be completed: ... start the authorization again. Tokens already in storage are not touched; send the user to authorize again and the new redirect completes.Credentials belong to the authorization server that issued them. The registration and the tokens are stored with an
issuerstamp and are never presented to another authorization server: stamped for a different one, they are read as absent and a new authorization is asked for. Storage written before the stamp existed keeps working — its values are used as they are and stamped on first use (the SDK says so once on the console). A customMcpOAuthStorageonly has to return what it was given.A token endpoint must be https (or loopback). The SDK refuses to send a code or a refresh token to a plain-http token endpoint; the error names it, and no new authorization is started in its place.
The metadata must be the server's own. Authorization server metadata whose
issueris not the URL it was fetched for is refused by the SDK (RFC 8414 section 3.3): the connect fails with the two issuers named, and nothing is registered. The 1.x SDK accepted such a document.403 insufficient_scope. When the server answers a request with403andWWW-Authenticate: Bearer error="insufficient_scope", the tool call fails withInsufficient scope: required "<scope>"(the SDK'sInsufficientScopeError, withrequiredScope; it is not anUnauthorizedError). No authorization is started from inside a run: a new authorization URL in the middle of a tool call would replace the state and PKCE verifier of the one the user may have open. Ask for the scope up front (scope), or authorize again with it. A provider without a human step (noredirectUrl: the enterprise one below) asks once for the wider scope and retries the request once.A refresh whose result cannot be saved is an error, not a new authorization: when storage throws while saving refreshed tokens (a full quota, a broken vault), the connect or the tool call fails with that error.
Enterprise-managed authorization (ID-JAG)
When the company's identity provider decides who may use which MCP server (the
MCP extension io.modelcontextprotocol/enterprise-managed-authorization, also
called Cross App Access), there is no consent page and no redirect. Your app
already holds the user's OpenID Connect ID token from single sign-on; the
provider turns it into an access token in two POSTs: a token exchange at the IdP
(ID token in, an ID-JAG out), then a jwt-bearer grant at the MCP server's
authorization server (ID-JAG in, access token out).
import { connectMcpHttp, createEnterpriseOAuthProvider } from '@dudko.dev/agent-web/mcp'
const provider = createEnterpriseOAuthProvider({
serverUrl: 'https://mcp.example.com/mcp',
clientId: 'agent-web', // at the MCP authorization server, a public client
expectedIssuer: 'https://auth.example.com', // required with a clientSecret, wise without
idp: { tokenEndpoint: 'https://acme.idp.example/oauth2/token', clientId: 'agent-web-at-idp' },
getIdToken: () => session.idToken, // yours: called for every new ID-JAG
})
const mcp = await connectMcpHttp({ docs: { url: 'https://mcp.example.com/mcp', authProvider: provider } })It runs before the first request when there is no usable token, and again when the token expires or the server answers 401 - a fresh ID token and a fresh exchange each time. No refresh token is used.
Only the access token (and what discovery found) is stored, in the vault by default (
storage). The ID token and the ID-JAG are never stored, logged or put in an error.Errors are
EnterpriseOAuthErrorwithhop:'idp','authorization-server'or'discovery'. A refusal by the authorization server readsMCP authorization server refused the ID-JAG grant: invalid_grant (HTTP 400)- the code and the status, never the server's own text - at connect (results[].error,needsAuthorizationunset) and in the middle of a session (the tool call fails with it). What the server said goes toonLogatwarn(to the package logger when there is none), with every token, assertion, secret and key cut out first.expectedIssueris required withclientSecretand withprivate_key_jwt(the constructor throws otherwise): without it the MCP server's metadata would choose who receives the secret, or which audience a signed assertion is made for. A client with no credential at the authorization server may omit it: the only thing sent there is then the ID-JAG, which the IdP addressed to that one server.private_key_jwt(clientAuthMethod/idp.clientAuthMethod) signs a client assertion with WebCrypto instead of sending a secret:privateKey(aCryptoKey- make it non-extractable - or a JWK),algorithm(ES256,RS256, ...), optionalkeyId, andidp.issuerfor the IdP. The assertion's only audience is the issuer of the server it is for, it lives 60 seconds and carries a newjtieach time.assertionAudience/assertionType(and the same two insideidp), for a server built to RFC 7523 rather than todraft-ietf-oauth-rfc7523bis:| Option | Values | Default | | --- | --- | --- | |
assertionAudience,idp.assertionAudience|'issuer'or'token-endpoint': what the assertion'saudis |'issuer'| |assertionType,idp.assertionType|'client-authentication+jwt'or'JWT': itstypheader |'client-authentication+jwt'|'token-endpoint'addresses the assertion toidp.tokenEndpoint(thenidp.issueris not required) or, for the authorization server, to the token endpoint of the discovered metadata once it matchedexpectedIssuer. It is the weaker form - see docs/security.md - so use it only for a server that refuses the default.clientIdmay be the https URL of a client ID metadata document (CIMD), withprivate_key_jwtor no credential, never with aclientSecret.In a browser: the IdP's token endpoint must allow your origin (CORS), and a
clientSecret(yours oridp.clientSecret) in a page is readable by anyone who can open the page. So this provider is for public clients, or for afetchthat routes the IdP call through your backend, which holds the secret. See docs/security.md.Verified against a test identity provider, not a commercial one. Options, checks and limits: docs/capabilities.md.
CORS: what the server must send
A browser tells JavaScript nothing about why it blocked a request — a CORS
rejection and a server that is down both arrive as TypeError: Failed to fetch,
with the real reason printed only to the devtools console. So these are worth
checking first rather than last:
Access-Control-Allow-Origin: <your origin>
Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, mcp-session-id,
MCP-Protocol-Version, Last-Event-ID
Access-Control-Expose-Headers: mcp-session-id, WWW-AuthenticateNothing changed here with the 2.x MCP SDK: recorded on the wire against a raw
HTTP server, the old and the new client send the same requests with the same
headers (Accept, Content-Type, then mcp-session-id and
MCP-Protocol-Version after initialize, Authorization and Last-Event-ID
when they apply), and the browser tests run against a server with exactly this
list.
For the 2026-07-28 revision (a server connected with protocol: 'auto' or
'modern') two more request headers are needed, and MCP-Protocol-Version is
on the very first request:
Access-Control-Allow-Headers: Content-Type, Authorization, MCP-Protocol-Version,
Mcp-Method, Mcp-Name(mcp-session-id and Last-Event-ID are not sent in that revision, and no new
response header needs exposing; keep them all in one list if the server also
serves 2025 clients.) This package does not send Mcp-Param-* headers -
the mirror of tool arguments a tool may ask for with x-mcp-header - so the
list above is the whole requirement for it; another client may send them, and
their names come from the tools, so a server that uses the feature has to
allow them by pattern. Without protocol, none of these headers is sent and
the 2025 list is still enough.
Each line earns its place:
MCP-Protocol-Versionin Allow-Headers is the one that bites hardest. The spec has required that header on every request afterinitializesince 2025-06-18, and CORS lists written before that date omit it. The first request does not carry it, so discovery, the whole OAuth dance andinitializeall succeed — and then everything afterwards is blocked. It reads exactly like the consent step failing, and sends you to debug the client.WWW-Authenticatein Expose-Headers, or the browser hides the 401 challenge from JS and OAuth discovery never starts.Last-Event-IDfor resuming a dropped SSE stream.- The authorization server's
/register, metadata and token endpoints need CORS too,OPTIONSincluded — a browser client calls them directly. - If the server uses the MCP SDK's DNS-rebinding protection, its
allowedOriginsmust contain your origin. Left empty, it answers 403Origin not allowedto any request that carries anOriginheader — which is every request a browser makes.
When a connection does fail this way, connectMcpHttp no longer just repeats the
browser's silence: it re-probes the endpoint with a plain request and, if that
gets through, says which header is being refused. diagnoseMcpCors(url) is
exported so a UI can show the same sentence.
With protocol: 'auto' or 'modern' it goes one step further, because the
browser will not say which header a preflight refused: it sends one request
per header (MCP-Protocol-Version, Mcp-Method, Mcp-Name, each alone) and
names the ones that were blocked - … one carrying Mcp-Method / Mcp-Name was
blocked: the server's Access-Control-Allow-Headers does not list them …. That
sentence is added to the connect error ('modern', and 'auto' against a
2026-only server) or logged at warn ('auto' that fell back to 2025). The
same from your own code: diagnoseMcpCors(url, fetch, { protocol: 'modern' }).
These extra requests are made only after a connect already failed or fell back.
Optional: WebMCP — a page's tools, both ways
WebMCP lets a page register named, typed tools
(document.modelContext.registerTool(tool, { signal })) that a browser's agent — Chrome's origin
trial, Edge, an extension, an in-page agent — can discover and call. The ./webmcp subpath bridges it
and an agent's ToolSet, with no extra dependency and as a no-op where the browser has no WebMCP:
import { connectWebMcp, registerWebMcpTools } from '@dudko.dev/agent-web/webmcp'
// 1. Publish the tools your in-page agent uses, so any agent of the browser can drive them too.
// One definition, two consumers; withdrawn when the signal aborts or unregister() is called.
const reg = await registerWebMcpTools(tools, {
prefix: 'myapp_', // WebMCP tool names are shared with everything else on the page
except: ['debug_dump'],
consequential: ['clear_page'], // annotated consequentialHint: true
signal: controller.signal,
})
// readOnly: true tools (defineTool) are annotated readOnlyHint: true
// 2. Use the tools a page has registered as the agent's own.
const web = await connectWebMcp({ onToolsChanged: () => rebuildAgent() })
const agent = await createAgent({ model, tools: { ...tools, ...web?.tools } })Both generations of the browser API are handled: the current one on document.modelContext (a
tool is withdrawn by aborting its signal) and Chrome's early preview on navigator.modelContext
(unregisterTool(name)). Results are returned as text content (structured results as JSON), as
WebMCP clients read them. Validate strictly inside your execute, loosely in the schema: a
rejected call should be a result the calling agent can read, not a stalled tool.
Thinking, limits, consent, skills, subagents
import { createAgent, createSubagentTool, defineSkill } from '@dudko.dev/agent-web'
const agent = await createAgent({
model,
tools: { ...tools, ...mcp.tools },
thinking: 'high', // or { level, budgetTokens }; per stage via stageThinking
limits: { maxTotalTokens: 200_000, maxReasoningTokens: 20_000 },
maxToolCalls: 40,
compaction: { contextWindowTokens: 128_000 }, // auto-compacts history and long runs
skills: [defineSkill({ name: 'triage', description: 'Triage a bug report', content: '…' })],
toolApproval: {
mode: 'ask-writes', // autopilot | ask-writes | ask-all | read-only
// `signal` aborts when the agent stops waiting (the bound, a stop): take your dialog down then
onRequest: async (req, { signal }) => askInADialog(`Allow ${req.toolName}?`, { signal }),
// no decision in 5 minutes (the default) -> deny; 0 or Infinity: wait until the run is stopped
timeoutMs: 300_000,
},
})
agent.setToolApprovalMode('autopilot') // flip the switch at any time
await agent.compact() // summarise the stored transcript now (waits for a run of the session; { wait: false } throws instead)With more than 40 tools (several MCP servers) the executor switches to tool
search: it starts each step small and calls find_tools to activate what it
needs. Subagents are tools too — createSubagentTool({ config }) runs a child
agent in-process, createSubagentTool({ worker, workerConfig }) isolates it in a
Web Worker served by serveSubagentWorker(). Add profiles and the parent model
chooses, per call, between named variants of the same subagent — another model,
thinking level, limits or system prompt. With subagents: { dynamic: true } the model
starts helpers itself (spawn_subagent): a sub-task, an optional role and a subset of its own
tools — a helper can only have less than the run that starts it, and its spend counts against
that run's limits. Give persistence a store
(new IndexedDBRunStore()) and a run interrupted by a reload or a crash resumes from its
last checkpoint with run('', { resumeFromRunId }) — the planner does not run again and
no finished step is repeated; every event of a run carries seq and attempt (one more
per resume, recorded by onRunResume before the resumed run emits anything), so
(attempt, seq) orders a run's events across reloads. run(goal, { runId }) starts a fresh
run under an id of yours (1-128 letters, digits, _ or -) instead of a random one, so that a
retry finds the same run: refused together with resumeFromRunId, and refused when loadRun
already has that run (resume it instead - a run on record is never written over); see
Resuming. createRunControl() steers a run that is going: send()
puts a message in front of the model at the next boundary (the replanner re-checks the plan
against it), stopSubagent(id) stops one subagent. egress (off by default) gives the model one safe web_fetch tool with allow / deny lists. search (off by default) adds web_search over a function of yours (any search API — recipes for Tavily, Brave and SearXNG are in the docs) or the built-in Google Search through Gemini grounding, which needs only a Gemini key and spends its tokens — the key stays in the credential store. sandbox (off by default) gives the model run_js: the code it wrote runs in QuickJS-in-WebAssembly inside a Web Worker that is killed at the deadline, so "I ran it" is a tool call you can see. media (off by default) mounts generate_image, generate_speech and transcribe_audio — each only when you configure its model — writes what they make into the virtual file system instead of the context, and turns attached audio into text for a model that cannot listen. learning (off by default) lets the agent write down what it figured out as skills of its own — in memory, or in the file system across sessions. askUser (off by default) lets the model ask the person one closed question with 2-6 options (ask_user) instead of guessing — your onQuestion shows the buttons and answers, at most 3 per run. Details, defaults and events:
docs/capabilities.md.
Pipelines: a graph of agents
A pipeline is a graph of agents - each node an agent with its own role, model and tools, each edge passing one node's output to the next, optionally on a condition, loops allowed - described in plain JSON, so it can be stored, shared and drawn by an editor.
import { createPipeline, nodeResolver } from '@dudko.dev/agent-web'
const definition = {
version: 1,
entry: 'writer',
nodes: [
{ id: 'writer', name: 'Writer', instructions: 'Write the text the request asks for.', model: 'smart' },
{
id: 'reviewer',
name: 'Reviewer',
instructions: 'Review the text. Be strict.',
routes: [{ label: 'approve', description: 'ready to publish' }, { label: 'revise' }],
},
{ id: 'publisher', instructions: 'Format the approved text for publication.', tools: ['files'] },
],
edges: [
{ from: 'writer', to: 'reviewer' },
{ from: 'reviewer', to: 'publisher', when: { kind: 'route', label: 'approve' } },
{ from: 'reviewer', to: 'writer', when: { kind: 'otherwise' } }, // the loop
],
limits: { maxNodeVisits: 3, maxRuns: 25 }, // the defaults
}
const pipeline = createPipeline(definition, {
// What the names in the definition stand for. A name that is not here fails its node.
resolveNode: nodeResolver({
base: { model, credentials }, // a BrowserAgentConfig: every node starts from it
models: { smart: { providerType: 'openai', model: 'gpt-4o-mini', credentialRef: 'openai' } },
tools: { files: createFileTools(vfs) },
// skills: { ... }, mcpServers: { docs: mcp }, configure: (config, node) => config
}),
})
const result = await pipeline.run({
input: 'A release note for v2',
onEvent: (e) => {
if (e.type === 'pipeline.node.started') highlightNode(e.nodeId)
if (e.type === 'pipeline.edge') highlightEdge(e.from, e.to, e.fired)
},
})
result.text // the last node's answer; result.outputs, result.trace, result.usage, result.stoppedByAbort: signal aborts every running node and run resolves with what it has and stoppedBy: 'aborted', as agent.run resolves with stopped (the Node sibling rejects with an AbortError, as its agent.run does). Memory: with memory in base, every node keeps a conversation of its own (<sessionId>:<node id>).
Conditions (always, contains, matches, route, otherwise), the scheduling rules (waves,
join, the loop caps), validation and the events: docs/capabilities.md.
Loading a definition someone else wrote: docs/security.md.
Pausing between steps, and talking to a step at work. run({ beforeNode, control }):
const control = createPipelineControl()
let paused = false
// Every visit held at the pause (parallel branches can hold several at once).
const held = new Set<(note?: string) => void>()
const resumed = (signal: AbortSignal) =>
new Promise<string | undefined>((resolve) => {
const go = (note?: string) => {
held.delete(go)
resolve(note)
}
held.add(go)
signal.addEventListener('abort', () => go(undefined), { once: true })
})
// Your own "Resume" button lets every held visit go with the person's note (or nothing).
const resume = (note?: string) => {
paused = false
for (const go of [...held]) go(note)
}
const result = await pipeline.run({
input: 'Build the landing page',
// Asked before every visit; the visit waits for it. A text is the person's note for that step.
beforeNode: async ({ nodeId, visit }, signal) => (paused ? await resumed(signal) : undefined),
control,
})
// While a step works: a message to it (or `{ nodeId }` for one node's visits), taken between its
// agent's steps, the way `RunControl.send` reaches one run. `false`: no step at work took it.
control.send('Keep the hero section short.')beforeNode({ nodeId, visit }, signal) is a pause: the visit starts when it settles, the run's
signal ends the wait (a stop), a rejection fails the node. A string it resolves with goes under
the step's request, for that visit only (withPipelineNote: "A note from the person running the
pipeline, for this step:", trimmed, at most PIPELINE_NOTE_MAX_CHARS). With runNode the pause
and the note apply too (the note is in input.request); control reaches agents only. A visit
waiting at its gate has already been announced (pipeline.node.started comes before it), so a
UI shows it as started; its time includes the wait. A message taken during the agent's last
step (the answer being written) is not read by it - the agent's own rule (RunResult.undelivered)
- so
truemeans "taken", not "read". Acontrolmust come fromcreatePipelineControl();control.active()names the nodes at work. Both are the Node sibling's names and rules.
Running the graph yourself
createPipeline is a scheduler with createAgent as its node runner. Both halves are public, so a
host can keep the scheduler and run every node its own way - a worker, a server job, another tab -
and make the route call where the node ran:
import { createAgent, pickPipelineRoute, preparePipeline, runPipelineGraph } from '@dudko.dev/agent-web'
const plan = preparePipeline(definition) // validates (PipelineValidationError) and compiles
const result = await runPipelineGraph(
plan,
async (node, input, ctx) => {
// input: { request, from: [{ nodeId, name?, text }], visit } - renderPipelineNodeInput(input)
// is the text a createPipeline node is given.
const text = await worker.run(node.id, input, { signal: ctx.signal }) // your runner
if (!node.routes?.length) return { text }
// The route call createPipeline makes: the node's decision model, then its planner model.
const config = configOf(node) // the node's BrowserAgentConfig
const { route, usage } = await pickPipelineRoute(node, text, {
agent: await agentOf(node, config), // createAgent(config), kept per node
config,
signal: ctx.signal,
onEvent: ctx.emit,
})
return { text, usage, route }
},
{ input: 'A release note for v2', signal, onEvent, onAbort: 'resolve' },
)The runner's contract:
- When it is called. Once per visit, never for an activation a cap refused (
plan.maxNodeVisits/plan.maxRuns: the definition'slimitsor the defaults). All visits of a wave are started, in the order their nodes were first activated, before any is awaited; the next wave starts when all of them have settled. A visit's answer is applied (events, trace, edges) when it settles. - What it returns.
{ text, usage?, route?, reason? }.textis what the edges test (not a string counts as'');usageis added toresult.usage, every numeric field;routemust be one ofnode.routes' labels exactly as written - anything else, or none, is no route;reason(why that route, one sentence) is kept with the route only, cut at 500 characters. To pick one with a model of your own:PIPELINE_ROUTER_SYSTEMandrenderPipelineRoutePrompt(node, text)are the prompt,matchPipelineRoute(node, answer)turns the answer into a label. - When it fails. A runner that rejects fails the run with a
PipelineNodeError(nodeId,visit,cause), whateveronAbortsays: the other visits'ctx.signalaborts, and what they return afterwards is ignored. - Abort.
signalaborts the visits in flight (theirctx.signal) and settles the run at once, without waiting for them: it rejects with anAbortError(onAbort: 'reject', the default, as the Node sibling'screatePipelinedoes) or resolves with what it has andstoppedBy: 'aborted'('resolve', ascreatePipelinedoes here). Aborted before it starts: no visit at all. - Events.
onEventgets thepipeline.*eventscreatePipelinesends;ctx.emit(event)forwards one of the node's own,
