Capabilities
Everything the agent loop does beyond “plan → execute → replan → synthesize”:
thinking, token budgets, context compaction, skills, tool consent and
autopilot, large MCP catalogues, prompt caching, subagents and autonomy. The
Node sibling @dudko.dev/agent
implements the same features with the same field and event names.
- Thinking
- Token limits and step caps
- Usage: what a session has spent
- Context management and compaction
- Prompt caching
- Token efficiency
- Skills
- Tool consent and autopilot
- Large tool catalogues (several MCP servers)
- MCP servers behind OAuth
- Subagents (in-process or Web Workers)
- Images, PDFs, files and URLs in
- Virtual file system
- Resuming an interrupted run
- Steering a run that is already going
- Learning: lessons that outlive the task
- Egress: what the model may fetch
- Pipelines: a graph of agents
- Autonomy
- Event reference
Thinking
Section titled “Thinking”createAgent({ model, thinking: 'high', // true | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'none' stageThinking: { executor: 'low', synthesizer: false }, // per stage; wins over `thinking`})// exact budget for providers that take one (Anthropic, Gemini):createAgent({ model, thinking: { level: 'high', budgetTokens: 8_000, includeThoughts: true } })- The level is the AI SDK’s portable
reasoningsetting; each provider maps it to its native API (OpenAI reasoning effort, Anthropic adaptive thinking, Gemini thinking level, xAI, DeepSeek, …). Providers without reasoning ignore it with a warning. budgetTokensbecomesanthropic.thinking.budgetTokensandgoogle.thinkingConfig.thinkingBudget(these win over the level for those providers, by the SDK’s precedence rules).includeThoughts(defaulttrue) asks Gemini for thought summaries and OpenAI for a reasoning summary, so thoughts can be streamed.- WebLLM ignores the portable level, so every setting also carries
web-llm.extra_body.enable_thinking:'none'turns a thinking model (Qwen3) off, any other level leaves it on; models without thinking ignore it. false/ unset sends nothing — the provider default applies (a local Qwen3 thinks by default).- Thoughts stream as
step.reasoning-delta(executor) andfinal.reasoning-delta(synthesizer); thinking tokens are reported inusage.reasoningTokens. - Local reasoning models (Qwen3, R1 distills) that inline
<think>…</think>in their text have those blocks stripped from parsed output and the answer.
resolveThinking(setting) is exported if you call the AI SDK yourself.
Token limits and step caps
Section titled “Token limits and step caps”createAgent({ model, limits: { maxInputTokens: 200_000, // cumulative per run maxOutputTokens: 20_000, // cumulative per run, thinking included maxReasoningTokens: 10_000, maxTotalTokens: 220_000, perCall: { planner: 800, executor: 1200, replanner: 400, synthesizer: 3000, compaction: 1024 }, }, maxIterations: 8, // executed steps per run (incl. after a revise) maxStepsPerTask: 4, // tool-calling rounds inside one step maxRevisions: 2, // replanner "revise" decisions per run maxToolCalls: 30, // tool calls per run maxPlanSteps: 8, // steps in one plan})Run-level caps are soft: they are checked between steps and at every
tool-calling round inside a step, so a run stops at the next boundary after
crossing one, emits budget.exceeded { kind, tokens, cap }, and still writes its
answer (bounded by perCall.synthesizer). RunResult.budgetExceeded tells you
which cap ended the run. checkLimits(usage, limits) is exported.
usage carries inputTokens, outputTokens, totalTokens, plus
reasoningTokens, cachedInputTokens and cacheWriteTokens when the provider
reports them. The legacy budgets option still works; limits.perCall wins.
perCall caps the output of ONE model call per phase. Unless you set them, the defaults are
shares of the context window (compaction.contextWindowTokens, or a local model’s own): at
the default 128k window they are planner 800, executor 1200, replanner 400, synthesizer 3000
(the answer the user reads) and compaction 1024; a 32k window gets 256 / 384 / 192 / 768 / 256, a
4k one the floors (256 / 384 / 192 / 512 / 256) and a very large one more, up to ceilings of
2000 / 8192 / 1500 / 8192 / 4096. resolveBudgets(config, window) returns them. A thinking model
spends part of its cap on thoughts, so raise the cap together with thinking; the executor’s cap
also bounds what it can write into one tool call (a long file body, say).
Usage: what a session has spent
Section titled “Usage: what a session has spent”RunResult.usage is one run’s tokens (inputTokens, outputTokens, totalTokens, and
reasoningTokens / cachedInputTokens / cacheWriteTokens when the provider reports them).
The agent keeps the running total itself:
agent.usage // everything this agent has spent, over all its runs (a snapshot)agent.sessionUsage() // the same for the agent's session (or sessionUsage('other-chat'))agent.resetUsage() // start counting againIt is counted call by call as the usage arrives - so a run that is stopped or fails still counts
what it used, a resumed run adds only what THIS process spent after the checkpoint, a subagent’s
tokens (charged to its parent run) count once, and so do the manual agent.compact() calls.
That includes a model answer that could not be parsed and was retried (the planner’s and the
replanner’s structured attempt, then the prompted fallback): both calls were paid for and both
are counted. (useAgent().totalUsage in the React package is a conversation’s total, kept by the
UI; this is the core’s own counter.)
Context management and compaction
Section titled “Context management and compaction”What each stage sees:
| Stage | System prompt (stable, cached) | User prompt (dynamic) |
|---|---|---|
| Planner | role, skills index, tool catalogue | goal, recent conversation, describeState |
| Executor | role, skills index, active skill instructions | goal, state, earlier steps with their results, current step (+ catalogue in prompted mode) |
| Replanner | role, active skills | goal, state, progress, remaining plan |
| Synthesizer | role, active skills | goal, state, progress, tool findings |
Each executed step contributes its executor summary (the data it found) to every
later step and to the answer, and the synthesizer also gets clipped excerpts of
successful tool results — so a “find X, then do Y with X” run, or a question
answered from an MCP server, works without describeState.
Compaction keeps long sessions and long runs inside the window:
createAgent({ model, memory: new IndexedDBStore(), compaction: { auto: true, // default contextWindowTokens: 128_000, thresholdRatio: 0.85, // default: compact at 85% of the window (0 < ratio <= 1) // thresholdTokens: 100_000, // ...or an absolute number; it wins over the ratio keepRecentTurns: 4, // transcript messages kept verbatim keepRecentSteps: 3, // run steps kept verbatim summaryMaxTokens: 1024, maxToolOutputChars: 20_000, // per tool result, as the MODEL sees it clearToolResultsAfterTokens: 32_000, // default: a quarter of the window; 0 = never keepToolResults: 3, // newest tool results kept verbatim when clearing },})await agent.compact() // manual: summarise the stored transcript now- History — before planning (and after the run) a transcript that no longer fits is
summarised into one message, keeping the last
keepRecentTurns. - Run trace — between steps a step log that no longer fits is folded into a summary,
keeping the last
keepRecentSteps. - Tool results — every tool’s model-facing output is capped at
maxToolOutputChars(via the AI SDKtoModelOutput); events and the trace still get the full result. - Stale tool results inside a step (context editing, like Anthropic’s
clear_tool_usesand Claude Code’s micro-compaction) — once a step’s tool loop grows pastclearToolResultsAfterTokens, the oldest results are replaced with a one-line stub (“… result cleared — call the tool again if you still need it”), keeping the newestkeepToolResults. The calls stay, so the model knows what it did. Clearing is sticky, so the cached prefix doesn’t flip back.
What “fits” means. The threshold is a share of the window (85% by default) and it is
judged on the whole context of the next call: the fixed prompt (stage instructions, tool
definitions, the skills index and active skills, your systemPrompt) plus the transcript
plus the run’s step log. Judging each part alone would let a long transcript and a long log
each stay under the line while together overflowing the window. The rest is room for the answer
and for what one step adds before the next check. The fixed prompt is estimated (about 1 500
tokens, your systemPrompt, the tool definitions, the skills; under tool search only a few
definitions are sent, so the tools count at most 3 000).
The estimate counts by kind of character, because text is not one thing: letters ~2.5 to a
token, digits and punctuation about one each, a space a quarter, a newline one, other scripts
(Russian) two characters, CJK and emoji one. It was calibrated against Claude’s tokenizer over
prose, markdown, code, JSON, a table, Russian and a mix, and comes out 1.1-1.4x the real count
and never below it (a flat “4 characters a token” was 0.4-0.7x for everything but Russian: JSON
and code run 1.6-2.4 characters a token, and tool definitions 2x what 4 would give). It leans high
on purpose: compacting a little early is cheap, overflowing the window is a failed run. So at the
default 85%, a Claude model has roughly 70-75% of its window really used when compaction starts;
a tokenizer that packs tighter (OpenAI, Gemini) starts a little earlier still. Raise
thresholdRatio (0.9, 0.95) to compact later. estimateTokens is exported. For a local model the
window is its own and the threshold follows it (never past 95% of it).
What the summariser is shown is the newest part of what is being folded that fits 60% of the window (it used to be the last 48 000 characters, whatever the window).
Each compaction emits context.compacted { scope, beforeTokens, afterTokens }
(scope: 'history' | 'trace' | 'tool-results') and, when a model summarised,
a usage event with phase 'compact'. Without compaction (and without a
local model, see below), the legacy compressAfterChars post-run compression
applies as before.
The model’s window is a hard limit
Section titled “The model’s window is a hard limit”A prompt that doesn’t fit is refused outright, so everything above is sized from the window, and the window must be the model’s real one:
-
Local WebLLM models report their own window. WebLLM loads its prebuilt models with 4096 tokens (to save VRAM; “-1k” builds with 1024), whatever the model was trained on. The agent reads it from the loaded engine (or the app config it was built with) and never assumes more — even when
contextWindowTokenssays more; it compacts by tokens even without acompactionconfig.agent.contextWindowTokensis the window in use. -
Raising it: Qwen3 and Llama 3.x take far more than 4096. A larger window costs KV-cache memory, not a new download:
createWebLLMModel('Qwen3.5-2B-q4f16_1-MLC', { contextWindowTokens: 32_768 })// under a bundler, with your own factory:import { prebuiltAppConfig } from '@mlc-ai/web-llm'webLLM(id, { engineConfig: { appConfig: withWebLLMContextWindow(prebuiltAppConfig, id, 32_768) } })(
@browser-ai/web-llmignores its top-levelappConfigsetting — it has to go inengineConfig.) -
Sizes follow the window: with a small window the threshold (½), the tool-result clearing point (¼), the cap on one tool result (a quarter of the window) and the verbatim results kept (1 below 16k) shrink with it — also when the host set them for a larger window.
-
Tools:
'auto'tool selection switches to search not only abovetoolSearchThresholdtools but also once the tool definitions would take a quarter of the window — a few MCP tools with rich schemas can fill a 4k window on their own. -
Overflow: when a provider still refuses a prompt for its length (WebLLM, OpenAI
context_length_exceeded, Claude “prompt is too long”, Gemini, llama.cpp), the run reports aContextWindowExceededError— “The conversation no longer fits the context window of … (4124 tokens; the window is 4096). Start a new chat or compact this one, connect fewer tools, or switch to a model with a larger window.” — instead of the provider’s text.
Helpers: webLLMContextWindow(model), withWebLLMContextWindow(appConfig, id, tokens), fitCompactionToWindow, toolDefinitionTokens(tools),
contextOverflowOf(err, model).
Prompt caching
Section titled “Prompt caching”promptCaching is on by default:
- every stage’s system prompt holds only run-stable content, the dynamic parts go to the user prompt — OpenAI’s and Gemini’s automatic prefix caches hit;
- the system message carries an Anthropic
cacheControlbreakpoint (promptCaching: { ttl: '1h' }for the longer TTL); - OpenAI calls get a
promptCacheKey(<clientName>:<stage>, or yourkey); - inside a step’s tool loop, a second breakpoint rolls to the newest message every round, so each round reads all earlier rounds from the cache and writes only the new tail (older message breakpoints are removed — a request carries at most two, Anthropic allows four);
- tools keep declaration order (hosts merge their tool sets in a fixed
order,
useMcpServersin list order), so the tool list — the head of every cached prefix — is identical from run to run, without reordering what a server declared: small models were measured to depend on that order.
Cache reads/writes show up as usage.cachedInputTokens / cacheWriteTokens.
promptCaching: false sends plain system strings.
Token efficiency
Section titled “Token efficiency”The agent follows the practices coding agents (Claude Code, the Claude and GitHub Copilot extensions) use to keep a long session cheap:
| Practice | How the agent does it | Knob |
|---|---|---|
| Stable, cacheable prefix | system prompts hold only run-stable content; deterministic tool order; dynamic state goes last | promptCaching |
| Cache the growing loop | rolling Anthropic breakpoint on the newest message; OpenAI promptCacheKey per stage |
promptCaching: { ttl } |
| Don’t send every tool | above toolSearchThreshold the model gets a compact catalogue and find_tools (deferred tools) |
toolSelectionStrategy, toolSearchThreshold |
| Load instructions on demand | skills: only name + description in the prompt, the body on activation | skills |
| Cap tool output | per result, as the model sees it (events keep the full value) | compaction.maxToolOutputChars |
| Clear stale tool results | oldest results in a long loop become stubs | compaction.clearToolResultsAfterTokens |
| Auto-compact | history and run trace summarised past a threshold; agent.compact() on demand |
compaction |
| Isolate side quests | subagents run in their own context; only their answer returns | createSubagentTool |
| Pass results, not transcripts | later steps and the answer get step summaries + clipped findings, not raw loops | — |
| Bound everything | token caps per run / per kind, tool-call and plan-step caps | limits, maxToolCalls, maxPlanSteps |
| Think only where it pays | thinking per stage (e.g. on for the planner, off for the synthesizer) | stageThinking |
| Cheaper model for summaries | compaction and the answer use the synthesizer stage model |
synthesizer |
| Small images | the React composer downsizes images before sending (≈1.15 MP), the size providers bill for | <AgentComposer imageMaxDimension> |
The usage events break every call down by kind (input / output / thinking /
cache read / cache write) and by phase, so the effect is measurable:
cachedInputTokens / inputTokens is the cache hit rate.
Skills
Section titled “Skills”Skills are reusable instruction bundles in the agentskills.io
shape (a SKILL.md with name / description frontmatter, a markdown body,
optional bundled files).
import { createAgent, defineSkill, parseSkillMarkdown, loadSkillFromUrl } from '@dudko.dev/agent-web'
const skills = [ defineSkill({ name: 'release-notes', description: 'Write release notes', content: '…' }), parseSkillMarkdown(markdownText, [{ path: 'template.md', content: '…' }]), await loadSkillFromUrl('/skills/triage/SKILL.md', { files: ['labels.md'] }),]createAgent({ model, skills })Progressive disclosure:
- Only the index (
- name: description) sits in the planner/executor system prompts. - The planner lists the skills that apply (
plan.skills); their full instructions enter the executor, replanner and synthesizer prompts. - The executor can pull one in later with the built-in
load_skilltool and read bundled files withread_skill_file(both read-only, never gated).
skill.activated { name, by: 'plan' | 'tool' } is emitted; RunResult.skills
lists the skills used; agent.skills lists the configured ones (and, with
learning, the agent’s own, marked learned).
Tool consent and autopilot
Section titled “Tool consent and autopilot”const agent = await createAgent({ model, tools, toolApproval: { mode: 'ask-writes', // 'autopilot' (default) | 'ask-writes' | 'ask-all' | 'read-only' rules: { 'github__delete_*': 'deny', 'docs__*': 'allow' }, // exact names or * globs onRequest: async (req) => ({ approved: await confirm(`Run ${req.toolName}?`), remember: false }), timeoutMs: 120_000, // no answer → deny },})agent.setToolApprovalMode('autopilot') // the "autopilot" switch, live — even mid-run| Mode | Read-only tools | Other tools |
|---|---|---|
autopilot |
run | run |
ask-writes |
run | ask |
ask-all |
ask | ask |
read-only |
run | refused (no prompt) |
Decision order per call: a tool the user chose to always allow
(remember: true) → the most specific rules entry (an exact name, else the
longest glob — rules apply even under autopilot) → the mode. A tool is
read-only when its MCP server says so (annotations.readOnlyHint) or you marked
it: defineTool({ readOnly: true, … }) / markReadOnly(tool). Unknown counts as
“may write”.
A denied call fails with ToolDeniedError (“…do not retry it…”), so the model
sees the refusal and the replanner can route around it. Events:
tool.approval-requested { id, name, input, readOnly } (only when someone is
asked) and tool.approval-resolved { id, name, approved, reason, automatic }.
The gate runs inside each tool’s execute, so it covers native and prompted
tool-calling, MCP tools and host tools called by subagents alike.
Large tool catalogues (several MCP servers)
Section titled “Large tool catalogues (several MCP servers)”Several MCP servers easily add up to hundreds of tools. Sending every schema on every call wastes the window — and OpenAI rejects more than 128 tools.
Loading (@dudko.dev/agent-web/mcp):
- servers connect concurrently; one failing server is reported in
resultsand the others still mount; tools/listis paginated — everynextCursorpage is followed;- each server has a deadline (
connectTimeoutMs, default 30 s, per server or perconnectMcpHttpcall) — a hanging server can’t block the rest; - names are
server__tool, sanitised to[a-zA-Z0-9_-]and capped at 64 chars; collisions get a_2suffix; annotations.readOnlyHintmarks tools read-only for the consent gate;notifications/tools/list_changed→onToolsChanged(server)→refreshServer.
Selection — toolSelectionStrategy (default 'auto'):
| Strategy | Executor sees | Planner sees |
|---|---|---|
all |
every tool | full catalogue |
plan-narrowed |
the step’s suggestedTools |
full catalogue |
search |
built-ins + the step’s suggested tools + tools discovered earlier, plus find_tools |
condensed catalogue grouped by server |
auto |
all up to toolSearchThreshold (40) tools, search above |
— |
find_tools({ query, server?, limit? }) ranks the catalogue by keywords (name
server > description, prefix matching, no model call) and activates the hits for the rest of the run (
tools.discoveredevent). In prompted mode the newly available tools — with parameter hints derived from their JSON schemas — are listed in the next round’s prompt.searchTools(catalog, query)is exported.
MCP servers behind OAuth
Section titled “MCP servers behind OAuth”The ./mcp subpath connects remote MCP servers; the README has the flow
(BrowserOAuthProvider, readOAuthCallback, finishMcpOAuth). What the
provider takes and does:
new BrowserOAuthProvider({ serverUrl, redirectUrl, clientName: 'my-app', scope: 'mcp:tools', clientMetadata: { software_id: '…' }, // merged over the registration defaults clientMetadataUrl: 'https://my-app.example/oauth/client.json', // CIMD, optional storage, // default: the encrypted vault})- Which client ID is used: a registration already in storage, else
clientMetadataUrlwhen the authorization server advertisesclient_id_metadata_document_supported, else dynamic registration (RFC 7591).clientMetadataUrlmust be https with a non-root path, and the document it serves must list the sameredirect_uris. - Registration defaults: a public client (
token_endpoint_auth_method: 'none', PKCE),authorization_code+refresh_token,application_typeby the redirect URL ('web'for an https page,'native'for a loopback one). - Stored per server URL: tokens, the client, the PKCE verifier, the
state, and the discovery state (the authorization server and its metadata), which later calls reuse instead of discovering again.reset()andinvalidateCredentials('all')drop all of it;'discovery','tokens','client'and'verifier'drop one. - On the way back
finishMcpOAuthchecksstate, then theissparameter (RFC 9207,checkAuthorizationResponseIssuer), then exchanges the code. See security.md.
The Node package has the same options and functions (createNodeOAuthProvider).
Subagents (in-process or Web Workers)
Section titled “Subagents (in-process or Web Workers)”A subagent is a tool: the parent delegates { task }, the child runs its own
loop and its answer is the tool result. Several delegations in one model step
run in parallel (maxConcurrent, default 4).
import { createSubagentTool } from '@dudko.dev/agent-web'
// In-process (shares the page's thread and models, e.g. a loaded WebLLM engine):const researcher = createSubagentTool({ name: 'researcher', description: 'Research a question with the docs tools and report the facts.', config: { model, tools: docsTools, maxIterations: 4 },})
// Isolated in a Web Worker:const analyst = createSubagentTool({ name: 'analyst', description: 'Analyse a chess position deeply.', worker: () => new Worker(new URL('./analyst.worker.ts', import.meta.url), { type: 'module' }), workerConfig: { model: { providerType: 'google', model: 'gemini-3.5-flash', credentialRef: 'google' } }, credentials, // resolves the key in the main thread, per task tools: { get_board }, // host tools, called back over RPC timeoutMs: 60_000,})createAgent({ model, tools: { researcher, analyst } })import { serveSubagentWorker, defineTool } from '@dudko.dev/agent-web'import { createGoogleGenerativeAI } from '@ai-sdk/google'
serveSubagentWorker({ // Bundlers can't resolve the core's dynamic provider imports in a worker — // import the factory statically and build the model here. resolveModel: (spec) => createGoogleGenerativeAI({ apiKey: spec.apiKey })(spec.model), tools: { deep_search: defineTool({ /* CPU-heavy, runs off the main thread */ }) },})- Worker-local tools run in the worker — heavy computation never blocks the UI.
- Host tools (
tools) stay in the main thread and are proxied overpostMessage; every such call passes the parent’s consent gate. - The parent’s abort signal and
timeoutMsstop the child; a worker is terminated after each task. - Events:
subagent.start,subagent.event(the child’s events, verbatim),subagent.complete { text, usage },subagent.error. Child tokens are charged to the parent (usagewith phase'subagent'), so the parent’s limits apply. - The protocol is plain structured-clone messages over any
MessageEndpoint(aWorker, a worker’sself, aMessagePort).
Profiles: other models, params and context per call
Section titled “Profiles: other models, params and context per call”A subagent normally has one fixed configuration. profiles lets the parent
model choose between named variants of it, per call:
const researcher = createSubagentTool({ name: 'researcher', description: 'Research a question with the docs tools and report the facts.', config: { model: fastModel, tools: docsTools, maxIterations: 3 }, // the default: cheap and quick profiles: { deep: { description: 'A hard question that needs a thorough, multi-source answer.', config: { model: strongModel, thinking: 'high', maxIterations: 8 }, }, skeptic: { description: 'Check a claim someone else made; look for what contradicts it.', config: { systemPrompt: 'Assume the claim is wrong until the sources show otherwise.' }, }, },})- The tool gains an optional
profileargument, an enum of the names; leaving it out runs the base config. Each profile’sdescriptionis appended to the tool’s description, so the parent chooses by when to use it — write them that way. - A profile’s fields are laid over the base config, field by field and
shallow: a profile’s
limitsreplaces the base’slimits, it is not merged into it. Anything inBrowserAgentConfigcan differ — the model (even another provider),thinking, limits,systemPrompt,skills,tools. - For a Web Worker subagent the override is
workerConfig(its model is a serializableProviderModelSpec, and acredentialRefis resolved to a key in the main thread for that profile’s model). Settingconfigon a worker profile, orworkerConfigon an in-process one, is refused when the tool is created. - The choice is bounded by what you listed: the parent cannot pick an arbitrary model, so cost stays in the host’s hands. An unknown name is a tool error the model can correct, raised before any child starts or is announced.
subagent.startcarriesprofilewhen one was chosen. Child tokens are charged to the parent as always, whichever profile ran.- The child’s context is still just
task. A different context means a profile that changessystemPrompt,skillsortools— the parent cannot hand a child more of its own conversation.
Images, PDFs, files and URLs in — and models that can’t take them
Section titled “Images, PDFs, files and URLs in — and models that can’t take them”await agent.run('What is wrong on this screenshot, and does the spec agree?', { images: [{ data: 'data:image/png;base64,…', name: 'screen.png' }], files: [ { data: pdfBytes, mediaType: 'application/pdf', name: 'spec.pdf' }, { data: 'https://example.com/diagram.png' }, // a link: sent as a URL ],})Attachments reach the planner, the executor (every step) and the synthesizer as
file parts of the user message (toFilePart). Data can be bytes, base64, a
data URL, or an http(s) URL — providers that accept links (Gemini, Claude,
OpenAI) fetch it themselves; for the rest the AI SDK downloads it (from a
browser: subject to CORS). The kind comes from the media type
(attachmentKind): image, pdf, or file.
What the model takes is agent.capabilities — { images, pdf, files }, each
true / false / undefined:
| images | other files | ||
|---|---|---|---|
| Gemini, Claude, OpenAI GPT-4o/4.1/5 | ✓ | ✓ | tried |
| xAI Grok | ✓ | tried | tried |
DeepSeek, gpt-3.5, o1-mini… |
✗ | ✗ | tried |
Local vision models (WebLLM Phi-3.5-vision…; ids naming vision / VL / LLaVA / SmolVLM / Gemma 3n) |
✓ | ✗ | ✗ |
| Other local models (WebLLM, built-in AI) | ✗ | ✗ | ✗ |
| OpenAI-compatible servers | tried | tried | tried |
Override with vision (images) or inputs: { images, pdf, files }.
- Known ✗ — the run ends immediately, no tokens spent, with an
errorevent (phaserun) andRunResult.finalset to a message the user can act on: The model “…” can’t take PDF files. Convert the PDF to text first (e.g. PDF → Markdown), or switch to a model that reads PDFs such as Gemini, Claude or GPT-4o/GPT-5. (AttachmentsNotSupportedError;ImagesNotSupportedErrorfor images.) - Tried — a provider refusal is turned into the same message (“the provider said: …”) instead of a raw API error.
A UI should check agent.capabilities before accepting a paste or an upload
(@dudko.dev/agent-web-react’s composer does, and can convert a PDF to
Markdown first). Memory stores a text note of the attachments (“[attached:
screen.png, spec.pdf]”), never their bytes.
Virtual file system
Section titled “Virtual file system”import { VirtualFileSystem, createFileTools } from '@dudko.dev/agent-web'
const vfs = new VirtualFileSystem() // IndexedDB; { memory: true } for tests / private modeawait vfs.write('/notes/todo.md', '- ship it')await vfs.writeDataUrl('/img/screen.png', dataUrl)createAgent({ model, tools: { ...tools, ...createFileTools(vfs) } }) // fs_list, fs_read, fs_write, fs_deleteA browser workspace shared by the user and the agent: attachments land there,
the agent reads them and writes reports back. Paths are absolute and POSIX-like
(.. cannot escape the root); text is stored as UTF-8, binary as base64 with a
MIME type; list(prefix), read, readDataUrl, delete, clear, and
onChange(listener) for live UIs. namespace isolates several file systems
in one database; maxFileBytes (10 MB) caps a file. fs_list / fs_read are
read-only (no consent prompt in ask-writes); fs_write / fs_delete are
not; createFileTools(vfs, { readOnly: true }) mounts only the readers. The
files live in the shared IndexedDB database (files store, schema v2 — an
existing v1 database is upgraded in place).
Resuming an interrupted run
Section titled “Resuming an interrupted run”A reload, a crashed tab or a killed worker normally loses a run — including the steps
that already ran. persistence checkpoints it:
import { createAgent, IndexedDBRunStore } from '@dudko.dev/agent-web'
const runs = new IndexedDBRunStore()const agent = await createAgent({ model, tools, persistence: runs, sessionId: chatId })const result = await agent.run('Triage the new tickets') // result.runId names the run
// After a reload:const unfinished = await runs.latestResumable(chatId)if (unfinished) await agent.run('', { resumeFromRunId: unfinished.runId })- A checkpoint is written when the plan is in hand and at the end of every
iteration. Resuming picks up at that boundary: the planner does not run again, a
finished step is not repeated, and the saved goal, plan, trace, step log, findings,
skills, discovered tools and counters all carry over. So
maxIterations,maxRevisionsandmaxToolCallsare per run, not per page load, and token usage keeps adding up. The goal you pass torun()when resuming is ignored — the saved one is the run’s. run.startcarries therunIdand, on a resume, how far the run had got (resumed: { completedSteps, remainingSteps });plan.createdthen shows the plan as it stands — finished steps first, then what is left.- A stopped run (
cancelled) and a failed one can be resumed; acompleteone cannot.IndexedDBRunStoredrops a completed run’s snapshot (keepCompleted: truekeeps it as an audit trail);MemoryRunStoredoes the same but does not survive a reload. - The hooks are
onRunStart,onStepComplete,onRunCompleteandloadRun— the names the Node package uses — so a store of your own is four methods. A hook that throws is logged and the run carries on: persistence is observability, not a correctness boundary. The snapshot’s field names follow this package’srun(goal)(goal, not Node’sinput). - The database gains a
runsobject store (schema v3); an existing database upgrades in place and keeps its data.
What a resume does not give you:
- A step in flight when the page died runs again from its start. For a read that is
free; for a write it may apply twice, so give tools with side effects idempotency — or
keep the consent gate on: a resumed run goes through
toolApprovallike any other. - Attachments are not stored. Pass
images/filestorun()again if the run needs them; the snapshot only records how many there were. - A snapshot holds the whole trace, tool outputs included, and is rewritten at each
checkpoint. For tools that return megabytes, trim in your store’s
onStepComplete. - Nothing resumes by itself: your app decides when to look for an unfinished run and whether to offer it.
Steering a run that is already going
Section titled “Steering a run that is already going”run() takes one goal and returns when the run is over. To say something in the
meantime — “use the staging database”, “skip the report” — or to stop one subagent out
of several, make a RunControl and pass it to the run:
import { createAgent, createRunControl } from '@dudko.dev/agent-web'
const control = createRunControl()const running = agent.run('Triage the new tickets', { control, onEvent })
control.send('Ignore anything older than a week') // any time while it runscontrol.subagents() // [{ id, name, task, profile?, startedAt }] — who is running nowcontrol.stopSubagent(id) // stops that one; the run goes onconst result = await runningresult.undelivered // messages the run never got to show the model — send them as the next runA message is not an interrupt. The run never cuts a tool call short (it may be a write); the message waits for the next boundary and is then shown to the model:
| It arrives… | It is shown… | message.delivered at |
|---|---|---|
| during a step, while tools are being called | to the executor on its next round of that step, as a user turn after the tool results | round |
| between steps | to the replanner, and to every later step | step |
| after the last step, before the answer is written | to the synthesizer | final |
| while the answer is being written, or after the run ended | to nobody — it comes back in result.undelivered |
— |
- A message always makes the replanner look at the plan again, at the end of the step
it was delivered in: a plan made before the user spoke may no longer be the right one.
That call (
replan.decisionwithbyUser: true) ignoresreplan: falseandmaxRevisions, and a revise it makes is not counted againstmaxRevisions; it costs one extra model call per boundary, not per message, and there is no cap on messages. It does need a step left to plan: atmaxIterationsthe message still reaches the synthesizer. A replanner that saysfinishends the run early — that is how “stop, that is enough” works. - Every later stage of the run sees what the user said (a
MESSAGES FROM THE USERblock), so a correction is not forgotten two steps later. It is also appended to the session transcript, in order, and saved in a run checkpoint — a resumed run still knows it. - A message arriving before the run starts is queued and announced (
message.queued) right afterrun.start.send()returnsfalsefor an empty text and once the run is over; it never throws. - Prompted mode (small local models) gets the message in the same turn as the tool results, before the “continue this step” contract; native mode adds it as a user turn after the tool results, which is the order Anthropic, OpenAI and Gemini all accept.
- Use one control per run. A hand-made object in its place is refused: only the ones
createRunControl()makes are read.
Stopping a subagent. stopSubagent(id) aborts that child (and its worker, if it has
one). Its delegation fails with a message the parent model can route around (“stopped by
the user … carry on without its result”), subagent.error carries stopped: true, and
sibling subagents and the run are untouched. Only a child that has started is listed; one
still waiting for a maxConcurrent slot is not. A child’s own subagents are not
individually stoppable — stopping the child stops them with it. The log of what each
child does is the subagent.event stream, the same events the parent emits.
Learning: lessons that outlive the task
Section titled “Learning: lessons that outlive the task”Switch on learning and the agent keeps a notebook. When it hits a problem and finds the way
around it — a tool error it resolved, a wrong assumption it corrected, a procedure it had to look
up — it writes the lesson down with save_skill, and the lesson is a skill: it
shows up in the planner’s SKILLS: index right away (even for the next step of the same run) and
loads with load_skill like any other. Nothing new to learn on the reading side.
import { createAgent, VfsSkillStore, VirtualFileSystem } from '@dudko.dev/agent-web'
createAgent({ model, learning: true }) // this session (the agent's lifetime)
// ...or keep them as /skills/<name>/SKILL.md in the agent's file system (IndexedDB), where the// user can see and edit them in the files panel like any file:const vfs = new VirtualFileSystem()createAgent({ model, learning: { store: new VfsSkillStore(vfs) } })
agent.skills // [{ name, description, learned? }] - liveagent.listLearnedSkills() // the agent's own, with origin: when, which run, revision, where it readawait agent.forgetSkill('image-format-jpg') // one went staleIt is a knowledge feature and nothing else:
- Knowledge, never policy. A lesson is loaded under a header saying it is the agent’s own
hint, not an instruction from the user; the user’s request and your rules win a conflict. It
cannot grant a permission, switch a tool on or loosen
egress. - A normal gated tool.
save_skill/forget_skillgo through tool consent like any write —ask-writesasks the user first,read-onlyrefuses, arulesentry can deny. - No secrets. Names, descriptions, instructions and sources are scanned for API keys, tokens, private keys and the like; a hit is refused to the model (and never stored). Sources keep origin and path only.
- Yours stay yours. A skill you configured is never overwritten or deleted by the agent; on a
name clash yours wins. Caps:
maxSkills(50),maxSkillChars(6000), a one-line description. - Provenance. Each lesson records when it was written, by which run, its revision and — recorded
by the harness, not by the model — the pages
web_fetchread in that run. - Quiet by default for the rest. Without
learningthere are no extra tools and not a word more in the prompts.learning: { nudge: false }keeps the tools but drops the guidance that tells the executor to write lessons down (and to look for a fix before giving up — withegresson,web_fetchcan read the docs). The notebook’s tools stay callable underplan-narrowedandsearchtool selection. - Bring your own store.
storeis any{ list, save, remove }(sync or async) — a database, a server. A tool of your own namedsave_skillreplaces the built-in one.
Every save emits skill.learned (name, description, update, chars, sources); a forget
by the model emits skill.forgotten (forgetSkill(name, onEvent) passes it to you).
Egress: what the model may fetch
Section titled “Egress: what the model may fetch”Off by default: with no egress in the config the agent has no way to make a request of its
own (the provider’s API, your MCP servers and the tools you pass are your configuration, not
the model’s). Set it and the model gets one tool, web_fetch({ url, maxChars? }) — a GET that
returns the page as readable text (HTML reduced, JSON and text as they are), flagged
untrusted: true: facts to use, never instructions.
createAgent({ model, egress: { allow: ['docs.example.com', '*.github.com'] }, // or `true` for any public host over https})The policy has the same shape and names as the server’s createSafeFetch
(@dudko.dev/agent): allow / deny (hosts, *.subdomains, IPs, CIDRs — deny wins, allow is
exclusive), allowPrivateNetwork, protocols (default https), ports (default 443), methods
(default GET), maxResponseBytes (2 MB), timeoutMs (15 s). What a page can enforce, it
does before a request is made: scheme, port, method, credentials in the URL, the host lists,
IP literals (loopback, private, link-local, metadata — also in IPv6, mapped or tunnelled, and the
URL parser’s 2130706433 / 0x7f.1 / 127.1 tricks) and names that are internal by shape
(localhost, *.local, *.internal, a bare intranet). Nothing of the user’s rides along (no
cookies, no credentials, no referrer), and the answer is bounded in size and time.
What a page cannot do, and a server can:
- Pin DNS. A public-looking name that resolves to a private address cannot be seen from a
browser. CORS is the backstop (most servers will not answer a cross-origin read at all), as are
the browser’s Private Network Access rules — but prefer an
allowlist, or giveegress.fetcha gateway that runs the server-side safe fetch and so gets the full protection. - See where a redirect goes. So a redirect fails the request by default (
bad-redirect);followRedirects: truefollows it and judges only the final URL — after the request was made, withholding what it returned.
Approval: an open-internet web_fetch is a way to leak data through the URL, so it asks like a
write; with an allow list it is read-only. Each request emits egress.request
(url is origin and path only — no query string —, allowed, status or reason).
Pipelines: a graph of agents
Section titled “Pipelines: a graph of agents”A pipeline is a graph of agents: each node is an agent with its own role, model and tools, each edge passes one node’s output to the next, optionally on a condition, and loops are allowed. The whole graph is 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: smartModel, fast: fastModel }, // a LanguageModel or a ProviderModelSpec each tools: { files: createFileTools(vfs) }, // named groups of tools // skills: { tone: skill }, mcpServers: { docs: mcp } (a connectMcpHttp result), // configure: (config, node) => config // the place to read node.settings }),})
const result = await pipeline.run({ input: 'A release note for v2', signal, onEvent })The definition is data: { version: 1, name?, entry, nodes, edges, limits? }.
| Field | Meaning |
|---|---|
entry |
The id of the node that receives the request. |
nodes[].id, name? |
The id is unique; the name is what other nodes and a UI see. |
nodes[].instructions? |
The node’s role, added to its agent’s system prompt. |
nodes[].model?, skills?, tools?, mcpServers? |
Names the host resolves - never a model object, never a key. |
nodes[].routes? |
{ label, description? }[]: after it answers, the node picks one. |
nodes[].join? |
'all' (default) or 'any', see below. |
nodes[].settings? |
Handed to the host’s resolver untouched; never applied by itself. |
nodes[].position? |
{ x, y } for an editor; the runner ignores it. |
edges[] |
{ id?, from, to, when? }. Ids are unique; an edge without one is given e<its position> (e0, e1, …). pipeline.definition and normalizePipeline(definition) return the definition with every id filled in. |
limits? |
maxNodeVisits (per node, default 3, 1-100), maxRuns (all nodes, default 25, 1-1000). |
Conditions (edge.when; absent = always):
kind |
Fires when |
|---|---|
always |
Always. |
contains |
The output contains text - a plain substring, case-insensitive unless caseSensitive: true. |
matches |
pattern (with flags from imsu) occurs in the output. |
route |
The node picked the route label. |
otherwise |
No other edge of the same node fired. At most one per node. |
contains and matches look at the first 50,000 characters of an output. A pattern is at most 500
characters and is not run by RegExp: it is compiled to a matcher that cannot backtrack, so
(a+)+$ costs the same as any other pattern (time grows with input length x pattern size, both
capped). The price is a subset of the syntax: literals, classes, ., ^ $ \b \B, groups,
alternation, * + ? {n,m}; no backreferences, no lookaround, no \p{...} - those are refused at
validation. It answers the same as RegExp.test on what it accepts.
How it runs
- Waves. Wave 0 is the entry node. All nodes of a wave run concurrently. When a node finishes,
its outgoing edges are evaluated against its output: every edge whose condition holds fires;
otherwisefires only if none of the node’s other edges did. A fired edge activates its target for a later wave and carries the source’s output to it. - Join. A node activated by several edges gets all their outputs in one visit. With
join: 'all'an activated node is deferred while any other activated node can still reach it through the graph (conditions aside) - so a fan-in waits for its slower branch even when the branches have different lengths. If every activated node is deferred (they wait for each other in a cycle), all of them run.join: 'any'never defers: the node runs once per wave it is activated in. - Loops are allowed. When starting a node would exceed
maxNodeVisitsfor it, ormaxRunsfor the pipeline, that activation is dropped (pipeline.node.skipped); the run goes on with what is left, ends normally, and the result carriesstoppedBy: 'maxNodeVisits'or'maxRuns'(maxRunswins when both happened). - A fan-in inside a loop has a limit: when a
join: 'all'node and a slower branch that leads to it can also reach each other through the loop, they wait for each other, so both run and the join fires without that branch. Usejoin: 'any'there, or keep the fan-in out of the cycle (a loop around the whole fan-out and fan-in works). - The end. The run ends when nothing is activated. A terminal visit is one that activated
nothing (no edge fired, or a cap dropped what it fired).
result.textis the output of the last terminal node to finish; several of the same wave are joined under## <name>headings. - A node that throws fails the pipeline:
runrejects with aPipelineNodeError(nodeId,visit,cause), the other running nodes are aborted through their signal, and the last event ispipeline.node.failed(nopipeline.finished). - Routes. For a node with
routes, the adapter asks the node’s planner model to pick one label with a small structured-output call after the node answered. An answer that is not one of the labels - or a call that fails - is no route: onlyalways, the text conditions andotherwisecan fire. Its tokens are part of the node’susage. - A node’s input is the original request, then each activating node’s output under its name.
One agent is created per node on its first visit and kept (with whatever memory its config gives
it) until
pipeline.close(). - What a node remembers. Without
memoryin its config: nothing - every visit starts from its input. WithmemoryinnodeResolver’sbase, each node gets a session of its own,<base sessionId>:<node id>(default:<node id>when the base has none): a writer sees its earlier drafts on its second visit, and no node reads another node’s conversation. AsessionIdset inconfigureis kept as it is; aresolveNodeof your own decides for itself.
The result: { text, outputs, trace, usage, stoppedBy?, runs } - outputs[nodeId] is
{ visit, text, route? }[], trace lists node runs, edge decisions and dropped activations in
order, usage is the sum over all nodes.
Events (through run({ onEvent })):
| Event | Payload |
|---|---|
pipeline.started |
pipeline? - the definition’s name |
pipeline.node.started |
nodeId, visit, from - the ids of the nodes whose outputs it got |
pipeline.node.finished |
nodeId, visit, text, route?, usage? |
pipeline.node.failed |
nodeId, visit, error (a string) |
pipeline.node.skipped |
nodeId, from, reason: 'maxRuns' | 'maxNodeVisits' - an edge fired towards the node, a cap refused the visit |
pipeline.edge |
from, to, edgeId, visit, fired - one per outgoing edge, right after the source finished; visit is the visit of the source node |
pipeline.finished |
stoppedBy?: 'maxRuns' | 'maxNodeVisits' | 'aborted', runs |
Every event of a node’s own agent is forwarded unchanged, plus nodeId and visit.
validatePipeline(definition) returns { ok, errors, warnings } without running anything (each
issue has a code, a message and the nodeId / edgeId / edgeIndex it is about) - errors for
a wrong version, empty or duplicate ids, a missing entry, an edge to or from an unknown node, a
duplicate edge id, a route edge whose label the source node does not have, a second otherwise, a bad pattern or
flag, limits out of range; warnings for unreachable nodes, routes no edge uses, and a loop (allowed:
the caps bound it). createPipeline throws a PipelineValidationError on errors.
options.runNode(node, input, ctx) replaces the agent altogether - the pipeline then only
schedules - which is also how to test a graph without a model.
signal aborts every running node; run then 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.) An agent run that ends on a run-level error event is a
failed node. A route is picked with generateStructured; a model that cannot do structured output
is asked again in plain text.
Autonomy
Section titled “Autonomy”The default prompts make the agent act on its own:
- the planner plans tool use for anything the tools can do or look up — questions that need data are real goals; an empty plan is reserved for pure greetings / small talk / questions answerable without tools;
- no stage ever asks the user for confirmation or plans an “ask the user” step; ambiguity is resolved by the most reasonable interpretation, stated as an assumption;
- the executor uses
[BLOCKER]only when a step is truly impossible (a tool is missing or denied, credentials or data are unavailable); - the replanner prefers routing around a failure over giving up;
- permission is the host’s
toolApprovalpolicy — never a question in text.
Soften it per app with systemPrompt, or replace any phase via prompts.
Event reference
Section titled “Event reference”Everything the agent does is a typed AgentEvent (the union is in src/events.ts).
Subscribe with onEvent (per run) or the handler you pass to createAgent; render them however you like.
The loop
| Event | Payload |
|---|---|
run.start |
goal, runId?, resumed?: { completedSteps, remainingSteps } — runId names the run for persistence |
model.load |
progress, text — a local WebLLM model’s weights downloading. In the union for hosts that forward WebLLM’s initProgressCallback; the agent does not emit it by itself yet |
plan.thought-delta |
delta — the planner’s thought, streamed |
plan.step-added |
step, index — a step is coherent enough to show; the plan can still change |
plan.created |
plan — the canonical plan |
plan.revised |
plan, reason — the replanner replaced the remaining steps |
step.start |
step, index, total |
step.text-delta |
step, delta |
step.reasoning-delta / final.reasoning-delta |
step, delta / delta — the executor’s / synthesizer’s thoughts (thinking) |
step.tool-call / step.tool-result |
step, name, input / step, name, output, ok |
step.complete |
step, result |
replan.decision |
mode: 'continue' | 'revise' | 'finish', reason, byUser? — byUser when the replanner ran because the user sent a message |
final.text-delta |
delta — the answer, streamed |
final |
text — the answer, whole |
retry |
phase: 'plan' | 'execute' | 'replan' | 'synthesize', attempt, error |
stopped |
— the run was stopped with stop() / an AbortSignal |
error |
phase: 'plan' | 'execute' | 'replan' | 'synthesize' | 'run', error |
Budgets, context and cost
| Event | Payload |
|---|---|
usage |
phase: 'plan' | 'execute' | 'replan' | 'synthesize' | 'compact' | 'subagent', usage — per LLM call; counted live into agent.usage |
budget.exceeded |
kind: 'input' | 'output' | 'reasoning' | 'total' | 'tool-calls', tokens, cap |
context.compacted |
scope: 'history' | 'trace' | 'tool-results', beforeTokens, afterTokens |
Tools, skills and consent
| Event | Payload |
|---|---|
skill.activated |
name, by: 'plan' | 'tool' |
tools.discovered |
step?, query, names — find_tools activated more tools |
tool.approval-requested |
id, name, input, readOnly, step? |
tool.approval-resolved |
id, name, approved, reason?, automatic |
egress.request |
url (origin + path), allowed, status?, reason? — a web_fetch request, allowed or refused (egress) |
skill.learned |
name, description, update, chars, sources — the agent wrote a lesson down (learning) |
skill.forgotten |
name — a lesson was deleted |
Subagents and steering
| Event | Payload |
|---|---|
subagent.start / subagent.event / subagent.complete / subagent.error |
id, name + task, profile? / event / text, usage / error, stopped? |
message.queued |
id, text — a RunControl.send() is waiting for a boundary |
message.delivered |
id, text, at: 'round' | 'step' | 'final' — the model has seen it |
Pipelines (pipelines)
| Event | Payload |
|---|---|
pipeline.started |
pipeline? — the definition’s name |
pipeline.node.started |
nodeId, visit, from — a node visit began; from = the nodes whose outputs it got |
pipeline.node.finished |
nodeId, visit, text, route?, usage? |
pipeline.node.failed |
nodeId, visit, error — the run rejects; no pipeline.finished follows |
pipeline.node.skipped |
nodeId, from, reason: 'maxRuns' | 'maxNodeVisits' — an edge fired towards the node, a cap refused the visit |
pipeline.edge |
from, to, edgeId, visit, fired — one per outgoing edge of a node that finished; visit is the source node’s |
pipeline.finished |
stoppedBy?: 'maxRuns' | 'maxNodeVisits' | 'aborted', runs |
Every event a pipeline forwards from a node’s agent carries nodeId and visit.