Skip to content

Svelte bindings

Svelte bindings for @dudko.dev/agent-web, the in-browser LLM agent. One function, createAgent, gives you the agent as a Svelte store: $agent is everything a view draws - the transcript, the status, the plan and steps, the tool calls waiting for consent, the model’s questions, token usage - and the store carries the agent’s methods: run, stop, send, approve, deny, answerQuestion, reset, …

<script>
import { createAgent } from '@dudko.dev/agent-web-svelte'
const agent = createAgent(config)
</script>
{#each $agent.messages as m (m.id)}<p>{m.content}</p>{/each}
<button disabled={!$agent.isReady} onclick={() => agent.run('Hello')}>Ask</button>

It is headless and thin. It draws nothing - your components do - and it holds no logic of its own: building the agent, folding its events into state, runs, steering, consent, questions, other tabs are all createAgentController from @dudko.dev/agent-web-ui/controller, the same controller React’s useAgent is made of. This package adds the store contract, derived stores and the lifecycle.

It works in Svelte 4 and Svelte 5 alike, through the store contract that both honour. There is no .svelte file and no rune in it: it ships as plain ESM (and CommonJS) with types, so it needs no Svelte compiler or preprocessor, and it imports nothing of svelte at run time.

Need the whole chat, not the parts? Use <dd-agent-chat>, the finished chat as a web component - it works in a Svelte page as it is:

<script>
import '@dudko.dev/agent-web-element'
</script>
<dd-agent-chat {config} lang="es" />

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 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 (this package) Svelte 4 and 5: createAgent(), the chat state as a store
Terminal window
npm install @dudko.dev/agent-web-svelte @dudko.dev/agent-web
# and the model providers you use, e.g.
npm install @ai-sdk/google

@dudko.dev/agent-web (the agent) and svelte (4 or 5) are peers: your app picks their versions, and there is one core on the page. @dudko.dev/agent-web-ui comes with this package.

The config is the core’s createAgent config (BrowserAgentConfig): see @dudko.dev/agent-web.

agent.ts
import { VaultCredentialStore } from '@dudko.dev/agent-web'
export const config = {
model: { providerType: 'google', model: 'gemini-flash-latest', credentialRef: 'google' },
credentials: new VaultCredentialStore(), // keys encrypted at rest, in IndexedDB
toolApproval: { mode: 'ask-writes' }, // tool calls that write wait in pendingApprovals
askUser: true, // the model may ask the person (pendingQuestions)
}
Chat.svelte
<script>
import { createAgent } from '@dudko.dev/agent-web-svelte'
let { config } = $props()
const agent = createAgent(config)
const { messages, pendingApprovals, pendingQuestions } = agent
// A new config object builds a new agent; the same one changes nothing.
$effect(() => agent.update(config))
let text = $state('')
const send = (event) => {
event.preventDefault()
if (!text.trim()) return
agent.run(text)
text = ''
}
</script>
<p class="status">{$agent.status}</p>
<ul>
{#each $messages as m (m.id)}
<li class="msg {m.role}">{m.content}</li>
{/each}
</ul>
{#each $pendingApprovals as a (a.id)}
<div class="approval">
{a.name}
<button onclick={() => agent.approve(a.id)}>Allow</button>
<button onclick={() => agent.deny(a.id)}>Deny</button>
</div>
{/each}
{#each $pendingQuestions as q (q.id)}
<div class="question">
{q.question}
{#each q.options ?? [] as o (o.label)}
<button onclick={() => agent.answerQuestion(q.id, { choice: [o.label] })}>{o.label}</button>
{/each}
</div>
{/each}
<form onsubmit={send}>
<input bind:value={text} aria-label="Message" />
<button disabled={!$agent.isReady}>Send</button>
{#if $agent.isRunning}<button type="button" onclick={agent.stop}>Stop</button>{/if}
</form>
Chat.svelte
<script>
import { createAgent } from '@dudko.dev/agent-web-svelte'
export let config
const agent = createAgent(config)
const { messages, pendingApprovals, pendingQuestions } = agent
// A new config object builds a new agent; the same one changes nothing.
$: agent.update(config)
let text = ''
const send = () => {
if (!text.trim()) return
agent.run(text)
text = ''
}
</script>
<p class="status">{$agent.status}</p>
<ul>
{#each $messages as m (m.id)}
<li class="msg {m.role}">{m.content}</li>
{/each}
</ul>
{#each $pendingApprovals as a (a.id)}
<div class="approval">
{a.name}
<button on:click={() => agent.approve(a.id)}>Allow</button>
<button on:click={() => agent.deny(a.id)}>Deny</button>
</div>
{/each}
{#each $pendingQuestions as q (q.id)}
<div class="question">
{q.question}
{#each q.options ?? [] as o (o.label)}
<button on:click={() => agent.answerQuestion(q.id, { choice: [o.label] })}>{o.label}</button>
{/each}
</div>
{/each}
<form on:submit|preventDefault={send}>
<input bind:value={text} aria-label="Message" />
<button disabled={!$agent.isReady}>Send</button>
{#if $agent.isRunning}<button type="button" on:click={agent.stop}>Stop</button>{/if}
</form>

Both examples are this package’s browser tests: compiled by Svelte 5’s and Svelte 4’s own compiler and run in Chromium against a real agent (e2e/).

Returns an AgentStore. Nothing is built yet: the agent is built when the store gets its first subscriber (see Lifecycle).

  • config — the core’s BrowserAgentConfig.
  • options — the controller’s options (AgentControllerOptions):
    • autoStart (default true) — build at once; false waits for reload().
    • onEvent(event) — every core event, as it happens.
    • maxEvents — how many raw events the state keeps.
    • approvals, questions (default true) — the store answers consent requests and the model’s questions (pendingApprovals, pendingQuestions); false leaves them to your own handler.
    • followUp, watch, appToolGrants — see the controller.

AgentStore is a Svelte readable store of the controller’s snapshot (AgentControllerSnapshot): subscribe(run) calls run at once with the current value, then after every change, and returns the unsubscribe - so $agent, get(agent) and derived(agent, …) work as with any store.

$agent has every field of the UI state (AgentUiState: status, messages, plan, steps, approvals, questions, subagents, totalUsage, queued, undelivered, learned, …) plus:

field
isReady the agent is built and nothing runs
isRunning a run is in flight (this tab’s, or this conversation’s in another tab)
pendingApprovals tool calls waiting for the person’s consent
pendingQuestions the model’s questions waiting for the person
approvalMode the consent policy in effect
sessionId the memory session runs use

Each value is a new frozen object when something changed, and the same object while nothing did. A subscriber is called on every change and never when nothing changed.

On the store, each called only when its own value changes:

store value
agent.isReady boolean
agent.isRunning boolean
agent.messages ChatMessage[]
agent.pendingApprovals ApprovalView[]
agent.pendingQuestions PendingQuestion[]
agent.status 'idle' | 'initializing' | 'ready' | 'running' | 'error'
agent.select(pick) any part: const plan = agent.select((s) => s.plan)

A store must be a top-level name for $: const { messages } = agent, then $messages. Equal means Object.is, and an array is equal when its items are.

The controller’s, unchanged. They are plain functions: destructure them, pass them as handlers.

method
run(goal, options?) run a goal; resolves with the core’s RunResult, or undefined if it could not start. options: label, images, files, attachments
stop() abort this tab’s run
send(text) say something to the running run (it reaches the model at its next boundary); false when nothing runs
stopSubagent(id) stop one subagent
approve(id, { remember? }) / deny(id, reason?) answer one of pendingApprovals
answerQuestion(id, answer) answer one of pendingQuestions: { choice: [label] }, { other: text } or { declined: true }
setApprovalMode(mode) switch the consent policy live
reset() clear the conversation and the agent’s memory of it
reload() rebuild the agent now (a new API key)
loadChat({ sessionId, messages?, totalUsage? }) switch to a saved conversation
compact() summarise the stored transcript
sendUndelivered() / discardUndelivered() a stopped run’s leftover messages
sendRemote(text) / stopRemote() this conversation’s run in another tab
forgetSkill(name) delete one of the agent’s lessons
approveAppToolCall(call, signal?), sampleForApp(…) MCP Apps: see the controller

What changes the view or the next agent - reset, reload, loadChat, setApprovalMode, discardUndelivered - waits for the agent when called before it is made (an onMount runs before it); what needs an agent or a run answers as with none (run resolves undefined, send returns false, approveAppToolCall throws).

A new config. A new object builds a new agent from it - the transcript stays, as when the model or the key changes; the same object only takes options (when given; they replace the old ones). So calling it with the latest config every time it may have changed is cheap: $effect(() => agent.update(config)) in Svelte 5, $: agent.update(config) in Svelte 4. Keep the config an object you change on purpose, not one made anew on every render. Without a live agent, the next one is built from it.

agent.agent, agent.destroy(), agent.destroyed

Section titled “agent.agent, agent.destroy(), agent.destroyed”

agent.agent is the core’s built Agent (undefined while building and without a live controller). destroy() ends the store for good - see below.

The store owns a controller - the agent and the channels it uses to follow the same conversation in other tabs - only while someone reads it:

  • Made a microtask after the first subscriber. A component that reads $agent subscribes when it mounts; the agent is built then. get(agent) on a store nobody reads returns the initial snapshot and builds nothing.
  • Disposed a microtask after the last subscriber leaves. The component unmounts: the run is aborted, its consent requests and questions are answered (denied, declined), the other-tab channels are closed, the timers cleared, every listener let go. Nothing is left behind - the tests count the channels, the timers and the listeners.
  • A leave and a return in the same tick keep it (a {#key} block re-creating its content, a get() while nothing else reads it).
  • A new subscriber after that gets a new controller, from the latest config: a new agent and an empty transcript (the conversation itself is in the agent’s memory, if you gave it one; load a saved one with loadChat).

So a store created in a component lives and dies with it - nothing to clean up. A store created in a module (shared by several components) lives while any of them is mounted. To keep one alive with no component on screen, hold a subscription (const keep = agent.subscribe(() => {})) and end it with destroy().

destroy() disposes the controller at once, lets go of every subscriber and makes every method a no-op; a late subscriber gets the last value and nothing more.

No controller is made on the server. A server render reads $agent by subscribing and unsubscribing within the same synchronous render, so the store gives the initial snapshot (status: 'idle', no messages) and the deferred creation never happens. The browser then builds the agent when the component hydrates. Do not call run on the server, and do not keep a subscription there. If your config needs browser APIs to be made (a VaultCredentialStore, IndexedDBStore), make it in the browser (import { browser } from '$app/environment', or in onMount) - or render the chat client-side only. This package’s tests render a component with Svelte 5’s and Svelte 4’s server renderers and check that nothing was built.

The chat’s labels in 33 languages come with @dudko.dev/agent-web-ui - the strings for statuses, buttons and notices, loaded on demand, one chunk per language:

<script>
import { defaultLabels, mergeLabels } from '@dudko.dev/agent-web-ui'
import { loadAgentLabels } from '@dudko.dev/agent-web-ui/locales'
let labels = $state(defaultLabels)
loadAgentLabels(navigator.language).then((l) => (labels = mergeLabels(defaultLabels, l)))
</script>
<p>{labels.status[$agent.status]}</p>

loadAgentLabels(tag) picks the exact tag, then its language, then English. See In your language.

A model answers in Markdown. @dudko.dev/agent-web-ui/markdown parses it into a small tree that a component draws as elements - never as HTML ({@html} of a model’s text is how a page gets <img onerror>): raw HTML stays text, links go only to http(s) / mailto, no picture is loaded.

<!-- Answer.svelte (Svelte 5): paragraphs, headings, code and lists; extend it to the rest -->
<script>
import { parseMarkdownCached } from '@dudko.dev/agent-web-ui/markdown'
import Inline from './Inline.svelte'
let { text } = $props()
const blocks = $derived(parseMarkdownCached(text))
</script>
{#each blocks as b}
{#if b.t === 'p'}<p><Inline nodes={b.c} /></p>
{:else if b.t === 'h'}<svelte:element this={'h' + b.level}><Inline nodes={b.c} /></svelte:element>
{:else if b.t === 'code'}<pre><code>{b.v}</code></pre>
{:else if b.t === 'list'}
<svelte:element this={b.ordered ? 'ol' : 'ul'}>
{#each b.items as item}<li><Inline nodes={item.c} /></li>{/each}
</svelte:element>
{/if}
{/each}
Inline.svelte
<script>
import Inline from './Inline.svelte'
let { nodes } = $props()
</script>
{#each nodes as n}
{#if n.t === 'text'}{n.v}
{:else if n.t === 'br'}<br />
{:else if n.t === 'code'}<code>{n.v}</code>
{:else if n.t === 'strong'}<strong><Inline nodes={n.c} /></strong>
{:else if n.t === 'em'}<em><Inline nodes={n.c} /></em>
{:else if n.t === 'del'}<del><Inline nodes={n.c} /></del>
{:else if n.t === 'link'}<a href={n.href} rel="noopener noreferrer" target="_blank"><Inline nodes={n.c} /></a>
{:else}<Inline nodes={n.c} />
{/if}
{/each}

For an answer still being written (m.pending), parseMarkdownStreaming keeps what is drawn from changing its kind or getting shorter. Every node kind and rule: Markdown.

  • No components, no styles. Your markup, your CSS. For a finished chat: <dd-agent-chat>.
  • No logic of its own. What the agent does in a view is the controller’s (@dudko.dev/agent-web-ui/controller); a fix or a feature there reaches React, the web component and this package at once.
  • No runes, no Svelte compile step. Use it from runes or legacy components, from .svelte.js modules or plain .js.

MIT