@dudko.dev/agent-web-ui
v0.0.12
Published
The framework-free UI logic of @dudko.dev/agent-web, the in-browser LLM agent: the headless reducer that turns the agent's events into UI state, every UI string, the composer's and transcript's pure helpers, voice, saved chats, the sandboxed-frame and MCP
Maintainers
Readme
@dudko.dev/agent-web-ui
agent.dudko.dev · docs · live demo · source
The UI logic of @dudko.dev/agent-web, the
in-browser LLM agent, with no framework. It is the part of
@dudko.dev/agent-web-react that never
needed React: what the chat shows, worked out as plain functions and data. Build a front end for
any framework on it - a web component, Vue, Angular, Svelte, plain DOM - or use it on a server.
- The headless reducer -
agentStateReducerfolds the core'sAgentEvents into anAgentUiState: the plan, the steps and their tool calls, the streamed answer, the transcript, usage, consent requests, a server's questions, the model's questions, subagents, files written, MCP Apps. Pure: no clock, no randomness, no DOM. - Every UI string -
AgentLabels/defaultLabels/mergeLabels(and the pipeline editor'sPipelineLabels): one object to translate or reword. - The pure helpers behind the chat: the message box (slash commands, attachments and their refusals, the long-text rule), the files an answer names, the scroll that follows an answer, the consent queue, the question queues, image downscaling, file kinds, formatting.
- Voice - recording over
getUserMedia+MediaRecorder(every track stopped when it ends), a recording as a speech recognizer, reading aloud with the device's voices or a provider's. - Saved chats -
ChatHistoryStore(IndexedDB, memory fallback) and the merge of two tabs' saves of one chat. - The security cores, as strings and plain objects: the sandboxed frame for untrusted HTML, the MCP Apps frame (its policy, its shell, the extension's JSON-RPC bridge) and the MCP Apps sandbox page a server serves on an origin of its own.
- The stylesheets -
styles.css(the chat) andpipeline.css(the pipeline editor): plain CSS,awr-classes and--awr-*custom properties, light and dark, with soft motion built in (see Motion) and skins switched at run time (see Skins).
It ships no agent logic (the core does that) and draws nothing: a front end draws, this package
says what to draw. @dudko.dev/agent-web-react is built on it and re-exports everything it used to
export, so a React app keeps importing from the React package.
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 | The same agent in a browser tab, with no backend: your own key or a local WebGPU model |
| @dudko.dev/agent-web-ui (this package) | 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 i @dudko.dev/agent-web-ui @dudko.dev/agent-web@dudko.dev/agent-web is a peer dependency (one core per page; the type imports come from it, and
the core itself is imported only when something needs it - see The core, loaded when needed).
There is no other dependency. A React app does
not install this package itself: @dudko.dev/agent-web-react depends on it.
Entries
| Import | What | Imports |
| --- | --- | --- |
| @dudko.dev/agent-web-ui | the reducer and its types, the labels, the pure helpers, voice, saved chats, the sandboxed frame | the core, dynamically (saved chats, other tabs) |
| @dudko.dev/agent-web-ui/mcp-app | MCP Apps on the page's side: the frame's policy and shell, the bridge, the link to a sandbox page, an app's requests | nothing |
| @dudko.dev/agent-web-ui/mcp-app-sandbox | the MCP Apps sandbox page for a SERVER (a Worker, Node, Deno, Bun): the page, its headers, a Request → Response handler | nothing |
| @dudko.dev/agent-web-ui/pipeline | the pipeline editor's logic: the reducer of a pipeline run, the editing helpers, the code generator, the editor's strings | the core |
| @dudko.dev/agent-web-ui/pipeline-format | the pipeline DEFINITION format an editor writes and an executor reads: its types, the validator (refuses secret values), references by name, the JSON Schema, the converters to and from the engine's definition (see The pipeline definition format) | nothing |
| @dudko.dev/agent-web-ui/canvas | the generic canvas's maths (viewport, curves, edge routing, hit tests, layout order) and its strings | nothing |
| @dudko.dev/agent-web-ui/controller | the agent as a store any front end wraps: createAgentController, and createRemoteAgentController for an agent on a server (see Controller) | the core, dynamically, when an agent is built in the page |
| @dudko.dev/agent-web-ui/markdown | the answers' Markdown as a tree any front end draws: the parser, the parser of an answer still being written, safeHref, the link allowlist, the renderer's helpers (see Markdown) | nothing |
| @dudko.dev/agent-web-ui/locales | the chat's labels in your language, loaded on demand: loadAgentLabels(tag), the list of tags, labelsFromCatalog | nothing |
| @dudko.dev/agent-web-ui/locales/<tag> | one language's labels (labels) and its catalog (catalog) | nothing |
| @dudko.dev/agent-web-ui/styles.css | the chat's stylesheet | - |
| @dudko.dev/agent-web-ui/pipeline.css | the pipeline editor's stylesheet (stands on its own) | - |
The main entry also carries the DOM-root helpers a front end needs when its chat may live in a
shadow root (a web component): rootOf, activeElementOf, deepActiveElement, nothingFocused,
isEventInside, eventTargetOf, deepElementFromPoint, composedContains, shadowRootsAround,
listenScrollAround, portalHostOf. From the document, everything inside a shadow root is its
host (the focus, a click's target, the element under a point); these ask the component's own root,
and in the light DOM answer exactly what the document call does.
Every entry is ESM and CommonJS with types. The main entry never mentions the core's
./mcp subpath, the MCP SDK, the pipeline code, the Markdown parser, the controller (the core's
createAgent) or the MCP Apps frame - not in itself and not in a
chunk it loads - so a host that uses none of them carries none of them (tests/entries.test.ts
reads the built files).
The core, loaded when needed
No entry but ./pipeline imports the core statically. A bundler that keeps one export of the core
keeps all of its top-level code - the AI SDK, zod, the providers -, so the few values the chat
needs of it (which media types are pictures, which text, the mark of a replayed write, the check of
an MCP App's origins; fileKindOf and mediaFamilyOf answer with them) are copies here, held to
the core's own by the tests. The rest goes through
loadAgentCore() - a dynamic import('@dudko.dev/agent-web'), the same module every time: the
controller when it builds an agent (createAgent, the run's control, another tab's run), the
chat history when it announces a write, followOtherTabs / listenToOtherTabs when there is a
database to follow (pass loadAgentCore instead of the core's module: the follow starts once it
resolves). agentCoreIfLoaded() answers without importing; AgentCoreModule is the module's type.
So a chat whose agent is on a server (createRemoteAgentController, the element's backend)
never loads the core: the support chat of agent.dudko.dev went from 1.35 MB (399 KB gzip) to
0.62 MB (182 KB gzip) on its first open - React and the chat. A page that builds an agent imports
the core itself anyway (its model, its stores); your bundler puts the core in a chunk of its own.
The reducer is the seam
Everything a chat shows is a function of the events the agent emitted. Keep a state, fold every event into it, draw the state:
import { createAgent } from '@dudko.dev/agent-web'
import { agentStateReducer, createInitialAgentState, defaultLabels } from '@dudko.dev/agent-web-ui'
let state = createInitialAgentState()
const render = () => {
// your framework here: state.status, state.steps, state.messages, state.approvals, …
document.querySelector('#status')!.textContent = defaultLabels.status[state.status]
}
const agent = await createAgent(config)
await agent.run(goal, {
onEvent: (event) => {
state = agentStateReducer(state, { type: 'event', event, at: Date.now() })
render()
},
})The reducer never mutates the state it is given: each action gives a new state object, which
suits any framework's change detection. The actions besides
event are what the host did (AgentAction): a status, a reset, a saved chat loaded, the
notebook, messages that never reached the model, a text sent to a run in another tab. The run's
own start, steps and end are events (run.start, …). at is the only clock: the reducer reads
none of its own. The state is made of plain, exported view types (StepView,
ToolCallView, ApprovalView, ElicitationView, QuestionView, SubagentView, ChatMessage,
AppView, …): see the React package's docs/chat.md for what each
field means - the React components draw exactly these.
What the reducer guarantees, for a UI of your own too: a person's own words given to the model's
ask_user never stay in the steps or a saved chat (withoutOwnWords), a server's form and an MCP
skill's text are never mirrored onto a saved message, and a consent request of an MCP App outlives
the run that showed it.
Controller
@dudko.dev/agent-web-ui/controller is everything useAgent of the React package does that is not
React, as a store: it builds the agent, folds its events into the state above, runs, stops and
steers it, keeps the consent and question queues, follows a run of the conversation in another
tab, and keeps the usage. React's useAgent is this controller and useSyncExternalStore; a web
component, Vue, Angular or Svelte wraps the same controller and re-implements none of it.
The contract:
createAgentController(config, options?)builds the agent at once (unlessautoStart: false, or the config has nomodelyet) and starts following other tabs. Make one when the view appears.getSnapshot()is everything the view draws: theAgentUiState,status,isReady,isRunning,pendingApprovals,pendingQuestions,approvalMode,sessionId. It is frozen, the same object while nothing changes and a new one after every change.subscribe(listener)callslistenerafter every change - never at once - and returns the unsubscribe (React'suseSyncExternalStorecontract).- The methods:
run,stop,send,stopSubagent,sendRemote,stopRemote,sendUndelivered,discardUndelivered,reset,reload,loadChat,approve,deny,answerQuestion,setApprovalMode,approveAppToolCall,sampleForApp,compact,forgetSkill, and theagentgetter (the built agent, once ready). They are whatuseAgentreturns, with the same meaning: see the React package's README. update(config, { options?, rebuild? })takes a new config: by default it builds a new agent (adepschange ofuseAgent), the transcript kept;rebuild: falseonly takes the latest config and options and applies what is live (a newtoolApproval.mode, another store to follow other tabs through).dispose()tears it all down: the run aborted, its consent requests denied and its questions declined ("the view was closed"), an MCP App's waiting request denied, a build in progress dropped, the other-tab channels closed, pending timers cleared, every listener let go. The snapshot stays as it was and every method is then a no-op. Call it when the view goes away.
Options (AgentControllerOptions): onEvent, autoStart, maxEvents, appToolGrants,
approvals, questions, followUp, watch - the options of useAgent without deps.
createInitialAgentSnapshot(config) is the snapshot before any controller exists (a first
render that must not make one, a server render).
A custom UI in plain JS:
import { createAgentController } from '@dudko.dev/agent-web-ui/controller'
const chat = createAgentController({ model, credentials, toolApproval: { mode: 'ask-writes' } })
const render = () => {
const s = chat.getSnapshot()
status.textContent = s.status
log.textContent = s.messages.map((m) => `${m.role}: ${m.content}`).join('\n')
allow.hidden = s.pendingApprovals.length === 0
}
const off = chat.subscribe(render)
render()
send.onclick = () => (chat.getSnapshot().isRunning ? chat.send(input.value) : chat.run(input.value))
stop.onclick = () => chat.stop()
allow.onclick = () => chat.approve(chat.getSnapshot().pendingApprovals[0].id)
// when the view goes away: off(); chat.dispose()An agent on a server
createRemoteAgentController(options) is the same store for an agent that runs on a SERVER - the
swarm's gateway (examples/swarm* in the repository: Temporal + Postgres, Cloudflare, Google
Cloud, AWS - one HTTP API). The same snapshot and the same methods, so any view of the controller
draws it unchanged; nothing of the agent is in the page (no model, no key, no tool). While a
session given (sessionId, loadChat) is replayed from its stream, the snapshot says
restoring: true (until the stream has been quiet REPLAY_QUIET_MS, 150 ms, at most
REPLAY_MAX_MS, 5 s): draw a placeholder then, not the empty state.
import { createRemoteAgentController } from '@dudko.dev/agent-web-ui/controller'
const chat = createRemoteAgentController({
baseUrl: 'https://support.example.com/agent',
headers: async () => ({ authorization: `Bearer ${await visitorToken()}` }), // or credentials: 'include'
sessionId: sessionStorage.getItem('chat') ?? undefined,
onSessionId: (id) => (id ? sessionStorage.setItem('chat', id) : sessionStorage.removeItem('chat')),
})The options (RemoteAgentOptions):
| Option | What |
| --- | --- |
| baseUrl | The gateway's base URL (required) |
| sessionId | A session to continue (below) |
| headers | Headers for every request: an object, or a function called before each one, async allowed (RemoteAgentHeaders) - a visitor token, a captcha token while there is no session yet |
| credentials | fetch's credentials (default 'same-origin'; 'include' sends a cookie cross-site - the gateway's anonymous visitor cookie) |
| fetch | The fetch to use (default the global one) |
| onSessionId | Told every change of the session (started, forgotten, reset()) |
| onEvent | Every event folded, the swarm's turn.started / turn.ended markers as they came (a tool.approval-resolved that only says the turn parked is not told) |
| maxEvents | The raw event log kept in the snapshot (default 200; 0 = unbounded) |
| reconnect | { minMs, maxMs }: the stream's reconnect backoff (default 1 s, doubled up to 30 s) |
run(text)- the first messagePOST /sessions, the next onesPOST /sessions/:id/messages(each with an id: a retried POST is harmless); shown at once, its turn takes its place. Resolves with the turn's result,undefinedwhen it failed (the error said, the words back inundelivered). Text only: images or files are refused in words.- The turn streams in from
GET /sessions/:id/events(SSE read throughfetch, soheaderscan carry a token), folded by the same reducer - the server's agent emits the core's events, the swarm'sturn.started/turn.endedframe each turn. A dropped stream is opened again withLast-Event-IDafterreconnect.minMs(default 1 s, or the gateway'sretry:), doubled up toreconnect.maxMs(30 s); a frame resets it. A later attempt's copy of a step, the answer or the plan replaces the earlier one (remoteEventScope): delivery is at-least-once. sessionId- a session to continue: its stream is replayed, the transcript comes back. 404: forgotten; 409session_ended: the next message starts a new one.onSessionIdis told every change.pendingApprovals- a call the server's policy asks about parks the turn;approve(id)/deny(id, reason)post{ approved }toPOST /sessions/:id/answers/:requestId(noremember: every call is decided on its own on a server).stop()isPOST /sessions/:id/stop.send(text)while a turn runs posts a message that waits inqueuedfor its own turn.- Not available, answered as before an agent exists:
agent(undefined),answerQuestion,stopSubagent,sendRemote,forgetSkill(false),compact(undefined),approveAppToolCall/sampleForApp(throw),setApprovalMode,stopRemote,update(do nothing).reset()forgets the session;loadChat({ sessionId })opens another;reload()opens the stream again now.dispose()closes the stream and clears the reconnect timer. onEvent(event, { live, id })- every event as the reducer took it.liveis true only for a turn that a message sent through THIS controller started, as it happens: never for the replay of a session's log (a reload,loadChat, asessionIdgiven) nor for a turn another tab or client started on the same session - so a host can act on what its own message caused (open a page the agent named, say) without acting again on every reload.idis the event's cursor on the stream (<turn>:<attempt>:<seq>); the controller's own events (a request that failed) are live, without an id.createInitialRemoteSnapshot({ sessionId })is its snapshot before one exists.createSseParser(SSE text, fed chunk by chunk, toRemoteFrames -id,data- andretry:),parseRemoteCursor(<turn>:<attempt>:<seq>),remoteEventScopeandremoteEventOf(a Node core event to the shape the reducer folds) are its pure parts.- Nothing of the core is loaded for it: the
./controllerentry takes the core only throughloadAgentCore(), which this controller never calls - see The core, loaded when needed.
The React package's useRemoteAgent / <RemoteAgentProvider> and the element's backend
attribute are this controller.
The pipeline definition format
@dudko.dev/agent-web-ui/pipeline-format is the JSON a pipeline is STORED and SHARED as: what an
editor saves and an executor (a server that runs pipelines, such as
examples/pipelines) reads. It
wraps the engine's definition - the PipelineDefinition of both cores, which stays the source of
truth for execution, and what the React package's PipelineEditor edits - with what a stored
document needs: a format and a schema version, a stable name, required edge ids, and the names of
the secrets a node may use. It imports nothing, so the same module runs in a page, a Worker and
Node.
import {
validatePipelineDocument,
documentToDefinition,
definitionToDocument,
unresolvedReferences,
pipelineDocumentJsonSchema,
} from '@dudko.dev/agent-web-ui/pipeline-format'
const v = validatePipelineDocument(json) // every issue at once: { path: '/nodes/0/id', code, message }
if (v.ok) {
const definition = documentToDefinition(v.document) // what the engine runs / the editor edits
const missing = unresolvedReferences(v.document, { tools: ['word_count'], models: () => true })
}
const doc = definitionToDocument(editedDefinition, { base: loadedDocument }) // an editor's saveformat: "agent-pipeline",schemaVersion: 1- a newer version is refused, never guessed at.- Conditions are data (
always,contains,matches,route,otherwise), as the engine's. - References by name only:
model,tools,mcpServers,skills,secretsper node, and{ "$secret": "NAME" }anywhere in a node'ssettings.pipelineReferenceslists them with their paths;unresolvedReferences(doc, resolvers)says which an executor cannot resolve (a kind the resolvers do not mention resolves nothing). - No secret values: a string that looks like a key or a token (
secretKindOf: provider key shapes, private keys, JWTs, bearer and basic credentials,password=..., long random runs) and any value under a secret-sounding settings key (apiKey,token,password, ...) is an issue (secret_value) - which names the kind, never the value. The scan is linear and bounded. pipelineDocumentJsonSchema(draft 2020-12,$idurn:dudko-dev:agent-pipeline:1) describes the shape for other tools; the validator is the full check. The engine's own rules (theotherwiserule, a pattern's size, ...) are the core'svalidatePipeline, run ondocumentToDefinition(doc).definitionToDocument(def, { base })keeps from the loaded document what the engine has no field for (the name, the description, each node's secrets);documentToDefinitioncopies only what the engine reads. A document round-trips through both unchanged.- A node's agent settings are
settings.agent- how that node's agent runs, for whoever builds it (Pipeline Studio applies them in the page):maxOutputTokens(the output cap of one model call of its steps and its answer - a file it writes goes into one call, so this bounds the largest file it writes at once;0= no cap),maxSteps(model rounds within one step of its plan),thinking(off|low|medium|high),temperature(0-2). Absent = the runner's defaults; a value of the wrong kind or out of range is an issue (range,enum,unknown_propertyat/nodes/<i>/settings/agent/...).nodeAgentSettingsOf(settings)reads the valid fields,withNodeAgentSettings(settings, agent)writes them back (the other keys kept),NODE_AGENT_SETTINGS_LIMITSholds the bounds. pipelineDocumentsEqual(a, b)is an editor's "unsaved changes" check: the same pipeline whatever the order of keys, atitleequal to thenameor an edge's default id (canonicalPipelineDocument(doc)is the document as an editor would save it back). Compare with it, not withJSON.stringify- a version stored by hand or by another tool would always look changed.
Motion
Soft motion is built into styles.css and on by default - the side panels slide in and out, menus,
dialogs, consent and question cards and notices ease in, a message of a turn just begun rises in,
the steps of the answer being written settle in, disclosures unfold by height (and close at once), and a saved
chat being read shows a placeholder (never the empty state) and fades in. Only transform and
opacity move (and a disclosure's height, by the browser: nothing is measured by script), and
nothing that is on the screen at the first paint animates.
| data-awr-motion on the chat's root | |
| --- | --- |
| absent / auto (default) | Soft motion; a short fade with no movement when the device asks for reduced motion (prefers-reduced-motion: reduce) |
| reduced | That fade, always: nothing travels |
| none | Nothing moves: every duration 0 |
A binding sets it from its option (<AgentChat motion>, <dd-agent-chat motion>); a front end of
your own puts it on its .awr-chat / .awr-theme element. The pure half is exported:
AgentMotion, AGENT_MOTIONS, agentMotionOf (an attribute's text, any case), motionAttribute
(the attribute for a motion - none for auto), enteringMessageIds (which messages arrive live
and may rise in: never the first drawing, a saved chat opened or a transcript replaced) and
exitDurationMs (how long a closing element's animation runs, from its computed style - 0 means
remove it now).
| Token | Default | |
| --- | --- | --- |
| --awr-motion-duration-fast / -base / -slow | 150 / 220 / 320 ms | Small parts (menus, rows), cards and panels, sheets |
| --awr-motion-duration-exit | 160 ms | What leaves goes faster than it came |
| --awr-motion-ease-out / -ease-in-out / -ease-in | cubic-bezier(…) | Entering, opening / closing, leaving |
| --awr-motion-rise / -shift / -sheet | 6px / 16px / 100% | How far a card rises, a wide side panel shifts, a narrow one slides |
| --awr-motion-scale | 0.97 | A menu or a dialog grows from |
Durations of 0 turn motion off the same way none does; distances of 0 make it reduced.
Skins
How to style the chat as a whole - the tokens, a palette per scheme, type, motion, parts: Styling the chat (the same for every front end).
A skin is the chat's look as a whole, switched at run time: data-awr-skin on the chat's root.
| data-awr-skin on the chat's root | |
| --- | --- |
| absent / default | The look above, exactly as it was |
| glass | Liquid glass: translucent surfaces that blur what is behind them, over a soft backdrop |
| any other name | Yours: your CSS brings its rules (below) |
A binding sets it from its option (<AgentChat skin>, <dd-agent-chat skin>), and changing it
re-styles the chat in place - nothing is rebuilt or reloaded. A front end of your own puts it on
its .awr-chat / .awr-theme element. The pure half is exported: AgentSkin, AGENT_SKINS,
agentSkinOf (an attribute's text as a skin: trimmed, lower-cased, letters, digits and dashes;
anything else is no skin), skinAttribute (the attribute for a skin - none for default), and the
contrast maths a translucent skin is held to: parseCssColor, compositeOver,
relativeLuminance, contrastRatio, worstCaseContrast (text over a stack of fills, composited
over a stack of fills), WCAG_AA_TEXT.
Glass. The header, the message box, the side panels, menus, dialogs and the consent /
question cards turn translucent (backdrop-filter: blur() saturate()), with a specular edge (an
inset highlight) and a soft shadow, over a soft backdrop behind the chat; light and dark, by the
theme. It is held to:
- Clear and readable. The main surface lets half of the backdrop through (the tests hold it at
60% opacity or less), and every text colour of the skin over every fill of the skin, composited
over every part of the skin's own backdrop (its canvas and tints), is WCAG AA (4.5:1). The tests
compute it from the sheet, and in a browser from the chat as drawn. A host that puts its own
picture behind the chat (
--awr-glass-backdrop) checks the contrast over that picture itself, or raises the fills. - One layer of blur. A glass surface inside another one is not blurred (a menu inside the
message box gets a stronger fill instead): phones pay for every blurred layer. The header and
the message box carry their glass on a
::before- abackdrop-filteron them would become the containing block of the fixed menus inside. - Opaque where it should be. Without
backdrop-filter(@supports) the surfaces are solid; withprefers-reduced-transparency: reduceeverything is opaque and the backdrop a plain colour; withprefers-contrast: morethe same, every surface's edge drawn; with forced colours, the system's colours and no blur.
| Token | Default | |
| --- | --- | --- |
| --awr-glass-backdrop | two soft radial tints over --awr-glass-canvas | What is behind the chat - your page's picture, or transparent to show the page |
| --awr-glass-blur / --awr-glass-saturate | 22px / 180% | The blur of what is behind a surface |
| --awr-glass-fill / --awr-glass-fill-strong | white 50% / 70% (dark: 45% / 68%) | A surface; one inside another |
| --awr-glass-solid | an opaque tint | A surface where glass is off |
| --awr-glass-highlight / --awr-glass-edge | | The specular top edge, the 1px rim |
| --awr-glass-depth | a soft shadow | Under a lifted surface |
| --awr-glass-fg, -muted, -accent, -danger, -warn, -ok, … | | The text colours, chosen for the contrast above |
Set them on .awr-chat like any token (on <dd-agent-chat> itself in a shadow root). A theme of
your own that sets the chat's tokens (--awr-bg, --awr-fg, …) on .awr-chat at a class's
weight is later than the skin and wins over it - scope it to the default look so a skin brings its
own palette: :where(.awr-chat):where(:not([data-awr-skin])) { --awr-bg: … } (what the demo does). Keep a
translucent fill at least as opaque as the default, or check your colours with
worstCaseContrast.
A skin of your own is a block of --awr-* token overrides - and, if you want, a few rules for
its surfaces - under [data-awr-skin='<name>'], light and dark:
/* Tokens: on the chat's root, a class's weight - after the theme's, so they win. */
.awr-chat[data-awr-skin='paper'] {
--awr-bg: #fbf7ef;
--awr-subtle: #f3ecdf;
--awr-assistant-bg: #f3ecdf;
--awr-border: #e4d9c5;
--awr-accent: #8a4b16;
--awr-radius: 4px;
--awr-font: Georgia, serif;
}
@media (prefers-color-scheme: dark) {
.awr-chat[data-awr-skin='paper']:not([data-awr-theme='light']) {
--awr-bg: #1f1b16;
--awr-subtle: #2a241d;
--awr-assistant-bg: #2a241d;
--awr-border: #3b3328;
--awr-accent: #e0a96d;
}
}
.awr-chat[data-awr-skin='paper'][data-awr-theme='dark'] {
/* the same dark values */
}
/* A surface rule: under the skin's attribute, so the default look is untouched. */
.awr-chat[data-awr-skin='paper'] .awr-composer2 {
box-shadow: 0 1px 0 var(--awr-border);
}<AgentChat skin="paper" /><dd-agent-chat skin="paper"> draws the chat in a shadow root, where the page's rules reach only
the element: set the tokens on it - dd-agent-chat[skin='paper'] { --awr-bg: #fbf7ef; … } (or
dd-agent-chat:state(skin-paper), the state it carries) - and they reach every part of the chat.
Labels
defaultLabels is every string the chat shows; counted phrases are functions so that languages
with several plural forms can say them. mergeLabels(defaultLabels, overrides) merges the nested
groups key by key. The React package's <AgentLabelsProvider> / useLabels are this object in a
React context; a web component or a Vue plugin can do the same with its own mechanism.
Markdown
./markdown turns a model's Markdown into a small tree - blocks (p, h, code, quote, hr,
list, table) of inline runs (text, br, code, strong, em, del, link, file) - that
a renderer of any front end draws as elements, never as HTML. The React package's <Markdown>
(@dudko.dev/agent-web-react/markdown) is one; a web component or a Vue / Svelte component draws
the same tree the same way.
import {
parseMarkdownCached, // a finished text (cached by its text)
parseMarkdownStreaming, // a text still being written, given the parse of what it was before
emptyMarkdownStream,
markdownCellIsLong,
type MarkdownBlock,
} from '@dudko.dev/agent-web-ui/markdown'
let stream = emptyMarkdownStream()
const blocksOf = (text: string, pending: boolean): MarkdownBlock[] =>
pending ? (stream = parseMarkdownStreaming(stream, text)).blocks : parseMarkdownCached(text)What it reads: paragraphs with their line breaks, headings, lists (nested, at most 9 levels),
fenced code (at any indentation), quotes, rules, GFM tables, **bold**, *italic*,
~~struck~~, `code`, links and bare http(s) URLs. While an answer is written
(parseMarkdownStreaming) nothing already drawn changes its kind or gets shorter: the last line
waits while it is only markers, emphasis open at the end is drawn closed, a link is its words
until its address is whole, and the finished blocks are kept as the same objects.
It is a security boundary for a host - the text is the model's:
- Raw HTML is text:
<script>,<img onerror>, entities - the characters as written. There is no node that is markup or carries an attribute. - A link only to
http(s)ormailto(safeHref): anything else -javascript:,data:,vbscript:,file:,//host, a relative address, and their obfuscated forms (entities, which are never decoded, percent-encoding, blanks inside, case) - stays text. - A link to a workspace file is
{ t: 'file', path }only when its destination, percent-decoded first, is a workspace path byworkspacePathOf(absolute, no.././ empty segment, no//host, no backslash or control character) -%2e%2e,%2F%2Fhost,%5Care refused; a whole code span that is one carriespath. A renderer draws it as a control that opens the file in the page, never as<a href>. A link's words hold no link of their own. - No picture is loaded from an answer:
is its!and a link (or a file link). - A link allowlist, for a chat that should link only to its own sites (opt-in, a renderer's
linkAllowed):linkHostAllowed(href, hosts)/linkPolicyOf(hosts)- each entryhostorhost/path;http(s)only, the host exactly (no subdomain, no look-alike), no user, password or port, a path entry a prefix by whole segments after the URL parser's normalisation.parseLinkHosts(attribute)reads a list separated by blanks or commas; a malformed entry empties it (no link kept - never every link). - Linear on any text: one pass for code spans, lookups for brackets and destinations, one
opener stack per kind of emphasis, list nesting bounded - long runs of
*,_,[, backticks,>,|or ever-deeper lists cost what plain text does (tests/markdown.test.tstimes them).
In your language
The chat's labels come translated into 33 languages - the same 33 as the app at https://agent.dudko.dev/app/, whose translations they are:
en, ru, uk, be, pl, cs, sk, hr, sr, sr-Latn, bg, ro, hu, de, fr, it,
es, pt, nl, da, sv, nb, fi, el, sq, ca, tr, es-419, pt-BR, fr-CA, ht,
qu, gn.
import { loadAgentLabels } from '@dudko.dev/agent-web-ui/locales'
import { defaultLabels, mergeLabels } from '@dudko.dev/agent-web-ui'
const labels = mergeLabels(defaultLabels, await loadAgentLabels(navigator.language))- One language, one file. Each language is an entry of its own
(
@dudko.dev/agent-web-ui/locales/<tag>), andloadAgentLabelsloads it with a literalimport(), so a bundler makes a chunk of each: a page in Russian downloads Russian only (about 27 KB, 7 KB gzipped), plus the builder every language shares (5 KB gzipped). The variants carry their base too:es-419is Spanish with the words of the Americas,fr-CAFrench with Québec's punctuation,sr-Latnthe Cyrillic catalog transliterated letter for letter. To have one language in your main bundle instead, import it:import { labels } from '@dudko.dev/agent-web-ui/locales/de'. - Which language.
loadAgentLabels(tag)takes any BCP 47 tag: the exact tag (pt-BR), then its language and script (sr-Latn-RS→sr-Latn), then its language (de-AT→de,es-MX→es,no→nb), then English - also for a tag that is not one.agentLabelLocaleOf(tag)tells which it picks;AGENT_LABEL_LOCALESis the list. Choosinges-419fores-MXis the host's call: pass the tag you mean. - What is not translated stays English. The labels are an
AgentLabelsOverride: the chat's strings the app shows. What they do not cover yet (a few parts ofAgentLabelsthe app does not mount, andemptyState, which is the host's own words) falls back todefaultLabelsonce merged. - Plurals and numbers are the language's own: a counted phrase picks its form with
Intl.PluralRules(tag)(Russian: 1 шаг, 2 шага, 5 шагов, 21 шаг) and writes its number withIntl.NumberFormat(tag)(1 234 in Russian, 1.234 in German); sizes and token counts areIntl.NumberFormat's units and compact form. No library. - Your own wording or language.
labelsFromCatalog(tag, catalog)builds the labels from a catalog of the same keys (AgentLabelCatalog; plural entries as{ one, few, many, other }- the categories of the language - with{count}): take a language'scatalog, change what you like, or translate English's. - Machine-made, not reviewed:
ht(Kreyòl ayisyen),qu(Runa Simi) andgn(Avañe'ẽ) were written with care but have not been read by a native speaker yet - the app marks them the same way. Corrections are welcome. The other 30 are reviewed.
Security boundaries
Four parts of this package are security boundaries. Each guard has a guard … test here
(tests/files.test.ts, tests/apps*.test.ts, tests/app-prompts.test.ts, tests/markdown.test.ts), the React package's
browser tests run hostile pages and a hostile MCP App against them, and a change needs a mutation
check.
- The sandboxed frame (
buildSandboxedDocument,sandboxedCsp,sandboxTokens): untrusted HTML goes into<iframe sandbox>WITHOUTallow-same-origin, under a policy with no network source, framed by a document of ours whoseframe-src 'none'is what stops it navigating itself. Never render a workspace file byblob:/data:URL or as markup. - The MCP Apps frame (
./mcp-app): the app's policy from its resource's declared origins ONLY (frames, workers and<base>never granted;'wasm-unsafe-eval'always,'unsafe-eval'never), one innersandbox="allow-scripts"frame, andMcpAppBridge- an allow-list of methods, their parameters checked, nothing butpingbeforeui/initialize. - The sandbox page (
./mcp-app-sandbox, for a server): an app on an origin of its own. It binds to the first ancestor on an allowed host that sendssandbox-resource-ready, once, relays to exact origins only, and ignores asandbox,csporpermissionsthe host sends: the header is the policy, andframe-ancestorsnames the hosts. - The Markdown parser (
./markdown): raw HTML is text, links only tohttp(s)/mailto, a file link only to a workspace path (decoded first), no picture, linear on any text - see Markdown.
// A Cloudflare Worker serving the sandbox page
import { mcpAppSandboxResponse } from '@dudko.dev/agent-web-ui/mcp-app-sandbox'
export default {
fetch: (request: Request, env: { HOSTS?: string }) =>
mcpAppSandboxResponse(request, { path: '/sandbox/v1', hosts: env.HOSTS }),
}How an app runs and what the two modes trade: the React package's docs/chat.md.
Who uses it
@dudko.dev/agent-web-react- the hook, the context and the components; it imports this package (one copy on a page) and re-exports its names, and ships its stylesheets at@dudko.dev/agent-web-react/styles.cssand/pipeline.css, copied from here.apps/appandapps/demodraw their answers' Markdown with./markdown, through the React package's<Markdown>.apps/app-sandbox- the demo's and the app's MCP Apps sandbox page on Cloudflare,./mcp-app-sandboxand nothing else.@dudko.dev/agent-web-element: the React chat as a web component, with React bundled inside, for a page that has none.@dudko.dev/agent-web-vue,-angularand-svelte: thin bindings of./controller, no React.
License
MIT © Siarhei Dudko
