};
aparteGlobalConfig.setHighlightProvider((code, lang) => myHighlighter.toHtml(code, lang));
```
The provider gets the code and its language, and returns the whole block as HTML, `` included, as a string or a promise of one. ## Keep it safe [Section titled “Keep it safe”](#keep-it-safe)
```ts
import DOMPurify from 'dompurify';
import { aparteGlobalConfig, defaultSanitizer } from '@aparte/core';
aparteGlobalConfig.setHtmlSanitizer((html) => defaultSanitizer(DOMPurify.sanitize(html)));
```
What marked and a highlighter return goes through the chat’s HTML sanitizer before it reaches the page, and so does a streamed reply once it finishes, so the Markdown a model writes cannot run script. While a reply streams, a link or an image with an unsafe address is dropped, and a link to another site opens in a new tab. The built-in sanitizer needs no dependency. To add DOMPurify, chain it in front of the built-in sanitizer, as above, rather than in its place. [`setHtmlSanitizer`](/reference/core/config/#sethtmlsanitizer) replaces the sanitizer, and DOMPurify’s defaults are written for any page, not for a chat: on their own they keep inline layout styles (a reply can cover the screen), core’s `aparte-` classes (a reply can draw a button that looks like an approval), form controls, `id`s, `role`s that make text a control, the `data-aparte-*` attributes core reads as commands (a reply can open a dialog), and they leave a link to another site opening in the chat’s own frame. ## Pictures a reply can load [Section titled “Pictures a reply can load”](#pictures-a-reply-can-load) Pictures a model or a tool chose do not load by themselves. A `data:` or `blob:` picture does; any other is shown as a small link that names where it would load from, and it loads in place when the reader clicks it (a click with a modifier key or the middle button is left to the browser, as for any link: a new tab, a new window or a download). A card shows one “Show images” button in place of the links. A held picture is not fetched while a reply streams either. A picture fetches its address the moment it is shown, and a prompt-injected model — one that read a web page, a document or a tool result written to steer it — can write the conversation into that address: `` sends it, with the reader’s IP address, to that host without a click, and nobody sees anything happen. The page’s own address is not trusted by default either. It carries the reader’s cookies, and an open redirect on your site turns a picture from your site into a picture from anywhere. The assistants this was done to closed it the same way: Gemini no longer shows external pictures in a reply, ChatGPT loads only addresses it has checked, and GitHub Copilot Chat stopped showing them, each after the attack was reported. Name what you trust with `setImagePolicy`:
```ts
import { aparteGlobalConfig } from '@aparte/core';
// Your own site and one CDN load; everything else waits for a click.
aparteGlobalConfig.setImagePolicy(['self', 'https://cdn.example.com']);
// Every picture loads, as before 1.0.
aparteGlobalConfig.setImagePolicy(['*']);
// Anything else: 'load' it, 'hold' it behind a click, or 'drop' it with no trace.
aparteGlobalConfig.setImagePolicy((url) =>
url.startsWith('https://images.example.com/') ? 'load' : 'hold');
```
Which one to choose: * **Your pictures come from places you know** — your site, a CDN, a product catalogue: list them. List hosts that serve only your own files: one where anyone can upload, or that redirects anywhere, gives the hole back. * **Every picture should load** — an internal tool whose model never reads content you do not control: `['*']`, as 0.x did. * **No picture should load by itself** — keep the default. `setImagePolicy([])` says so, and silences the note below. The first picture held on a page also writes a note in the browser console, with its host and the line to add, so a picture waiting for a click is not mistaken for a broken one. Naming any policy, the default included, silences it. A list takes `'self'`, `'*'` and origins; a function gets the address resolved against the page. An answer that is none of the three holds the picture. Every picture that loads goes with `referrerpolicy="no-referrer"`, so the host does not learn which page showed it. A plugin, or an app that draws pictures itself, asks the same rule before it sets a `src`, because setting it is the request:
```ts
import { aparteGlobalConfig } from '@aparte/core';
declare const url: string;
declare const frame: HTMLElement;
if (aparteGlobalConfig.decideImage(url) === 'load') {
const img = document.createElement('img');
img.referrerPolicy = 'no-referrer'; // before `src`, which starts the request
img.src = url;
frame.append(img);
}
// The reader chose to see it: it loads from now on where the policy would only have held it.
aparteGlobalConfig.showImage(url);
```
For a card of your own, `ctx.image(src, props)` returns an ` ` that loads, or `null` when the policy does not let it, and `ctx.loads(url)` says whether a video, a sound or a poster may load now ([cards](/guides/cards/#pictures-and-the-image-policy)). ### Beside a Content-Security-Policy [Section titled “Beside a Content-Security-Policy”](#beside-a-content-security-policy) The policy is what the library can do on its own. An `img-src` header is the stronger rule beside it, because it also checks where a redirect leads, which no script on the page can see:
```http
Content-Security-Policy: img-src 'self' data: blob: https://cdn.example.com
```
Or proxy third-party pictures through your own server and allow that origin in the policy and in the header. A `` or an `` cannot be told to send no referrer; a page that cares sets its own `Referrer-Policy` header. ### What it does not cover [Section titled “What it does not cover”](#what-it-does-not-cover) * It runs after whichever sanitizer is set, DOMPurify included, and covers ` ` and ``. A sanitizer of your own that keeps ``, ``, an SVG `` or a `style` with `url()` lets those load: chain it in front of `defaultSanitizer`, as above. * With no page, as in a server render, a relative address cannot be resolved, so a list other than `'*'` holds it. * The map tiles you configure (`mapTiles`) and the pictures your own code draws, such as avatars, attachments and a tool renderer that returns its own markup, are yours, not the policy’s. ## Maths and diagrams [Section titled “Maths and diagrams”](#maths-and-diagrams)
````ts
import { aparteGlobalConfig, escapeHtml } from '@aparte/core';
// A ```csv fence drawn as a table, in any reply.
aparteGlobalConfig.registerCodeLanguageRenderer({
languages: ['csv'],
render: ({ source }) =>
`${source.trim().split('\n').map((row) =>
`${row.split(',').map((cell) => `${escapeHtml(cell)} `).join('')} `).join('')}
`,
});
````
A fence or a formula is drawn by the renderer registered for its language — `math` by [`@aparte/plugin-katex`](/guides/math/), `mermaid` by [`@aparte/plugin-mermaid`](/guides/diagrams/), or one of your own — whichever Markdown provider is installed. A provider hands a source over by marking it: `` for a fence, which every provider already writes, and `` or `math-display` for maths, which marked and streaming-markdown write once a `math` renderer is registered. While a reply streams the renderer is also asked about a source still arriving, and may draw it or wait. To draw them inside an element of your own, call `renderCodeLanguages(element)` after writing its HTML. A drawing goes beside its source, which stays in the page hidden: copying, and the history the model reads, still use the source. What `render` returns is inserted as it is, not through the sanitizer, which would strip the SVG, MathML and positioning a drawing is made of; it has the standing of a segment renderer’s output — code you installed — so escape anything from the source you put in it. ## Route the links a model writes [Section titled “Route the links a model writes”](#route-the-links-a-model-writes)
```ts
declare const router: { push(path: string): void }; // your app's router
const chat = document.querySelector('aparte-chat');
chat?.addEventListener('aparte-link-click', (event) => {
const url = new URL(event.detail.href, location.href);
if (url.origin !== location.origin) return; // another site: let the browser open it
event.preventDefault(); // this one is yours
router.push(url.pathname + url.search);
});
```
Before the browser follows a link in a reply, the message fires `aparte-link-click`. It bubbles, so one listener on the chat covers every message, and it can be cancelled: call `preventDefault()` and the navigation is yours — your router, a webview, a question first. The detail is `{ href, anchor, messageId }`. ## Two chats, two setups [Section titled “Two chats, two setups”](#two-chats-two-setups)
```ts
import { AparteConfig, attachConfig } from '@aparte/core';
import { setupStreamingMarkdownProvider } from '@aparte/plugin-streaming-markdown';
import { setupMarkedProvider } from '@aparte/plugin-marked';
import { setupShikiProvider } from '@aparte/plugin-shiki';
const support = new AparteConfig();
setupStreamingMarkdownProvider(support);
setupMarkedProvider({ breaks: true }, support);
setupShikiProvider({ theme: 'github-dark' }, support);
const chat = document.querySelector('#support-chat');
if (chat) attachConfig(chat, support);
```
Every setup takes a configuration as its last argument, the page-wide one by default. A configuration of your own starts from the built-in defaults and reads nothing the page-wide one registered, so set up on it every formatter that chat uses; attached to a chat, it formats that chat alone. The framework packages take it as their `config` prop. ## Next [Section titled “Next”](#next) * [Response The formatted reply, its variants and its options.](/components/response/) * [Code block Code as its own part of a reply, with its language and copy button.](/components/code-block/) * [Customization Your own way to draw a part of a message.](/guides/customization/)
# Render maths with KaTeX
> Draw the formulas a model writes — $…$, $$…$$, \(…\), \[…\] — while the reply streams, with @aparte/plugin-katex.
[Maths drawn while the reply streams](/preview/demo/math-streaming/)
```html
```
Formulas drawn as the reply streams; the prices stay text. ## Install and register [Section titled “Install and register”](#install-and-register)
```bash
npm install @aparte/plugin-katex katex
```
```ts
import 'katex/dist/katex.min.css';
import { setupKatex } from '@aparte/plugin-katex';
setupKatex();
```
A formula is drawn by [KaTeX](https://katex.org), loaded on the first one. Its stylesheet is yours to import, because its fonts are relative URLs your bundler resolves; without it each formula shows twice, and the plugin says so once in the console. ## Which Markdown provider [Section titled “Which Markdown provider”](#which-markdown-provider) Maths is recognised by the Markdown provider, before Markdown can read it: to Markdown, `\,` is an escape and `a*b*c` is emphasis. [`@aparte/plugin-marked`](/guides/markdown/), streaming or not, and `@aparte/plugin-streaming-markdown` do it on their own once `setupKatex()` has run — nothing else to configure. To keep dollars as text whatever is registered, pass `math: false` to the marked provider. Both read maths by the rules in the table below; they differ in when a formula appears while the reply streams. `@aparte/plugin-marked/streaming` draws a `$$`, `\[` or `\(` formula as it arrives, and a single `$` once it closes. `@aparte/plugin-streaming-markdown` draws a display formula opened by `$$` or `\[` on its own line as it arrives, and any other once its closer has come. The finished reply is drawn by the one-shot provider — marked, in the [recommended setup](/guides/markdown/). A provider of your own hands maths over by writing the markup remark-math already writes: `TeX` inline, and `TeX ` for a block. ## What counts as maths [Section titled “What counts as maths”](#what-counts-as-maths) | written | drawn as | | ------------------------------------------------------------- | -------- | | `$x^2$`, `\(x^2\)` | inline | | `$$x^2$$`, `\[x^2\]`, on their own lines or inside a sentence | display | | `$5 and $10` | text | A single `$` follows Pandoc’s rule: a character right after the opening `$`, one right before the closing `$`, and no digit right after it. A price stays a price. Code always wins: a `$` in backquotes or a fence is code. ## While the reply streams [Section titled “While the reply streams”](#while-the-reply-streams) A formula is drawn as it arrives. Half a formula — `\frac{1}{` — does not parse, so the last drawing that did stays on screen until the next one does, and nothing flashes red mid-stream. A single `$` is drawn only once it closes, since until then it could be a price. Once the reply is finished, a formula that still does not parse shows its TeX, quietly, with KaTeX’s message as a tooltip. ## What a model cannot do with it [Section titled “What a model cannot do with it”](#what-a-model-cannot-do-with-it) `trust` is always off, so a formula cannot carry a link (`\href`) or set a class or a style (`\htmlClass`); `maxSize` and `maxExpand` are capped, so a size cannot pass 10em and a macro cannot expand forever; KaTeX does not cap a negative shift, so a formula taller than 100em — `\raisebox{-10000em}{x}`; a 30-row matrix is under 40 — shows as its TeX; every formula is painted inside its own box, so `\smash`, `\raisebox` or a negative `\kern` cannot lay one over the chat around it; and every formula gets a fresh set of `macros`, so a `\gdef` in one reply cannot reach the next. KaTeX’s own options pass through `setupKatex({ katex: { … } })`; these are kept whatever they say. ## Bring your own KaTeX [Section titled “Bring your own KaTeX”](#bring-your-own-katex) `@aparte/plugin-katex/core` imports nothing from `katex`: hand it the instance, or a function that loads it.
```ts
import katex from 'katex';
import { setupKatexWith } from '@aparte/plugin-katex/core';
setupKatexWith(katex, { live: false });
```
`KatexOptions` takes `live` (`false` draws a formula once it has closed), `katex` and `maxLength`. Any object shaped like `KatexLike` will do. Both setups return a function that removes the renderer. ## Next [Section titled “Next”](#next) * [Diagrams Mermaid fences drawn as they stream.](/guides/diagrams/) * [Markdown and code The providers that recognise maths, and the rest of a reply.](/guides/markdown/)
# Migrate from chatscope to aparté
> Move an AI chat built on @chatscope/chat-ui-kit-react to aparté — what each component becomes, how the message model maps, and how to keep your own backend or stream a model.
`@chatscope/chat-ui-kit-react` is a kit for chats between people: you assemble the components, and the messages and the sending stay in your code. If you built an AI chat on it, `` from `@aparte/react` is the whole chat in one component, and it draws what a model’s reply needs: tokens as they stream, tool calls, reasoning. You can move in two steps: change the view and keep your own backend call, then stream the reply. ## Swap the packages [Section titled “Swap the packages”](#swap-the-packages)
```bash
npm uninstall @chatscope/chat-ui-kit-react @chatscope/chat-ui-kit-styles
npm install @aparte/react @aparte/core
```
## Change the view, keep your backend call [Section titled “Change the view, keep your backend call”](#change-the-view-keep-your-backend-call) A typical chatscope chat holds the messages and the typing flag itself:
```jsx
import { useState } from 'react';
import '@chatscope/chat-ui-kit-styles/dist/default/styles.min.css';
import { MainContainer, ChatContainer, MessageList, Message, MessageInput, TypingIndicator } from '@chatscope/chat-ui-kit-react';
export function Chat() {
const [messages, setMessages] = useState([]);
const [typing, setTyping] = useState(false);
async function send(_html, text) {
setMessages((m) => [...m, { message: text, direction: 'outgoing', position: 'single' }]);
setTyping(true);
const answer = await askMyServer(text);
setMessages((m) => [...m, { message: answer, direction: 'incoming', position: 'single' }]);
setTyping(false);
}
return (
: null}>
{messages.map((m, i) => )}
);
}
```
With aparté, the person’s message is added for you and the waiting dots show until the first word:
```tsx
import { useCallback } from 'react';
import { uuid } from '@aparte/core';
import { AparteChat, useAparteChat } from '@aparte/react';
import '@aparte/core/styles.css';
async function* reply(text: string) {
yield await askMyServer(text);
}
export function Chat() {
const chat = useAparteChat();
const onMessageSent = useCallback(async (event: { content: string }) => {
const id = uuid();
chat.ref.current?.appendMessage({ id, role: 'assistant', content: '', timestamp: Date.now() });
await chat.ref.current?.injectTokenStream(id, reply(event.content));
}, [chat.ref]);
return (
);
}
```
## What each part becomes [Section titled “What each part becomes”](#what-each-part-becomes) | chatscope | aparté | | --------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | `MainContainer`, `ChatContainer`, `MessageList`, `MessageInput` | ``, in a parent with a height | | `Message` and its `model` | an `AparteMessage` in `messages` | | `direction: 'outgoing'`, `'incoming'` | `role: 'user'`, `'assistant'` | | `message` | `content`, drawn as Markdown once a [renderer](/guides/markdown/) is set up | | `sentTime`, a string | `timestamp`, a number such as `Date.now()` | | `position` | not needed | | `type: 'custom'` and `payload` | `renderBubble(message)` | | `TypingIndicator` | built in, while a reply has no words yet | | `MessageInput`’s `onSend` | `onMessageSent`; it receives `event.content` | | `MessageInput`’s `attachButton` | the `attachments` prop ([Attachments](/guides/attachments/)) | | `InputToolbox` | the `toolbar` prop | | `Avatar` on a message | [`setAvatarProvider()`](/guides/customization/icons-and-avatars/) | | `ConversationHeader` | the [header](/components/header/) | | `Sidebar` | [``](/components/sidebar/) | | `ConversationList`, `Conversation` | [``](/components/conversation-list/) | | `@chatscope/use-chat` | `useAparteChat`, and [conversation persistence](/guides/conversation-persistence/) | | `MessageSeparator` | no equivalent in the transcript | | `onYReachStart`, `loadingMore` | no equivalent: you give the messages up front | ## Styles [Section titled “Styles”](#styles) `@chatscope/chat-ui-kit-styles` is replaced by `@aparte/core/styles.css`. Where you set Sass variables, set CSS variables instead ([Theme](/guides/theming/)):
```css
:root {
--aparte-primary: #b45309;
--aparte-bg: #fbf7f0;
--aparte-text: #241a12;
}
```
## Stream the reply [Section titled “Stream the reply”](#stream-the-reply) `injectTokenStream` takes any async iterable, so a server that streams text only changes `reply`:
```ts
async function* reply(text: string) {
const res = await fetch('/api/chat', { method: 'POST', body: text });
const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) return;
yield value;
}
}
```
## Or let aparté call the model [Section titled “Or let aparté call the model”](#or-let-aparté-call-the-model) If you have no loop worth keeping, remove `onMessageSent` and start a client. Register a provider ([Connect a model](/providers/)), or keep the key on your server ([Key on your server](/guides/backend-transport/)):
```tsx
import { AparteChat, useAparteClient } from '@aparte/react';
import '@aparte/core/styles.css';
export function Chat() {
useAparteClient();
return ;
}
```
## When to stay on chatscope [Section titled “When to stay on chatscope”](#when-to-stay-on-chatscope) aparté draws one person talking to an assistant: a message is `user` or `assistant`, and has no sender. For a chat between several people, with a name on each message, chatscope fits better.
# Run the agent loop on your server
> Run the agent loop next to your tools — a handler on your server, a runner in the page — with approvals that cross the network and survive a reload, and browser tools that still run in the page.
Your tools live on your server — files, a database, secrets — and the model has to call them. With the loop on the server, next to them, there is nothing to expose, and the page keeps its tool rows, Stop, the approval panel and your approval policy. To keep only the key off the browser, the [backend transport](/guides/backend-transport/) is enough; to drive the chat from a loop of your own, see [Your own loop](/guides/bring-your-own-loop/). ## The server [Section titled “The server”](#the-server)
```ts
// app/api/agent/route.ts (Next.js)
import { createAparteAgentHandler } from '@aparte/core';
import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat';
export const POST = createAparteAgentHandler({
providers: { openai: createOpenAICompatProvider(presets.OPENAI) },
defaultModel: 'gpt-4.1-mini', // when the page selects none
resolveKey: () => process.env.OPENAI_API_KEY,
authorize: (req) => isSignedIn(req), // required: this route spends your key
secret: process.env.AGENT_SECRET!, // required, 32+ characters
tools: [{
tool: {
name: 'read_file',
description: 'Read a file from the site content.',
inputSchema: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
},
handler: readFileHandler,
}],
});
```
`createAparteAgentHandler` returns a Fetch handler, `Request` to `Response`, for a Next.js route in the Node runtime, Deno, Bun, a Cloudflare Worker, a Vercel edge route, or Node behind a small adapter — runtimes that resolve `@aparte/core` to its entry without a DOM ([On the server](/frameworks/elements/#on-the-server)). `authorize` returns `false`, for a 401, or a `Response` of its own. `secret` signs the calls a paused run leaves pending; an array rotates it, the first signing and all verifying. | Option | What it does | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `approvalPolicy` | rules on each call, as `setApprovalPolicy` does in the page | | `clientTools` | whether the page’s own tools are accepted: `true` (the default), `false`, or a list of names | | `prepareRequest(request, req)` | rewrites the request before the run, on every request a resume included: a model, a temperature, a system prompt. A tool you remove from `request.tools` does not run, even if the model names it | | `allowedOrigins` | the origins of your pages, such as `['https://app.example.com']`: a request from any other `Origin` is refused with a 403, before `authorize` | | `maxTurns`, `toolTimeoutMs` | the model’s turns in one run, ten by default — a resume after a pause counts again — and a tool’s time, five minutes by default; a tool’s own `maxTurns` applies too | | `ticketMaxAgeMs` | how long a paused run can wait, seven days by default | | `onTicket(id)` | a check on each resume; `false` refuses it with a 409 | | `transport` | how the server calls the model, `new AparteDirectTransport({ byok: true })` by default | | `crypto` | the Web Crypto used to sign, for [Node 18](#node-18) | A page on another site can post to this route It does so with your visitor’s cookie, in a form that needs no preflight. The handler refuses any body not declared `application/json` with a 415, which such a form cannot send, before it calls `authorize`. For a cookie session also set `SameSite=Lax` or `Strict`, and list your pages in `allowedOrigins`. A tool that changes something still wants `needsApproval`. On Node’s own `http` server, hand it a `Request` and stream the `Response` back. Stop in the browser closes the connection, and the handler stops the run — the model call and any tool still running — when its request is aborted:
```ts
import { createServer } from 'node:http';
// handler = createAparteAgentHandler({ … }), as above
createServer(async (req, res) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk);
const closed = new AbortController();
res.on('close', () => closed.abort());
const response = await handler(new Request(`http://localhost${req.url}`, {
method: req.method, headers: req.headers as HeadersInit, body: Buffer.concat(chunks),
signal: closed.signal,
}));
res.writeHead(response.status, Object.fromEntries(response.headers));
if (response.body) for await (const chunk of response.body) res.write(chunk);
res.end();
}).listen(3000);
```
## The browser [Section titled “The browser”](#the-browser)
```ts
import { AparteClient, createAgentStreamRunner } from '@aparte/core';
const client = new AparteClient({
streamRunner: createAgentStreamRunner({
endpoint: '/api/agent',
headers: async () => ({ authorization: `Bearer ${sessionStorage.getItem('token') ?? ''}` }),
}),
});
client.start();
```
The runner sends each turn to your endpoint and replays the server’s events, which the page draws as it draws a loop run in the page. A function for `headers` is called for each request, which is where a fresh token goes, and `fetch` replaces the one it calls. `credentials: 'include'` sends cookies to another origin; the handler sets no CORS headers, so your route or proxy answers the preflight (`OPTIONS`) and adds `Access-Control-Allow-Origin` (the page’s origin) and `Access-Control-Allow-Credentials: true`. The page registers no provider: the server runs its only provider, on `defaultModel`. When the handler has several, the page names one by its key in `providers`:
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.setModelConfig({ defaultProvider: 'openai', defaultModel: 'gpt-4.1' });
```
A model the page selects with `setModelConfig` wins over `defaultModel`; `prepareRequest` runs after it. ## Approvals across the network [Section titled “Approvals across the network”](#approvals-across-the-network) A server tool with `needsApproval: true`, or a call the server’s `approvalPolicy` answers `ask`, suspends the run: the stream ends with the pending call and a signed ticket, the page asks with the [approval panel](/guides/tools/#require-approval-human-in-the-loop), and the answer resumes the run on the server, in the same reply. The server decides which calls need a person; the page answers, through the person or through its own approval policy, such as [`@aparte/plugin-approval`](/components/approval-mode/)’s modes. The server can also refuse outright, with no one asked:
```ts
createAparteAgentHandler({
// …
approvalPolicy: (call) => (call.name === 'delete_file' ? { verdict: 'deny', reason: 'Not from the website.' } : undefined),
});
```
The person can leave and come back: nothing is stored on the server, the paused call lives in the conversation you already save. A [conversation manager](/guides/conversation-persistence/) saves the reply when the run pauses — the chat sends `aparte-message-paused` — and when it opens a conversation whose last reply is paused, the panel comes back. Saving another way, listen for `aparte-message-paused` on the chat — it bubbles — and save the message as it is, its segments included, since the paused call and its ticket are in them; after `setMessages`, call `await client.resumeDeferred()`. A new message sent instead of an answer closes the paused call. ## Browser tools [Section titled “Browser tools”](#browser-tools) A tool that needs the page stays registered in the page: `setupAskUser()` registers [`ask_user`](/components/question/), and `registerTool` your own. The runner sends its definition along; the server lets the model call it, pauses on it, and the page runs its handler and sends the result back. Before it runs, the page gates it exactly as its own loop would: a `needsApproval` tool puts the approval panel up, the approval policy can allow or refuse it, and a refusal goes back to the server as the call’s answer, which the model reads; the row says who refused it (`You said: “…”`, `Refused by policy`) in the person’s language. To refuse browser tools, or accept a list of them:
```ts
createAparteAgentHandler({
// …
clientTools: ['ask_user'], // or false
});
```
A browser tool may not share a server tool’s name: the request is refused. ## Open a file in the page when a server tool runs [Section titled “Open a file in the page when a server tool runs”](#open-a-file-in-the-page-when-a-server-tool-runs) To have the page do something when a call runs — open a file in the editor beside the chat — without a pause, make the tool a server tool that answers by itself, with what the page needs in its `structuredContent`, and act in the page when its call resolves:
```ts
createAparteAgentHandler({
// …
tools: [{
tool: {
name: 'open_file',
description: 'Open a file in the editor beside the chat.',
inputSchema: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
},
handler: async (call) => ({ toolCallId: call.id, content: 'opened', structuredContent: { openFile: String(call.input.path) } }),
}],
});
```
```ts
import { AparteClient, createAgentStreamRunner } from '@aparte/core';
import type { AparteStreamRunner } from '@aparte/core';
declare function openFile(path: string): void; // your page's own code
const runner = createAgentStreamRunner({ endpoint: '/api/agent' });
const openingFiles: AparteStreamRunner = (opts) => runner({
...opts,
emitter: (event) => {
if (event.type === 'tool-resolved') {
const result = event.structuredResult as { openFile?: string } | undefined;
if (result?.openFile) openFile(result.openFile);
}
opts.emitter(event);
},
});
new AparteClient({ streamRunner: openingFiles }).start();
```
`tool-resolved` arrives once the server tool has succeeded, a call resumed after a pause included, so a failed call opens nothing. A conversation opened later draws its finished calls from its history and runs none of them, so the file is not opened again. The same wrapping works on any runner. ## What the ticket protects, and what it does not [Section titled “What the ticket protects, and what it does not”](#what-the-ticket-protects-and-what-it-does-not) The ticket is a signature over the pending calls: a resume runs only calls this server emitted, for the reply it paused. Three things it does not do: * **It does not make a tool’s input safe.** The model chose the arguments; a tool checks the caller’s rights itself. Its handler gets the request being served as `context.request` — for a call answered after a pause, the request that resumed the run. * **It does not prove a person approved.** The browser sends the decision, so a caller holding the ticket can approve any call it names: `needsApproval` asks a person, and the handler still checks the caller’s rights. * **It is not single-use.** A server that stores nothing cannot tell a replay from a first use; if yours can, `onTicket` refuses a ticket it has seen.
```ts
createAparteAgentHandler({
// …
onTicket: async (id) => {
if (await seen.has(id)) return false; // replayed: refused with a 409
await seen.add(id);
return true;
},
tools: [{
tool: {
name: 'delete_file',
description: 'Delete a file.',
inputSchema: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
needsApproval: true,
},
handler: async (call, signal, context) => {
const user = await userOf(context?.request);
const path = String(call.input.path);
if (!user?.canWrite(path)) return { toolCallId: call.id, content: 'You cannot delete this file.' };
await removeFile(path, { signal });
return { toolCallId: call.id, content: `Deleted ${path}.` };
},
}],
});
```
An approval’s `payload` — data an approval surface merges into the arguments — is dropped unless the tool opts in with `acceptsApprovalPayload: true`. ## Node 18 [Section titled “Node 18”](#node-18) The ticket is signed with Web Crypto, which browsers, Node 19 and later, Deno, Bun and Workers have. On Node 18, pass it in:
```ts
import { webcrypto } from 'node:crypto';
createAparteAgentHandler({
// …
crypto: webcrypto.subtle as SubtleCrypto,
});
```
## The wire [Section titled “The wire”](#the-wire) NDJSON, one event per line: the [engine’s run events](/guides/engine/) as they are, a `run-suspended` line carrying the `ticket`, and a `run-error` line, never the vendor’s own words, when the run fails after the stream began. A server tool that throws ends the run: the page shows the call as failed — `The tool failed.` — then the reply fails, and the error itself goes to your server’s log; to let the model read a failure and go on, return it as `content`. An error before the stream is JSON with an HTTP status. The body is `{ v: 1, providerId?, messageId, request, clientTools, resume? }`, which the runner builds. Among the 400s, two concern tools: a `toolChoice` that names a tool, and a history ending on unanswered calls with no `resume` ticket.
# Theme the chat to your brand, in light and dark
> Restyle the whole chat with CSS variables — your brand colours, light and dark, density and shape — on the page, on one part of it, or on one chat.
[The chat in a brand of its own](/preview/demo/theme-brand/)
```html
```
Eight variables on a wrapper, and every part of the chat follows them. ## Set your brand colours [Section titled “Set your brand colours”](#set-your-brand-colours)
```css
:root,
[data-aparte-theme="light"] {
--aparte-primary: #b45309; /* the accent: send button, links, the user's bubble */
--aparte-primary-hover: #92400e;
--aparte-bg: #fbf7f0; /* your page's background */
--aparte-surface-1: #ffffff; /* cards, code blocks, the composer */
--aparte-surface-2: #f4ece0; /* headers, inline code */
--aparte-text: #241a12;
--aparte-text-muted: #7c6f60;
--aparte-border: #e7dccb;
}
```
The chat’s colours follow these eight: 244 of core’s variables read another one, such as `--aparte-input-bg`, which is `var(--aparte-surface-1)`, or `--aparte-avatar-bg-user`, which is `var(--aparte-primary)`. Set the bases, not each value they feed. The block wins whichever stylesheet loads first, and its second selector keeps it on an element [forced light](#light-and-dark). A few do not follow them. The status colours — `--aparte-info`, `--aparte-success`, `--aparte-warning`, `--aparte-error` — and `--aparte-secondary` are yours to set in the same block if your brand has an opinion, and so is `--aparte-neutral`, which draws the focus ring, the scrollbar and the neutral buttons. The chat paints `--aparte-bg` behind itself and writes in `--aparte-text`, so its text always sits on the ground it was chosen for. Set `--aparte-bg` to your page’s colour and the chat blends into the page; to let the page show through instead, write `aparte-chat, [data-aparte-chat] { background: none; }`, and your page then has to follow the chat’s theme. ### The text on a fill [Section titled “The text on a fill”](#the-text-on-a-fill)
```css
:root,
[data-aparte-theme="light"] {
--aparte-primary: #1a1a2e;
--aparte-on-primary: #f8fafc;
}
```
The label on a filled button, badge or checkbox is worked out from the fill’s lightness, so it stays readable whatever colour you choose. Set its pair to choose it yourself: `--aparte-on-primary`, `--aparte-on-secondary`, `--aparte-on-neutral`, `--aparte-on-info`, `--aparte-on-success`, `--aparte-on-warning` and `--aparte-on-error`. Two numbers tune the worked-out ink: `--aparte-ink-flip`, the fill lightness where it turns from light to dark, and `--aparte-ink-dark`, how dark it gets. ## Light and dark [Section titled “Light and dark”](#light-and-dark)
```html
…
```
With no attribute, the system’s `prefers-color-scheme` decides. `data-aparte-theme` forces either way, on the chat or on any ancestor, so a light panel inside a dark page stays light. The attribute puts core’s palette on the element that carries it, which is why your light block names `[data-aparte-theme="light"]` beside `:root`. Whichever palette applies, the chat paints its own ground with it: a dark chat on a white page is a dark panel, never light text on white. A site that is light only puts `data-aparte-theme="light"` on `` — with no attribute, a visitor whose system is dark gets the dark palette. ## Give dark its own colours [Section titled “Give dark its own colours”](#give-dark-its-own-colours)
```css
/* light */
:root,
[data-aparte-theme="light"] {
--aparte-primary: #087ea4;
/* …the rest of your light palette */
}
/* dark, when your toggle sets the attribute */
[data-aparte-theme="dark"] {
--aparte-primary: #58c4dc;
/* …the same tokens, in dark */
}
/* dark, when the system decides */
@media (prefers-color-scheme: dark) {
:root:not([data-aparte-theme="light"]) {
--aparte-primary: #58c4dc;
/* …the same tokens, in dark */
}
}
```
Without a dark block, a dark system shows core’s dark palette rather than your light colours. Give each dark block every token your light block sets. Core’s dark palette has a value for the eight, `--aparte-neutral`, the shadows, the scrim behind dialogs and the error colours (`--aparte-error-bg`, `--aparte-error-text`, `--aparte-error-border`, `--aparte-error-solid`), and any of those you leave out takes core’s dark value rather than yours. Keep the selector of the third block as it is: a bare `:root` inside the media query loses to core’s dark palette. ## Theme one chat, or part of the page [Section titled “Theme one chat, or part of the page”](#theme-one-chat-or-part-of-the-page)
```html
```
A variable set on an element reaches everything inside it: one [chat](/components/chat/), a sidebar, a section of the page. A token that reads another one, such as `--aparte-avatar-bg-user` or `--aparte-radius-bubble`, is worked out again on every `aparte-chat`, every `[data-aparte-chat]` root the React, Vue and Svelte components render, and every `[data-aparte-theme]` element, so a chat given its own `--aparte-primary` gets its own user bubble and avatar too. The same rule stops a value you give such a token on `:root` at the chat: set it on the chat, in a rule with a class as above, which outweighs core’s own declaration there whatever order the stylesheets load in. The [CSS variables](/reference/css-variables/) reference marks those tokens **anchored**. In React, Vue and Svelte, the chat’s root is a ``, and the same tokens are worked out again there: give it a class and write `[data-aparte-chat].sales { … }`. ## Make it denser, squarer or larger [Section titled “Make it denser, squarer or larger”](#make-it-denser-squarer-or-larger)
```css
:root {
--aparte-space-unit: 1.5px; /* every gap and padding, tighter */
--aparte-radius-unit: 2px; /* every corner, squarer */
--aparte-font-scale: 1; /* every text size, a notch smaller */
--aparte-btn-size-md: 28px; /* the medium control, and every size read from it */
}
```
The sizes are scales, each a base times a step, so one base moves a whole family: | Scale | Tokens | Base | | -------- | --------------------------------------------------- | ---------------------- | | Spacing | `--aparte-space-1` … `--aparte-space-8` | `--aparte-space-unit` | | Corners | `--aparte-radius-xs` … `--aparte-radius-xl` | `--aparte-radius-unit` | | Text | `--aparte-font-size-2xs` … `--aparte-font-size-2xl` | `--aparte-font-scale` | | Controls | `--aparte-btn-size-sm`, `-md`, `-lg`, `-xl` | each its own | `--aparte-radius-full`, the pill, stays a pill whatever the unit. A single step can be set too, on the chat with a class: `aparte-chat.chat { --aparte-space-6: 8px; }` pulls in the paddings that use it and leaves the rest of the scale alone. The kit’s controls read the same tokens, so a page of [buttons](/components/button/) and [fields](/components/field/) moves with the chat. ## Small recipes [Section titled “Small recipes”](#small-recipes) They set tokens on `
`. In React, Vue and Svelte, give the chat’s root the class with `className` and write `[data-aparte-chat].chat`. ### Give the assistant a bubble too [Section titled “Give the assistant a bubble too”](#give-the-assistant-a-bubble-too)
```css
aparte-chat.chat {
--aparte-message-content-bg-assistant: var(--aparte-surface-2);
--aparte-message-content-padding-assistant: var(--aparte-message-content-padding);
}
.aparte-message[data-role="assistant"] .aparte-message-content { width: fit-content; }
```
The assistant’s reply is plain text across the column by default, and only the person’s words sit in a bubble. The two tokens give the reply a ground and the user bubble’s padding; the rule makes it hug its text. `--aparte-message-content-text-user` and `-assistant` colour each side’s words, and fall back to `--aparte-content-color`. ### Resize the composer [Section titled “Resize the composer”](#resize-the-composer)
```css
aparte-chat.chat { --aparte-composer-control-size: 52px; }
```
The input’s height and every button in the composer follow it. On a touch screen they take `--aparte-touch-target-size` instead. ### Change the code font [Section titled “Change the code font”](#change-the-code-font)
```css
:root { --aparte-code-font-family: 'JetBrains Mono', ui-monospace, monospace; }
```
### Mark a row as chosen [Section titled “Mark a row as chosen”](#mark-a-row-as-chosen)
```css
:root {
--aparte-mark-tint: 12%; /* a quieter ground, for marked rows and the user's bubble */
--aparte-mark-bar: 3px; /* a bar on the start edge, which has none by default */
}
```
```html
Chosen
Accepted
Declined
```
The [mark](/components/mark/) is how the chat shows what was chosen: a select’s option, a checked choice in a question, the answer a question kept. The same class marks a row of yours. `--success`, `--danger` and `--neutral` change the intent; `--quiet` is the one that did not happen, with no tint and muted text. ### Type a theme in TypeScript [Section titled “Type a theme in TypeScript”](#type-a-theme-in-typescript)
```ts
import type { AparteThemeVariables } from '@aparte/core';
export const brand: AparteThemeVariables = {
'--aparte-primary': '#b45309',
'--aparte-surface-1': '#ffffff',
};
for (const [name, value] of Object.entries(brand)) {
if (value) document.documentElement.style.setProperty(name, value);
}
```
A key that does not start with `--aparte-` is a compile error. The name after the prefix is not checked, which is what the next recipe is for. ### Check that every token you use exists [Section titled “Check that every token you use exists”](#check-that-every-token-you-use-exists) A `var(--aparte-text-primary)` that names a token the library does not have fails without a word: the property falls back to its inherited or initial value, and the page looks almost right. The stylesheet you import names every token it declares or reads, so a script can check your CSS against it:
```js
// aparte-tokens.mjs — node aparte-tokens.mjs src/**/*.css
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
const sheet = readFileSync(createRequire(import.meta.url).resolve('@aparte/core/styles.css'), 'utf8');
const known = new Set(sheet.match(/--aparte-[\w-]+/g));
let bad = 0;
for (const file of process.argv.slice(2)) {
for (const name of new Set(readFileSync(file, 'utf8').match(/--aparte-[\w-]+/g) ?? [])) {
if (!known.has(name)) { bad++; console.log(`${file}: ${name} is not an @aparte/core token`); }
}
}
process.exit(bad ? 1 : 0);
```
Run it with your tests. A name it reports that you declared yourself is fine, though a token of your own reads better under a prefix of your own. ## Inside a shadow root of your own [Section titled “Inside a shadow root of your own”](#inside-a-shadow-root-of-your-own) Load `@aparte/core/styles.css` inside the shadow root — a ` ` in it, or `adoptedStyleSheets` — since a document’s stylesheet does not cross into it. The stylesheet declares its tokens on `:host` as well as `:root`, so the chat themes the same way: set the variables on the host or on any element inside, and put `data-aparte-theme` on the host itself, since an attribute on an element outside the shadow root does not reach the chat. `` and `` look their partner up in the document; inside a shadow root, put them in the chat and leave `target` out. ## Next [Section titled “Next”](#next) * [Customization Past colours and sizes: your own icons, avatars, buttons and parts of a message.](/guides/customization/) * [CSS variables Every token, its default, and whether it is anchored.](/reference/css-variables/) * [Layouts A reading column, a full-width feed, a side panel, a floating composer.](/guides/layout/) * [The kit The controls around the chat, in the same theme.](/kit/)
# Give each conversation a short title
> Title conversations from their first message — with a small model that runs in the browser, or with your own titling on a server or a model.
## When a title is decided [Section titled “When a title is decided”](#when-a-title-is-decided) A conversation in a [manager](/guides/conversation-persistence/) takes its title from the person’s first message, written as they typed it — even over a title the conversation was created with. Editing that message gives it a new title while the title is still the manager’s, which `autoTitle: true` says. A title typed in after that, through `updateTitle` or the list’s rename, is never replaced; the list renames through the manager when it has `manage`, or when you answer its `aparte-conversation-rename`. A title provider replaces the “as typed” part: it gets the message and answers a short title. ## Title in the browser [Section titled “Title in the browser”](#title-in-the-browser)
```bash
npm install @aparte/plugin-titler @aparte/titler-latin
```
```ts
import { aparteGlobalConfig } from '@aparte/core';
import { loadTitler } from '@aparte/titler-latin';
import modelUrl from '@aparte/titler-latin/model?url';
import { setupTitler } from '@aparte/plugin-titler';
const manager = aparteGlobalConfig.getConversationManager(); // the one your chat saves to
if (manager) setupTitler(manager, { titler: () => loadTitler(modelUrl) });
```
The model reads the first message in the browser, with no API call, and picks the words that make the title: it copies them in the message’s order and does not rephrase. `loadTitler` runs once, the first time a conversation needs a title, and fetches the model file from your own site; a load that fails is tried again on the next title. The `?url` import is Vite’s way of serving the package’s model file; with another bundler, copy the `.bin` from the package’s `model` folder into what you serve and give `loadTitler` its path. Run the setup once the manager is registered — after `setConversationManager`, or once a framework helper’s `init` has resolved. Left to its default, the model keeps among its six best-scored words those it is confident about, never fewer than three, and every word of a short message. `budget: 4` keeps exactly four of its best-scored words instead. `setupTitler` returns the function that gives the manager back its previous provider, unless another was set since. [Try the model](/models/titler/#demo) on its own page. ## Pick a model [Section titled “Pick a model”](#pick-a-model) | Package | Reads | Model file | | --------------------------- | -------------------------------------------------------------------------------- | ---------- | | `@aparte/titler-latin` | 17 languages: en, fr, es, de, pt, it, nl, pl, sv, da, fi, cs, ro, no, hu, hr, lt | 133 KB | | `@aparte/titler-latin-mini` | the same 17, with a smaller vocabulary | 96 KB | | `@aparte/titler-efigsp` | 6 languages: en, fr, es, de, pt, it | 77 KB | For a model file of your choice, download a `.bin` from the [model repository](https://huggingface.co/apartejs/aparte-titler), serve it from your site, and give its bytes to the runtime alone, `@aparte/titler`:
```ts
import type { AparteConversationManager } from '@aparte/core';
import { loadTitler } from '@aparte/titler';
import { setupTitler } from '@aparte/plugin-titler';
declare const manager: AparteConversationManager;
const bytes = (url: string): Promise =>
fetch(url).then((r) => {
if (!r.ok) throw new Error(`${url}: ${r.status}`);
return r.arrayBuffer();
});
setupTitler(manager, { titler: () => loadTitler(bytes('/models/titler-fr.bin')) });
```
## Title your own way [Section titled “Title your own way”](#title-your-own-way)
```ts
import type { AparteConversationManager } from '@aparte/core';
declare const manager: AparteConversationManager;
manager.setTitleProvider(async (text) => {
const response = await fetch('/api/title', { method: 'POST', body: text });
return response.ok ? response.text() : '';
});
```
A title provider gets the message’s text and the message, and answers a title, at once or as a promise: a request to your server, a call to a model, a rule of yours. An empty answer, or an error, keeps the message as typed, and an error is logged. `setTitleProvider(null)` puts the default back. ## Without a setup call [Section titled “Without a setup call”](#without-a-setup-call)
```ts
import { AparteConversationManager, type AparteStorageAdapter } from '@aparte/core';
import { loadTitler } from '@aparte/titler-latin';
import modelUrl from '@aparte/titler-latin/model?url';
import { createTitleProvider } from '@aparte/plugin-titler';
declare const adapter: AparteStorageAdapter;
const manager = new AparteConversationManager(adapter, {
titleProvider: createTitleProvider({ titler: () => loadTitler(modelUrl) }),
});
```
`createTitleProvider` is the provider alone, for a manager you build with one. Its options are a `TitlerOptions`, and any object with `title(message, budget?)` — a `TitlerLike` — can be the `titler`. ## Next [Section titled “Next”](#next) * [aparte-titler The model, running in your browser, and the numbers behind it.](/models/titler/) * [Save conversations The manager the titles are written to, and the list that shows them.](/guides/conversation-persistence/) * [Conversation list The sidebar list, with each conversation under its title.](/components/conversation-list/)
# Showing tool calls to a person, or to a developer
> Name your tools in words, give them icons, keep the raw JSON from a person or put a detail of your own behind the line, hide the calls a consumer chat does not need, or open every row with raw input and output for a developer — with registerToolDisplay.
A tool call is drawn as a row that names the tool by its identifier, `web_search` or `delete_file`, because that is all core knows: the identifier is your wire format, and core never turns it into words. Who reads the row decides what it should say. A person asking a question wants “Searching the web”; a developer watching an agent wants the raw input and output, open. Both are one call, `registerToolDisplay(match, display)`.
```ts
import { aparteGlobalConfig } from '@aparte/core';
import type { AparteToolDisplay } from '@aparte/core';
const display: AparteToolDisplay = {
label: 'Web search', // in place of web_search
icon: 'search', // an icon-provider key
summary: (segment) => String(segment.toolCall.input['query'] ?? ''),
formatInput: (input) => String(input['query'] ?? ''),
hidden: false, // true draws nothing
open: false, // true opens the row
// details: false // the line alone; or a function that draws what is behind it
};
aparteGlobalConfig.registerToolDisplay('web_search', display);
```
Every field is optional, and what you leave out keeps core’s row. ## A consumer chat [Section titled “A consumer chat”](#a-consumer-chat) The person asked a question; what matters is the answer. Hide every call by default, then describe the few that are worth a line.
```ts
import { aparteGlobalConfig } from '@aparte/core';
import type { AparteToolCallSegment } from '@aparte/core';
import { searchIcon, globeIcon } from '@aparte/core/icons';
aparteGlobalConfig.registerIcons({ search: () => searchIcon, globe: () => globeIcon });
// The label's tense says where the call is, so the quiet line (the default) needs no "Running"
// and no "Done":
// running, done, and a plain name for the rest (a wait for approval, a refusal, a failure).
const tense = (running: string, done: string, name: string) => (segment: AparteToolCallSegment) =>
segment.status === 'pending' ? running : segment.status === 'resolved' ? done : name;
// Every tool nothing more specific describes: no row. A tool with an entry of its own
// (below) is described whole by it, so it is not hidden.
aparteGlobalConfig.registerToolDisplay('*', { hidden: true });
aparteGlobalConfig.registerToolDisplay('web_search', {
label: tense('Searching the web…', 'Searched the web', 'Search the web'),
icon: 'search',
summary: (segment) => `“${String(segment.toolCall.input['query'] ?? '')}”`,
details: false, // the line alone: no raw JSON behind it
});
aparteGlobalConfig.registerToolDisplay('fetch_page', {
label: tense('Reading a page…', 'Read a page', 'Open a page'),
icon: 'globe',
summary: (segment) => String(segment.toolCall.input['url'] ?? ''),
details: false,
});
```
[Tools named in words, with an icon](/preview/demo/tool-display/)
```html
```
Labels, icons and summaries on three tools. What the person sees: * **A label** in the chat’s own font, in place of the identifier: “Searching the web…” while it runs, “Searched the web” once done, “Search the web” when it waits for approval or failed. The identifier stays on the row as `data-tool-name`, for a stylesheet or a test. * **A quiet line**, the default: the label [shimmers](/components/shimmer/) while the call runs, and nothing marks success once it is done. A wait for approval, a refusal, a failure and a stop still show their word and their note. The target is set in the chat’s font and the chevron sits at the end of the line. `quiet: false` gives an agent’s row instead, with a spinner and “Running”, then “Done”. * **An icon** from the icon provider. `file`, `edit` and `terminal` are core’s; `search` and `globe` are in `@aparte/core/icons`, and are drawn once you register them as above. A key nobody registered falls back to `tool`. * **A summary**, the line after the label, as before. * **No raw JSON** behind the two lines: `details: false` keeps the line alone, with nothing to open. Each described tool says it, since an entry is used whole; a list of sources or any other detail of your own is in [what’s behind the line](#whats-behind-the-line). * **No row** for every other tool: they fall to the `'*'` entry. The two described tools are not hidden although they never say so, because an entry is used whole (see [how a display is matched](#how-a-display-is-matched)). A turn made only of hidden calls shows no header either, just the reply. [A chat where only the reply shows](/preview/demo/tool-hidden/)
```html
```
A '\*' hide: the calls happened, and the reply is all the person sees. Hiding is a matter of the screen only. A hidden call stays in the message, in storage, and in the history the model reads on its next turns; a reload draws it hidden again. An approval it needs is still asked, and the question names it by its label and summary, so the person is never asked about something they cannot see described. The default question is `Allow {tool}?`, so “Allow Search the web?”; it is the built-in approval channel’s (`AparteClient`’s), and an app with its own loop writes its own. `extendLocale({ approvalAsk: … })` changes the wording. Registering a display notifies the chats on the page. One that changes a label, an icon or a summary relabels the rows already drawn, keeping what the reader opened; one that sets or drops `hidden`, `open`, `details` or `quiet` redraws the messages already on screen. A `label` can be a function of the segment, for a label that depends on the call:
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.registerToolDisplay('delete_file', {
label: (segment) => (segment.status === 'resolved' ? 'Deleted a file' : 'Delete a file'),
});
```
A label that throws, or is empty, falls back to the identifier. ## What’s behind the line [Section titled “What’s behind the line”](#whats-behind-the-line) An opened row shows **Input** and **Output**: the arguments and the result, raw. That is right for a developer and wrong for a person. `details` decides what is behind the line: * left out, Input and Output, as in [a developer’s view](#a-developers-view); * `false`, nothing: the line alone, with no disclosure, so `open` and a segment’s `collapsed` have nothing to open; * a function, what it returns, in place of Input and Output, under the same line.
```ts
import { aparteGlobalConfig } from '@aparte/core';
import type { AparteToolCallSegment } from '@aparte/core';
// A finished search shows the pages it found; nothing while it runs.
function sources(segment: AparteToolCallSegment): HTMLElement | string {
if (segment.status !== 'resolved') return '';
const list = document.createElement('ul');
for (const page of JSON.parse(segment.result ?? '[]') as { title: string }[]) {
const item = document.createElement('li');
item.textContent = page.title;
list.append(item);
}
return list;
}
aparteGlobalConfig.registerToolDisplay('web_search', { label: 'Searched the web', details: sources });
aparteGlobalConfig.registerToolDisplay('read_file', { label: 'Read a file', details: false });
```
[What is behind the line: nothing, or a detail of your own](/preview/demo/tool-details/)
```html
```
A read with nothing behind its line, and a search whose detail is the pages it found. The function: * is called when the row is drawn and on every update of the call, so it reads the status and the result as they land. An update replaces what it drew and leaves the row as open or as closed as the reader left it. * returns an element, or a string that core inserts as HTML after the [HTML sanitizer](/guides/markdown/), the one Markdown goes through: a script or an event handler that came in with the tool’s result is removed. Prefer the element all the same, or escape every value from the call with `escapeHtml`: the sanitizer keeps harmless markup, which can still mislead. * returns `''` when there is nothing behind the line yet. The row then has no disclosure, and gets one once the function returns something. * costs the row its detail if it throws. The line stays, and the raw Input and Output never come back in its place. A language switch asks the function again, so a detail written with [`t()`](/guides/localization/) follows the reader’s language like the line does. What it draws now is written into the nodes already there: unchanged, nothing is touched; the same shape with other words, only the words change, and the reader’s scroll and what they opened stay. Only a detail whose shape changed is replaced. The approval panel is not the row: a call that needs approval shows its arguments there, as JSON unless the tool has a `formatInput`. `hidden` wins over `details`, and a tool renderer draws the whole row instead. `details` is for keeping core’s line with a detail of your own. An entry is used whole, so `registerToolDisplay('*', { details: false })` keeps the raw JSON off every tool nothing more specific describes, and a tool with an entry of its own says its own `details`. ## A developer’s view [Section titled “A developer’s view”](#a-developers-view) The reader wants to see what the agent did: every call, open, with the input and output, its state in words, and how long it took.
```ts
import { aparteGlobalConfig, isSegmentSettled, segmentDuration } from '@aparte/core';
import type { AparteToolSummary } from '@aparte/core';
// Every row arrives open in a chat (the default is written onto each segment as it enters it).
// A row drawn by hand, as in the demo below, takes `open` from a display instead.
aparteGlobalConfig.setSegmentDefaults('tool_call', { collapsed: false });
// How long each call took, on the row's line; and an agent's row (`quiet: false`): a spinner and
// "Running", then "Done", where the default, quiet line says neither.
const took: AparteToolSummary = (segment) => {
const ms = segmentDuration(segment);
return isSegmentSettled(segment) && ms !== undefined ? `${(ms / 1000).toFixed(1)}s` : '';
};
aparteGlobalConfig.registerToolDisplay('*', { summary: took, quiet: false });
// Or open only the tools you are debugging. An entry is used whole, so it repeats the rest.
aparteGlobalConfig.registerToolDisplay('run_command', { open: true, summary: took, quiet: false });
```
[Tool rows opened by default](/preview/demo/tool-open/)
```html
```
Rows opened by default. The demo draws one bubble by hand, which never applies a segment default, so it opens them with a display's open. An opened row shows the arguments under **Input** and the result under **Output**, as the model and the tool wrote them (unless the tool has a `formatInput`, which then writes the Input): JSON is pretty-printed, and coloured when a [highlighter](/guides/markdown/) is registered; anything else stays as it is. Each part has a copy button, and a part longer than `--aparte-tool-part-max-height` (300px) scrolls in its own box, on the code surface at the small size. A refused call shows who refused it, as a note after the state word, and no Output. A row opens in this order: the segment’s own `collapsed` — which is where a `setSegmentDefaults` default lands, written onto the segment when it enters the message — else the display’s `open`, else closed. So a segment default wins over a display’s `open`. The choice is read when the row is drawn; an update never forces it, so a row the reader closed stays closed. The duration comes from the timing every segment carries: [Durations](/guides/customization/segment-timing/) explains it, and core draws none for a tool. A `summary` registered on `'*'` is used for every tool that has no entry of its own. A tool with its own entry gets that entry whole, and not the `'*'` one: add the summary there too, or register by pattern, below. ## How a display is matched [Section titled “How a display is matched”](#how-a-display-is-matched) `match` is one of three things: * an exact tool name, `'web_search'`; * a `RegExp`, tested against the name with `name.search(re)`, so `/^mcp__/` covers every tool an MCP server brings and a `g` flag is harmless; * `'*'`, every tool nothing more specific describes.
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.registerToolDisplay('*', { icon: 'tool' });
aparteGlobalConfig.registerToolDisplay(/^mcp__/, { icon: 'terminal', label: 'MCP tool' });
aparteGlobalConfig.registerToolDisplay('mcp__github__search', { label: 'GitHub search' });
aparteGlobalConfig.getToolDisplay('mcp__github__search'); // the exact entry: { label }
aparteGlobalConfig.getToolDisplay('mcp__slack__post'); // the pattern entry: { icon, label }
aparteGlobalConfig.getToolDisplay('read_file'); // the '*' entry: { icon }
```
Three rules: 1. **Exact name, else the first pattern registered that matches, else `'*'`.** Patterns are tried in the order you registered them. 2. **One entry per matcher, and calls merge into it.** Registering `'web_search'` twice, once with a label and once with an icon, leaves one entry with both. 3. **The entry that applies is used whole, never mixed.** `'mcp__github__search'` above gets its label and nothing from the pattern’s entry, not even the icon. Repeat what it should keep. `unregisterToolDisplay(match)` drops an entry:
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.registerToolDisplay('web_search', { label: 'Searching the web' });
aparteGlobalConfig.unregisterToolDisplay('web_search'); // back to web_search
```
`registerToolSummary` and `registerToolInputFormatter` are shorthands that write the `summary` and `formatInput` fields of the same entry, with the same matchers, and their `unregister…` twins drop only that field. `registerToolRenderer` and `unregisterToolRenderer` take the same matchers too, and `'*'` there is one renderer for every tool without its own. ## Hide, or draw something else [Section titled “Hide, or draw something else”](#hide-or-draw-something-else) `hidden: true` and a tool renderer that returns `''` do the same thing: an empty placeholder stands in for the call, which stays in the message and the history. Use `hidden` when the point is to draw nothing; use a [renderer](/guides/tools/#custom-tool-renderer) when you draw something else, a card or a receipt. When both exist for one tool, the more specific one wins, and `isToolHidden(name)` answers which:
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.registerToolDisplay('*', { hidden: true });
aparteGlobalConfig.registerToolRenderer('ask_user', {
render: () => 'Question asked', // a receipt, drawn by a plugin in practice
});
aparteGlobalConfig.isToolHidden('web_search'); // true: the '*' hide applies
aparteGlobalConfig.isToolHidden('ask_user'); // false: the renderer is more specific than '*'
```
A `'*'` hide therefore leaves a tool with a renderer of its own drawn, such as [`ask_user`](/components/question/)’s receipt. A hide as specific as the renderer wins: `registerToolDisplay('ask_user', { hidden: true })` hides it, and that is what `receipt: false` on `setupAskUser()` does. ## On a narrow screen [Section titled “On a narrow screen”](#on-a-narrow-screen) The row keeps its state word whatever the width (a quiet row shows it only when something went wrong or waits for approval, and then keeps it too). The note and the target give way first, cut with an ellipsis, and the note carries its full text as a `title`, so a hover still reads it. ## Next [Section titled “Next”](#next) * [Tools and approval Register a tool, see the row in every state, ask a person first.](/guides/tools/) * [Tool call The row, its states and its options, live.](/components/tool/) * [Durations How long a reasoning block or a tool call took.](/guides/customization/segment-timing/)
# Your own components in tool calls
> Draw a tool call — or a segment type of your own — with a component of yours, mounted once, updated as the call changes and unmounted when it leaves, with defineMountedToolRenderer and overrideToolRenderer.
A tool call is drawn as core’s row until you say otherwise. When a call deserves a card of its own — the weather for `get_weather`, a diff for `edit_file`, a chart for `run_query` — you can draw it with a component of yours instead: mounted once in the element core gives it, handed every change of the call (the result landing, an approval decided), and unmounted when the call leaves the page. ## In your framework [Section titled “In your framework”](#in-your-framework) Each wrapper has a component that declares the card, for as long as it is mounted, with a component of your framework inside. Put it anywhere under your providers: the card renders from where the declaration sits, so it reads what your app provides there — a theme, a router, a store. * React
```tsx
import { AparteChat, AparteToolUI, type AparteToolCallView } from '@aparte/react';
type Weather = AparteToolCallView<{ city: string }>;
function WeatherCard({ tool }: { tool: Weather }) {
return {tool.status === 'resolved' ? `${tool.input.city}: ${tool.result}` : `Looking up ${tool.input.city}…`}
;
}
export function Chat() {
return (
<>
name="get_weather">{(tool) => }
>
);
}
```
Each card is a portal into the element core gives the call. * Vue
```vue
```
The slot is teleported into each call, and `inject` reads what your app provides around the declaration. `isAparteElement` is the test to give Vue’s `isCustomElement`, so your templates can use `` and the other elements without a warning (write `` in PascalCase: Vue reads `` as `AparteToolUi`):
```ts
// vite.config.ts
import vue from '@vitejs/plugin-vue';
import { isAparteElement } from '@aparte/vue';
export default { plugins: [vue({ template: { compilerOptions: { isCustomElement: isAparteElement } } })] };
```
* Svelte
```svelte
{#snippet children(tool)} {/snippet}
```
Svelte 5, from `@aparte/svelte/runes`. The snippet is mounted with the contexts of where you declare it, so `getContext` finds what your app set there. * Angular
```html
```
Import `AparteToolUIDirective` into your standalone component. The view is created where the template is declared, so the components in it inject what your app provides there, and it works zoneless. A config other than the global one goes in `[aparteToolUIConfig]`. The card is mounted once per call and updated in place when the call changes, so a component keeps its local state when the result arrives; it is unmounted when the call leaves the page or when the declaration unmounts, and the call goes back to core’s row. `AparteSegmentUI` does the same for a segment type (`` with `AparteSegmentUIDirective` in Angular). In a server render nothing is declared and nothing is drawn: the cards appear in the browser. The sections below are what the four use underneath, and what to use from any other library. ## Mount a component for a tool [Section titled “Mount a component for a tool”](#mount-a-component-for-a-tool)
```ts
import { aparteGlobalConfig, defineMountedToolRenderer, type AparteToolCallView } from '@aparte/core';
type Weather = AparteToolCallView<{ city: string }>;
function draw(host: HTMLElement, view: Weather) {
host.textContent = view.status === 'resolved' ? `${view.input.city}: ${view.result}` : `Looking up ${view.input.city}…`;
}
const restore = aparteGlobalConfig.overrideToolRenderer('get_weather', defineMountedToolRenderer((host, view) => {
draw(host, view as Weather);
return {
update: (next) => draw(host, next as Weather),
destroy: () => host.replaceChildren(),
};
}));
```
`defineMountedToolRenderer` turns a mount function — an `AparteToolMount`, `(host, view) =>` what you mounted — into a complete tool renderer. Core creates the host — an empty `div.aparte-tool-ui` in place of the row — and calls your function once, when the host is in the page. What you return is how core reaches what you mounted: `update` with every newer state of the call, never a remount, so a component keeps its local state when the result arrives; `destroy` when the host leaves for good. Mount a Preact, Lit or Solid component there, or plain DOM as above. `overrideToolRenderer` puts the renderer over whatever the tool had and returns the function that takes it off again — the registration a component makes for as long as it is mounted. `registerToolRenderer` works too, for a card that stays for the page’s lifetime. The matcher is a name, a `RegExp` or `'*'`, as everywhere else for tools. ## What a card is given [Section titled “What a card is given”](#what-a-card-is-given) `toToolCallView(segment)` builds the `AparteToolCallView` your mount and `update` receive, one object with the fields a card draws from: | Field | What it holds | | ----------------------------------- | ----------------------------------------------------------------------------- | | `id`, `name` | the call’s id as the model issued it, and the tool’s name | | `input` | the arguments the model passed — typed with the view’s first parameter | | `status` | `pending`, `awaiting-approval`, `resolved`, `rejected`, `aborted` or `failed` | | `result`, `structuredResult` | the tool’s answer as text, and as data (the view’s second parameter) | | `deferred`, `refusal`, `abortCause` | why the call waits, who refused it and what they said, why it stopped | | `segment` | the whole segment, for anything else | `input` and `result` are chosen by the model: render them as text, or escape them, like anything else a model wrote. ## When a card is mounted, updated and unmounted [Section titled “When a card is mounted, updated and unmounted”](#when-a-card-is-mounted-updated-and-unmounted) A card is mounted once and updated in place for as long as it stays. It is unmounted — `destroy`, through the renderer’s `cleanup` — exactly once, when its element leaves for good: the call removed, its message redrawn or removed, a conversation switch, or the renderer replaced. It is not unmounted when a framework only moves its message: a message taken out of the page and put back before the next microtask keeps its cards. A message that comes back later (a keep-alive cache, a reused route) mounts its cards again. A Markdown or highlight provider that arrives late redraws the text around the cards, not the cards, and the end of a turn — when the finished message is synced again — hands each card its final state without remounting it. The registry is live. A renderer registered while calls are already on screen — a restored conversation, a page that declares its cards after the first messages, a chat whose own config arrives after its first rows — takes those calls over, and taking it off gives them back to core’s row; calls to other tools are not touched. The change reaches the screen in a microtask, gathered: ten components declaring cards in one render cost one pass, and an override taken off in the same tick costs nothing at all. Overrides stack: of two declarations for the same tool the newer wins, and taking off the older one leaves the newer in place. Each `restore` function is safe to call twice, and does nothing after a `reset()` of the config. A card’s own changes count as content arriving: if the reader is at the bottom of the chat, it follows them; if they scrolled up to read, it stays where they are. ## A segment type of your own [Section titled “A segment type of your own”](#a-segment-type-of-your-own)
```ts
import { defineMountedSegmentRenderer, overrideSegmentRenderer, type AparteSegmentBase } from '@aparte/core';
interface ChartSegment extends AparteSegmentBase {
type: 'chart';
points: number[];
}
const restoreChart = overrideSegmentRenderer(defineMountedSegmentRenderer('chart', (host, segment) => {
host.textContent = segment.points.join(' · ');
return {
update: (next) => { host.textContent = next.points.join(' · '); },
destroy: () => host.replaceChildren(),
};
}));
```
The same mechanism for a segment `type` of your own — a type your stream emits through a [block grammar](/guides/customization/#custom-segment-types), say. `defineMountedSegmentRenderer` takes the type and an `AparteSegmentMount`, and `overrideSegmentRenderer` stacks the way `overrideToolRenderer` does; taking the last override off a built-in type such as `code` gives it back to core’s renderer. Both mounts return an `AparteMountedView` — `update` and `destroy`. A renderer written by hand gets the same lifecycle: `cleanup(element, segment)` on a segment renderer or a tool renderer is called once, when its element leaves for good. * [Showing tool calls Words, icons and details for core's own row.](/guides/tool-display/) * [Custom tool renderer A renderer written by hand, as markup.](/guides/tools/#custom-tool-renderer)
# Let the model call your code, and ask a person first
> Register a tool the model can call, show each call as it runs, say what it targets, and make a person approve it before it runs.
## Register a tool [Section titled “Register a tool”](#register-a-tool)
```ts
import { aparteGlobalConfig, AparteClient } from '@aparte/core';
import type { AparteTool, AparteToolHandler } from '@aparte/core';
const getTime: AparteTool = {
name: 'get_time',
description: 'Return the current time in a given IANA timezone.',
inputSchema: {
type: 'object',
properties: { timezone: { type: 'string' } },
required: ['timezone'],
},
};
const handleGetTime: AparteToolHandler = async (call) => ({
toolCallId: call.id,
content: new Date().toLocaleString('en-US', { timeZone: String(call.input['timezone']) }),
});
aparteGlobalConfig.registerTool(getTime, handleGetTime);
new AparteClient().start();
```
`AparteClient` offers every registered tool to the model, runs your handler when the model calls it, gives the result back, and lets the model go on. `inputSchema` is a JSON Schema, sent as it is. The handler gets the call — `{ id, name, input }` — an `AbortSignal` that fires when the turn is stopped or the tool runs too long, and a context whose `target` is the chat the turn belongs to. It answers `{ toolCallId, content }`: `content` is what the model reads, and an optional `structuredContent` reaches a [renderer of yours](#custom-tool-renderer) as `segment.structuredResult`, never the model. A tool’s `systemPrompt` tells the model when to use it, and its `maxTurns` is the last turn of a reply in which it may still run. On the client, `toolTimeoutMs` is the time a handler may take, five minutes by default: a call past its turns or its time is stopped, and the reply ends with it. The client’s `maxTurns` caps the model’s turns in one reply, ten by default, and a reply that reaches it ends on an error message. A model whose declared `capabilities` leave out `function_calling` gets no tools; a model that declares nothing gets them. ## What the row shows [Section titled “What the row shows”](#what-the-row-shows) [Every status a tool call can be in](/preview/demo/tool-statuses/)
```html
```
A tool call in each of its states, on an agent's row (quiet: false). Each call is one line in the reply, in the order it happened: the tool’s name and its state. The row is quiet by default: while the call runs its name [shimmers](/components/shimmer/) instead of a spinner, and “Running” and “Done” are read by a screen reader but not shown — under reduced motion and in forced colours, where the shimmer cannot say it, “Running” is shown. A wait, a refusal, a stop and a failure show their word on every row. The table is an agent’s row (`registerToolDisplay('*', { quiet: false })`), which shows them all. Opened, it shows the arguments the model chose under **Input** and the result under **Output**. A part that is JSON is pretty-printed, and coloured when a [highlighter](/guides/markdown/) is registered; any other text stays as it is. Each part has a copy button, and a long one scrolls inside a box capped by `--aparte-tool-part-max-height` (300px), a focusable region a keyboard can scroll. What a tool is called, and whether its row is drawn at all, is yours to say: [Showing tool calls to a person, or to a developer](/guides/tool-display/). | State | Word | Note after the word | When | | ------------------- | -------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `awaiting-approval` | Waiting | | a person has not decided yet | | `pending` | Running | | the handler runs, with a spinner on an agent’s row and a shimmer on a quiet one | | `resolved` | Done | | the handler answered | | `rejected` | Rejected | `You said: “…”`, when the person wrote something instead of choosing | a person refused it | | `rejected` | Rejected | `Refused by policy` | a [policy](#decide-in-code) refused it | | `rejected` | Rejected | `Not run: an earlier call was refused` | a paused [server](/guides/server-loop/) or agent run asked about several calls, and an earlier one was refused | | `aborted` | Stopped | none | the reply was stopped (Stop) | | `aborted` | Stopped | `Timed out` | the handler outlived `toolTimeoutMs` | | `aborted` | Stopped | `Not available here` | no handler is registered for the tool | | `aborted` | Stopped | `No one could approve it` | the call needs approval and nothing can ask | | `aborted` | Stopped | `Turn limit reached` | the tool’s own `maxTurns` ran out | | `failed` | Failed | | the handler threw | The note tells the person who refused a call, or why it did not run, in their language. It is not the sentence the model reads: a refused row shows the note and **no Output at all**, because its result is the sentence written for the model, a policy’s reason included (a conversation saved by an earlier version keeps its Output). On the segment, `refusal` holds `{ by, instruction? }` (`by` is `'person'`, `'policy'` or `'earlier-refusal'`) and `abortCause` holds `'stopped'`, `'timeout'`, `'no-handler'`, `'no-resolver'` or `'turn-limit'`; `result` stays the model’s sentence. A handler that throws marks its call failed and ends the reply on the error. A failure the model should read and work around is a result instead: return it as `content`. The words are locale keys, and `extendLocale` changes them:
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.extendLocale({
toolRunning: 'Working…', toolCompleted: 'Done', toolRejected: 'Refused',
toolStopped: 'Stopped', toolFailed: 'Failed', approvalWaiting: 'Waiting',
toolInput: 'Arguments', toolOutput: 'Result',
// the notes after the word
toolRejectedSaid: 'You answered: “{instruction}”', toolRefusedByPolicy: 'Blocked by a rule',
toolNotRunAfterRefusal: 'Skipped', toolTimedOut: 'Took too long',
toolUnavailable: 'Not available', toolNoApprover: 'Nobody to ask', toolTurnLimit: 'Too many steps',
});
```
The row is `.aparte-segment-tool-call`: its line `.aparte-tool-summary`, rounded by `--aparte-tool-row-radius`, the word `.aparte-tool-state`, the note `.aparte-tool-note`, and the opened part `.aparte-tool-detail`. The [class reference](/reference/classes/) lists them all. ## Show what a call targets [Section titled “Show what a call targets”](#show-what-a-call-targets)
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.registerToolSummary('read_file', (segment) =>
String(segment.toolCall.input['path'] ?? ''));
```
[A tool row that says what it ran on](/preview/demo/tool-summary/)
```html
```
read\_file with the file it read, without opening the row. A summary is the line the row writes after the tool’s name: `read_file skills.json` rather than `read_file` alone. It is read again each time the call changes and when the language switches, and written as text; an empty string, or a summary that throws, shows nothing. A tool drawn by a [renderer of its own](#custom-tool-renderer) shows no summary. `registerToolSummary` writes the `summary` field of the tool’s display, on its own. Its first argument is a tool name, a `RegExp` tested against it, or `'*'` for every tool nothing more specific describes, so `registerToolSummary(/^mcp__/, …)` covers every tool an MCP server brings. `registerToolDisplay` sets a summary beside a label, an icon and the rest, and `unregisterToolSummary` drops only the summary. See [how a display is matched](/guides/tool-display/#how-a-display-is-matched). ## Show the arguments as a person reads them [Section titled “Show the arguments as a person reads them”](#show-the-arguments-as-a-person-reads-them)
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.registerToolInputFormatter('write_file', (input) =>
`${String(input['path'] ?? '')}, ${String(input['content'] ?? '').length} characters`);
```
The approval panel shows a call’s arguments under its question, and the row behind its disclosure; both show the JSON the model sent, until the tool has a formatter. Then both show its text, so a person approves the call the row describes. It is written as text; an empty string shows no arguments, and a formatter that throws falls back to the JSON. The panel reads the client’s configuration and the row the chat’s, so register it on the one the chat uses. Like the summary, it is a field of the tool’s display (`formatInput`), takes a name, a `RegExp` or `'*'`, and `unregisterToolInputFormatter` drops only that field. ## Require approval (human-in-the-loop) [Section titled “Require approval (human-in-the-loop)”](#require-approval-human-in-the-loop)
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.registerTool(
{
name: 'delete_file',
description: 'Delete a file from the workspace.',
inputSchema: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] },
needsApproval: true,
},
async (call) => ({ toolCallId: call.id, content: `Deleted ${String(call.input['path'])}` }),
);
```
[A tool call waiting for a person](/preview/demo/approval/)
```html
```
The decision, asked at the composer: the question, the arguments, the choices. With `needsApproval`, the call waits before its handler runs. The row says which tool waits, and the decision is asked at the composer: the question, the arguments the model chose, the choices, and a field to write something else. The panel is ``, which `` and the framework wrappers already hold; a layout you compose yourself has to include it, or, with no one to ask, the call is stopped. Its words are the locale keys `approvalAsk` (`Allow {tool}?`), `approveTool`, `rejectTool` and `approvalInstructionPlaceholder`. The question names the call the way its row does: `{tool}` is the row’s label (else the tool’s identifier), then what the summary says it targets. With a label and a summary it can read “Allow Delete a file a.ts?”. The question belongs to the built-in approval channel, `AparteClient`’s; an app with its own loop writes its own. `approvalAsk` is the lever for the wording of this one: `extendLocale({ approvalAsk: 'Run {tool}?' })`. The arguments block under the question is unchanged. * **Approve** runs the handler. * **Reject** never runs it: the model reads the refusal, the other calls of that turn are skipped, and the model gets a turn to answer it. * **Writing instead of choosing** is a refusal that carries your words, which the model reads and the row quotes back to the person (`You said: “…”`) — except when an [AG-UI agent](/providers/agent/ag-ui/) paused on its own tool (an interrupt), which gets only `{ approved: false }`. * **Stop** ends the reply, and the call shows Stopped; the model is told nothing. Each time a call starts to wait, the chat sends `aparte-tool-approval-request` with `{ toolCallId, toolName, input }`, for a notification of yours. When the loop runs on your server, the same panel answers its tools, even after a reload: [approvals across the network](/guides/server-loop/#approvals-across-the-network). Approval is not authorization The approval runs in the browser: it spares the person a surprise, it does not protect your system. A tool that acts on your backend is checked there, in the endpoint it calls, every time: who is calling, and whether they may. When the loop runs on your server, the handler reads the caller from `context.request` ([server loop](/guides/server-loop/)). ## Decide in code [Section titled “Decide in code”](#decide-in-code)
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.setApprovalPolicy((call) => {
if (call.name === 'run_command' && String(call.input['cmd']).startsWith('rm '))
return { verdict: 'deny', reason: 'Deleting is off in this workspace.' };
if (call.name.startsWith('read_')) return { verdict: 'allow' };
return undefined; // the tool's own needsApproval decides
});
```
A policy rules on each call before anyone is asked: `allow` runs it, `ask` asks the person as `needsApproval` would, and `deny` refuses it, with the `reason` the model reads; the row says `Refused by policy`; the person does not read the reason, the model does. The modes people know from agent apps — plan, ask, auto-edit, auto — with a switch in the composer’s toolbar, are [`@aparte/plugin-approval`](/components/approval-mode/). To answer with no panel at all — from a command line, a webhook, a team channel — give the client an `approvalResolver`. It answers every call of a `needsApproval` tool, and a policy set with `setApprovalPolicy`, the approval modes included, is then not consulted: rule on the call in the resolver, or use a policy, not both.
```ts
import { AparteClient } from '@aparte/core';
declare function askTheTeam(name: string, input: Record, signal: AbortSignal): Promise;
new AparteClient({
approvalResolver: async (call, signal) => ({
approved: await askTheTeam(call.name, call.input, signal),
instruction: 'Use the staging bucket instead.', // read by the model on a refusal
by: 'person', // the row quotes the instruction back: You said: “…”
}),
}).start();
```
A resolver may also answer a `payload`, an object merged into the arguments before the handler runs, to correct a path while approving; the row still shows what the model sent. On a refusal it may answer `by: 'policy'` when a rule refused the call and not a person, so the row says `Refused by policy` and not `You said: …`; without `by`, a `reason` is read as a policy’s and an `instruction` as the person’s. So an answer that carries a `reason` of its own and no `by` shows `Refused by policy`: say `by: 'person'` when a person gave it. ## Custom tool renderer [Section titled “Custom tool renderer”](#custom-tool-renderer)
```ts
import { aparteGlobalConfig } from '@aparte/core';
import type { AparteToolRenderer } from '@aparte/core';
const searchRenderer: AparteToolRenderer = {
render(segment) {
const el = document.createElement('div');
el.className = 'my-search';
el.textContent = `Searching for ${String(segment.toolCall.input['query'] ?? '')}`;
return el;
},
update(el, segment) {
if (segment.status === 'awaiting-approval') el.textContent = 'Waiting for your approval';
else if (segment.status === 'pending') el.textContent = 'Searching…';
else if (segment.status === 'resolved') el.textContent = segment.result ?? '';
else el.textContent = `Search ${segment.status}`; // rejected, aborted, failed
},
};
aparteGlobalConfig.registerToolRenderer('web_search', searchRenderer);
```
[A tool drawn by a renderer of your own](/preview/demo/tool-renderer/)
```html
```
A tool drawn by a renderer of its own, in place of the row. A renderer draws every call of one tool in place of the row, in every state: `render` when the call appears, `update` when it changes — a decision is made, its result lands — and `relabel` when the language or the icons change. Without `update`, the call is drawn again from `render` at each change. Read `segment.status`, as above: the renderer shows the wait for approval itself, and a refused or failed call carries the refusal or the error in `segment.result`. Return one element or a string of markup. An empty string returned as the call starts keeps it out of the reply; returned at any other time — a later change, a stored conversation drawn again — it brings back the default row. The arguments and the result come from the model and the tool: never write them into markup as they are. Set them as `textContent`, as above, or pass them through `escapeHtml` and `escapeAttr`. A result meant to be shown as a thing — a document, a form, a receipt — comes as the handler’s `structuredContent`, which the renderer reads as `segment.structuredResult`; the [question](/components/question/) and [artifact](/components/artifact/) plugins draw their cards so. A renderer is shown a refused or stopped call too, with the reason on the segment: `refusal` (`{ by, instruction? }`) and `abortCause`. Read them to say it in your own words:
```ts
import { aparteGlobalConfig } from '@aparte/core';
import type { AparteToolCallSegment } from '@aparte/core';
function whyNot(segment: AparteToolCallSegment): string {
if (segment.refusal?.by === 'person')
return segment.refusal.instruction ? `You said: ${segment.refusal.instruction}` : 'You refused it';
if (segment.refusal?.by === 'policy') return 'A rule blocked it';
if (segment.refusal?.by === 'earlier-refusal') return 'Skipped after a refusal';
if (segment.abortCause === 'timeout') return 'It took too long';
return 'It did not run';
}
aparteGlobalConfig.registerToolRenderer('send_email', {
render(segment) {
const el = document.createElement('div');
el.textContent = segment.status === 'rejected' || segment.status === 'aborted'
? `Email not sent. ${whyNot(segment)}`
: `Email to ${String(segment.toolCall.input['to'] ?? '')}`;
return el;
},
});
```
A message clips what its parts draw outside it, so a renderer’s menu or popover goes on `document.body`, placed from its trigger’s position:
```ts
function openMenu(trigger: HTMLElement): HTMLElement {
const menu = document.createElement('div');
menu.className = 'aparte-menu';
const r = trigger.getBoundingClientRect();
menu.style.cssText = `position: fixed; left: ${r.left}px; top: ${r.bottom}px;`;
document.body.append(menu);
return menu;
}
```
## Next [Section titled “Next”](#next) * [Ask the user a question A choice, a yes or no, some text or a small form, in the middle of a run.](/guides/elicitation/) * [Run the loop on your server The same tools and approvals, with the loop and the key on your server.](/guides/server-loop/) * [Tool The row in every state, its parts and its options.](/components/tool/)
# Troubleshooting
> The failures people meet first — a bare import the browser cannot resolve, a local model the browser refuses, no provider, the key warning, missing buttons — and what an error tells you.
## `Failed to resolve module specifier "@aparte/core"` [Section titled “Failed to resolve module specifier "@aparte/core"”](#failed-to-resolve-module-specifier-apartecore) The page imports `@aparte/core` by name with no bundler in front of it, and a browser cannot resolve a bare name on its own. Use a bundler — Vite, Next, Astro, esbuild, any of them — as every snippet here assumes, or load the packages from a CDN by URL, as in [From a CDN](/guides/getting-started/#from-a-cdn). ## CORS on local BYOK (LM Studio / Ollama) [Section titled “CORS on local BYOK (LM Studio / Ollama)”](#cors-on-local-byok-lm-studio--ollama) The server’s log shows the request, and the reply ends in *The assistant can’t be reached right now* (code `NET_ERROR`), with `[aparte] A turn failed (NET_ERROR): Failed to fetch` on the console beside the browser’s own CORS message (Firefox writes `NetworkError when attempting to fetch resource.`, Safari `Load failed`): the browser called the local server itself — `http://localhost:1234` for LM Studio, `http://localhost:11434` for Ollama — and refused the answer, because the server did not allow the page’s origin. * **LM Studio:** turn on **Enable CORS** in the server settings, in the Developer tab, then restart the server. * **Ollama:** start it with `OLLAMA_ORIGINS` set to the page’s origin, or `*` while you develop.
```bash
OLLAMA_ORIGINS=* ollama serve
```
```powershell
$env:OLLAMA_ORIGINS = "*"
ollama serve
```
If the Ollama app is running, quit it first, or set `OLLAMA_ORIGINS` as a user environment variable and restart the app. [Local models](/guides/local-models/) has the whole setup for both, and for llama.cpp. ## ”Provider is not registered”, “No provider selected” [Section titled “”Provider is not registered”, “No provider selected””](#provider-is-not-registered-no-provider-selected)
```
[AparteClient] Send dropped: no model is selected. …
```
```ts
import { aparteGlobalConfig, AparteClient, AparteDirectTransport } from '@aparte/core';
import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat';
aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider(presets.OLLAMA));
aparteGlobalConfig.setModelConfig({ defaultProvider: 'ollama', defaultModel: 'llama3.2' });
aparteGlobalConfig.setTransport(new AparteDirectTransport({ byok: true }));
new AparteClient().start();
```
Neither error appears in the chat: the person’s message gets no reply, the console warns, and `aparte-message-error` carries the code. **Provider is not registered:** the selected `defaultProvider` names an id no provider was registered under. **No provider selected:** nothing chose a model — no `setModelConfig`, and no [model selector](/components/model-selector/) has picked one; `aparteGlobalConfig.hasSelectedModel()` is `false` until one is. A provider registered alone with a single model is selected by itself; for a list fetched from the server, `` picks one. To keep the composer from sending until a model is chosen, `aparteGlobalConfig.setRequireModelSelection(true)`. A page that never calls `new AparteClient().start()` looks the same from the outside: nothing streams, because nothing answers the send. ## ”Sending the API key straight from the browser” warning [Section titled “”Sending the API key straight from the browser” warning”](#sending-the-api-key-straight-from-the-browser-warning)
```
[Aparte] AparteDirectTransport is sending the "" API key straight from the browser —
it is visible to anyone who opens devtools. …
```
`AparteDirectTransport` sent a real key from the browser, and says so once per transport. When the key is the person’s own, or the model is local, say so and the warning stops: `new AparteDirectTransport({ byok: true })`; a keyless local provider never triggers it. When the key is yours, anyone with devtools can read and spend it: send the requests through [your server](/guides/backend-transport/) instead. ## `[Unknown segment type: …]` in a message [Section titled “\[Unknown segment type: …\] in a message”](#unknown-segment-type--in-a-message) No renderer claims that segment’s type. * **A type of yours:** register a renderer for it with `registerSegmentRenderer`, or give the segment a `fallback`, a sentence drawn as text when nothing claims it. A `custom` segment’s `subType` is not a key of its own: one renderer answers every `custom` segment and reads its `subType` ([Custom segment types](/guides/customization/#custom-segment-types)). * **A built-in type** — `text`, `thinking`, `code`, `tool_call`, `error` — means the built-in renderers were declined, with `new AparteClient({ autoRegister: false })`. Drop the option, or register what you need yourself. ## The retry, edit or ⓘ buttons are not there [Section titled “The retry, edit or ⓘ buttons are not there”](#the-retry-edit-or-ⓘ-buttons-are-not-there)
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.setBubbleActions({ retry: true, edit: true }); // you run an AparteClient
aparteGlobalConfig.setBubbleActions({ feedback: true, info: true }); // you answer these events
aparteGlobalConfig.setHostHandlers({ attachmentPreview: true }); // you open it on aparte-attachment-preview
```
None is on by default. Copy the chat answers alone (`{ copy: true }`); the others need something outside the chat to answer them, so they stay off until you say it is there. ⓘ also needs the reply’s token usage: it shows on a reply whose provider reported usage. The bar hides while a reply streams, and a bar with no action in it is not drawn at all. [Buttons](/guides/customization/actions/) lists each one. ## The composer toolbar is not showing [Section titled “The composer toolbar is not showing”](#the-composer-toolbar-is-not-showing) An empty toolbar is hidden: it carries `data-empty` while it holds nothing visible, and whitespace or comments do not count. If you put a control in it and still see `data-empty`, either the control never arrived — a mistyped slot name, a framework that rendered nothing — or it hides itself: a child with `hidden` or `data-empty` does not count, and `` stays `data-empty` until the first reply reports its usage. A toolbar that shows but is unstyled, with your control at the start instead of the end, means the stylesheet did not load: import `@aparte/core/styles.css` ([The composer toolbar](/guides/customization/composer-toolbar/)). ## What an error tells you [Section titled “What an error tells you”](#what-an-error-tells-you)
```ts
document.querySelector('aparte-chat')?.addEventListener('aparte-message-error', (event) => {
const { error } = event.detail; // an AparteError
console.error(error.code, error.message, error.httpStatus);
});
```
A failure that reaches the chat — a refused key, a rate limit, a dropped connection — is an `AparteError`: its `message`, a `code`, the `httpStatus` when there was one, its `data` and the `originalError`. The message shows it as an [error](/components/error/), and the chat sends `aparte-message-error` with `{ messageId, error }`. A missing or unregistered provider is the exception: the send is refused before a reply exists, so nothing appears in the chat and only the event reports it. A vendor’s HTTP status sets the code: | Status | `code` | | ------------- | ---------------------- | | 400 | `USAGE_BAD_REQUEST` | | 401, 403 | `CONFIG_INVALID_KEY` | | 408 | `NET_TIMEOUT` | | 429 | `USAGE_RATE_LIMIT` | | 503 | `PROVIDER_UNAVAILABLE` | | any other 5xx | `PROVIDER_ERROR` | A network failure is `NET_ERROR`, or `NET_OFFLINE` when the browser says it is offline; a timeout is `NET_TIMEOUT`; no provider selected is `CONFIG_NO_PROVIDER`, and one not registered `CONFIG_MISSING_KEY`. Anything else is `UNKNOWN_ERROR` — except under a runner that calls the model elsewhere (`createAgentStreamRunner`, an AG-UI runner), where a failed or cut run, and a status the table does not name, is `PROVIDER_ERROR`. `@aparte/runner-n8n` raises `PROVIDER_MISCONFIGURED` for a workflow set up so it cannot answer: not published, waiting for credentials, streaming nothing, answering without a text field or through response nodes. `AparteError.from(error)` turns any error into one by the same rules, and `AparteError.codeForStatus(status)` is the table above, for a provider of yours. To change how the error looks, use `aparteGlobalConfig.setErrorRenderer`. ## Next [Section titled “Next”](#next) * [Installation and first chat The setup these failures come from, step by step.](/guides/getting-started/) * [Docs for AI agents Give a coding agent these docs to read.](/guides/docs-for-agents/)
# Upgrading to 1.0
> What to change when an app moves from aparté 0.x to 1.0 — one version for every package, pictures that wait for a click, the names the beta deprecated and 1.0 removes, and the few behaviours that changed with them.
1.0.0 is the first release under the [stability promise](/reference/stability/): from here on, a name on the declared surface keeps its name, and what it does, until 2.0. Getting there takes a few changes to code written against 0.x, and most apps need one or two of them. ## Move every package at once [Section titled “Move every package at once”](#move-every-package-at-once) Every `@aparte/*` package ships at the same version, and each one’s peer range on another is now `>=1.0.0 <2.0.0`. Upgrade them together, every one your `package.json` lists:
```bash
npm install @aparte/core@1 @aparte/react@1 @aparte/plugin-marked@1
```
A 0.x package beside a 1.x one is a peer conflict, and your package manager reports it. Coming from a release before 0.27? `@aparte/locale-fr` no longer exists, and the same `fr` is in `@aparte/locales`:
```diff
- import { fr } from '@aparte/locale-fr';
+ import { fr } from '@aparte/locales/fr';
```
The beta also changed a few behaviours along the way, each in the notes of its release; the [stability page](/reference/stability/#the-beta-017-to-032) lists them with what to change. ## Pictures wait for a click [Section titled “Pictures wait for a click”](#pictures-wait-for-a-click) A picture a model or a tool chose no longer loads by itself. `data:` and `blob:` pictures do; any other shows as a link that names its host, and loads when the reader clicks it. A card shows one “Show images” button in place of its pictures, and a held picture is not fetched while a reply streams either. Allow the places your own pictures come from:
```ts
import { aparteGlobalConfig } from '@aparte/core';
aparteGlobalConfig.setImagePolicy(['self', 'https://cdn.example.com']);
```
`['*']` loads every picture, as 0.x did. [Pictures a reply can load](/guides/markdown/#pictures-a-reply-can-load) says why a picture waits by default — a reply can carry the conversation to any host through a picture’s address, without a click — and which policy to choose. Until you name one, the first picture held on a page writes a note in the browser console with the line to add. ## What 1.0 removes [Section titled “What 1.0 removes”](#what-10-removes) Each of these was marked deprecated during the beta. If your code uses none of them, there is nothing to do here. **``.** Remove the attribute: the gauge no longer asks for a compaction, and `@aparte/plugin-compaction` compacts by itself once it is set up, past 80 % of the window by default.
```diff
-
+
```
**The `window` of an `aparte-compact` request.** It is no longer read. Give `setupCompaction` the window, or let the model declare it:
```ts
import { setupCompaction } from '@aparte/plugin-compaction';
setupCompaction({ contextWindow: 128_000 });
```
**A `CompactionTarget` without `updateMessage`.** The type now requires it, and `clearAll` and `appendMessage` are no longer part of it: since 0.26.0 a compaction writes one checkpoint through `updateMessage` and calls nothing else.
```diff
const target: CompactionTarget = {
getMessages: () => store.messages,
- appendMessage: (message) => store.append(message),
- clearAll: () => store.clear(),
+ updateMessage: (id, updates) => store.update(id, updates),
};
```
**The `compactionSummaryTitle` locale key.** Remove it from your locale. Nothing has read it since 0.26.0, and the nine locales of `@aparte/locales` no longer carry it. **The viewport’s `clearMessages()`.** Call `clearAll()`, which also removes the bubbles. `clearMessages()` on ``, on the framework components and on the imperative API is unchanged.
```diff
- viewport.clearMessages();
+ viewport.clearAll();
```
**`AparteMessageBranch`, and the `branches` and `activeBranchIndex` fields of `AparteMessage`.** Nothing read them. Branches are the message tree: `addSiblingOf`, `navigateBranch` and the `aparte-path-changed` event, in [Conversations and branching](/guides/conversations-branching/). **`AparteCodeSegment.showLineNumbers` and `AparteErrorSegment.stack`.** Nothing read them either; put a stack in the error’s `details`. ## Behaviours that changed [Section titled “Behaviours that changed”](#behaviours-that-changed) These keep their names; what they do moved. Most apps meet none of them. * **Suggestion buttons the model writes send their label.** In a `suggestions` block, a `{ "label", "prompt" }` reply sends its label and the `prompt` is ignored, because the block is model text and the button must send what it shows. Suggestions your app passes still send their `prompt`. * **A card the model wrote no longer draws its own buttons.** A card’s `actions` receives `{ origin }` as its second argument — `'tool'`, `'segment'` or `'fence'`. In a card the model wrote as a code block (`'fence'`), an action of the card’s own data that carries an `id` is not drawn, and its links are. The buttons your `actions` returns are drawn on every card, so do not build a `send` from a `'fence'` card’s fields: keep its text fixed, or give the button an `id` and decide in your `aparte-card-action` listener. * **A reply cannot drive your page’s controls.** Markup in a message no longer carries the attributes core reads as controls (`data-aparte-dialog-open` and the rest), and ` ` in a reply is limited to a disabled checkbox. Change your code only if a custom segment renderer, a tool’s `details` string or a custom sanitizer’s output relied on them. * **The server handlers answer 415 to a body that is not declared JSON.** `createAparteAgentHandler` and `createAparteChatHandler` refuse a request whose `Content-Type` is not `application/json`. `AparteBackendTransport` sends it; a bare `fetch` with a JSON body must set the header. * **A link with a scheme and no slash is an external link.** `[docs](http:example.com/x)` opens in a new tab like any other external link. * **A Mermaid node picture from a URL is not drawn.** The diagram shows its source instead, since drawing it sent a request to that address; an inline `data:image/…` picture still draws. * **`@aparte/runner-n8n` shows a Chat node’s buttons only when their links resume the running execution**, and an n8n error frame no longer puts the workflow’s own words in front of the person. The [changelog](/changelog/) has each of these in full, with the release it came in.
# UI Kit for an AI Chat App — plain CSS classes, 26 families
> 26 families of plain CSS classes for the chrome around a chat — buttons, fields, tabs, dialogs, avatars, the sidebar — themed by the same variables as the chat itself.
Every recipe here is **plain classes on plain elements**: no component to import, no framework, no shadow DOM — copy the markup, restyle it with the same [CSS variables](/reference/css-variables/) the chat reads. Each family has one page, its live preview first; every class of the kit on one page is the [classes reference](/reference/classes/). ## Controls [Section titled “Controls”](#controls) * **[Button](/components/button/)** — The button. Ready-made classes; nothing to configure. * **[Field](/components/field/)** — Form fields. Ready-made classes; nothing to configure. ## Display [Section titled “Display”](#display) * **[Avatar](/components/avatar/)** — Sizes, shape, image + initials fallback * **[Icon](/components/icon/)** — The icon. Every glyph the library draws carries this class. * **[Badge](/components/badge/)** — Small count or status pill * **[Tag](/components/tag/)** — A removable chip * **[Thumbnail](/components/thumbnail/)** — The thumbnail. A media tile: a fixed square that clips whatever is dropped * **[Spinner](/components/spinner/)** — A rotating indicator * **[Progress](/components/progress/)** — Determinate bar + indeterminate variant * **[Skeleton](/components/skeleton/)** — A loading placeholder * **[Shimmer](/components/shimmer/)** — A label while something runs * **[Divider](/components/divider/)** — Horizontal, vertical, optionally labelled * **[Alert](/components/alert/)** — A callout * **[Card](/components/card/)** — A surface with optional header/body/footer * **[Kbd](/components/kbd/)** — A keyboard key * **[Mark](/components/mark/)** — The mark: a row a list has settled on. ## Surfaces [Section titled “Surfaces”](#surfaces) * **[Tabs](/components/tabs/)** — One row of tabs, and the panel under it * **[Accordion](/components/accordion/)** — Stacked disclosures * **[Menu](/components/menu/)** — A floating list of commands * **[Popover](/components/popover/)** — A floating box, and nothing else * **[Dialog](/components/dialog/)** — A modal, drawn on the native \. * **[Tooltip](/components/tooltip/)** — A short label, with an arrow ## Shell [Section titled “Shell”](#shell) * **[Sidebar](/components/sidebar/)** — The column beside the chat. * **[App Header](/components/header/)** — The bar above the chat. * **[App Shell](/components/app-shell/)** — Sidebar beside, header above, the chat in the rest. * **[Split](/components/split/)** — Two panes and a draggable seam.
# Other plugins
> Packages built on aparté that live in their own repositories, on versions of their own, each pinned to exact aparté versions.
These packages are built on aparté but are not part of the library. Each lives in its own repository, with its own versions, issues and changelog, and depends on **exact** versions of aparté’s packages: it moves to a newer aparté only in a release of its own, so what you install keeps running as you tested it while aparté goes on releasing. | Package | What it is | | ---------------------------------------------- | -------------------------------------------------------------------------------------------------- | | [`@aparte/n8n-chat`](/other-plugins/n8n-chat/) | n8n’s chat widget, drawn by aparté: `createChat()` takes `@n8n/chat`’s options. From npm or a CDN. | Their README is their reference; this section says what each is for and where to find it. An issue about one goes to its own repository.
# n8n chat widget
> @aparte/n8n-chat — n8n's chat widget, drawn by aparté: createChat() takes @n8n/chat's options, response nodes and buttons included, from npm or a CDN.
[`@aparte/n8n-chat`](https://github.com/apartejs/n8n-chat) is n8n’s chat widget, drawn by aparté. `createChat()` takes [`@n8n/chat`](https://www.npmjs.com/package/@n8n/chat)’s options and mounts the same widget on an n8n Chat Trigger — a button in the corner, or a chat that fills its target. A page that uses n8n’s widget changes the import and keeps its call. ## Install [Section titled “Install”](#install) From a CDN, with no build step:
```html
```
Or from npm:
```bash
npm install @aparte/n8n-chat
```
```ts
import { createChat } from '@aparte/n8n-chat';
import '@aparte/n8n-chat/style.css';
createChat({ webhookUrl: 'https://your-n8n.example.com/webhook//chat' });
```
## What it does [Section titled “What it does”](#what-it-does) * **Every option of `@n8n/chat` 1.43**, the same defaults, and the session kept in the same place, so a visitor keeps their conversation across the switch. * **A workflow that answers through response nodes**: its Chat nodes’ messages, their buttons and their written questions, Block User Input included. * **Rich cards from a text answer.** A `card-` block in the workflow’s reply is drawn as a card (an order, a product, a place, the weather), with the other cards of [`@aparte/plugin-cards`](/guides/cards/). * **Quick replies.** A `suggestions` block in the reply becomes buttons above the input. * **aparté’s plugins, through `setup`**: maths, diagrams and charts, or a card of your own, each in a line. * **A handle** to drive it from the page: `open`, `close`, `toggle`, `send`, `reset`, `setDisabled`, `destroy`. * **Errors a visitor can read**, with the workflow’s own words under them, and a console that says what to change in n8n. * **Ten languages**, a page loading only the one it uses; keyboard and screen-reader access; AA contrast; a dark scheme; a history without raw tool JSON. * **About 143 KB** compressed on the first load, against about 471 KB for `@n8n/chat` 1.44.7 (measured 2026-10-31). MIT. It wears n8n’s look by default and reads n8n’s `--chat--*` variables, so a page that themed n8n’s widget keeps most of its theme. Its options, its handle, the workflow setup and a comparison with n8n’s widget are in [its README](https://github.com/apartejs/n8n-chat#readme). ## Built on [Section titled “Built on”](#built-on) The widget puts together aparté’s `` inside an [``](/components/launcher/), the [n8n runner](/providers/agent/n8n/), the [locales](/guides/localization/), the [cards](/guides/cards/) plugin, and the Markdown and highlighting plugins, at exact versions. To put an n8n workflow behind a chat you compose yourself — in React, Vue, Svelte or Angular, in your own look — use the runner directly. ## Links [Section titled “Links”](#links) * Its own site, in ten languages, with a live demo on a real workflow: [n8n-chat.apartejs.dev](https://n8n-chat.apartejs.dev) * Repository and issues: [apartejs/n8n-chat](https://github.com/apartejs/n8n-chat) * npm: [`@aparte/n8n-chat`](https://www.npmjs.com/package/@aparte/n8n-chat) * The article: [n8n’s chat widget: what people run into, and a replacement that takes the same call](/articles/n8n-chat-widget/)
# Connect the chat to a model or an agent
> Reach your model — OpenAI or any compatible API, Ollama, the Vercel AI SDK, a model in the browser — or your agent, and decide where the key lives.
## Pick a package [Section titled “Pick a package”](#pick-a-package) | You want to reach | Package | | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | OpenAI, Mistral, OpenRouter, Z.ai, LM Studio, Ollama — or any other OpenAI-compatible endpoint | [`@aparte/provider-openai-compat`](/providers/ai/openai-compat/) | | Anthropic, Google, Amazon Bedrock, or another `@ai-sdk/*` vendor | [`@aparte/provider-ai-sdk`](/providers/ai/ai-sdk/) | | A model running in the browser, with no server and no key | [`@aparte/provider-transformers`](/providers/ai/transformers/) | | Scripted replies, for a demo or a test | [`@aparte/provider-scenario`](/providers/ai/scenario/) | | An agent on its own server, over AG-UI — Agno, LangGraph, Mastra, CrewAI, Pydantic AI | [`@aparte/runner-ag-ui`](/providers/agent/ag-ui/) | | A TanStack AI chat route | [`@aparte/runner-ag-ui`](/providers/agent/tanstack-ai/) | | An n8n chat workflow — a Chat Trigger and its AI Agent | [`@aparte/runner-n8n`](/providers/agent/n8n/) | A provider is the wire format of a family of models: how a request is shaped and how its answer is read. The transport is where the request goes — from the browser to the model, or to [your server](/guides/backend-transport/), which keeps the key. ## Wire it [Section titled “Wire it”](#wire-it)
```ts
import { aparteGlobalConfig, AparteClient, AparteDirectTransport } from '@aparte/core';
import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat';
aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider(presets.OPENROUTER));
aparteGlobalConfig.setModelConfig({ defaultProvider: 'openrouter', defaultModel: 'openai/gpt-4o-mini' });
aparteGlobalConfig.setTransport(new AparteDirectTransport({ byok: true }));
new AparteClient({
keyResolver: (providerId) => localStorage.getItem(`${providerId}.key`) ?? undefined,
}).start();
```
Register a provider, name the model — or let the person pick it in the [model selector](/components/model-selector/) — and start a client: the `` on the page streams from there ([Installation and first chat](/guides/getting-started/)). A provider that lists its models over the network selects none by itself. The browser transport is the default, so `setTransport` only says `byok: true` — the key is the person’s own — which keeps the console from warning, once, that a key went out from the page. ## The key [Section titled “The key”](#the-key) `keyResolver` is asked for a provider’s key on each request, and may be async — a vault, an input of yours:
```ts
declare const keyInput: HTMLInputElement; // a field in your settings
keyInput.addEventListener('change', () => localStorage.setItem('openrouter.key', keyInput.value.trim()));
```
It may also answer `{ apiKey, endpoint }`, which points the provider, and its list of models, at a host of yours. `aparteGlobalConfig.setKeyProvider(fn)` does the same for every client, and `registerKeyProvider(fn)` adds a source and returns the function that removes it; a client’s own resolver is asked first. A local server — the Ollama and LM Studio presets — needs no key. A cloud provider without one lists no models, and the vendor refuses its requests. To keep the key off the browser altogether, send the requests through [your server](/guides/backend-transport/). ## Agents are not providers [Section titled “Agents are not providers”](#agents-are-not-providers) An agent that runs its own loop and its own tools does not plug in as a provider: it plugs in one level up, as the client’s `streamRunner`. The page registers no provider and picks no model; it draws what the agent streams. [AG-UI](/providers/agent/ag-ui/), [TanStack AI](/providers/agent/tanstack-ai/) and [n8n](/providers/agent/n8n/) work this way, and so does [aparté’s own loop on your server](/guides/server-loop/). ## Write your own provider [Section titled “Write your own provider”](#write-your-own-provider) A provider is an `AparteAIProvider`, in one of two shapes: * **a format adapter** — `defaultEndpoint`, `buildRequest(request)`, `parseStream(body)`, one of `authHeaders(key)` or `authQuery(key)`, and `parseText` for an answer that does not stream. The transport sends the request and holds the key. This is [`openai-compat`](/providers/ai/openai-compat/). * **its own I/O** — `chat(request, config, { providerId, signal })`, which makes the call itself, through an SDK or a runtime in the page. This is [`ai-sdk`](/providers/ai/ai-sdk/) and [`transformers`](/providers/ai/transformers/). A transport of your own tells the two apart with `isFormatAdapter(provider)`. Both answer `id`, `getMetadata()` — an `AparteAIProviderMetadata`, whose `name` the model selector shows as a group label, with an `icon` and a `color` for a picker of your own — and `getModels()`. `fetchModels` fetches the list at run time, and is what the [model selector](/components/model-selector/) shows; `getModelStatus`, `prepareModel` and `deleteModel` are for a model that has to be downloaded first. A model’s `capabilities` say what it can do; one that declares them without `function_calling` gets no tools. A tool turn reaches the provider as an `assistant` message carrying the model’s `toolCalls`, then one `tool` message per result, which the provider turns into its vendor’s shape:
```ts
import type { AparteChatMessage } from '@aparte/core';
const history: AparteChatMessage[] = [
{ role: 'user', content: 'Any news on the beta?' },
{ role: 'assistant', content: 'Let me look.', toolCalls: [{ id: 'call_1', name: 'search', input: { query: 'beta' } }] },
{ role: 'tool', content: '3 results', toolCallId: 'call_1', toolName: 'search' },
];
```
## Next [Section titled “Next”](#next) * [OpenAI-compatible OpenAI, Mistral, OpenRouter, Ollama and every compatible endpoint.](/providers/ai/openai-compat/) * [Local models A model on your machine, from Ollama, LM Studio or llama.cpp.](/guides/local-models/) * [Keep the key on your server The same chat, with each request going through your server.](/guides/backend-transport/)
# Put a chat on an AG-UI agent
> Connect an agent served over AG-UI — Agno, LangGraph, Mastra, CrewAI, Pydantic AI — and the chat draws its replies, its reasoning, its tool calls and its approvals while the agent runs on its own server.
## Connect the agent [Section titled “Connect the agent”](#connect-the-agent)
```bash
npm install @aparte/runner-ag-ui @aparte/core
```
```ts
import { AparteClient } from '@aparte/core';
import { createAgUiRunner } from '@aparte/runner-ag-ui';
new AparteClient({
streamRunner: createAgUiRunner({ endpoint: 'https://agents.example.com/agui' }),
}).start();
```
[AG-UI](https://docs.ag-ui.com) is the protocol many agent frameworks serve their agents over: Agno, LangGraph, Mastra, CrewAI, Pydantic AI, and [TanStack AI](/providers/agent/tanstack-ai/). The agent runs its loop and its tools on its server, so the page registers no provider and picks no model. The runner is the client’s `streamRunner`: the chat, Stop, the conversation manager and the approval panel work as they do with aparté’s own loop. ## What the agent’s stream becomes [Section titled “What the agent’s stream becomes”](#what-the-agents-stream-becomes) | The agent sends | The chat shows | | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `TEXT_MESSAGE_*` | the reply’s text | | `REASONING_*` | a [reasoning block](/components/reasoning/) | | `TOOL_CALL_START`, `TOOL_CALL_ARGS` or `TOOL_CALL_CHUNK`, `TOOL_CALL_END` | a [tool row](/components/tool/), drawn with its whole arguments once the call ends | | `TOOL_CALL_RESULT` | the row’s result | | `RUN_FINISHED` | the end of the reply, with its usage — or, with an interrupt, a decision to make or a tool the page runs | | `RUN_ERROR` | the [error card’s](/components/error/#what-the-card-says) sentence, below what the stream drew; the agent’s message goes to the console and stays on the segment | | `STATE_SNAPSHOT`, `STATE_DELTA` | nothing drawn: the agent’s state, kept for the thread and sent back as the next run’s `state` | | an HTTP error | the error card’s sentence; the start of the response body goes to the console and stays on the segment, stored with the conversation — keep secrets out of it | Each model step of the run is a turn of its own in the reply, and the reply reports the usage of its last step, as a run in the page does: the size of what the model last saw, which is what the context gauge reads. A `RUN_ERROR` does not cut the stream: the runner reads it to the end, as the protocol asks, and the error lands below what was drawn — unless the agent runs again in the same stream, in which case the new run decides how the reply ends and the failure goes to `onWarning`. A stream that ends without `RUN_FINISHED` ends the reply with an error. `STEP_*`, `MESSAGES_SNAPSHOT`, `ACTIVITY_*`, `RAW`, `CUSTOM` and sub-agent events are checked, not drawn. The runner reads the answer as server-sent events, or as NDJSON when its content type says so. ## The protocol’s own rules [Section titled “The protocol’s own rules”](#the-protocols-own-rules) The runner speaks AG-UI 1.0: it declares `protocolVersion: "1.0"` on every request, and holds the agent’s stream to the rules 1.0 sets a client. A run opens with `RUN_STARTED` and ends with `RUN_FINISHED` or `RUN_ERROR`; a message, a tool call, a step or a sub-agent is opened before it continues and closed before the run finishes, each owner — the agent, or each sub-agent — keeping its own; a known field has its type. A stream that breaks one ends the reply with an error that names the rule; what was drawn before it stays. What the agent sends that 1.0 does not describe — an event type, a property, an outcome — is dropped, and the runner tells `onWarning` what and where, `console.warn` by default. It is held to that by the protocol’s own conformance corpus: the 68 streams of AG-UI’s `spec/1.0/conformance`, replayed through the runner on every build, each with what the specification requires of a client. They were written for clients that keep the run’s messages and state themselves, so the runner’s suite says, stream by stream, what it reads through and what aparté does not draw yet: activities, a messages snapshot rewriting what was drawn, and message metadata. ## Tools the page runs [Section titled “Tools the page runs”](#tools-the-page-runs) A tool registered in the page — `ask_user` through `setupAskUser()`, your own through `registerTool` — is sent to the agent as an AG-UI frontend tool. When the agent calls it, the run pauses with the call open; the page runs the tool, shows its result in the row, and calls the agent again with it. For an agent server, the pause is an interrupt whose reason contains `client_tool`, or a call the agent leaves without a result. Before it runs, the page gates it as its own loop would: a `needsApproval` tool asks through the approval panel (its row says it is waiting), your approval policy can allow or refuse it, and a refusal goes back to the agent with its reason — as the tool’s result, or as its error when the agent paused on the call. A call the person approved once in the turn is not asked about again when the agent pauses to run it. ## Approvals [Section titled “Approvals”](#approvals) When the agent pauses on a call that needs a person — an interrupt whose reason is `tool_call` or `confirmation` — the page asks with the same [approval panel](/guides/tools/#require-approval-human-in-the-loop) as for its own tools, and your [approval policy](/components/approval-mode/) can answer first. Every answer goes back to the agent in one `resume`, and the run goes on on the agent’s server, in the same reply. The pause is part of the conversation, so a [saved conversation](/guides/conversation-persistence/) brings the question back after a reload. ## Options [Section titled “Options”](#options)
```ts
import { uuid } from '@aparte/core';
import { createAgUiRunner } from '@aparte/runner-ag-ui';
let conversationId = uuid(); // set it when your app opens a conversation
const runner = createAgUiRunner({
endpoint: '/agui',
headers: async () => ({ authorization: `Bearer ${sessionStorage.getItem('token') ?? ''}` }),
threadId: () => conversationId, // read on every turn
});
```
| Option | What it does | | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `endpoint` | the agent’s AG-UI URL; required | | `headers` | sent with every request; a function is called for each, for a fresh token | | `fetch` | the `fetch` the runner calls; the global one by default | | `credentials` | for a cross-origin endpoint that authenticates by cookie | | `threadId` | the AG-UI thread a turn runs in: a string, or a function of the run’s options | | `forwardedProps` | `RunAgentInput.forwardedProps`: settings your agent reads from the request | | `context` | `RunAgentInput.context`: `{ description, value }` entries for the agent | | `onWarning` | told what the runner dropped or translated; `console.warn` by default | | `relaxedRunFraming` | reads runs framed otherwise than 1.0 frames them — a `RUN_FINISHED` per model step, a resume answered before `RUN_STARTED` — as [TanStack AI](/providers/agent/tanstack-ai/) does; every other rule holds | | `peerProtocolVersion` | the version of an agent older than 1.0, such as `'0.0.47'`: its stream is read by that version’s rules, and the request leaves out `protocolVersion` | These are the `AgUiRunnerOptions`. By default every turn runs in a new thread with the whole history, which suits a stateless agent; give `threadId` when the agent keeps state per thread, as Agno does with its session — the conversation’s id is the usual choice. The state the agent streams is kept for that thread and sent back as the next run’s `state`; on a thread minted for one turn, it lasts as long as the turn, pauses included. A paused run resumes in its own thread, whatever `threadId` answers. An agent on another origin than the page has to allow it: answer the preflight (`OPTIONS`) with `Access-Control-Allow-Origin` (the page’s origin) and `Access-Control-Allow-Headers: content-type` plus the headers you send, and with `Access-Control-Allow-Credentials: true` when `credentials` is `'include'`. ## Agno [Section titled “Agno”](#agno)
```py
from agno.agent.agent import Agent
from agno.models.openai import OpenAIResponses
from agno.os import AgentOS
from agno.os.interfaces.agui import AGUI
chat_agent = Agent(model=OpenAIResponses(id="gpt-5.4"))
agent_os = AgentOS(agents=[chat_agent], interfaces=[AGUI(agent=chat_agent)])
app = agent_os.get_app() # POST /agui
```
Agno serves an agent or a team over AG-UI with the `AGUI` interface of its `AgentOS`, at `POST /agui`; give that URL to `createAgUiRunner`. This is [Agno’s AG-UI example](https://docs.agno.com/agent-os/interfaces/ag-ui/introduction). ## LangGraph, Pydantic AI and Google ADK [Section titled “LangGraph, Pydantic AI and Google ADK”](#langgraph-pydantic-ai-and-google-adk) Each of these examples is a Python agent with a tool that waits for a person, and a scripted model so it runs without a key: | Framework | How the tool waits | Example | | ----------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | LangGraph | `interrupt()` with a `reason` and the call’s id, and `emit_interrupt_outcome=True` on the agent | [langgraph-ag-ui](https://github.com/apartejs/examples/tree/main/langgraph-ag-ui) | | Pydantic AI | `requires_approval=True` on the tool | [pydantic-ai-ag-ui](https://github.com/apartejs/examples/tree/main/pydantic-ai-ag-ui) | | Google ADK | `require_confirmation=True` on the tool, and `emit_interrupt_outcome=True` on the agent | [google-adk-ag-ui](https://github.com/apartejs/examples/tree/main/google-adk-ag-ui) | ADK asks through a tool of its own, `adk_request_confirmation`. Its example hides that row with [`registerToolDisplay`](/guides/tool-display/) and has the question name the real tool. ## What is not supported [Section titled “What is not supported”](#what-is-not-supported) * A person’s message goes as text and images, as AG-UI 1.0 content; other files are left out. * An interrupt the page cannot answer — one such as `input_required`, or one that names no `toolCallId` — ends the reply without an error, and is answered `cancelled` when the thread resumes or runs again. * A refusal reaches the agent as `{ approved: false }`, without the words the person wrote. The row still shows them: the runner takes the refusal from core’s `toolRefusal`, so the row says who refused (`You said: “…”`, `Refused by policy`), and the agent reads the same sentence as before. ## Next [Section titled “Next”](#next) * [TanStack AI A TanStack AI chat route, through the same runner.](/providers/agent/tanstack-ai/) * [Run the loop on your server aparté's own loop next to your tools, instead of an agent framework.](/guides/server-loop/)
# Put a chat on an n8n workflow
> Connect an n8n chat workflow — a Chat Trigger and its AI Agent — and aparté draws the conversation on your page, streamed or not, while the agent, its tools and its memory run in n8n.
## Connect the workflow [Section titled “Connect the workflow”](#connect-the-workflow)
```bash
npm install @aparte/runner-n8n @aparte/core
```
```ts
import { AparteClient } from '@aparte/core';
import { createN8nRunner } from '@aparte/runner-n8n';
new AparteClient({
streamRunner: createN8nRunner({ webhookUrl: 'https://your-n8n.example.com/webhook//chat' }),
}).start();
```
[n8n](https://n8n.io) runs the workflow: the Chat Trigger receives the message, the AI Agent answers with its model, its tools and its memory. aparté takes the place of n8n’s chat widget on your page — the page sends what the widget sends and draws the answer, so the page registers no provider and picks no model. The runner is the client’s `streamRunner`: the chat, Stop and the Markdown plugins work as they do with aparté’s own loop. What depends on the history the page keeps — retry, edit, branches, compaction — does not reach n8n’s memory; see [what is not supported](#what-is-not-supported). On a website, the button in the corner that n8n’s widget draws is [``](/components/launcher/) around the chat, in aparté’s look or your own theme:
```html
```
## Set up the workflow in n8n [Section titled “Set up the workflow in n8n”](#set-up-the-workflow-in-n8n) In the **Chat Trigger** node: 1. Turn on **Make Chat Publicly Available**. The production URL it shows, the one that ends in `/chat`, is the `webhookUrl`. 2. Put your site’s origin in **Allowed Origins (CORS)**, or `*` while you try it. 3. Set **Response Mode** to **Streaming** to see the answer arrive as it is written — the AI Agent streams by default, under *Options → Enable Streaming*. Or set it to **When Last Node Finishes** for a whole answer. 4. **Publish** the workflow (on n8n 1.x: activate it): a production URL answers only a published workflow. Attach a memory to the agent — *Simple Memory*, or any other — and n8n keeps the conversation per session, keyed by the `sessionId` the page sends. To read a session back after a reload, set **Load Previous Session** to **From Memory** and connect the memory to the Chat Trigger as well as to the agent: with the memory on the agent only, n8n answers that request with an error 500. ## Sessions and memory [Section titled “Sessions and memory”](#sessions-and-memory) The page sends only the person’s new message: the conversation lives in n8n, in the memory attached to the agent. So a session is a conversation. By default the runner starts a new session for each new conversation — a message with no reply before it — and continues it after, so two chats never share a memory. Give `sessionId` when your app keeps a conversation across reloads, and read it back with `loadN8nHistory`:
```ts
import { uuid } from '@aparte/core';
import { createN8nRunner, loadN8nHistory } from '@aparte/runner-n8n';
const webhookUrl = 'https://your-n8n.example.com/webhook//chat';
// One conversation per visitor, kept across reloads.
const sessionId = localStorage.getItem('n8n-session') ?? uuid();
localStorage.setItem('n8n-session', sessionId);
const runner = createN8nRunner({
webhookUrl,
sessionId: () => sessionId, // read on every turn
metadata: { page: location.pathname },
});
// What the person and the agent said before, from n8n's memory.
const earlier = await loadN8nHistory({ webhookUrl, sessionId });
```
`loadN8nHistory` returns messages a viewport takes (`setMessages`): what the person wrote and what the agent answered. A tool’s call and its result, which n8n’s memory stores beside them, are left out, as the live stream leaves them out. With a conversation manager, return its `activeId` from the `sessionId` function, so each conversation runs in its own session. A function is read on every turn, so it can follow the conversation your app has open. `metadata` travels with every message; the workflow reads it from the Chat Trigger’s output. The transcript on the page is aparté’s: [Conversation persistence](/guides/conversation-persistence/) keeps it, while n8n keeps what the agent remembers. ## What n8n’s answer becomes [Section titled “What n8n’s answer becomes”](#what-n8ns-answer-becomes) | n8n sends | The chat shows, and the console says | | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | the streamed frames of a node (`begin`, `item`, `end`) | the reply’s text, as it arrives | | the frames of a second node that streams | a block of its own, below the first — never interleaved | | a whole answer (`{ output }`, `text` or `message`) | the reply’s text, at once | | a whole answer with none of those fields | the [error card’s](/components/error/#what-the-card-says) sentence; the console names the fields it got and how to end the workflow — never the JSON | | an `error` frame | the error card’s sentence, below what was drawn; the console has the workflow’s message | | `keepalive` frames, every 30 seconds while a slow node runs | nothing: the stream goes on | | nothing, from a trigger that streams | the error card’s sentence; the console says to turn on streaming in the agent | | an HTTP error, such as an inactive workflow’s 404 | the error card’s sentence; the console has n8n’s message and hint | | a 428 from a workflow that waits for credentials | the error card’s sentence; the console names the credentials to connect | | a proxy’s page instead of the answer (a 502, a 504) | the timeout sentence; the console says the workflow may still be running — never the page’s markup | The runner’s message stays on the error segment’s `content`, and reaches [`setErrorRenderer`](/components/error/#customize) as `message` for an app that wants it on screen. The answer is read line by line as it streams, whatever pieces the network cuts it into. A frame type the runner does not know is skipped, and `onWarning` is told, `console.warn` by default; so is a stream cut in the middle of a frame, whose text before the cut is kept. ## Files [Section titled “Files”](#files) The files the person attaches go to the workflow as files, in a form, the way the Chat Trigger takes uploads — PDFs and spreadsheets included: the client hands the runner the files as they were picked. Give the client `rawFileInject: 'none'`, so text files are not also inlined into the message. Turn on **Allow File Uploads** in the trigger’s options, and list the types it accepts; an AI Agent reads text files and passes images on to its model. See [Attachments](/guides/attachments/). In a form, n8n hands the workflow `metadata` as text, as it does from its own widget: `JSON.parse($json.metadata)` reads it.
```ts
import { AparteClient } from '@aparte/core';
import { createN8nRunner } from '@aparte/runner-n8n';
new AparteClient({
streamRunner: createN8nRunner({ webhookUrl: 'https://your-n8n.example.com/webhook//chat' }),
rawFileInject: 'none', // the files go to n8n as files, not into the message's text
}).start();
```
## Options [Section titled “Options”](#options) | Option | What it does | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `webhookUrl` | the Chat Trigger’s production URL, ending in `/chat`, or a Webhook node’s URL; required | | `sessionId` | the n8n session a turn runs in: a string, or a function of the run’s options; a new one per new conversation by default | | `metadata` | sent with every message as `metadata`: an object, or a function of the run’s options | | `headers` | sent with every request — the trigger’s Basic Auth, say; a function is called for each, for a fresh token | | `fetch` | the `fetch` the runner calls; the global one by default | | `credentials` | for a workflow on another origin that authenticates by cookie | | `chatSessionKey` | the body field that carries the session, `sessionId` by default, for a workflow that reads another | | `chatInputKey` | the body field that carries the message, `chatInput` by default, for a workflow that reads another | | `onWarning` | told what the runner skipped; `console.warn` by default | | `WebSocket` | what a workflow with response nodes is read with; the global `WebSocket` by default | | `waitingPrefix` | the path n8n serves a waiting execution’s button links under, for an instance that moved it; by default the webhook URL’s own mount followed by `/webhook-waiting/` | These are the `N8nRunnerOptions`. `loadN8nHistory` takes `N8nHistoryOptions` — the same `webhookUrl`, `sessionId`, `metadata`, `headers`, `fetch`, `credentials` and `chatSessionKey`, plus a `signal` — and `n8nHistoryToMessages` turns the stored messages into the chat’s, for a history you fetch yourself. A Webhook node can stand in for the Chat Trigger: give its URL, read `chatInput` and `sessionId` from its body (or name your fields with `chatInputKey` and `chatSessionKey`), and answer with a streaming *Respond to Webhook* or with the agent’s output. ## Response nodes and buttons [Section titled “Response nodes and buttons”](#response-nodes-and-buttons) A Chat Trigger whose Response Mode is *Using Response Nodes* answers through **Chat** nodes placed in the workflow, over n8n’s chat WebSocket. The runner reads it: each message a Chat node sends is drawn as a block of its own, and a Chat node that waits for a written reply is answered by the next message the person sends. A Chat node that waits for an approval sends **buttons**; register what answers them once, on the config the chat renders with:
```ts
import { AparteClient } from '@aparte/core';
import { createN8nRunner, setupN8nButtons } from '@aparte/runner-n8n';
setupN8nButtons();
new AparteClient({
streamRunner: createN8nRunner({ webhookUrl: 'https://your-n8n.example.com/webhook//chat' }),
}).start();
```
The turn pauses on the buttons, which are asked at the composer with the labels the Chat node gave them; the one chosen goes back to n8n, and the workflow’s next messages follow in the same turn. Without *Block User Input*, the person may write instead, as in n8n’s widget: n8n reads the words as a message and the Chat node goes on as not approved. With it, the answer has to be a button. The transcript keeps the answer as a quiet line. Buttons are shown only when every link is **this** execution’s waiting link: http(s), on the webhook’s origin, and under n8n’s own `/webhook-waiting//…` at the place the webhook URL says n8n is mounted (webhook `https://site/n8n/webhook/…` takes `/n8n/webhook-waiting//…`; a path that only contains that segment further down does not count). If any link is not, no button is shown, `onWarning` says so, and the Chat node’s question is drawn as text. An instance that moved the waiting endpoint (`N8N_ENDPOINT_WEBHOOK_WAIT`) gives `waitingPrefix: '/n8n/webhook-waiting'`, and the links must then start with `/`. This matters because on n8n 2.x a Chat node’s message travels as plain text, so an answer that looks like a buttons frame is read as one. An error frame shows “The n8n workflow failed.”; the frame’s own words go to `onWarning`. On n8n 2.x, Chat nodes run only when the Chat Trigger’s **Mode** is *Hosted Chat*: an embedded one stops with “Embedded chat is not supported”. A runtime without a global `WebSocket` passes one as the runner’s `WebSocket` option, typed `N8nWebSocketLike`. To answer the buttons your own way, register a tool named `N8N_BUTTONS_TOOL` instead of calling `setupN8nButtons`: its input is an `N8nButtonsInput` (the question, the buttons’ labels and styles, n8n’s `blockUserInput`), and it answers with an `N8nButtonsResult` as `structuredContent` — the button’s `index` and `text`, or `written: true` with the person’s own words, which n8n hears as a message. ## What is not supported [Section titled “What is not supported”](#what-is-not-supported) * The agent’s tool calls are not drawn: n8n’s stream carries the text of the answer only, so a tool runs in n8n without a row in the chat. The answer that follows is drawn as usual. * Retry, edit and branch navigation cannot rewind n8n’s memory: n8n keeps every message it was sent, so a retried or edited turn reaches an agent that remembers the first one. Leave them off with this runner (`setBubbleActions({ retry: false, edit: false })`, their default). * Stop ends the drawing and the request, not the n8n execution, which runs to its end. * Compaction and the context gauge measure the page’s history, which n8n never receives; the memory node’s window bounds what the agent reads. ## Next [Section titled “Next”](#next) * [AG-UI agents An agent on its own server — Agno, LangGraph, Mastra — with its tool calls drawn.](/providers/agent/ag-ui/) * [Conversation persistence Keep the transcript on the page across reloads.](/guides/conversation-persistence/)
# Put a chat on a TanStack AI route
> Give a TanStack AI chat route a UI — the chat draws its stream, its tool calls and its approvals, and a tool can run in the page — in React, Vue, Svelte, Angular or plain HTML.
## Pass the run’s fields in your route [Section titled “Pass the run’s fields in your route”](#pass-the-runs-fields-in-your-route)
```ts
// app/api/chat/route.ts
import { chat, chatParamsFromRequest, mergeAgentTools, toServerSentEventsResponse } from '@tanstack/ai';
import { openaiText } from '@tanstack/ai-openai';
import { serverTools } from './tools';
export async function POST(request: Request) {
let params;
try { params = await chatParamsFromRequest(request); }
catch (error) { if (error instanceof Response) return error; throw error; } // a malformed body
return toServerSentEventsResponse(chat({
adapter: openaiText('gpt-5.5'), // your adapter: any TanStack AI text adapter
messages: params.messages,
threadId: params.threadId,
runId: params.runId,
parentRunId: params.parentRunId,
resume: params.resume,
tools: mergeAgentTools(serverTools, params.tools),
}));
}
```
[TanStack AI](https://tanstack.com/ai) runs the model, the tools and the approvals, and leaves the interface to you. Read the request with `chatParamsFromRequest` and hand `chat()` the run’s fields with the messages: `resume`, `threadId`, `runId` and `parentRunId` are what let a paused run continue. A route that passes only `messages` streams, but an approval or a tool the page ran never reaches the run. `mergeAgentTools` adds the tools the page declares to yours; a page tool must not share a name with a server tool, since the server’s wins. This route trusts the history the browser sends `chat()` rebuilds a paused run from the messages in the request, so a caller can write the pause itself: an assistant message with a call to one of your server tools, and the approval that answers it. `needsApproval` is a prompt to the person, not a check on your server. Every server tool decides whether *this user* may run *these arguments*, and one without `needsApproval` runs from a call the caller invented. [Pin the pauses to your server](#pin-the-pauses-to-your-server) below shows how to refuse a call the route never made. ## Connect the page [Section titled “Connect the page”](#connect-the-page)
```bash
npm install @aparte/runner-ag-ui @aparte/core
```
```ts
import { AparteClient } from '@aparte/core';
import { createAgUiRunner } from '@aparte/runner-ag-ui';
new AparteClient({
streamRunner: createAgUiRunner({ endpoint: '/api/chat', relaxedRunFraming: true }),
}).start();
```
The route streams AG-UI, so [`@aparte/runner-ag-ui`](/providers/agent/ag-ui/) draws it as it is: text, reasoning, tool rows, the approval panel. Your route stays a TanStack AI route. `relaxedRunFraming` is what lets the runner read it: TanStack AI, 1.0 included, closes each model step with a `RUN_FINISHED` and answers a resume before its `RUN_STARTED`, a framing AG-UI 1.0 asks a client to reject. Every other rule of the protocol still holds. Under a framework, hand the same runner to the wrapper’s client: `useAparteClient({ streamRunner })` in React and Vue, `createAparteClient({ streamRunner })` in Svelte, `provideAparte({ clientOptions: { streamRunner } })` in Angular. ## Approvals and tools in the page [Section titled “Approvals and tools in the page”](#approvals-and-tools-in-the-page) * **`needsApproval: true`** on a server tool pauses the run. The page asks with its [approval panel](/guides/tools/#require-approval-human-in-the-loop), and its [approval policy](/components/approval-mode/) can answer first. Approve runs the tool on your server; Reject sends `{ approved: false }`, without the words the person wrote, and the row stays refused; it still says who refused (`You said: “…”` for a person’s words, `Refused by policy` for your approval policy). * **A tool that needs the page** — `ask_user` through `setupAskUser()`, your own through `registerTool` — reaches your route as a declared tool, which `mergeAgentTools` adds. TanStack AI pauses on it, the page runs it, and its result resumes the run: TanStack’s `.client()` implementation is not needed, the page’s handler is the implementation. As with any [AG-UI agent](/providers/agent/ag-ui/#tools-the-page-runs), the page asks nobody before running it. ## Pin the pauses to your server [Section titled “Pin the pauses to your server”](#pin-the-pauses-to-your-server) A server tool that deletes, pays or sends does not rely on `needsApproval`: it checks the caller’s rights on its own input, as a [server-loop tool does](/guides/server-loop/#what-the-ticket-protects-and-what-it-does-not). What the route can add is a record of what it did: every call to a server tool it made (who for, in which thread, with which arguments, and whether it ran) and every pause it raised. Then it refuses a request whose history holds a call to a server tool it never made, whatever else that request carries, a call that already ran and comes back without its result (TanStack runs a call that has no result row, so that is how a call would run twice), and a resume that is not for a pause it raised, for this user, in this thread, and not yet answered. It reads the history the way TanStack’s `chat()` does, through `convertMessagesToModelMessages`, not the rows as they arrived: a result row tagged `subagentRunId` is taken out of the conversation by `chat()`, so it must not count as the answer to a call either. The ticket of the [server loop](/guides/server-loop/) does the same with a signature, for a server that stores nothing.
```ts
// app/api/chat/pauses.ts
import { convertMessagesToModelMessages } from '@tanstack/ai';
type Event = {
type: string;
toolCallId?: string;
toolCallName?: string;
delta?: string;
outcome?: { type?: string; interrupts?: Array> };
};
type Call = { name: string; args: string; user: string; thread: string; ran: boolean };
type Pause = { run: string; user: string; thread: string; answered: boolean };
// Both maps live in memory here. Use a database with an expiry when you run several
// instances, restart, or want a pause to lapse.
const calls = new Map(); // toolCallId → the call this server made
const pauses = new Map(); // interruptId → the pause this server raised
/** The same text whatever the order of an object's keys. */
function canonical(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
if (value && typeof value === 'object') {
const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1));
return `{${entries.map(([key, v]) => `${JSON.stringify(key)}:${canonical(v)}`).join(',')}}`;
}
return JSON.stringify(value) ?? 'null';
}
/** A call's arguments, as text that is equal when the arguments are. */
function argsOf(text: unknown): string {
try { return canonical(!text ? {} : JSON.parse(String(text))); } catch { return `unreadable:${text}`; }
}
/** Pass chat()'s events through, noting each call it makes and each pause it raises for `user`. */
export async function* notePauses(
events: AsyncIterable,
user: string,
thread: string,
run: string,
): AsyncGenerator {
const names = new Map();
const streamed = new Map();
for await (const event of events) {
const id = event.toolCallId;
if (id && event.type === 'TOOL_CALL_START') { names.set(id, String(event.toolCallName)); streamed.set(id, ''); }
if (id && event.type === 'TOOL_CALL_ARGS') streamed.set(id, (streamed.get(id) ?? '') + (event.delta ?? ''));
if (id && event.type === 'TOOL_CALL_END' && names.has(id)) {
calls.set(id, { name: names.get(id)!, args: argsOf(streamed.get(id)), user, thread, ran: false });
}
// The tool ran (or was refused): chat() has an answer for the call, and will not ask for another.
if (id && event.type === 'TOOL_CALL_RESULT' && calls.has(id)) calls.get(id)!.ran = true;
if (event.type === 'RUN_FINISHED' && event.outcome?.type === 'interrupt') {
for (const pause of event.outcome.interrupts ?? []) pauses.set(pause.id, { run, user, thread, answered: false });
}
yield event;
}
}
/**
* Why the request must be refused, or `undefined` when it only continues what this server did for
* `user`. Returning `undefined` also marks the pauses it resumes as answered: a pause is answered once.
*/
export function refusal(
params: { threadId: string; parentRunId?: string; messages: any[]; resume?: Array<{ interruptId: string }> },
user: string,
serverTools: string[],
): string | undefined {
const resumed: Pause[] = [];
for (const { interruptId } of params.resume ?? []) {
const pause = pauses.get(interruptId);
if (!pause || pause.answered || pause.user !== user || pause.thread !== params.threadId || pause.run !== params.parentRunId) {
return `Unknown pause ${interruptId}`;
}
resumed.push(pause);
}
// Read the history the way chat() reads it, through TanStack's own conversion: it moves a message
// tagged `subagentRunId` out of the conversation, turns a message written as `parts` into calls and
// result rows, and so on. A check on the raw rows would be checking a history chat() does not see.
let history: any[];
try { history = convertMessagesToModelMessages(params.messages as never) as any[]; }
catch { return 'Unreadable history'; }
// chat() runs any call in the last assistant message that has no result row (or a
// `pendingExecution` placeholder), so the result rows the request carries matter.
const answered = new Set();
for (const row of history) {
if (row.role !== 'tool' || !row.toolCallId) continue;
let pending = false;
try { pending = JSON.parse(String(row.content))?.pendingExecution === true; } catch { /* a plain result */ }
if (!pending) answered.add(row.toolCallId);
}
// Every call to a server tool in the history must be one this server made, with these arguments:
// whether it has a result row or not, since the row comes from the caller too. And one that
// already ran comes back only with its result row: without it, chat() would run it again.
for (const message of history) {
if (message.role !== 'assistant') continue;
for (const call of message.toolCalls ?? []) {
if (!serverTools.includes(call.function?.name)) continue;
const made = calls.get(call.id);
if (!made || made.user !== user || made.thread !== params.threadId || made.name !== call.function.name || made.args !== argsOf(call.function.arguments)) {
return `The call ${call.id} was not made by this server`;
}
if (made.ran && !answered.has(call.id)) return `The call ${call.id} already ran`;
}
}
for (const pause of resumed) pause.answered = true;
return undefined;
}
```
Then the route asks it before running anything, and requires `application/json`: a page on another site can post a form with `text/plain`, and a cookie goes with it, while a JSON body needs a CORS preflight your route does not answer.
```ts
import { notePauses, refusal } from './pauses';
export async function POST(request: Request) {
if (!request.headers.get('content-type')?.startsWith('application/json')) {
return new Response('Send application/json', { status: 415 });
}
const user = await userOf(request); // your session; no user, no chat
if (!user) return new Response('Sign in', { status: 401 });
let params;
try { params = await chatParamsFromRequest(request); }
catch (error) { if (error instanceof Response) return error; throw error; }
const problem = refusal(params, user, serverTools.map((tool) => tool.name));
if (problem) return new Response(problem, { status: 400 });
return toServerSentEventsResponse(notePauses(chat({
adapter: openaiText('gpt-5.5'),
messages: params.messages,
threadId: params.threadId,
runId: params.runId,
parentRunId: params.parentRunId,
resume: params.resume,
tools: mergeAgentTools(serverTools, params.tools),
}), user, params.threadId, params.runId));
}
```
A forged call or approval now gets a 400 and runs nothing, and an approval can be answered once: a resume that fails before the tool ran needs a new approval. A call the route made, a pause it raised, answered by the person it was raised for, runs as before. Because the record is in memory, a conversation that outlives a restart is refused until its calls are in your database: keep them there if conversations are long. The arguments can still be edited by the person who approves (TanStack’s `editedArgs`), so the tool’s own check stays. It works with `@tanstack/ai` `^1.0.0`. TanStack AI is at 1.x, and a major can change its wire: check that range when you upgrade it. ## Next [Section titled “Next”](#next) * [AG-UI agents What the stream becomes, the options, and what is not supported.](/providers/agent/ag-ui/) * [Tools and approval The tool rows and the approval panel the route's calls use.](/guides/tools/)
# Connect Claude, Gemini and other vendors through the Vercel AI SDK
> Bring an @ai-sdk/* package — Anthropic, Google, Amazon Bedrock and the others the SDK supports — and the chat streams its replies, reasoning and tool calls.
## Install and register [Section titled “Install and register”](#install-and-register)
```bash
npm install @aparte/core @aparte/provider-ai-sdk ai @ai-sdk/anthropic
```
```ts
import { createAnthropic } from '@ai-sdk/anthropic';
import { createAiSdkProvider } from '@aparte/provider-ai-sdk';
import { aparteGlobalConfig, AparteClient, AparteDirectTransport } from '@aparte/core';
aparteGlobalConfig.registerAIProvider(createAiSdkProvider({
id: 'anthropic',
name: 'Anthropic',
languageModel: (modelId, auth) =>
createAnthropic({
apiKey: typeof auth === 'string' ? auth : auth?.apiKey,
headers: { 'anthropic-dangerous-direct-browser-access': 'true' }, // a key used from the browser
})(modelId),
}));
aparteGlobalConfig.setTransport(new AparteDirectTransport({ byok: true }));
aparteGlobalConfig.setModelConfig({ defaultProvider: 'anthropic', defaultModel: 'claude-sonnet-4-5' });
new AparteClient({
keyResolver: (providerId) => localStorage.getItem(`${providerId}.key`) ?? undefined, // the person's key
}).start();
```
The provider needs `ai` in the range `^7.0.0` beside it, and the `@ai-sdk/*` package of your vendor; its options are an `AiSdkProviderOptions`. `languageModel` is called for each request with the model’s id and what the [key resolver](/providers/#the-key) answered, so a key the person types reaches the vendor’s SDK; a factory that already holds its key ignores `auth`. Stop cancels the vendor’s call. ## Choose the model [Section titled “Choose the model”](#choose-the-model) The SDK has no list of models to fetch. Choose the model with `setModelConfig`, as above, or give the provider a `models` option: the [model selector](/components/model-selector/) lists those, and the client reads a model’s capabilities from them; a model without `capabilities` is sent the tools. Without `models`, the selector shows nothing for this provider. ## What maps to what [Section titled “What maps to what”](#what-maps-to-what) | From the SDK | In the chat | | -------------------------- | ------------------------------------------------------------------ | | text | the reply | | reasoning | a [reasoning block](/components/reasoning/) | | a tool call | a [tool](/guides/tools/) the chat runs, then calls the model again | | the finish, with its usage | the end of the reply, with its tokens, cached ones included | | an error | the message’s error | The provider calls `streamText` for one step at a time: the tools go as declarations without an `execute`, and the chat’s loop runs them. An image in the person’s message goes as an image part. ## In a server route [Section titled “In a server route”](#in-a-server-route) `toModelMessages`, `toToolSet`, `toToolChoice` and `fullStreamToAparteEvents` are exported on their own, to answer the chat from a route that already uses the SDK ([Keep the key on your server](/guides/backend-transport/#if-your-server-already-uses-the-ai-sdk)). `fullStreamToAparteEvents` passes the vendor’s error text along, and a vendor’s refusal can quote parts of the key: replace an `error` event with a message of your own before it leaves the server. ## Next [Section titled “Next”](#next) * [Keep the key on your server The same vendors, with the key on your server.](/guides/backend-transport/) * [OpenAI-compatible The vendors that speak OpenAI's format, with no SDK.](/providers/ai/openai-compat/)
# Connect OpenAI and every OpenAI-compatible endpoint
> One adapter for every OpenAI-compatible endpoint: OpenAI, Mistral, OpenRouter, Ollama, LM Studio, Groq, vLLM, or your own backend's /v1 chat completions.
## Register a preset, or any endpoint [Section titled “Register a preset, or any endpoint”](#register-a-preset-or-any-endpoint)
```bash
npm install @aparte/core @aparte/provider-openai-compat
```
```ts
import { aparteGlobalConfig } from '@aparte/core';
import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat';
aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider(presets.MISTRAL));
aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider({
id: 'groq',
name: 'Groq',
baseURL: 'https://api.groq.com/openai/v1',
}));
```
`createOpenAICompatProvider` takes an `OpenAICompatProviderOptions`. A preset is one filled in — a vendor’s base URL and branding — and any other endpoint takes an `id` and its `baseURL`. Spread a preset to change a field: `{ ...presets.OPENAI, baseURL: 'https://my-proxy.example/v1' }`. The key goes through the [key resolver](/providers/#the-key). Nothing is selected until you name a model — `aparteGlobalConfig.setModelConfig({ defaultProvider: 'mistral', defaultModel: 'mistral-small-latest' })` — or the person picks one in the [model selector](/components/model-selector/). | Preset | Base URL | Key | | --------------------------------- | -------------------------------------- | ------------------------------ | | `presets.OPENAI` — OpenAI | `https://api.openai.com/v1` | yours | | `presets.MISTRAL` — Mistral AI | `https://api.mistral.ai/v1` | yours | | `presets.ZAI` — Z.ai (Zhipu) | `https://open.bigmodel.cn/api/paas/v4` | yours | | `presets.OPENROUTER` — OpenRouter | `https://openrouter.ai/api/v1` | yours | | `presets.PERPLEXITY` — Perplexity | `https://api.perplexity.ai` | yours | | `presets.LMSTUDIO` — LM Studio | `http://localhost:1234/v1` | none, a server on your machine | | `presets.OLLAMA` — Ollama | `http://localhost:11434/v1` | none, a server on your machine | | `presets.LLAMACPP` — llama.cpp | `http://localhost:8080/v1` | none, a server on your machine | | `presets.VLLM` — vLLM | `http://localhost:8000/v1` | none, a server on your machine | `presets.OPENROUTER` sends OpenRouter’s attribution headers, `HTTP-Referer` with the page’s origin and `X-Title: aparté`; name your app with `{ ...presets.OPENROUTER, extraHeaders: { 'HTTP-Referer': location.origin, 'X-Title': 'My app' } }`. ## The list of models [Section titled “The list of models”](#the-list-of-models) The provider fetches `GET {baseURL}/models`, and the [model selector](/components/model-selector/) lists each model by its `name`, or its `id` when the server sends none. The model’s window, the `contextWindow` the [context gauge](/components/context-gauge/) and compaction read, comes from the entry’s `context_length` (OpenRouter, Together), `max_model_len` (vLLM), `context_window` (Groq) or `max_context_length` (Mistral). With `server` set, as the LM Studio, Ollama and llama.cpp presets do, the provider also asks that server’s own API for the window it runs the model with, which wins over the trained maximum: LM Studio’s `/api/v1/models` (or `/api/v0/models`), Ollama’s `/api/ps`, llama.cpp’s `/props`. A model the server has not loaded has no window until it is. A `contextWindow` you give a model in `models` wins over all of them. Each fetched model is marked as streaming and calling tools. A cloud provider fetches nothing without a key; a local one — `isLocal: true`, which the local-server presets set — lists its models with none. A `models` option gives the provider a list of its own, which the client reads for a model the fetched list does not have: a fetched entry with the same id wins, and the selector shows only the fetched list. An endpoint with no `GET /models` at all says so with `listsModels: false`, as the Perplexity preset does: `fetchModels` then serves `models` without asking. ## Sources and citations [Section titled “Sources and citations”](#sources-and-citations) A search model’s sources reach the reply on their own: the `url_citation` annotations of OpenAI’s search models and of OpenRouter’s web search (an `:online` model, or `plugins: [{ id: 'web' }]` in `extraBody`), and Perplexity’s `search_results` with the `[1]` markers in its text, streamed or not. Each becomes a chip at the end of the passage it backs and a line in the list under the reply — see [Sources and citations](/guides/citations/). ## Fields the OpenAI format does not have [Section titled “Fields the OpenAI format does not have”](#fields-the-openai-format-does-not-have)
```ts
import { aparteGlobalConfig } from '@aparte/core';
import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat';
aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider({
...presets.ZAI,
extraBody: { thinking: { type: 'disabled' } },
}));
```
`extraBody` adds fields to every request body, for a vendor’s own switch — here, Z.ai’s `thinking` field — and `extraHeaders` adds headers to every request and to the list of models; spreading a preset with `extraHeaders` replaces its own. The fields the adapter writes itself stay its own: `model`, `messages`, `temperature`, `max_tokens`, `stream`, `stream_options`, `seed`, `tools` and `tool_choice`. ## What it sends and reads [Section titled “What it sends and reads”](#what-it-sends-and-reads) | In the chat | On the wire | | ---------------------------------- | --------------------------------------------------------------------------------------- | | registered tools | `tools`, with `tool_choice: 'auto'`, or the tool a `toolChoice` forces | | an image part in a message | an `image_url` part; an assistant turn that calls tools goes as text only | | `temperature`, `maxTokens`, `seed` | `temperature`, `max_tokens`, `seed` | | the usage of a reply | `stream_options.include_usage`, read back as input, output, total and cached tokens | | reasoning | `reasoning_content` in the stream, drawn as a [reasoning block](/components/reasoning/) | The key goes as `Authorization: Bearer …`, and a key pasted with its `Bearer `is not doubled. ## Without aparté’s client [Section titled “Without aparté’s client”](#without-apartés-client)
```ts
import { readableToAsyncIterable } from '@aparte/core';
import type { AparteChatRequest } from '@aparte/core';
import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat';
const provider = createOpenAICompatProvider(presets.MISTRAL);
const request: AparteChatRequest = { messages: [{ role: 'user', content: 'hi' }], modelId: 'mistral-small-latest', stream: true };
const { path, body, headers } = provider.buildRequest(request);
const response = await fetch(`${provider.defaultEndpoint}${path}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers, ...provider.authHeaders(process.env['MISTRAL_API_KEY'] ?? '') },
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`); // an error body has no events
const stop = new AbortController();
for await (const event of readableToAsyncIterable(provider.parseStream(response.body!), stop.signal)) {
// text, thinking, tool_use, error, then done with its usage
}
```
The provider is the wire format alone: build the request, send it yourself, read the stream back as events — in a server route, a worker, another process. It is an `OpenAICompatProvider`, whose `buildRequest`, `authHeaders` and `parseText` are always there; `parseOpenAICompatStream(body)` is the same stream reader on its own. `readableToAsyncIterable` makes the stream something `for await` reads in every browser. ## A model on your machine [Section titled “A model on your machine”](#a-model-on-your-machine) Ollama and LM Studio speak this format at their `/v1` endpoint — for Ollama, rather than its own `/api/chat`. [Local models](/guides/local-models/) covers the browser’s permission, llama.cpp, and picking a model. ## Next [Section titled “Next”](#next) * [Local models Ollama, LM Studio or llama.cpp, from the browser.](/guides/local-models/) * [Vercel AI SDK Anthropic, Google and the vendors this format does not reach.](/providers/ai/ai-sdk/) * [Keep the key on your server The same provider, called from your server.](/guides/backend-transport/)
# Script a model for demos and tests
> Replay turns you wrote — text at a typing pace, reasoning, tool calls, errors — with no key and no network, the same way every time, for a demo page or your own tests.
## Script the replies [Section titled “Script the replies”](#script-the-replies)
```bash
npm install @aparte/core @aparte/provider-scenario @aparte/plugin-marked marked
```
```html
```
```ts
import { aparteGlobalConfig, AparteClient, AparteDirectTransport } from '@aparte/core';
import { createScenarioProvider } from '@aparte/provider-scenario';
import { setupMarkedProvider } from '@aparte/plugin-marked';
setupMarkedProvider(); // draws the **markdown** below; without it, text streams plain
aparteGlobalConfig.registerAIProvider(createScenarioProvider({
turns: [
'Hello! Ask me anything.',
[{ thinking: 'Let me see…' }, { text: 'Here is my **answer**, with *markdown*.' }],
],
}));
aparteGlobalConfig.setTransport(new AparteDirectTransport({ byok: true }));
new AparteClient().start();
```
The provider never calls a model: it replays the turns you wrote, and everything around it — the loop, your tools, the transcript — runs for real. `turns` answers the calls in order and repeats the last one; every call advances, a retry and the second half of a tool round-trip included. Given both `turns` and `scenarios`, `turns` answers. The client adds the person’s message itself. A turn, a `ScenarioTurn`, is a string — one text step — or a list of `ScenarioStep`s: | Step | What it does | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `{ text }` | streams the text, drawn as [Markdown](/guides/markdown/) once a Markdown plugin is set up | | `{ thinking }` | streams reasoning | | `{ tool, input?, id? }` | calls the tool of that name: the loop runs the handler you registered and calls the provider again with its result | | `{ error }` | fails the turn with that message; the steps after it do not run | | `{ sources, citations? }` | sends the [sources](/guides/citations/) the turn’s text cites, and where — offsets into the text the turn has streamed | | `{ wait }` | pauses for that many milliseconds | | `{ usage }` | replaces fields of the usage reported at the end | ## Answer by what was asked [Section titled “Answer by what was asked”](#answer-by-what-was-asked)
```ts
import { createScenarioProvider } from '@aparte/provider-scenario';
createScenarioProvider({
scenarios: {
default: 'Ask me for a haiku, or the weather.',
haiku: { when: /haiku/i, turn: 'Web components hum — \nno framework in the wind, \njust the page, alive.' },
weather: { when: 'weather', turn: [{ text: 'Let me check.' }, { tool: 'get_weather', input: { city: 'Lille' } }] },
forecast: { after: 'get_weather', turn: 'Cloudy, 14 °C. Bring a jacket.' },
},
});
```
A `Scenario` is `{ when?, after?, turn }`, or a bare turn. Each call picks one: after a tool, the one whose `after` names it; otherwise the first whose `when` matches the last message — the person’s, or a tool’s result that no `after` claims — a string as a substring, any case, a RegExp as it is; otherwise `default`, or the first one declared. A tool called here only runs if the app registered one of that name; one that is not fails the call, as it would with a real model. A tool with no `after` route hands its result to whatever that rule picks next. When that is the scenario that called the tool, the call repeats until the client’s `maxTurns` stops it, so the provider warns when you create it. ## Branch on the person’s answer [Section titled “Branch on the person’s answer”](#branch-on-the-persons-answer)
```ts
import { aparteGlobalConfig } from '@aparte/core';
import { createScenarioProvider } from '@aparte/provider-scenario';
import { setupAskUser } from '@aparte/plugin-ask-user';
setupAskUser(); // registers ask_user, and draws its question
aparteGlobalConfig.registerAIProvider(createScenarioProvider({
scenarios: {
start: { turn: [{ tool: 'ask_user', input: { question: 'Where do you run?', options: [{ title: 'browser' }, { title: 'server' }] } }] },
browser: { turn: 'In the browser, then: the direct transport, your key stays local.' },
server: { turn: 'On a server: the backend transport, the key never leaves it.' },
other: { turn: 'Either works: start with the direct transport.' },
},
match: (request, scenarios) => {
const last = request.messages[request.messages.length - 1];
if (last?.role !== 'tool') return 'start'; // a message from the person
const picked = String(last.content).trim(); // the tool's result: "browser" or "server"
return Object.hasOwn(scenarios, picked) ? picked : 'other'; // a decline, an answer of their own
},
}));
```
`after` routes on which tool ran, not on what it answered. To pick the next scenario from the answer — the option chosen in an `ask_user` question, a step of a wizard — read the tool’s result in a `match` of your own, from the last message: earlier results stay in the history of every later call. It returns a scenario’s key, or `undefined` to leave the call to the rule above, which ships as `defaultMatch`; a key it does not know streams an empty turn and says so in the console. Here the creation warning is expected: your `match` routes the result. ## Pace, usage and models [Section titled “Pace, usage and models”](#pace-usage-and-models) `pacing`, a `ScenarioPacing`, is `{ chunk: 12, delay: 24 }` by default — twelve characters every 24 ms — and `pacing: 'instant'` gives a test the whole reply at once. A turn ends with its usage, estimated at four characters a token with its duration, so a [context gauge](/components/context-gauge/) given a `window` moves; a failed turn reports none. The provider is local and needs no key. It offers one model, `scripted`, which streams and calls tools, and the [model selector](/components/model-selector/) lists it. `models` replaces that list; with more than one, pick one with the selector or `setModelConfig`. Its `id` is `scenario` and its `name` `Scripted model` unless its `ScenarioProviderOptions` say otherwise. The `turns` cursor belongs to the provider, so two chats on one provider take turns from the same script: create one per chat, or use `scenarios`, which answers from the request and keeps nothing. ## The ready-made showcase [Section titled “The ready-made showcase”](#the-ready-made-showcase)
```ts
import { aparteGlobalConfig } from '@aparte/core';
import { createScenarioProvider } from '@aparte/provider-scenario';
import { showcase } from '@aparte/provider-scenario/showcase';
aparteGlobalConfig.registerAIProvider(createScenarioProvider({ scenarios: showcase }));
```
`showcase` is the set this site’s live examples run on: Markdown, a table, code, reasoning, tool calls, questions, an artifact, a slow turn and a failure. It ships on its own entry point, so your own scenarios never bring it into your bundle. It answers what the person types: | Scenario | Starts when the message matches | | ----------- | ------------------------------------------------------------------------------------- | | `haiku` | `/haiku/i` | | `table` | `/table/i` | | `math` | `/math\|equation\|formula\|latex\|integral/i` | | `diagram` | `/diagram\|flowchart\|flow chart\|mermaid/i` | | `citations` | `/\bsources\b\|\bcit(?:e\|es\|ation\|ations)\b\|why is the sky\|sky blue\|rayleigh/i` | | `code` | `/code\|example\|snippet/i` | | `weather` | `/weather\|forecast/i` | | `release` | `/ship it\|release\|checklist/i` | | `survey` | `/survey\|two questions\|a few questions/i` | | `question` | `/question\|ask me\|colou?r scheme/i` | | `artifact` | `/artifact\|document\|write me/i` | | `slow` | `/slow\|think hard\|take your time/i` | | `failure` | `/fail\|error\|crash/i` | It calls `get_weather`, `search_docs`, `read_file`, `write_file`, `run_command` and `ask_user`: register those tools with `aparteGlobalConfig.registerTool` for its tool turns to run, `ask_user` through `setupAskUser()` from [`@aparte/plugin-ask-user`](/guides/elicitation/#let-the-model-ask), and `setupArtifacts()` from the [artifacts plugin](/components/artifact/) for its artifact to be drawn as a card. ## In your tests [Section titled “In your tests”](#in-your-tests)
```ts
import type { AparteChatRequest } from '@aparte/core';
import { playTurn } from '@aparte/provider-scenario';
const request: AparteChatRequest = { messages: [{ role: 'user', content: 'Hi' }], modelId: 'scripted' };
const reader = playTurn([{ text: 'Hello.' }, { tool: 'search', input: { q: 'docs' } }], request, 'instant').getReader();
const events = [];
for (let next = await reader.read(); !next.done; next = await reader.read()) events.push(next.value);
// { type: 'text', delta: 'Hello.' }, then { type: 'tool_use', name: 'search', … }, then { type: 'done', usage }
```
A chat on this provider behaves the same at every run, which is what a test of your app around the chat needs; `playTurn` gives the events of one turn with no provider at all. It stands in for the whole provider: what sits above it runs for real, and what sits below — a wire format, the network, a provider of yours — does not run at all, so test that layer with a fake of its own. ## Next [Section titled “Next”](#next) * [Tools and approval The tools a scripted turn calls, and the approval asked before they run.](/guides/tools/) * [Connect a model The providers that reach a real model, when the script is done.](/providers/)
# Run a model in the browser
> Run a language model inside the page with Transformers.js, on the graphics card through WebGPU or on the processor through WASM — no server, no key — with its download shown, its cache kept and its memory released.
## Register a model [Section titled “Register a model”](#register-a-model)
```bash
npm install @aparte/core @aparte/provider-transformers @huggingface/transformers
```
```ts
import { aparteGlobalConfig, AparteClient } from '@aparte/core';
import { TransformersProvider, registerModel } from '@aparte/provider-transformers';
registerModel({
id: 'onnx-community/Qwen2.5-0.5B-Instruct',
name: 'Qwen2.5 0.5B',
capabilities: ['streaming'],
dtype: 'q4',
});
aparteGlobalConfig.registerAIProvider(TransformersProvider);
new AparteClient().start();
```
The model runs in a Web Worker, off the page’s main thread, through the [Transformers.js](https://huggingface.co/docs/transformers.js) you install beside the provider; its weights download once into the browser’s cache. `capabilities` is required: `['streaming']` for a chat model. With one model registered, the chat uses it; with several, name one with `aparteGlobalConfig.setModelConfig({ defaultProvider: 'transformers', defaultModel })`, or let the person pick in the [model selector](/components/model-selector/). A reply stops at 8192 tokens, or sooner where the model’s context window ends, and Stop interrupts it. To change the ceiling, give the model a `maxTokens` in `registerModel`, or set `maxTokens` on the request, which wins: `new AparteClient({ requestInterceptor: (r) => ({ ...r, maxTokens: 16000 }) })`. The built-in runners send a model no tools, and a conversation that already holds tool calls runs with those calls and their results left out of the prompt; the console says so once. A [runner of your own](#a-runner-of-your-own) receives the request’s tools. ## Bundler, CDN and security policy [Section titled “Bundler, CDN and security policy”](#bundler-cdn-and-security-policy) The package starts its worker with `new Worker(new URL('./worker.js', import.meta.url))`, the form Vite and webpack recognise. From a CDN, map `@huggingface/transformers` in the page’s import map beside the provider. When the package is served from another origin than the page — a CDN, an asset host — the provider starts its worker from a `blob:` URL. A Content-Security-Policy then allows `blob:` in `worker-src` (or `script-src`), and, for the model itself, the hosts it comes from in `connect-src` — huggingface.co, and cdn.jsdelivr.net, where Transformers.js fetches its WASM runtime by default — with `'wasm-unsafe-eval'` in `script-src`. ## Show the download [Section titled “Show the download”](#show-the-download)
```ts
import { TransformersProvider } from '@aparte/provider-transformers';
declare const bar: HTMLProgressElement;
bar.max = 100;
await TransformersProvider.prepareModel('onnx-community/Qwen2.5-0.5B-Instruct', (p) => {
if (p.progress !== undefined) bar.value = p.progress; // this file's percentage: each file starts at 0
bar.title = p.file ?? p.status; // 'downloading' (from the network or the cache), 'loading', 'ready'
});
```
A first load downloads the whole model. `prepareModel` downloads and loads it before the first message, reporting each file as a `ModelLoadProgress`, and rejects if the load fails; without it, the first message loads the model and the reply waits with no progress to show. `TransformersProvider.getModelStatus(id)` answers `'ready'` once the model is loaded, `'cached'` when its files are in the cache or while it loads, and `'not-downloaded'` otherwise. The [model selector](/components/model-selector/) lists the registered models, and only those: register a model downloaded earlier to offer it. `listCachedModels()` reports everything in the cache, for a settings panel. ## The cache and the memory [Section titled “The cache and the memory”](#the-cache-and-the-memory) | Function | What it does | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `listCachedModels()` | the models in the browser’s cache, each a `CachedModelEntry`: `modelId`, `name`, `sizeBytes`, `loaded` | | `deleteCachedModel(id)` | deletes that model’s cached files, and only its own — a model whose id extends it keeps its weights — ending the worker first if the model is loaded; `TransformersProvider.deleteModel` does the same | | `setMaxCachedModels(n)` | how many of your registered models stay downloaded: `1` by default, `0` for no limit | | `getLoadedModelId()` | the model in the worker’s memory, or `null` | | `terminateWorker()` | ends the worker and the model in memory; a reply still streaming ends with an error | The worker holds one model in memory at a time, for the whole page: two chats on the same model share it, and two chats on different models take turns, each reply loading its own model again — the console warns once. Another model replaces the one in memory; closing a chat does not release it. `terminateWorker()` does, on leaving the route or behind an “unload” button, and the next message starts a new worker. When a model finishes loading and the cache holds more of your registered models than `setMaxCachedModels` allows, the others are deleted, the earliest downloaded first. Only the models given to `registerModel` count: weights your app downloaded with Transformers.js for something else are neither counted nor deleted. The budget bounds what stays on disk, not memory, which holds one model whatever it says. At the default of one, switching to another model deletes the previous one’s weights, so switching back downloads it again; `setMaxCachedModels(2)` keeps both, and `0` keeps everything. ## Choose the device [Section titled “Choose the device”](#choose-the-device)
```ts
import { aparteGlobalConfig } from '@aparte/core';
import { detectHardware, registerModel, setHardwareTierModels } from '@aparte/provider-transformers';
registerModel({ id: 'onnx-community/Qwen2.5-0.5B-Instruct', name: 'Qwen2.5 0.5B', capabilities: ['streaming'], dtype: 'q4' });
registerModel({ id: 'onnx-community/Qwen3-0.6B-ONNX', name: 'Qwen3 0.6B', capabilities: ['streaming'], dtype: 'q4' });
setHardwareTierModels({ low: 'onnx-community/Qwen2.5-0.5B-Instruct', high: 'onnx-community/Qwen3-0.6B-ONNX' });
const { recommendedModelId } = await detectHardware();
aparteGlobalConfig.setModelConfig({ defaultProvider: 'transformers', defaultModel: recommendedModelId });
```
A model runs on the graphics card when the browser has a WebGPU adapter, and on the processor through WASM otherwise; a model that fails to load on the graphics card is loaded again on WASM, and the console says so. `setComputeDevice` forces one, a `ComputeDevice`: `'webgpu'`, `'wasm'`, or `'auto'`, the default; `getComputeDevice()` reads it back. It is one setting for the page — a `device` on a registered model is not read — and it applies when a model loads: to change it afterwards, call `terminateWorker()`, and the next message loads the model on the new device. `detectHardware()` answers a `HardwareProfile`: it looks for a WebGPU adapter and sorts the machine into a `low`, `mid` or `high` tier — no WebGPU adapter, whatever the hardware, or under 4 GB of memory is low, under 8 GB is mid — then answers the model you gave that tier, or the `high` one for a tier you left out. Only Chromium reports the memory, and at most 8 GB; in other browsers the machine counts as 4 GB. ## A model that reads images [Section titled “A model that reads images”](#a-model-that-reads-images)
```ts
import { registerModel } from '@aparte/provider-transformers';
registerModel({
id: 'HuggingFaceTB/SmolVLM-256M-Instruct',
name: 'SmolVLM 256M',
task: 'image-text-to-text',
capabilities: ['streaming', 'vision'],
dtype: { embed_tokens: 'fp16', vision_encoder: 'q4', decoder_model_merged: 'q4' },
});
```
`task` picks the runner that loads the model: `'text-generation'`, the default, for a chat model, and `'image-text-to-text'` for one that reads the images the person [attaches](/guides/attachments/) — SmolVLM, Qwen2-VL, Gemma 3 and the other models Transformers.js loads as `AutoModelForImageTextToText`. `dtype` is one precision for the whole model, or one per part, as here. A text model sent an image answers without it, and the console says the image was left out. Stop interrupts the model itself, not only the reply on screen. ## A runner of your own [Section titled “A runner of your own”](#a-runner-of-your-own)
```ts
import { registerModel } from '@aparte/provider-transformers';
registerModel({ id: 'my-org/my-model', name: 'Mine', capabilities: ['streaming'], runner: '/runners/mine.js' });
```
```js
// /runners/mine.js — served as it is (from public/ under a bundler); the worker imports it by URL
export async function createRunner(ctx) {
const { AutoTokenizer, AutoModelForCausalLM, TextStreamer, InterruptableStoppingCriteria } = ctx.transformers;
const tokenizer = await AutoTokenizer.from_pretrained(ctx.modelId);
const model = await AutoModelForCausalLM.from_pretrained(ctx.modelId, {
dtype: ctx.dtype,
device: ctx.device,
});
return {
async generate({ messages, options, emit, signal }) {
if (signal.aborted) return;
const turns = messages
.filter((m) => m.role === 'user' || m.role === 'assistant' || m.role === 'system')
.map((m) => ({ role: m.role, content: typeof m.content === 'string' ? m.content : m.content.filter((p) => p.type === 'text').map((p) => p.text).join('') }));
const inputs = tokenizer.apply_chat_template(turns, { add_generation_prompt: true, return_dict: true });
const stopping = new InterruptableStoppingCriteria();
signal.addEventListener('abort', () => stopping.interrupt(), { once: true });
await model.generate({
...inputs,
max_new_tokens: options.maxTokens ?? 8192, // a runner of yours picks its own ceiling
streamer: new TextStreamer(tokenizer, {
skip_prompt: true, skip_special_tokens: true,
callback_function: (text) => emit({ type: 'text', delta: text }),
}),
stopping_criteria: stopping,
});
},
async command(name, payload) { /* what is not a reply: swap an adapter, warm a cache */ },
dispose() { return model.dispose(); },
};
}
```
`runner` names an ES module that exports `createRunner`, and it wins over `task`. Give it an absolute path: a relative one is resolved against the current page’s URL. The module runs in the worker, where neither your bundler nor your import map applies, so it imports nothing by package name: it gets the same Transformers.js as the built-in runners as `ctx.transformers`, and a model they cannot load keeps the worker, the queue, the progress, Stop and the cache. `messages` arrive with their content parts, and the runner decides what the model reads. `tools` are the tools the request allows — what the app registered, when the model declares `function_calling` — each a `RunnerTool` (`name`, `description`, `inputSchema`), and `toolChoice` is the request’s: `'auto'`, `'none'` (answer directly this turn) or `{ name }`, a tool the model must call. Both are absent when the request has none; the built-in runners take neither. `emit` sends `text`, `thinking`, `tool_use`, `done` or `error`; `signal` fires on Stop; `ctx.progress` and `ctx.warn` reach the page; `ctx.device` is `'webgpu'` or `'wasm'`, `'auto'` already resolved. `runnerCommand(modelId, name, payload)` calls a runner’s `command` from the page, after the replies already waiting; when that model is not the one in memory, it is loaded first, in its place, with no progress to show. The contract’s types are exported — `TransformersRunner`, `RunnerContext`, `RunnerGenerateInput`, `RunnerTool`, `RunnerProgress`, `CreateRunner`, `RunnerModule`, `BuiltInRunner`, `TransformersModule` — and a model’s options are a `TransformersModelConfig`. ## Next [Section titled “Next”](#next) * [Local models A model on a server of your own machine instead: Ollama, LM Studio, llama.cpp.](/guides/local-models/) * [Model selector Let the person pick among the registered models.](/components/model-selector/)
# Reference
> The pages generated from the source — the UI kit's classes, every CSS variable, the events, the core API, the engine, the wrappers and the icons — beside where aparté runs and what will not change under you.
| Page | The question it answers | | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Classes](/reference/classes/) | *Which ready-made classes can I put on my own elements?* Buttons, fields, switches, tags, alerts, menus, tabs, avatars — plain classes on plain elements, themed by the same variables as the chat. Each family has its page, with a live example, in the [kit](/components/#kit). | | [CSS variables](/reference/css-variables/) | *Which `--aparte-*` token do I set to change this?* Every declared variable with its default, and the ones a component reads with a fallback. | | [Events](/reference/events/) | *What does aparté dispatch, with what `detail`?* One row per event. | | [Core API](/reference/core/) | *What does `@aparte/core` export, with which signature?* Every export by area: configuration, client, transports, messages, conversations, questions, element types, utilities. | | [Engine](/reference/engine/) | *What does `@aparte/engine` export?* The loop and its run events. | | [Wrappers](/reference/wrappers/) | *What is the same on React, Vue, Svelte and Angular?* Every slot and callback, and how each framework spells it. | | [Icons](/reference/icons/) | *Which glyphs exist, and how do I swap them?* The built-in set and the extended one behind `@aparte/core/icons`. | | [Support matrix](/reference/support/) | *Does it run where my users and my build are?* Browsers, Node, frameworks, bundlers and TypeScript. | | [Stability](/reference/stability/) | *What can I build on without a rename landing on me?* The frozen names and the notice a change gets first. | The elements themselves — ``, ``, ``… — are under [Components](/components/), and [`llms-full.txt`](/llms-full.txt) holds every built page in one file.
# Core API
> Generated reference for @aparte/core: every export, by area — configuration, client, transports, messages, conversations, questions, element types and utilities.
The custom elements are on their catalogue pages, with their attributes, properties, methods, events, slots and CSS variables. Everything else `@aparte/core` exports is here, generated from its source and JSDoc. | Page | What it documents | | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | [Configuration](/reference/core/config/) | `aparteGlobalConfig`, the class behind it, and the provider, renderer and locale types it takes. | | [Client](/reference/core/client/) | The client that runs a conversation, the host every framework wrapper binds to, and the stream runners. | | [Transports](/reference/core/transports/) | How a request reaches a model, straight from the browser or through your endpoint, and the handlers that endpoint can use. | | [Messages and segments](/reference/core/messages/) | A message and the segments it is made of, the parser that builds them from a stream, the renderers that draw them, and the errors. | | [Conversations](/reference/core/conversations/) | Conversations and their storage, the history of one conversation with its branches, and the context of it that goes to the model. | | [Questions and approvals](/reference/core/elicitation/) | Asking the person a question, or for an approval, in the middle of a turn. | | [Element types](/reference/core/elements/) | The data and event types the elements take and send. The elements themselves are on their catalogue pages. | | [Utilities](/reference/core/utilities/) | Small helpers: escaping, ids, copying, attachments from files, segment timing, and what the framework wrappers share. | ## Every export, by page [Section titled “Every export, by page”](#every-export-by-page) ### Configuration [Section titled “Configuration”](#configuration) [`AparteConfig`](/reference/core/config/#aparteconfig), [`AparteAction`](/reference/core/config/#aparteaction), [`AparteModelPreference`](/reference/core/config/#apartemodelpreference), [`AparteModelPreferenceProvider`](/reference/core/config/#apartemodelpreferenceprovider), [`AparteStreamingMarkdownRenderer`](/reference/core/config/#apartestreamingmarkdownrenderer), [`AparteCodeLanguageContext`](/reference/core/config/#apartecodelanguagecontext), [`AparteCodeLanguageRenderer`](/reference/core/config/#apartecodelanguagerenderer), [`AparteAvatarProvider`](/reference/core/config/#aparteavatarprovider), [`AparteConfigAware`](/reference/core/config/#aparteconfigaware), [`AparteElicitationFieldContext`](/reference/core/config/#aparteelicitationfieldcontext), [`AparteElicitationFieldControl`](/reference/core/config/#aparteelicitationfieldcontrol), [`AparteIconProvider`](/reference/core/config/#aparteiconprovider), [`AparteActionZone`](/reference/core/config/#aparteactionzone), [`AparteMarkdownProvider`](/reference/core/config/#apartemarkdownprovider), [`AparteHighlightProvider`](/reference/core/config/#apartehighlightprovider), [`AparteSystemPromptVarsProvider`](/reference/core/config/#apartesystempromptvarsprovider), [`AparteKeyProvider`](/reference/core/config/#apartekeyprovider), [`AparteStreamingMarkdownProvider`](/reference/core/config/#apartestreamingmarkdownprovider), [`AparteAttachmentRenderer`](/reference/core/config/#aparteattachmentrenderer), [`AparteBubbleShellRenderer`](/reference/core/config/#apartebubbleshellrenderer), [`AparteElicitationFieldRenderer`](/reference/core/config/#aparteelicitationfieldrenderer), [`AparteErrorRenderer`](/reference/core/config/#aparteerrorrenderer), [`AparteIconName`](/reference/core/config/#aparteiconname), [`AparteCoreIconName`](/reference/core/config/#apartecoreiconname), [`AparteImageDecision`](/reference/core/config/#aparteimagedecision), [`AparteImagePolicy`](/reference/core/config/#aparteimagepolicy), [`AparteLocale`](/reference/core/config/#apartelocale), [`AparteLocaleExtensions`](/reference/core/config/#apartelocaleextensions), [`AparteSanitizer`](/reference/core/config/#apartesanitizer), [`AparteSiblingNavRenderer`](/reference/core/config/#apartesiblingnavrenderer), [`AparteStatusRenderer`](/reference/core/config/#apartestatusrenderer), [`APARTE_DEFAULT_BUBBLE_ACTIONS`](/reference/core/config/#aparte_default_bubble_actions), [`APARTE_DEFAULT_HOST_HANDLERS`](/reference/core/config/#aparte_default_host_handlers), [`aparteGlobalConfig`](/reference/core/config/#aparteglobalconfig), [`APARTE_HOST_ATTR`](/reference/core/config/#aparte_host_attr), [`APARTE_CONFIG_CHANGE`](/reference/core/config/#aparte_config_change), [`APARTE_DEFAULT_ICON_FALLBACKS`](/reference/core/config/#aparte_default_icon_fallbacks), [`APARTE_DEFAULT_LOCALE`](/reference/core/config/#aparte_default_locale), [`defaultSanitizer`](/reference/core/config/#defaultsanitizer), [`attachConfig()`](/reference/core/config/#attachconfig), [`detachConfig()`](/reference/core/config/#detachconfig), [`resolveConfig()`](/reference/core/config/#resolveconfig), [`runWithConfig()`](/reference/core/config/#runwithconfig), [`contextConfig()`](/reference/core/config/#contextconfig), [`subscribeConfigChange()`](/reference/core/config/#subscribeconfigchange), [`isSafeUrl()`](/reference/core/config/#issafeurl), [`AparteConfigChangeEventDetail`](/reference/core/config/#aparteconfigchangeeventdetail) ### Client [Section titled “Client”](#client) [`AparteClient`](/reference/core/client/#aparteclient), [`AparteChatHost`](/reference/core/client/#apartechathost), [`AgentStreamRunnerOptions`](/reference/core/client/#agentstreamrunneroptions), [`AparteClientOptions`](/reference/core/client/#aparteclientoptions), [`StreamAdapterTarget`](/reference/core/client/#streamadaptertarget), [`CreateStreamAdapterOptions`](/reference/core/client/#createstreamadapteroptions), [`AparteChatHostBinding`](/reference/core/client/#apartechathostbinding), [`AparteChatHostOptions`](/reference/core/client/#apartechathostoptions), [`AparteToolApprovalResolver`](/reference/core/client/#apartetoolapprovalresolver), [`AparteStreamRunEvent`](/reference/core/client/#apartestreamrunevent), [`AparteStreamRunEmitter`](/reference/core/client/#apartestreamrunemitter), [`AparteStreamRunOptions`](/reference/core/client/#apartestreamrunoptions), [`AparteStreamRunner`](/reference/core/client/#apartestreamrunner), [`toolRefusal`](/reference/core/client/#toolrefusal), [`createAgentStreamRunner()`](/reference/core/client/#createagentstreamrunner), [`createStreamAdapter()`](/reference/core/client/#createstreamadapter), [`readableToAsyncIterable()`](/reference/core/client/#readabletoasynciterable) ### Transports [Section titled “Transports”](#transports) [`AparteBackendTransport`](/reference/core/transports/#apartebackendtransport), [`AparteDirectTransport`](/reference/core/transports/#apartedirecttransport), [`AparteAgentTool`](/reference/core/transports/#aparteagenttool), [`AparteAgentHandlerOptions`](/reference/core/transports/#aparteagenthandleroptions), [`AparteAgentRequestBody`](/reference/core/transports/#aparteagentrequestbody), [`AparteChatHandlerOptions`](/reference/core/transports/#apartechathandleroptions), [`BackendTransportOptions`](/reference/core/transports/#backendtransportoptions), [`DirectTransportOptions`](/reference/core/transports/#directtransportoptions), [`AparteVendorRequest`](/reference/core/transports/#apartevendorrequest), [`AparteFormatAdapter`](/reference/core/transports/#aparteformatadapter), [`AparteTransportContext`](/reference/core/transports/#apartetransportcontext), [`AparteTransport`](/reference/core/transports/#apartetransport), [`createAparteAgentHandler()`](/reference/core/transports/#createaparteagenthandler), [`createAparteChatHandler()`](/reference/core/transports/#createapartechathandler), [`isFormatAdapter()`](/reference/core/transports/#isformatadapter) ### Messages and segments [Section titled “Messages and segments”](#messages-and-segments) [`AparteErrorCode`](/reference/core/messages/#aparteerrorcode), [`AparteStreamParser`](/reference/core/messages/#apartestreamparser), [`AparteError`](/reference/core/messages/#aparteerror), [`AparteThinkingDelimiterPair`](/reference/core/messages/#apartethinkingdelimiterpair), [`AparteStreamParserOptions`](/reference/core/messages/#apartestreamparseroptions), [`AparteParserState`](/reference/core/messages/#aparteparserstate), [`AparteParserResult`](/reference/core/messages/#aparteparserresult), [`AparteRenderCodeLanguagesOptions`](/reference/core/messages/#aparterendercodelanguagesoptions), [`AparteTextPart`](/reference/core/messages/#apartetextpart), [`AparteImagePart`](/reference/core/messages/#aparteimagepart), [`AparteChatMessage`](/reference/core/messages/#apartechatmessage), [`AparteChatRequest`](/reference/core/messages/#apartechatrequest), [`AparteRequestMeta`](/reference/core/messages/#aparterequestmeta), [`AparteUsage`](/reference/core/messages/#aparteusage), [`AparteStreamEventMap`](/reference/core/messages/#apartestreameventmap), [`AparteCompactorRequest`](/reference/core/messages/#apartecompactorrequest), [`AparteCompactor`](/reference/core/messages/#apartecompactor), [`AparteSendEventDetail`](/reference/core/messages/#apartesendeventdetail), [`AparteSiblingInfo`](/reference/core/messages/#apartesiblinginfo), [`AparteChatImperativeApi`](/reference/core/messages/#apartechatimperativeapi), [`AparteUiHandle`](/reference/core/messages/#aparteuihandle), [`AparteAIModel`](/reference/core/messages/#aparteaimodel), [`ModelLoadProgress`](/reference/core/messages/#modelloadprogress), [`AparteAIProviderMetadata`](/reference/core/messages/#aparteaiprovidermetadata), [`AparteAIProviderConfigField`](/reference/core/messages/#aparteaiproviderconfigfield), [`AparteAIProviderConfigSchema`](/reference/core/messages/#aparteaiproviderconfigschema), [`AparteModelConfig`](/reference/core/messages/#apartemodelconfig), [`AparteAttachment`](/reference/core/messages/#aparteattachment), [`AparteBubbleActionsConfig`](/reference/core/messages/#apartebubbleactionsconfig), [`AparteHostHandlersConfig`](/reference/core/messages/#apartehosthandlersconfig), [`AparteContextSummary`](/reference/core/messages/#apartecontextsummary), [`AparteMessage`](/reference/core/messages/#apartemessage), [`AparteViewportConfig`](/reference/core/messages/#aparteviewportconfig), [`AparteInputConfig`](/reference/core/messages/#aparteinputconfig), [`AparteContentParser`](/reference/core/messages/#apartecontentparser), [`AparteSegmentBase`](/reference/core/messages/#apartesegmentbase), [`AparteSegmentTiming`](/reference/core/messages/#apartesegmenttiming), [`AparteTextSegment`](/reference/core/messages/#apartetextsegment), [`AparteSource`](/reference/core/messages/#apartesource), [`AparteCitation`](/reference/core/messages/#apartecitation), [`AparteThinkingSegment`](/reference/core/messages/#apartethinkingsegment), [`AparteCodeSegment`](/reference/core/messages/#apartecodesegment), [`AparteErrorSegment`](/reference/core/messages/#aparteerrorsegment), [`AparteToolCallSegment`](/reference/core/messages/#apartetoolcallsegment), [`AparteCustomSegment`](/reference/core/messages/#apartecustomsegment), [`AparteSegmentTypes`](/reference/core/messages/#apartesegmenttypes), [`AparteSegmentRenderer`](/reference/core/messages/#apartesegmentrenderer), [`AparteSegmentUpdateEventDetail`](/reference/core/messages/#apartesegmentupdateeventdetail), [`AparteStreamBlockMatch`](/reference/core/messages/#apartestreamblockmatch), [`AparteStreamBlock`](/reference/core/messages/#apartestreamblock), [`AparteTool`](/reference/core/messages/#apartetool), [`AparteToolCall`](/reference/core/messages/#apartetoolcall), [`AparteApprovalRuling`](/reference/core/messages/#aparteapprovalruling), [`AparteToolResult`](/reference/core/messages/#apartetoolresult), [`AparteToolContext`](/reference/core/messages/#apartetoolcontext), [`AparteToolDisplay`](/reference/core/messages/#apartetooldisplay), [`AparteToolRenderer`](/reference/core/messages/#apartetoolrenderer), [`AparteToolCallView`](/reference/core/messages/#apartetoolcallview), [`AparteMountedView`](/reference/core/messages/#apartemountedview), [`AparteContentPart`](/reference/core/messages/#apartecontentpart), [`AparteFinishReason`](/reference/core/messages/#apartefinishreason), [`AparteStreamEvent`](/reference/core/messages/#apartestreamevent), [`AparteChatResponse`](/reference/core/messages/#apartechatresponse), [`AparteCompactorReason`](/reference/core/messages/#apartecompactorreason), [`AparteCompactorOutcome`](/reference/core/messages/#apartecompactoroutcome), [`AparteAttrValue`](/reference/core/messages/#aparteattrvalue), [`AparteTemplateAttrs`](/reference/core/messages/#apartetemplateattrs), [`ModelStatus`](/reference/core/messages/#modelstatus), [`AparteAIProvider`](/reference/core/messages/#aparteaiprovider), [`AparteStatus`](/reference/core/messages/#apartestatus), [`AparteBubbleRole`](/reference/core/messages/#apartebubblerole), [`AparteBubbleActionName`](/reference/core/messages/#apartebubbleactionname), [`AparteSegmentDefaults`](/reference/core/messages/#apartesegmentdefaults), [`AparteSegment`](/reference/core/messages/#apartesegment), [`AparteSegmentType`](/reference/core/messages/#apartesegmenttype), [`AparteSegmentMount`](/reference/core/messages/#apartesegmentmount), [`AparteThemeVariables`](/reference/core/messages/#apartethemevariables), [`AparteApprovalPolicy`](/reference/core/messages/#aparteapprovalpolicy), [`AparteToolHandler`](/reference/core/messages/#apartetoolhandler), [`AparteToolSummary`](/reference/core/messages/#apartetoolsummary), [`AparteToolInputFormatter`](/reference/core/messages/#apartetoolinputformatter), [`AparteToolMatcher`](/reference/core/messages/#apartetoolmatcher), [`AparteToolDetails`](/reference/core/messages/#apartetooldetails), [`AparteToolMount`](/reference/core/messages/#apartetoolmount), [`parseAparteEventStream()`](/reference/core/messages/#parseaparteeventstream), [`parseMarkdownToSegments()`](/reference/core/messages/#parsemarkdowntosegments), [`renderCitations()`](/reference/core/messages/#rendercitations), [`renderCodeLanguages()`](/reference/core/messages/#rendercodelanguages), [`toToolCallView()`](/reference/core/messages/#totoolcallview), [`defineMountedToolRenderer()`](/reference/core/messages/#definemountedtoolrenderer), [`defineMountedSegmentRenderer()`](/reference/core/messages/#definemountedsegmentrenderer), [`registerSegmentRenderer()`](/reference/core/messages/#registersegmentrenderer), [`overrideSegmentRenderer()`](/reference/core/messages/#overridesegmentrenderer), [`declineDefaultRenderers()`](/reference/core/messages/#declinedefaultrenderers), [`installDefaultRenderersOnce()`](/reference/core/messages/#installdefaultrenderersonce), [`unregisterSegmentRenderer()`](/reference/core/messages/#unregistersegmentrenderer), [`getSegmentRenderer()`](/reference/core/messages/#getsegmentrenderer), [`getAllRenderers()`](/reference/core/messages/#getallrenderers), [`collectRendererStyles()`](/reference/core/messages/#collectrendererstyles), [`registerDefaultRenderers()`](/reference/core/messages/#registerdefaultrenderers), [`contentToText()`](/reference/core/messages/#contenttotext), [`AparteMessageDoneEventDetail`](/reference/core/messages/#apartemessagedoneeventdetail), [`AparteModelChangeEventDetail`](/reference/core/messages/#apartemodelchangeeventdetail), [`AparteLinkClickEventDetail`](/reference/core/messages/#apartelinkclickeventdetail), [`AparteBranchNavigateEventDetail`](/reference/core/messages/#apartebranchnavigateeventdetail), [`ApartePathChangedEventDetail`](/reference/core/messages/#apartepathchangedeventdetail), [`AparteRetryEventDetail`](/reference/core/messages/#aparteretryeventdetail), [`AparteEditEventDetail`](/reference/core/messages/#aparteediteventdetail), [`AparteFeedbackEventDetail`](/reference/core/messages/#apartefeedbackeventdetail), [`AparteActionEventDetail`](/reference/core/messages/#aparteactioneventdetail), [`AparteMessageInfoEventDetail`](/reference/core/messages/#apartemessageinfoeventdetail), [`AparteMessageStartEventDetail`](/reference/core/messages/#apartemessagestarteventdetail), [`AparteMessageErrorEventDetail`](/reference/core/messages/#apartemessageerroreventdetail), [`AparteMessagePausedEventDetail`](/reference/core/messages/#apartemessagepausedeventdetail), [`AparteMessageResumedEventDetail`](/reference/core/messages/#apartemessageresumedeventdetail), [`AparteMessageAbortedEventDetail`](/reference/core/messages/#apartemessageabortedeventdetail), [`AparteAbortEventDetail`](/reference/core/messages/#aparteaborteventdetail), [`AparteCompactEventDetail`](/reference/core/messages/#apartecompacteventdetail), [`AparteCompactStartEventDetail`](/reference/core/messages/#apartecompactstarteventdetail), [`AparteCompactDoneEventDetail`](/reference/core/messages/#apartecompactdoneeventdetail), [`AparteCompactErrorEventDetail`](/reference/core/messages/#apartecompacterroreventdetail), [`AparteAttachmentPreviewEventDetail`](/reference/core/messages/#aparteattachmentprevieweventdetail), [`AparteApprovalModeChangeEventDetail`](/reference/core/messages/#aparteapprovalmodechangeeventdetail), [`AparteToolApprovalRequestDetail`](/reference/core/messages/#apartetoolapprovalrequestdetail) ### Conversations [Section titled “Conversations”](#conversations) [`AparteConversationController`](/reference/core/conversations/#aparteconversationcontroller), [`AparteConversationManager`](/reference/core/conversations/#aparteconversationmanager), [`AparteMessageRepository`](/reference/core/conversations/#apartemessagerepository), [`AparteContextMeasure`](/reference/core/conversations/#apartecontextmeasure), [`AparteContextMeasureInput`](/reference/core/conversations/#apartecontextmeasureinput), [`AparteChatBinding`](/reference/core/conversations/#apartechatbinding), [`AparteConversationControllerOptions`](/reference/core/conversations/#aparteconversationcontrolleroptions), [`ConversationManagerOptions`](/reference/core/conversations/#conversationmanageroptions), [`AparteConversation`](/reference/core/conversations/#aparteconversation), [`AparteConversationMeta`](/reference/core/conversations/#aparteconversationmeta), [`AparteAttachmentRow`](/reference/core/conversations/#aparteattachmentrow), [`AparteStorageAdapter`](/reference/core/conversations/#apartestorageadapter), [`AparteConversationsListener`](/reference/core/conversations/#aparteconversationslistener), [`AparteConversationTitleProvider`](/reference/core/conversations/#aparteconversationtitleprovider), [`AparteConversationStatus`](/reference/core/conversations/#aparteconversationstatus), [`ExportedMessageRepository`](/reference/core/conversations/#exportedmessagerepository), [`APARTE_CONVERSATION_SCHEMA_VERSION`](/reference/core/conversations/#aparte_conversation_schema_version), [`historyFromCheckpoint()`](/reference/core/conversations/#historyfromcheckpoint), [`estimateTokens()`](/reference/core/conversations/#estimatetokens), [`estimateWireTokens()`](/reference/core/conversations/#estimatewiretokens), [`measureContext()`](/reference/core/conversations/#measurecontext), [`AparteConversationLoadedDetail`](/reference/core/conversations/#aparteconversationloadeddetail) ### Questions and approvals [Section titled “Questions and approvals”](#questions-and-approvals) [`AparteElicitationAbortError`](/reference/core/elicitation/#aparteelicitationaborterror), [`BuiltApprovalPanel`](/reference/core/elicitation/#builtapprovalpanel), [`BuiltElicitationPanel`](/reference/core/elicitation/#builtelicitationpanel), [`AparteElicitationEnumField`](/reference/core/elicitation/#aparteelicitationenumfield), [`AparteElicitationBooleanField`](/reference/core/elicitation/#aparteelicitationbooleanfield), [`AparteElicitationStringField`](/reference/core/elicitation/#aparteelicitationstringfield), [`AparteElicitationObjectSchema`](/reference/core/elicitation/#aparteelicitationobjectschema), [`AparteElicitationRequest`](/reference/core/elicitation/#aparteelicitationrequest), [`AparteApprovalOption`](/reference/core/elicitation/#aparteapprovaloption), [`AparteApprovalAnswer`](/reference/core/elicitation/#aparteapprovalanswer), [`AparteElicitationField`](/reference/core/elicitation/#aparteelicitationfield), [`AparteElicitationSchema`](/reference/core/elicitation/#aparteelicitationschema), [`AparteElicitationResult`](/reference/core/elicitation/#aparteelicitationresult), [`AparteElicitationPresenter`](/reference/core/elicitation/#aparteelicitationpresenter), [`buildApprovalPanel()`](/reference/core/elicitation/#buildapprovalpanel), [`requestUserInput()`](/reference/core/elicitation/#requestuserinput), [`buildElicitationPanel()`](/reference/core/elicitation/#buildelicitationpanel) ### Element types [Section titled “Element types”](#element-types) [`SyncableBubble`](/reference/core/elements/#syncablebubble), [`AparteComposerEventMap`](/reference/core/elements/#apartecomposereventmap), [`AparteComposerState`](/reference/core/elements/#apartecomposerstate), [`AparteComposerChangeEventDetail`](/reference/core/elements/#apartecomposerchangeeventdetail), [`AparteContextThresholdEventDetail`](/reference/core/elements/#apartecontextthresholdeventdetail), [`AparteConversationListItem`](/reference/core/elements/#aparteconversationlistitem), [`AparteConversationSelectDetail`](/reference/core/elements/#aparteconversationselectdetail), [`AparteConversationDeleteDetail`](/reference/core/elements/#aparteconversationdeletedetail), [`AparteConversationArchiveDetail`](/reference/core/elements/#aparteconversationarchivedetail), [`AparteConversationPinDetail`](/reference/core/elements/#aparteconversationpindetail), [`AparteConversationRenameDetail`](/reference/core/elements/#aparteconversationrenamedetail), [`AparteLauncherToggleDetail`](/reference/core/elements/#apartelaunchertoggledetail), [`AparteScrollRailJumpDetail`](/reference/core/elements/#apartescrollrailjumpdetail), [`AparteSidebarToggleDetail`](/reference/core/elements/#apartesidebartoggledetail), [`AparteSplitResizeDetail`](/reference/core/elements/#apartesplitresizedetail), [`AparteSuggestionEventDetail`](/reference/core/elements/#apartesuggestioneventdetail), [`AparteChatAttributes`](/reference/core/elements/#apartechatattributes), [`AparteChatBubbleAttributes`](/reference/core/elements/#apartechatbubbleattributes), [`AparteChatStatusAttributes`](/reference/core/elements/#apartechatstatusattributes), [`AparteChatViewportAttributes`](/reference/core/elements/#apartechatviewportattributes), [`AparteComposerAttributes`](/reference/core/elements/#apartecomposerattributes), [`AparteComposerActionAttributes`](/reference/core/elements/#apartecomposeractionattributes), [`AparteComposerAddAttachmentAttributes`](/reference/core/elements/#apartecomposeraddattachmentattributes), [`AparteComposerInputAttributes`](/reference/core/elements/#apartecomposerinputattributes), [`AparteComposerToolbarAttributes`](/reference/core/elements/#apartecomposertoolbarattributes), [`AparteContextAttributes`](/reference/core/elements/#apartecontextattributes), [`AparteConversationListAttributes`](/reference/core/elements/#aparteconversationlistattributes), [`AparteIconAttributes`](/reference/core/elements/#aparteiconattributes), [`AparteLauncherAttributes`](/reference/core/elements/#apartelauncherattributes), [`AparteOptgroupAttributes`](/reference/core/elements/#aparteoptgroupattributes), [`AparteOptionAttributes`](/reference/core/elements/#aparteoptionattributes), [`AparteProgressSpinnerAttributes`](/reference/core/elements/#aparteprogressspinnerattributes), [`AparteScrollRailAttributes`](/reference/core/elements/#apartescrollrailattributes), [`AparteSelectAttributes`](/reference/core/elements/#aparteselectattributes), [`AparteSidebarAttributes`](/reference/core/elements/#apartesidebarattributes), [`AparteSplitAttributes`](/reference/core/elements/#apartesplitattributes), [`AparteSuggestionsAttributes`](/reference/core/elements/#apartesuggestionsattributes), [`AparteElementAttributes`](/reference/core/elements/#aparteelementattributes), [`AparteSelectChangeDetail`](/reference/core/elements/#aparteselectchangedetail), [`AparteComposerPanelMode`](/reference/core/elements/#apartecomposerpanelmode), [`AparteComposerEventType`](/reference/core/elements/#apartecomposereventtype), [`AparteContextLevel`](/reference/core/elements/#apartecontextlevel), [`AparteScrollRailEvery`](/reference/core/elements/#apartescrollrailevery), [`AparteSuggestion`](/reference/core/elements/#apartesuggestion), [`AparteNoAttributes`](/reference/core/elements/#apartenoattributes), [`AparteElementTagName`](/reference/core/elements/#aparteelementtagname), [`SUGGESTIONS_BLOCK_LANGUAGE`](/reference/core/elements/#suggestions_block_language), [`populateBubbleFromMessage()`](/reference/core/elements/#populatebubblefrommessage), [`setupSuggestionBlocks()`](/reference/core/elements/#setupsuggestionblocks), [`AparteActionClickEventDetail`](/reference/core/elements/#aparteactionclickeventdetail), [`AparteConversationStatusDetail`](/reference/core/elements/#aparteconversationstatusdetail), [`AparteOptgroupToggleEventDetail`](/reference/core/elements/#aparteoptgrouptoggleeventdetail) ### Utilities [Section titled “Utilities”](#utilities) [`AparteUiEventName`](/reference/core/utilities/#aparteuieventname), [`APARTE_DEFAULT_UI_EVENTS`](/reference/core/utilities/#aparte_default_ui_events), [`escapeAttr`](/reference/core/utilities/#escapeattr), [`registerAllComponents()`](/reference/core/utilities/#registerallcomponents), [`releaseDeferredHydration()`](/reference/core/utilities/#releasedeferredhydration), [`deferHydrationOf()`](/reference/core/utilities/#deferhydrationof), [`installDialogTriggersOnce()`](/reference/core/utilities/#installdialogtriggersonce), [`applyElementProps()`](/reference/core/utilities/#applyelementprops), [`copyText()`](/reference/core/utilities/#copytext), [`cssEscape()`](/reference/core/utilities/#cssescape), [`escapeHtml()`](/reference/core/utilities/#escapehtml), [`filesToAttachments()`](/reference/core/utilities/#filestoattachments), [`revokeAttachmentUrls()`](/reference/core/utilities/#revokeattachmenturls), [`isAwaitingReply()`](/reference/core/utilities/#isawaitingreply), [`segmentTiming()`](/reference/core/utilities/#segmenttiming), [`isSegmentSettled()`](/reference/core/utilities/#issegmentsettled), [`segmentDuration()`](/reference/core/utilities/#segmentduration), [`uuid()`](/reference/core/utilities/#uuid) ### Elements [Section titled “Elements”](#elements) [`AparteChatBubble`](/components/message/), [`AparteChat`](/components/chat/), [`AparteComposerAction`](/components/composer/), [`AparteComposerAddAttachment`](/components/composer/), [`AparteComposerAttachments`](/components/composer/), [`AparteComposerCancel`](/components/composer/), [`AparteComposerInput`](/components/composer/), [`AparteComposerSend`](/components/composer/), [`AparteComposerToolbar`](/components/composer/), [`AparteComposer`](/components/composer/), [`AparteContext`](/components/context-gauge/), [`AparteConversationList`](/components/conversation-list/), [`AparteElicitation`](/components/question/), [`AparteLauncher`](/components/launcher/), [`AparteScrollRail`](/components/scroll-rail/), [`AparteSidebar`](/components/sidebar/), [`AparteSplit`](/components/split/), [`AparteChatStatus`](/components/status-line/), [`AparteSuggestions`](/components/suggestions/), [`AparteChatViewport`](/components/conversation/), [`AparteIcon`](/components/icon/), [`AparteProgressSpinner`](/components/spinner/), [`AparteOptgroup`](/components/select/), [`AparteOption`](/components/select/), [`AparteSelect`](/components/select/)
# Client — core API
> Generated reference for @aparte/core. The client that runs a conversation, the host every framework wrapper binds to, and the stream runners.
## Classes [Section titled “Classes”](#classes) ### AparteClient [Section titled “AparteClient”](#aparteclient) Defined in: [packages/core/src/client/aparte-client.ts:311](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L311) AparteClient The “Automatic Transmission” for Aparte. Connects the UI events (aparte-send) to the AI Providers (chat). Handles: * Listening to send events * Resolving API keys * Calling the appropriate Provider * Streaming the response back to the UI * Tool use: awaiting handlers and re-calling the provider #### Example [Section titled “Example”](#example)
```typescript
const client = new AparteClient({
keyResolver: (providerId) => process.env[providerId.toUpperCase() + '_KEY']
});
client.start();
```
#### Constructors [Section titled “Constructors”](#constructors) ##### Constructor [Section titled “Constructor”](#constructor)
```ts
new AparteClient(options?): AparteClient;
```
Defined in: [packages/core/src/client/aparte-client.ts:417](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L417) A `keyResolver` becomes a key source on the client’s config at once, before `start()`, so everything that needs a key can use it — the model selector’s list included. `autoRegister` (on by default) installs core’s built-in renderers on that config. ###### Parameters [Section titled “Parameters”](#parameters) | Parameter | Type | | --------- | --------------------------------------------- | | `options` | [`AparteClientOptions`](#aparteclientoptions) | ###### Returns [Section titled “Returns”](#returns) [`AparteClient`](#aparteclient) #### Methods [Section titled “Methods”](#methods) ##### start() [Section titled “start()”](#start)
```ts
start(): void;
```
Defined in: [packages/core/src/client/aparte-client.ts:508](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L508) Answer the chats: listen on `window` for `aparte-send`, `aparte-retry`, `aparte-edit`, `aparte-abort` and `aparte-conversation-loaded`. Nothing streams before this is called. Starting a stopped client puts its `keyResolver` back on the config. ###### Returns [Section titled “Returns”](#returns-1) `void` ##### stop() [Section titled “stop()”](#stop)
```ts
stop(): void;
```
Defined in: [packages/core/src/client/aparte-client.ts:564](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L564) Stop answering: abort the reply in flight, take this client’s `keyResolver` off the config, and remove the listeners. ###### Returns [Section titled “Returns”](#returns-2) `void` ##### abort() [Section titled “abort()”](#abort)
```ts
abort(): void;
```
Defined in: [packages/core/src/client/aparte-client.ts:615](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L615) Abort the current streaming response and all active tool calls. Dispatches `aparte-message-aborted` on the target element. ###### Returns [Section titled “Returns”](#returns-3) `void` ##### resumeDeferred() [Section titled “resumeDeferred()”](#resumedeferred)
```ts
resumeDeferred(target?): Promise;
```
Defined in: [packages/core/src/client/aparte-client.ts:2167](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L2167) Answer a turn a server loop paused, when the conversation comes back — a reload, a conversation reopened days later. The last reply’s paused calls (they carry the server’s ticket) are put to the person again, or run in the page, and the loop resumes on the server, into the same bubble. Called on its own when a conversation manager loads a conversation (`aparte-conversation-loaded`); call it yourself after `setMessages` if you load conversations another way. Resolves `true` when a resume ran, `false` when there was nothing to resume. ###### Parameters [Section titled “Parameters”](#parameters-1) | Parameter | Type | Description | | --------- | ------------------------- | --------------------------------------------------------------------------------------------------------- | | `target?` | `string` \| `HTMLElement` | The chat — an element, or its id. Defaults to the one `targetResolver` names, else the first on the page. | ###### Returns [Section titled “Returns”](#returns-4) `Promise`<`boolean`> *** ### AparteChatHost [Section titled “AparteChatHost”](#apartechathost) Defined in: [packages/core/src/host/aparte-chat-host.ts:196](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L196) #### Constructors [Section titled “Constructors”](#constructors-1) ##### Constructor [Section titled “Constructor”](#constructor-1)
```ts
new AparteChatHost(binding, options?): AparteChatHost;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:260](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L260) ###### Parameters [Section titled “Parameters”](#parameters-2) | Parameter | Type | | --------- | ------------------------------------------------- | | `binding` | [`AparteChatHostBinding`](#apartechathostbinding) | | `options` | [`AparteChatHostOptions`](#apartechathostoptions) | ###### Returns [Section titled “Returns”](#returns-5) [`AparteChatHost`](#apartechathost) #### Accessors [Section titled “Accessors”](#accessors) ##### streamingId [Section titled “streamingId”](#streamingid) ###### Get Signature [Section titled “Get Signature”](#get-signature)
```ts
get streamingId(): string | null;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:347](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L347) ###### Returns [Section titled “Returns”](#returns-6) `string` | `null` ##### isStreaming [Section titled “isStreaming”](#isstreaming) ###### Get Signature [Section titled “Get Signature”](#get-signature-1)
```ts
get isStreaming(): boolean;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:348](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L348) ###### Returns [Section titled “Returns”](#returns-7) `boolean` ##### conversationController [Section titled “conversationController”](#conversationcontroller) ###### Get Signature [Section titled “Get Signature”](#get-signature-2)
```ts
get conversationController():
| AparteConversationController
| undefined;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:351](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L351) The internally-managed conversation controller (created in [bind](#bind)). ###### Returns [Section titled “Returns”](#returns-8) \| [`AparteConversationController`](/reference/core/conversations/#aparteconversationcontroller) | `undefined` #### Methods [Section titled “Methods”](#methods-1) ##### takeEcho() [Section titled “takeEcho()”](#takeecho)
```ts
takeEcho(list): boolean;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:286](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L286) Whether a list the parent hands back is this host’s own report coming back — the echo of `onMessagesChange` through a two-way binding (`bind:messages`, `v-model:messages`, `[(messages)]`, a controlled React prop). A wrapper asks before applying the list it is given, because applying an echo rolls back what the host did since without reporting (an optimistic append). True for a list reported and not handed back yet, however late it lands — a parent whose render comes after the host’s next write hands back an EARLIER report — and that list and every older one are taken. False for any other list, the parent’s own word, which clears them: a list the parent restores later (a reopened conversation, an undo) is applied, where remembering every list ever reported swallowed it. ###### Parameters [Section titled “Parameters”](#parameters-3) | Parameter | Type | | --------- | ------------------------------------------------------------- | | `list` | [`AparteMessage`](/reference/core/messages/#apartemessage)\[] | ###### Returns [Section titled “Returns”](#returns-9) `boolean` ##### bind() [Section titled “bind()”](#bind)
```ts
bind(): () => void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:303](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L303) Install the host-method surface + event listeners and create the conversation controller. Returns a teardown function; call once after the view (viewport + composer) has mounted. ###### Returns [Section titled “Returns”](#returns-10) () => `void` ##### unbind() [Section titled “unbind()”](#unbind)
```ts
unbind(): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:332](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L332) ###### Returns [Section titled “Returns”](#returns-11) `void` ##### clearRenderCache() [Section titled “clearRenderCache()”](#clearrendercache)
```ts
clearRenderCache(): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:356](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L356) Clear the bubble-render cache (e.g. when the host clears messages externally). ###### Returns [Section titled “Returns”](#returns-12) `void` ##### setConversationId() [Section titled “setConversationId()”](#setconversationid)
```ts
setConversationId(id): Promise;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:375](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L375) Load / switch the active conversation via the controller. ###### Parameters [Section titled “Parameters”](#parameters-4) | Parameter | Type | | --------- | ------------------ | | `id` | `string` \| `null` | ###### Returns [Section titled “Returns”](#returns-13) `Promise`<`void`> ##### appendMessage() [Section titled “appendMessage()”](#appendmessage)
```ts
appendMessage(message, options?): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:477](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L477) Append a message optimistically (streaming writes target the new last). Deliberately does NOT call `onMessagesChange` (unlike the other mutations): `setMessages` updates the wrapper’s OWN render list, but `onMessagesChange` is the OUTBOUND “the user changed the list” notification. During an optimistic append the wrapper’s local list can lag a controlled parent’s (the parent added a user message that hasn’t propagated back yet), so echoing the local list to the parent would overwrite the parent’s authoritative list and drop that message — a real race the Angular wrapper spec guards (“optimistic-append + parent-push race”). `onMessageAppended` is the append-specific signal instead. ###### Parameters [Section titled “Parameters”](#parameters-5) | Parameter | Type | | --------------------- | ---------------------------------------------------------- | | `message` | [`AparteMessage`](/reference/core/messages/#apartemessage) | | `options?` | { `historical?`: `boolean`; } | | `options.historical?` | `boolean` | ###### Returns [Section titled “Returns”](#returns-14) `void` ##### updateMessage() [Section titled “updateMessage()”](#updatemessage)
```ts
updateMessage(messageId, updates): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:510](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L510) Atomic partial update of a message by id. ###### Parameters [Section titled “Parameters”](#parameters-6) | Parameter | Type | | ----------- | --------------------------------------------------------------------- | | `messageId` | `string` | | `updates` | `Partial`<[`AparteMessage`](/reference/core/messages/#apartemessage)> | ###### Returns [Section titled “Returns”](#returns-15) `void` ##### updateLastMessage() [Section titled “updateLastMessage()”](#updatelastmessage)
```ts
updateLastMessage(content, options?): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:549](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L549) Append/replace the last message content (streaming text). ###### Parameters [Section titled “Parameters”](#parameters-7) | Parameter | Type | | ----------------- | ------------------------- | | `content` | `string` | | `options?` | { `append?`: `boolean`; } | | `options.append?` | `boolean` | ###### Returns [Section titled “Returns”](#returns-16) `void` ##### addSegment() [Section titled “addSegment()”](#addsegment)
```ts
addSegment(segment): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:562](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L562) Add a segment to the last message (immediate bubble + state sync). ###### Parameters [Section titled “Parameters”](#parameters-8) | Parameter | Type | | --------- | ---------------------------------------------------------- | | `segment` | [`AparteSegment`](/reference/core/messages/#apartesegment) | ###### Returns [Section titled “Returns”](#returns-17) `void` ##### updateSegment() [Section titled “updateSegment()”](#updatesegment)
```ts
updateSegment(segmentId, updates): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:593](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L593) Update a segment in the last message in place. ###### Parameters [Section titled “Parameters”](#parameters-9) | Parameter | Type | | ----------- | --------------------------------------------------------------------- | | `segmentId` | `string` | | `updates` | `Partial`<[`AparteSegment`](/reference/core/messages/#apartesegment)> | ###### Returns [Section titled “Returns”](#returns-18) `void` ##### removeSegment() [Section titled “removeSegment()”](#removesegment)
```ts
removeSegment(segmentId): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:613](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L613) Remove a transient segment (a status row the host added itself). ###### Parameters [Section titled “Parameters”](#parameters-10) | Parameter | Type | | ----------- | -------- | | `segmentId` | `string` | ###### Returns [Section titled “Returns”](#returns-19) `void` ##### appendToSegment() [Section titled “appendToSegment()”](#appendtosegment)
```ts
appendToSegment(segmentId, content): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:643](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L643) Append text to a segment’s content in the last message — the streaming path for thinking blocks, tool pills and any segment that grows token by token. Two writes, deliberately asymmetric: 1. straight into the bubble, every chunk, so the text appears immediately — the same direct path `appendToken` uses; 2. into the framework’s message list, **coalesced to once per frame**. Coalescing (2) avoids a full list rebuild plus `setMessages` + `onMessagesChange`, i.e. one complete framework render, for every chunk. Any structural change flushes the buffer first (see \_flushStreamState), so ordering is never observable. ###### Parameters [Section titled “Parameters”](#parameters-11) | Parameter | Type | | ----------- | -------- | | `segmentId` | `string` | | `content` | `string` | ###### Returns [Section titled “Returns”](#returns-20) `void` ##### getMessages() [Section titled “getMessages()”](#getmessages)
```ts
getMessages(): AparteMessage[];
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:747](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L747) Read the current message list. ###### Returns [Section titled “Returns”](#returns-21) [`AparteMessage`](/reference/core/messages/#apartemessage)\[] ##### clearMessages() [Section titled “clearMessages()”](#clearmessages)
```ts
clearMessages(options?): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:754](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L754) Clear all messages + reset viewport state. The option travels to the viewport untouched: a compaction passes `{ revokeAttachments: false }` because it re-appends the turns it keeps and revokes the dropped ones’ object URLs itself. ###### Parameters [Section titled “Parameters”](#parameters-12) | Parameter | Type | | ---------------------------- | ------------------------------------ | | `options?` | { `revokeAttachments?`: `boolean`; } | | `options.revokeAttachments?` | `boolean` | ###### Returns [Section titled “Returns”](#returns-22) `void` ##### addBranch() [Section titled “addBranch()”](#addbranch)
```ts
addBranch(messageId): number;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:761](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L761) Create a new branch from a message (returns the new sibling index). ###### Parameters [Section titled “Parameters”](#parameters-13) | Parameter | Type | | ----------- | -------- | | `messageId` | `string` | ###### Returns [Section titled “Returns”](#returns-23) `number` ##### addSiblingOf() [Section titled “addSiblingOf()”](#addsiblingof)
```ts
addSiblingOf(existingId, newMessage): string | null;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:767](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L767) Add a sibling of an existing message (returns the new id). ###### Parameters [Section titled “Parameters”](#parameters-14) | Parameter | Type | | ------------ | ---------------------------------------------------------- | | `existingId` | `string` | | `newMessage` | [`AparteMessage`](/reference/core/messages/#apartemessage) | ###### Returns [Section titled “Returns”](#returns-24) `string` | `null` ##### truncateFrom() [Section titled “truncateFrom()”](#truncatefrom)
```ts
truncateFrom(messageId): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:773](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L773) Remove a message and all descendants (edit flow). ###### Parameters [Section titled “Parameters”](#parameters-15) | Parameter | Type | | ----------- | -------- | | `messageId` | `string` | ###### Returns [Section titled “Returns”](#returns-25) `void` ##### truncateResponsesAfter() [Section titled “truncateResponsesAfter()”](#truncateresponsesafter)
```ts
truncateResponsesAfter(userMessageId): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:783](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L783) Keep up to and including a user message, drop later responses (retry). ###### Parameters [Section titled “Parameters”](#parameters-16) | Parameter | Type | | --------------- | -------- | | `userMessageId` | `string` | ###### Returns [Section titled “Returns”](#returns-26) `void` ##### streamTokens() [Section titled “streamTokens()”](#streamtokens)
```ts
streamTokens(messageId, tokens): Promise;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:806](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L806) Drive a manual token stream into the viewport. Sets the streaming guard, appends each token, completes the message at the end. Per-framework wrappers adapt their native stream type (RxJS Observable, AsyncIterable, ReadableStream) into this. Each token reaches the bubble immediately and the framework’s message list is synced **once per frame** (same discipline as [appendToSegment](#appendtosegment)), with a guaranteed flush before completion and on abort, so the framework list and the DOM agree and a custom bubble (which renders from that state) shows the reply. ###### Parameters [Section titled “Parameters”](#parameters-17) | Parameter | Type | | ----------- | ------------------------- | | `messageId` | `string` | | `tokens` | `AsyncIterable`<`string`> | ###### Returns [Section titled “Returns”](#returns-27) `Promise`<`void`> ##### stopTokenStream() [Section titled “stopTokenStream()”](#stoptokenstream)
```ts
stopTokenStream(): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:892](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L892) Abort an in-flight [streamTokens](#streamtokens) loop. ###### Returns [Section titled “Returns”](#returns-28) `void` ##### syncBubbles() [Section titled “syncBubbles()”](#syncbubbles)
```ts
syncBubbles(): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:911](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L911) Reconcile rendered bubbles with the current message list. The framework calls this from its reactive message-change hook after rendering; the last message is always re-synced (streaming), the others whenever the list holds a different object for them than the one they were drawn from. ###### Returns [Section titled “Returns”](#returns-29) `void` ##### syncRepoFromMessages() [Section titled “syncRepoFromMessages()”](#syncrepofrommessages)
```ts
syncRepoFromMessages(): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:929](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L929) Rebuild the viewport’s internal repo from the message list before branch operations (streaming fills the framework state but not the repo). ###### Returns [Section titled “Returns”](#returns-30) `void` *** ## Functions [Section titled “Functions”](#functions) ### createAgentStreamRunner() [Section titled “createAgentStreamRunner()”](#createagentstreamrunner)
```ts
function createAgentStreamRunner(options): AparteStreamRunner;
```
Defined in: [packages/core/src/client/agent-runner.ts:38](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/agent-runner.ts#L38) An `AparteStreamRunner` that runs `AparteClient`’s loop on YOUR server — the one `createAparteAgentHandler` serves — and replays its events here, where the client’s adapter draws them exactly as it draws a loop run in the page.
```ts
const client = new AparteClient({ streamRunner: createAgentStreamRunner({ endpoint: '/api/agent' }) });
```
The page needs no provider of its own: the server runs the model. A provider and model the page selects anyway travel with the turn, and the server uses them. A pipe, nothing more. It sees no message and no segment, so it opens no panel and runs no tool: when the server suspends a run, the CLIENT asks the person or runs the browser tool, then calls this runner again with the answers in `deferral` — the same path it takes when a conversation with a paused call is reloaded days later. #### Parameters [Section titled “Parameters”](#parameters-18) | Parameter | Type | | --------- | ------------------------------------------------------- | | `options` | [`AgentStreamRunnerOptions`](#agentstreamrunneroptions) | #### Returns [Section titled “Returns”](#returns-31) [`AparteStreamRunner`](#apartestreamrunner) *** ### createStreamAdapter() [Section titled “createStreamAdapter()”](#createstreamadapter)
```ts
function createStreamAdapter(opts): StreamRunEmitter;
```
Defined in: [packages/core/src/client/stream-adapter.ts:117](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L117) Build the event → DOM adapter for one streamed message. Returns a synchronous [AparteStreamRunEmitter](#apartestreamrunemitter) to hand to `runStreamAgent` as its `emitter`. Reproduces the inline loop’s `targetElement.*` call sequence exactly (validated by the engine parity test against the real loop). #### Parameters [Section titled “Parameters”](#parameters-19) | Parameter | Type | | --------- | ----------------------------------------------------------- | | `opts` | [`CreateStreamAdapterOptions`](#createstreamadapteroptions) | #### Returns [Section titled “Returns”](#returns-32) `StreamRunEmitter` *** ### readableToAsyncIterable() [Section titled “readableToAsyncIterable()”](#readabletoasynciterable)
```ts
function readableToAsyncIterable(stream, signal): AsyncIterable;
```
Defined in: [packages/core/src/client/stream-adapter.ts:450](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L450) Bridge a `ReadableStream` (what the transport returns) to the `AsyncIterable` `runStreamAgent` consumes, cancelling the reader **synchronously** on abort so a user “stop” cuts the in-flight read. Used by `AparteClient` when building `transportCall` for the runner. Mirrors the inline loop’s `reader.read()` loop + `reader.cancel()`. #### Parameters [Section titled “Parameters”](#parameters-20) | Parameter | Type | | --------- | ------------------------------------------------------------------------------------ | | `stream` | `ReadableStream`<[`AparteStreamEvent`](/reference/core/messages/#apartestreamevent)> | | `signal` | `AbortSignal` | #### Returns [Section titled “Returns”](#returns-33) `AsyncIterable`<[`AparteStreamEvent`](/reference/core/messages/#apartestreamevent)> *** ## Variables [Section titled “Variables”](#variables) ### toolRefusal [Section titled “toolRefusal”](#toolrefusal)
```ts
const toolRefusal: typeof engineToolRefusal = engineToolRefusal;
```
Defined in: [packages/core/src/client/stream-adapter.ts:56](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L56) What a refused tool call tells the model, and who refused it — engine’s `toolRefusal`, under core’s roof. `reason` is the sentence the model reads (the refuser’s own, else the person’s words quoted, else “Tool execution was rejected by the user.”); `by` and `instruction` are what a row shows the person. For a runner that answers an agent the loop does not run (an AG-UI agent, a server): it writes the sentence the loop writes, so the model reads one refusal however it ran. #### Example [Section titled “Example”](#example-1)
```ts
toolRefusal({ instruction: 'use the staging bucket' });
// → { reason: 'The user rejected this tool call and said: use the staging bucket',
// by: 'person', instruction: 'use the staging bucket' }
```
*** ## Interfaces [Section titled “Interfaces”](#interfaces) ### AgentStreamRunnerOptions [Section titled “AgentStreamRunnerOptions”](#agentstreamrunneroptions) Defined in: [packages/core/src/client/agent-runner.ts:8](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/agent-runner.ts#L8) #### Properties [Section titled “Properties”](#properties) ##### endpoint [Section titled “endpoint”](#endpoint)
```ts
endpoint: string;
```
Defined in: [packages/core/src/client/agent-runner.ts:10](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/agent-runner.ts#L10) The route that serves `createAparteAgentHandler`, e.g. `/api/agent`. ##### headers? [Section titled “headers?”](#headers)
```ts
optional headers?:
| Record
| (() =>
| Record
| Promise>);
```
Defined in: [packages/core/src/client/agent-runner.ts:12](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/agent-runner.ts#L12) Sent with every request; a function is called per request (a fresh token each time). ##### fetch? [Section titled “fetch?”](#fetch)
```ts
optional fetch?: {
(input, init?): Promise;
(input, init?): Promise;
};
```
Defined in: [packages/core/src/client/agent-runner.ts:14](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/agent-runner.ts#L14) ###### Call Signature [Section titled “Call Signature”](#call-signature)
```ts
(input, init?): Promise;
```
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) ###### Parameters [Section titled “Parameters”](#parameters-21) | Parameter | Type | | --------- | ---------------------- | | `input` | `RequestInfo` \| `URL` | | `init?` | `RequestInit` | ###### Returns [Section titled “Returns”](#returns-34) `Promise`<`Response`> ###### Call Signature [Section titled “Call Signature”](#call-signature-1)
```ts
(input, init?): Promise;
```
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) ###### Parameters [Section titled “Parameters”](#parameters-22) | Parameter | Type | | --------- | ------------------------------ | | `input` | `string` \| `Request` \| `URL` | | `init?` | `RequestInit` | ###### Returns [Section titled “Returns”](#returns-35) `Promise`<`Response`> ###### Default [Section titled “Default”](#default) the global `fetch` ##### credentials? [Section titled “credentials?”](#credentials)
```ts
optional credentials?: RequestCredentials;
```
Defined in: [packages/core/src/client/agent-runner.ts:16](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/agent-runner.ts#L16) For a cross-origin endpoint that authenticates by cookie. *** ### AparteClientOptions [Section titled “AparteClientOptions”](#aparteclientoptions) Defined in: [packages/core/src/client/aparte-client.ts:90](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L90) Configuration options for AparteClient #### Properties [Section titled “Properties”](#properties-1) ##### keyResolver? [Section titled “keyResolver?”](#keyresolver)
```ts
optional keyResolver?: (providerId) =>
| string
| Record
| Promise | null | undefined>
| null
| undefined;
```
Defined in: [packages/core/src/client/aparte-client.ts:95](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L95) Function to resolve API keys for a given provider. Can return a string (key) or a full configuration object. ###### Parameters [Section titled “Parameters”](#parameters-23) | Parameter | Type | | ------------ | -------- | | `providerId` | `string` | ###### Returns [Section titled “Returns”](#returns-36) \| `string` | `Record`<`string`, `string`> | `Promise`<`string` | `Record`<`string`, `string`> | `null` | `undefined`> | `null` | `undefined` ##### approvalResolver? [Section titled “approvalResolver?”](#approvalresolver)
```ts
optional approvalResolver?: StreamApprovalResolver;
```
Defined in: [packages/core/src/client/aparte-client.ts:114](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L114) Custom human-in-the-loop approval resolver for tools marked `needsApproval`. Without one, the gate asks at the composer through `requestUserInput`, like every other request for the user. Inject this to decide from the call itself — it receives `(call, signal)` — or to drive approval from a headless source (CLI / webhook) with no DOM. It owns the WHOLE decision: with one injected, an `AparteApprovalPolicy` registered through `setApprovalPolicy()` — and therefore `@aparte/plugin-approval`’s modes — is not consulted at all, neither for the gate nor for the answer, and the tool’s own `needsApproval` decides which calls reach this resolver. Rule on the call here, or drop this option and use a policy; do not expect both. On a refusal it may return an `instruction` (the user’s words) or a `reason` (nobody spoke), which the model reads as the tool result. ##### streamRunner? [Section titled “streamRunner?”](#streamrunner)
```ts
optional streamRunner?: AparteStreamRunner;
```
Defined in: [packages/core/src/client/aparte-client.ts:123](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L123) The stream-loop runner. Default: `@aparte/engine`’s `runStreamAgent`, rendered through the core adapter ([createStreamAdapter](#createstreamadapter)). Set it to wrap that loop — `(opts) => runStreamAgent({ ...opts, onHistoryAppend })` for a host that owns its transcript — or to replace it with a loop of your own that emits the same events. Same injection pattern as [approvalResolver](#approvalresolver). See [AparteStreamRunner](#apartestreamrunner). ##### requestInterceptor? [Section titled “requestInterceptor?”](#requestinterceptor)
```ts
optional requestInterceptor?: (request) =>
| AparteChatRequest
| Promise;
```
Defined in: [packages/core/src/client/aparte-client.ts:128](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L128) Optional request interceptor to modify the chat request before sending. ###### Parameters [Section titled “Parameters”](#parameters-24) | Parameter | Type | | --------- | ------------------------------------------------------------------ | | `request` | [`AparteChatRequest`](/reference/core/messages/#apartechatrequest) | ###### Returns [Section titled “Returns”](#returns-37) \| [`AparteChatRequest`](/reference/core/messages/#apartechatrequest) | `Promise`<[`AparteChatRequest`](/reference/core/messages/#apartechatrequest)> ##### autoRegister? [Section titled “autoRegister?”](#autoregister)
```ts
optional autoRegister?: boolean;
```
Defined in: [packages/core/src/client/aparte-client.ts:140](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L140) Whether to register core’s default segment renderers. Rarely needed either way: the built-ins install themselves the first time a segment needs one, so leaving this alone just works. Set it to `false` to keep them out entirely — a decision that is remembered, so nothing installs them later; register your own with `registerSegmentRenderer`. Do it at startup, before the first segment renders. ###### Default [Section titled “Default”](#default-1)
```ts
true
```
##### history? [Section titled “history?”](#history)
```ts
optional history?:
| "none"
| "viewport"
| ((viewportMessages) => AparteChatMessage[]);
```
Defined in: [packages/core/src/client/aparte-client.ts:160](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L160) Conversation history strategy: * ‘viewport’ (default) — sends every user/assistant turn up to the last answered one. A turn that errored, or is still in flight (‘streaming’ / ‘pending’), is held back and does not move that cutoff; a turn a host seeded with NO `status` counts as answered, so a restored or server-rendered transcript goes out as history without inventing a status for it. * ‘none’ — sends only the current message * function — custom: receives viewport messages, returns AparteChatMessage\[] With ‘viewport’, a checkpoint (`AparteMessage.contextSummary`, written by `@aparte/plugin-compaction`) shortens what goes out: the summary, then the messages from the checkpoint on. A function receives the WHOLE transcript, checkpoint and everything before it — what to send is its call. To honour the checkpoint, pass the messages through `historyFromCheckpoint` and send its `summary` first. Retry and edit rebuild the history themselves and do not call this function. ##### targetResolver? [Section titled “targetResolver?”](#targetresolver)
```ts
optional targetResolver?: () => HTMLElement | null;
```
Defined in: [packages/core/src/client/aparte-client.ts:170](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L170) Optional resolver that returns the host element exposing `appendMessage`. Use this when the default event-bubble walk cannot reach the host (e.g. Angular re-renders detach the input element mid-flight). ###### Returns [Section titled “Returns”](#returns-38) `HTMLElement` | `null` ###### Example [Section titled “Example”](#example-2)
```ts
targetResolver: () => document.querySelector('aparte-chat')
```
##### scopeToTargetId? [Section titled “scopeToTargetId?”](#scopetotargetid)
```ts
optional scopeToTargetId?: string;
```
Defined in: [packages/core/src/client/aparte-client.ts:184](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L184) Scope this client to a specific target element id. When set, the client will only handle `aparte-send`, `aparte-retry`, `aparte-edit` and `aparte-abort` events whose `detail.targetId` matches this id. This allows multiple AparteClient instances (one per conversation) to coexist on the same page without interfering with each other. ###### Example [Section titled “Example”](#example-3)
```ts
// Two independent conversations:
new AparteClient({ scopeToTargetId: 'chat-left' }).start();
new AparteClient({ scopeToTargetId: 'chat-right' }).start();
```
##### maxTurns? [Section titled “maxTurns?”](#maxturns)
```ts
optional maxTurns?: number;
```
Defined in: [packages/core/src/client/aparte-client.ts:192](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L192) Maximum number of agentic tool-call loop turns before the loop is forcibly stopped and an error segment is shown. Prevents infinite loops. Individual tools can override this via `AparteTool.maxTurns`. ###### Default [Section titled “Default”](#default-2)
```ts
10
```
##### toolTimeoutMs? [Section titled “toolTimeoutMs?”](#tooltimeoutms)
```ts
optional toolTimeoutMs?: number;
```
Defined in: [packages/core/src/client/aparte-client.ts:198](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L198) Per-call ceiling (ms) for a tool handler to resolve before its signal is aborted. Defaults to 5 minutes — the same default, and the same option name, as `runStreamAgent`, so the value means one thing whichever loop runs. ##### echoUserMessage? [Section titled “echoUserMessage?”](#echousermessage)
```ts
optional echoUserMessage?: boolean;
```
Defined in: [packages/core/src/client/aparte-client.ts:212](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L212) Whether a send appends the optimistic USER bubble before the reply streams. Default `true` — and opt-OUT on purpose: if the host had to append the bubble, whoever forgot would ship a chat where the person cannot see what they typed. It compiles, it streams, and nothing errors. Pass `false` when the host owns its transcript and appends the user message itself — the four framework wrappers do (their ConversationController is that owner) and pass it. The wire cannot double either way: the history builder already excludes trailing unanswered user messages. ##### rawFileInject? [Section titled “rawFileInject?”](#rawfileinject)
```ts
optional rawFileInject?: "none" | "all" | "images-only";
```
Defined in: [packages/core/src/client/aparte-client.ts:231](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L231) Controls which files attached by the user are injected as raw content parts in the LLM request. * `'all'` (default) — images as base64, text files as code-fenced text * `'images-only'` — only images are injected; text/binary documents are left for the application layer (e.g. a RAG pipeline) to handle * `'none'` — no files are injected as content parts; ALL file types (including images) are routed to the application layer. Used when images go through a captioning pipeline before RAG ingest, so the chat context only ever sees retrieved text — never raw image bytes. Saves bytes on every turn. Set `'images-only'` when a `requestInterceptor` retrieves relevant document chunks and injects them as a system message instead, to avoid flooding the context window with full file contents. ##### fileInjectFilter? [Section titled “fileInjectFilter?”](#fileinjectfilter)
```ts
optional fileInjectFilter?: (file) => boolean;
```
Defined in: [packages/core/src/client/aparte-client.ts:244](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L244) Per-file veto on top of [rawFileInject](#rawfileinject): called for each file the mode would inject; return `false` to keep that file out of the request. The file still rides on the `aparte-send` event for the application layer (upload, RAG). Use it to block sensitive names while keeping the default inline UX:
```ts
fileInjectFilter: (f) => !/(^|\.)env$|\.(pem|key)$/i.test(f.name)
```
###### Parameters [Section titled “Parameters”](#parameters-25) | Parameter | Type | | --------- | ------ | | `file` | `File` | ###### Returns [Section titled “Returns”](#returns-39) `boolean` ##### config? [Section titled “config?”](#config)
```ts
optional config?: AparteConfig;
```
Defined in: [packages/core/src/client/aparte-client.ts:252](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L252) Config this client reads (providers, model selection, tools, system prompt). Defaults to `aparteGlobalConfig`. Pass a host’s instance config when scoping a client to one chat among several (pairs with `scopeToTargetId`). *** ### StreamAdapterTarget [Section titled “StreamAdapterTarget”](#streamadaptertarget) Defined in: [packages/core/src/client/stream-adapter.ts:84](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L84) The imperative surface the adapter drives (subset of `AparteChatTargetElement`). Every method is optional so a partial/mock target degrades gracefully. #### Methods [Section titled “Methods”](#methods-2) ##### updateMessage()? [Section titled “updateMessage()?”](#updatemessage-1)
```ts
optional updateMessage(id, updates): void;
```
Defined in: [packages/core/src/client/stream-adapter.ts:85](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L85) ###### Parameters [Section titled “Parameters”](#parameters-26) | Parameter | Type | | --------- | --------------------------------------------------------------------- | | `id` | `string` | | `updates` | `Partial`<[`AparteMessage`](/reference/core/messages/#apartemessage)> | ###### Returns [Section titled “Returns”](#returns-40) `void` ##### updateLastMessage()? [Section titled “updateLastMessage()?”](#updatelastmessage-1)
```ts
optional updateLastMessage(content, options?): void;
```
Defined in: [packages/core/src/client/stream-adapter.ts:86](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L86) ###### Parameters [Section titled “Parameters”](#parameters-27) | Parameter | Type | | ----------------- | ------------------------- | | `content` | `string` | | `options?` | { `append?`: `boolean`; } | | `options.append?` | `boolean` | ###### Returns [Section titled “Returns”](#returns-41) `void` ##### addSegment()? [Section titled “addSegment()?”](#addsegment-1)
```ts
optional addSegment(segment): void;
```
Defined in: [packages/core/src/client/stream-adapter.ts:87](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L87) ###### Parameters [Section titled “Parameters”](#parameters-28) | Parameter | Type | | --------- | ---------------------------------------------------------- | | `segment` | [`AparteSegment`](/reference/core/messages/#apartesegment) | ###### Returns [Section titled “Returns”](#returns-42) `void` ##### updateSegment()? [Section titled “updateSegment()?”](#updatesegment-1)
```ts
optional updateSegment(segmentId, updates): void;
```
Defined in: [packages/core/src/client/stream-adapter.ts:88](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L88) ###### Parameters [Section titled “Parameters”](#parameters-29) | Parameter | Type | | ----------- | --------------------------------------------------------------------- | | `segmentId` | `string` | | `updates` | `Partial`<[`AparteSegment`](/reference/core/messages/#apartesegment)> | ###### Returns [Section titled “Returns”](#returns-43) `void` ##### typeName()? [Section titled “typeName()?”](#typename)
```ts
optional typeName(text): void;
```
Defined in: [packages/core/src/client/stream-adapter.ts:89](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L89) ###### Parameters [Section titled “Parameters”](#parameters-30) | Parameter | Type | | --------- | -------- | | `text` | `string` | ###### Returns [Section titled “Returns”](#returns-44) `void` ##### setUsage()? [Section titled “setUsage()?”](#setusage)
```ts
optional setUsage(id, usage): void;
```
Defined in: [packages/core/src/client/stream-adapter.ts:90](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L90) ###### Parameters [Section titled “Parameters”](#parameters-31) | Parameter | Type | | --------- | ------------------------------------------------------ | | `id` | `string` | | `usage` | [`AparteUsage`](/reference/core/messages/#aparteusage) | ###### Returns [Section titled “Returns”](#returns-45) `void` ##### dispatchEvent() [Section titled “dispatchEvent()”](#dispatchevent)
```ts
dispatchEvent(event): boolean;
```
Defined in: [packages/core/src/client/stream-adapter.ts:91](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L91) ###### Parameters [Section titled “Parameters”](#parameters-32) | Parameter | Type | | --------- | ------- | | `event` | `Event` | ###### Returns [Section titled “Returns”](#returns-46) `boolean` *** ### CreateStreamAdapterOptions [Section titled “CreateStreamAdapterOptions”](#createstreamadapteroptions) Defined in: [packages/core/src/client/stream-adapter.ts:94](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L94) #### Properties [Section titled “Properties”](#properties-2) ##### target [Section titled “target”](#target)
```ts
target: StreamAdapterTarget;
```
Defined in: [packages/core/src/client/stream-adapter.ts:96](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L96) The chat target element the events are rendered onto. ##### config [Section titled “config”](#config-1)
```ts
config: AparteConfig;
```
Defined in: [packages/core/src/client/stream-adapter.ts:98](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L98) Config for tool-renderer lookup + per-tool style injection. ##### messageId [Section titled “messageId”](#messageid)
```ts
messageId: string;
```
Defined in: [packages/core/src/client/stream-adapter.ts:100](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L100) The streamed assistant message id (carried in the run events). ##### targetId? [Section titled “targetId?”](#targetid)
```ts
optional targetId?: string;
```
Defined in: [packages/core/src/client/stream-adapter.ts:108](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L108) The id of the CHAT the target belongs to, stamped on every lifecycle event the adapter dispatches. The target is whatever renders — a shell’s `.viewport`, which has no id of its own — so it cannot be read off the target, and an unstamped event is read as “for every chat on the page”. Omitted, the dispatcher falls back to `target.id`, which is right for the viewport-only chat shape. *** ### AparteChatHostBinding [Section titled “AparteChatHostBinding”](#apartechathostbinding) Defined in: [packages/core/src/host/aparte-chat-host.ts:82](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L82) Everything `AparteChatHost` needs from the framework, expressed without any framework types. Each wrapper (Angular signals, React state, Vue refs, Svelte stores) implements these \~10 closures over its own reactive message list. #### Properties [Section titled “Properties”](#properties-3) ##### hostId [Section titled “hostId”](#hostid)
```ts
readonly hostId: string;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:84](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L84) Stable id for the host element (used as `targetId` for scoped events). ##### host [Section titled “host”](#host)
```ts
readonly host: HTMLElement;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:86](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L86) The element `AparteClient` drives + that emits lifecycle/path events. ##### viewport [Section titled “viewport”](#viewport)
```ts
readonly viewport: HTMLElement | null;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:88](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L88) The `` element (branch ops, token append, bubbles). #### Methods [Section titled “Methods”](#methods-3) ##### getMessages() [Section titled “getMessages()”](#getmessages-1)
```ts
getMessages(): AparteMessage[];
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:91](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L91) Read the current message list (a snapshot). ###### Returns [Section titled “Returns”](#returns-47) [`AparteMessage`](/reference/core/messages/#apartemessage)\[] ##### setMessages() [Section titled “setMessages()”](#setmessages)
```ts
setMessages(messages): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:93](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L93) Replace the framework’s message list (triggers its re-render). ###### Parameters [Section titled “Parameters”](#parameters-33) | Parameter | Type | | ---------- | ------------------------------------------------------------- | | `messages` | [`AparteMessage`](/reference/core/messages/#apartemessage)\[] | ###### Returns [Section titled “Returns”](#returns-48) `void` ##### onMessagesChange()? [Section titled “onMessagesChange()?”](#onmessageschange)
```ts
optional onMessagesChange(messages): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:96](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L96) Notify the consumer that messages changed (drives `messagesChange`). ###### Parameters [Section titled “Parameters”](#parameters-34) | Parameter | Type | | ---------- | ------------------------------------------------------------- | | `messages` | [`AparteMessage`](/reference/core/messages/#apartemessage)\[] | ###### Returns [Section titled “Returns”](#returns-49) `void` ##### onMessageAppended()? [Section titled “onMessageAppended()?”](#onmessageappended)
```ts
optional onMessageAppended(message): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:98](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L98) Notify the consumer a message was appended (drives `messageAppended`). ###### Parameters [Section titled “Parameters”](#parameters-35) | Parameter | Type | | --------- | ---------------------------------------------------------- | | `message` | [`AparteMessage`](/reference/core/messages/#apartemessage) | ###### Returns [Section titled “Returns”](#returns-50) `void` ##### onTypingChange()? [Section titled “onTypingChange()?”](#ontypingchange)
```ts
optional onTypingChange(isTyping): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:100](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L100) Flip the typing/“thinking” indicator. ###### Parameters [Section titled “Parameters”](#parameters-36) | Parameter | Type | | ---------- | --------- | | `isTyping` | `boolean` | ###### Returns [Section titled “Returns”](#returns-51) `void` ##### onStreamingChange()? [Section titled “onStreamingChange()?”](#onstreamingchange)
```ts
optional onStreamingChange(streamingId): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:102](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L102) Streaming target id changed (drives `isStreaming`). ###### Parameters [Section titled “Parameters”](#parameters-37) | Parameter | Type | | ------------- | ------------------ | | `streamingId` | `string` \| `null` | ###### Returns [Section titled “Returns”](#returns-52) `void` ##### afterRender() [Section titled “afterRender()”](#afterrender)
```ts
afterRender(cb): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:104](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L104) Run a callback after the framework has applied the latest render. ###### Parameters [Section titled “Parameters”](#parameters-38) | Parameter | Type | | --------- | ------------ | | `cb` | () => `void` | ###### Returns [Section titled “Returns”](#returns-53) `void` ##### resetComposer()? [Section titled “resetComposer()?”](#resetcomposer)
```ts
optional resetComposer(): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:106](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L106) Reset the composer (clear text/attachments) on conversation swap. ###### Returns [Section titled “Returns”](#returns-54) `void` ##### onLoadingChange()? [Section titled “onLoadingChange()?”](#onloadingchange)
```ts
optional onLoadingChange(loading): void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:117](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L117) The transcript is on its way (`true`) or has arrived (`false`): the controller’s wait, forwarded so a wrapper that draws its own DOM can draw the wait — the skeleton, the empty state kept off, the composer disabled. Declaring it makes the wait YOURS, `aria-busy` included: the host stops writing the viewport’s `loading` attribute and leaves it to you, so two writers never disagree about when the wait ends. A binding without this callback keeps the attribute written for it. ###### Parameters [Section titled “Parameters”](#parameters-39) | Parameter | Type | | --------- | --------- | | `loading` | `boolean` | ###### Returns [Section titled “Returns”](#returns-55) `void` *** ### AparteChatHostOptions [Section titled “AparteChatHostOptions”](#apartechathostoptions) Defined in: [packages/core/src/host/aparte-chat-host.ts:120](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L120) #### Properties [Section titled “Properties”](#properties-4) ##### layoutTransitionMs? [Section titled “layoutTransitionMs?”](#layouttransitionms)
```ts
optional layoutTransitionMs?: number;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:122](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L122) Forwarded to `viewport.configure({ layoutTransitionMs })` when > 0. ##### conversationId? [Section titled “conversationId?”](#conversationid)
```ts
optional conversationId?: string | null;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:124](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L124) Initial conversation id to load when the controller is created. ##### onConversationCreated? [Section titled “onConversationCreated?”](#onconversationcreated)
```ts
optional onConversationCreated?: (id) => void;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:126](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L126) Called when the controller lazily creates a conversation on first send. ###### Parameters [Section titled “Parameters”](#parameters-40) | Parameter | Type | | --------- | -------- | | `id` | `string` | ###### Returns [Section titled “Returns”](#returns-56) `void` ##### config? [Section titled “config?”](#config-2)
```ts
optional config?: AparteConfig;
```
Defined in: [packages/core/src/host/aparte-chat-host.ts:134](https://github.com/apartejs/aparte/blob/main/packages/core/src/host/aparte-chat-host.ts#L134) Instance config for this chat. When provided, bind marks the host element as a `[data-aparte-host]` boundary so every Aparte component inside it (bubbles, composer, renderers) resolves THIS config instead of the global `aparteGlobalConfig` — the seam that lets several independently-configured chats coexist on one page. Omit to keep the global-config behaviour. *** ## Type Aliases [Section titled “Type Aliases”](#type-aliases) ### AparteToolApprovalResolver [Section titled “AparteToolApprovalResolver”](#apartetoolapprovalresolver)
```ts
type AparteToolApprovalResolver = StreamApprovalResolver;
```
Defined in: [packages/core/src/client/aparte-client.ts:78](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/aparte-client.ts#L78) Resolves a human-in-the-loop tool approval for a `needsApproval` tool call. Resolves `{ approved, payload? }`; the `signal` aborts a pending decision. It receives the CALL, not just its id. You cannot ask a person “run this?” without naming what — the built-in channel needs the tool’s name for its question, and an id alone forced a lookup table filled by one event and read by another, which is the shape that breaks in silence. Engine’s `StreamApprovalResolver`, under core’s name — one type, not a twin to keep in step: its result’s `instruction`, `reason` and `by` are documented there. *** ### AparteStreamRunEvent [Section titled “AparteStreamRunEvent”](#apartestreamrunevent)
```ts
type AparteStreamRunEvent = StreamRunEvent;
```
Defined in: [packages/core/src/client/stream-adapter.ts:40](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L40) The DOM-free run events `@aparte/engine`’s `runStreamAgent` emits — engine’s `StreamRunEvent`, under core’s name. See `packages/engine/src/agent/stream-events.ts` for the per-event documentation. *** ### AparteStreamRunEmitter [Section titled “AparteStreamRunEmitter”](#apartestreamrunemitter)
```ts
type AparteStreamRunEmitter = StreamRunEmitter;
```
Defined in: [packages/core/src/client/stream-adapter.ts:59](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L59) Synchronous, ordered event sink — engine’s `StreamRunEmitter`. *** ### AparteStreamRunOptions [Section titled “AparteStreamRunOptions”](#apartestreamrunoptions)
```ts
type AparteStreamRunOptions = StreamRunOptions;
```
Defined in: [packages/core/src/client/stream-adapter.ts:68](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L68) Options for an injected [AparteStreamRunner](#apartestreamrunner) — engine’s `StreamRunOptions`. `AparteClient` builds these from its config / provider / transport and hands them to the runner; core’s request, message and tool types are assignable to the structural ones the engine declares, and that assignment is checked where it is made rather than in a guard beside it. *** ### AparteStreamRunner [Section titled “AparteStreamRunner”](#apartestreamrunner)
```ts
type AparteStreamRunner = (opts) => Promise;
```
Defined in: [packages/core/src/client/stream-adapter.ts:78](https://github.com/apartejs/aparte/blob/main/packages/core/src/client/stream-adapter.ts#L78) A headless structured-stream loop injected via `AparteClientOptions.streamRunner` — the seam by which a host wraps or replaces the loop `AparteClient` runs, which is `@aparte/engine`’s `runStreamAgent` by default. `runStreamAgent` IS this type — pass it, do not cast it. The alias makes any drift between the two packages’ message types a typecheck error in the composition itself. #### Parameters [Section titled “Parameters”](#parameters-41) | Parameter | Type | | --------- | --------------------------------------------------- | | `opts` | [`AparteStreamRunOptions`](#apartestreamrunoptions) | #### Returns [Section titled “Returns”](#returns-57) `Promise`<`StreamUsage` | `undefined`> ***
# Configuration — core API
> Generated reference for @aparte/core. aparteGlobalConfig, the class behind it, and the provider, renderer and locale types it takes.
## Classes [Section titled “Classes”](#classes) ### AparteConfig [Section titled “AparteConfig”](#aparteconfig) Defined in: [packages/core/src/config/aparte-config.ts:313](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L313) Everything a chat is configured with: the providers and the selected model, the transport and the keys, the tools, the renderers and render hooks, the Markdown and highlight providers, the locale, the icons, the avatars, the actions. [aparteGlobalConfig](#aparteglobalconfig) is the one every chat on the page reads. A chat that needs a configuration of its own takes a `new AparteConfig()` attached to its element or to an ancestor with [attachConfig](#attachconfig); the framework wrappers take it as their `config` prop. A change to what is drawn — providers, the model, the locale, icons, avatars, actions, renderers — reaches the components already on the page: [subscribe()](#subscribe) listeners are called, and `aparte-config-change` is dispatched on `window` with the instance that changed. The Markdown, streaming-Markdown and highlight providers are among them: a message drawn before they were set is drawn again with them (one still streaming, once it ends). The sanitizer, segment defaults, tools, tool renderers and summaries apply to what is drawn after they are set, so set them before the chat renders; the transport, the keys and the system prompt apply from the next request. #### Constructors [Section titled “Constructors”](#constructors) ##### Constructor [Section titled “Constructor”](#constructor)
```ts
new AparteConfig(): AparteConfig;
```
###### Returns [Section titled “Returns”](#returns) [`AparteConfig`](#aparteconfig) #### Methods [Section titled “Methods”](#methods) ##### registerAction() [Section titled “registerAction()”](#registeraction)
```ts
registerAction(action): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:450](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L450) Register a custom action button. `zones` places it in the message (bubble) toolbar. Re-registering the same id overwrites it. Notifies mounted elements so they re-render. A button in the composer is an `` element you write in your markup, not a registry entry. ###### Parameters [Section titled “Parameters”](#parameters) | Parameter | Type | | --------- | ------------------------------- | | `action` | [`AparteAction`](#aparteaction) | ###### Returns [Section titled “Returns”](#returns-1) `void` ##### getActions() [Section titled “getActions()”](#getactions)
```ts
getActions(zone): AparteAction[];
```
Defined in: [packages/core/src/config/aparte-config.ts:462](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L462) All registered actions for a zone, sorted by `order` (lower first). ###### Parameters [Section titled “Parameters”](#parameters-1) | Parameter | Type | | --------- | ---------- | | `zone` | `"bubble"` | ###### Returns [Section titled “Returns”](#returns-2) [`AparteAction`](#aparteaction)\[] ##### unregisterAction() [Section titled “unregisterAction()”](#unregisteraction)
```ts
unregisterAction(id): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:469](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L469) Remove a custom action by id (from every zone); notifies mounted elements if it existed. ###### Parameters [Section titled “Parameters”](#parameters-2) | Parameter | Type | | --------- | -------- | | `id` | `string` | ###### Returns [Section titled “Returns”](#returns-3) `void` ##### setBubbleActions() [Section titled “setBubbleActions()”](#setbubbleactions)
```ts
setBubbleActions(config): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:487](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L487) Configure which action buttons appear in message bubbles. Unset keys keep their defaults — see [APARTE\_DEFAULT\_BUBBLE\_ACTIONS](#aparte_default_bubble_actions): none, so a message carries no button until you turn one on. ###### Parameters [Section titled “Parameters”](#parameters-3) | Parameter | Type | | --------- | ---------------------------------------------------------------------------------- | | `config` | [`AparteBubbleActionsConfig`](/reference/core/messages/#apartebubbleactionsconfig) | ###### Returns [Section titled “Returns”](#returns-4) `void` ###### Example [Section titled “Example”](#example)
```ts
aparteGlobalConfig.setBubbleActions({ copy: true }) // core copies on its own
aparteGlobalConfig.setBubbleActions({ retry: true, edit: true }) // you run AparteClient
aparteGlobalConfig.setBubbleActions({ feedback: true }) // you listen for aparte-feedback; calls merge, so copy stays on
// Explicit per-role ordered sets (replace the flag defaults for that role):
aparteGlobalConfig.setBubbleActions({ user: ['edit', 'copy'], assistant: ['copy', 'thumbUp', 'thumbDown', 'retry'] })
```
##### setHostHandlers() [Section titled “setHostHandlers()”](#sethosthandlers)
```ts
setHostHandlers(config): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:499](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L499) Declare which host-dependent affordances your app handles. Core renders the trigger only for the ones you claim — see [AparteHostHandlersConfig](/reference/core/messages/#apartehosthandlersconfig). ###### Parameters [Section titled “Parameters”](#parameters-4) | Parameter | Type | | --------- | -------------------------------------------------------------------------------- | | `config` | [`AparteHostHandlersConfig`](/reference/core/messages/#apartehosthandlersconfig) | ###### Returns [Section titled “Returns”](#returns-5) `void` ###### Example [Section titled “Example”](#example-1)
```ts
aparteGlobalConfig.setHostHandlers({ attachmentPreview: true });
```
##### getHostHandlers() [Section titled “getHostHandlers()”](#gethosthandlers)
```ts
getHostHandlers(): Required;
```
Defined in: [packages/core/src/config/aparte-config.ts:510](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L510) Returns the resolved host-handler declarations (undeclared = false). ###### Returns [Section titled “Returns”](#returns-6) `Required`<[`AparteHostHandlersConfig`](/reference/core/messages/#apartehosthandlersconfig)> ##### getBubbleActions() [Section titled “getBubbleActions()”](#getbubbleactions)
```ts
getBubbleActions(): {
copy: boolean;
retry: boolean;
edit: boolean;
feedback: boolean;
info: boolean;
user?: AparteBubbleActionName[];
assistant?: AparteBubbleActionName[];
};
```
Defined in: [packages/core/src/config/aparte-config.ts:518](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L518) Returns the resolved bubble actions config (flag defaults applied; per-role sets passed through). ###### Returns [Section titled “Returns”](#returns-7)
```ts
{
copy: boolean;
retry: boolean;
edit: boolean;
feedback: boolean;
info: boolean;
user?: AparteBubbleActionName[];
assistant?: AparteBubbleActionName[];
}
```
###### copy [Section titled “copy”](#copy)
```ts
copy: boolean;
```
###### retry [Section titled “retry”](#retry)
```ts
retry: boolean;
```
###### edit [Section titled “edit”](#edit)
```ts
edit: boolean;
```
###### feedback [Section titled “feedback”](#feedback)
```ts
feedback: boolean;
```
###### info [Section titled “info”](#info)
```ts
info: boolean;
```
###### user? [Section titled “user?”](#user)
```ts
optional user?: AparteBubbleActionName[];
```
###### assistant? [Section titled “assistant?”](#assistant)
```ts
optional assistant?: AparteBubbleActionName[];
```
##### setMarkdownProvider() [Section titled “setMarkdownProvider()”](#setmarkdownprovider)
```ts
setMarkdownProvider(fn): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:541](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L541) Set a custom Markdown renderer (e.g., marked, maritime-it) ###### Parameters [Section titled “Parameters”](#parameters-5) | Parameter | Type | | --------- | --------------------------------------------------- | | `fn` | [`AparteMarkdownProvider`](#apartemarkdownprovider) | ###### Returns [Section titled “Returns”](#returns-8) `void` ##### setStreamingMarkdownProvider() [Section titled “setStreamingMarkdownProvider()”](#setstreamingmarkdownprovider)
```ts
setStreamingMarkdownProvider(fn): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:558](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L558) Set an incremental (streaming) Markdown renderer provider. Optional — when set, the chat bubble uses it to render the assistant message token-by-token DURING streaming (incremental parse + DOM append, O(n)), instead of re-parsing the whole string on every token. With no one-shot `setMarkdownProvider` registered, it also renders a COMPLETE string (`renderMarkdown`): a restored reply, a non-streaming provider’s answer, a stored segment — so a reply renders the same however it arrived. A registered one-shot provider takes over for those, and re-renders the finished message at full fidelity. ###### Parameters [Section titled “Parameters”](#parameters-6) | Parameter | Type | | --------- | --------------------------------------------------------------------- | | `fn` | [`AparteStreamingMarkdownProvider`](#apartestreamingmarkdownprovider) | ###### Returns [Section titled “Returns”](#returns-9) `void` ##### createStreamingMarkdownRenderer() [Section titled “createStreamingMarkdownRenderer()”](#createstreamingmarkdownrenderer)
```ts
createStreamingMarkdownRenderer(target):
| AparteStreamingMarkdownRenderer
| null;
```
Defined in: [packages/core/src/config/aparte-config.ts:569](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L569) Create an incremental Markdown renderer bound to `target`, or `null` when no streaming-markdown provider is registered (the caller then falls back to the one-shot `renderMarkdown`). ###### Parameters [Section titled “Parameters”](#parameters-7) | Parameter | Type | | --------- | ------------- | | `target` | `HTMLElement` | ###### Returns [Section titled “Returns”](#returns-10) \| [`AparteStreamingMarkdownRenderer`](#apartestreamingmarkdownrenderer) | `null` ##### setHighlightProvider() [Section titled “setHighlightProvider()”](#sethighlightprovider)
```ts
setHighlightProvider(fn): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:577](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L577) Set a custom Syntax Highlighter (e.g., prism, highlight.js, shiki) Supports both synchronous and asynchronous renderers. ###### Parameters [Section titled “Parameters”](#parameters-8) | Parameter | Type | | --------- | ----------------------------------------------------- | | `fn` | [`AparteHighlightProvider`](#apartehighlightprovider) | ###### Returns [Section titled “Returns”](#returns-11) `void` ##### hasHighlightProvider() [Section titled “hasHighlightProvider()”](#hashighlightprovider)
```ts
hasHighlightProvider(): boolean;
```
Defined in: [packages/core/src/config/aparte-config.ts:588](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L588) Whether a syntax-highlight provider is registered. Lets consumers (e.g. the bubble) skip the highlight pass — and avoid replacing already-rendered code blocks with the plain fallback — when no highlighter is installed. ###### Returns [Section titled “Returns”](#returns-12) `boolean` ##### registerCodeLanguageRenderer() [Section titled “registerCodeLanguageRenderer()”](#registercodelanguagerenderer)
```ts
registerCodeLanguageRenderer(renderer): () => void;
```
Defined in: [packages/core/src/config/aparte-config.ts:599](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L599) Draw a language — `math`, `mermaid` — wherever it appears in a reply, whichever Markdown provider produced it. Messages already on screen are drawn again. ###### Parameters [Section titled “Parameters”](#parameters-9) | Parameter | Type | | ---------- | ----------------------------------------------------------- | | `renderer` | [`AparteCodeLanguageRenderer`](#apartecodelanguagerenderer) | ###### Returns [Section titled “Returns”](#returns-13) a disposer that removes the renderer, if it is still the one registered. () => `void` ###### Example [Section titled “Example”](#example-2)
```ts
aparteGlobalConfig.registerCodeLanguageRenderer({ languages: ['math'], render: ({ source }) => katex.renderToString(source) });
```
##### getCodeLanguageRenderer() [Section titled “getCodeLanguageRenderer()”](#getcodelanguagerenderer)
```ts
getCodeLanguageRenderer(language): AparteCodeLanguageRenderer | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:618](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L618) The renderer registered for `language`, if any. ###### Parameters [Section titled “Parameters”](#parameters-10) | Parameter | Type | | ---------- | -------- | | `language` | `string` | ###### Returns [Section titled “Returns”](#returns-14) [`AparteCodeLanguageRenderer`](#apartecodelanguagerenderer) | `undefined` ##### hasCodeLanguageRenderer() [Section titled “hasCodeLanguageRenderer()”](#hascodelanguagerenderer)
```ts
hasCodeLanguageRenderer(language?): boolean;
```
Defined in: [packages/core/src/config/aparte-config.ts:623](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L623) Whether a renderer is registered for `language`, or for any language when none is given. ###### Parameters [Section titled “Parameters”](#parameters-11) | Parameter | Type | | ----------- | -------- | | `language?` | `string` | ###### Returns [Section titled “Returns”](#returns-15) `boolean` ##### setHtmlSanitizer() [Section titled “setHtmlSanitizer()”](#sethtmlsanitizer)
```ts
setHtmlSanitizer(sanitizer): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:645](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L645) Replace or disable the HTML sanitizer applied to markdown/highlight provider output before it is injected into the DOM. Defaults to a built-in zero-dependency allowlist sanitizer. The function you pass REPLACES the built-in one, chat rules included: no `aparte-` classes, no layout styles, no form controls, external links in a new tab. DOMPurify’s defaults hold none of the four, so chain it in front of `defaultSanitizer` rather than in its place (the example below). ###### Parameters [Section titled “Parameters”](#parameters-12) | Parameter | Type | Description | | ----------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `sanitizer` | [`AparteSanitizer`](#apartesanitizer) \| `null` | A sanitizer function, or `null` to DISABLE sanitization. Disabling exposes you to XSS from LLM-authored content — only do so for content you fully trust and have already sanitized upstream. `null` prints a console warning, once. | ###### Returns [Section titled “Returns”](#returns-16) `void` ###### Example [Section titled “Example”](#example-3)
```ts
aparteGlobalConfig.setHtmlSanitizer((html) => defaultSanitizer(DOMPurify.sanitize(html)));
```
##### sanitizeHtml() [Section titled “sanitizeHtml()”](#sanitizehtml)
```ts
sanitizeHtml(html): string;
```
Defined in: [packages/core/src/config/aparte-config.ts:676](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L676) Run the active sanitizer over provider-produced HTML, then the image policy ([setImagePolicy](#setimagepolicy)): a picture the policy does not let load comes back as a link that loads it on a click. Public so a streaming-markdown provider (which appends DOM directly, bypassing `renderMarkdown`) can apply the same rules. The image policy runs whichever sanitizer is set, none included, so replacing it does not turn a reply’s pictures back into requests the reader never made. ###### Parameters [Section titled “Parameters”](#parameters-13) | Parameter | Type | | --------- | -------- | | `html` | `string` | ###### Returns [Section titled “Returns”](#returns-17) `string` ##### setImagePolicy() [Section titled “setImagePolicy()”](#setimagepolicy)
```ts
setImagePolicy(policy): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:702](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L702) Which pictures a model or a tool chose load before the reader asks — in a reply’s Markdown, in a card, in a tool’s details. By default only `data:` and `blob:` pictures, which make no request: any other is held, drawn as a small link that says where it would load from, and loads in place when the reader clicks it. The reason is that a picture fetches its address the moment it is shown, and a prompt-injected model can write the conversation into that address. Name what you trust: * a list — `'self'` for the page’s own origin, an origin (`'https://cdn.example.com'`), or `'*'` for every picture; * a function, which gets the picture’s address (resolved against the page) and answers `'load'`, `'hold'` or `'drop'`. Every picture that loads goes with `referrerpolicy="no-referrer"`. What is on screen is drawn again under the new policy. A CSP `img-src` is the stronger rule beside this one: it also checks where a redirect leads, which no script on the page can see. ###### Parameters [Section titled “Parameters”](#parameters-14) | Parameter | Type | | --------- | ----------------------------------------- | | `policy` | [`AparteImagePolicy`](#aparteimagepolicy) | ###### Returns [Section titled “Returns”](#returns-18) `void` ###### Examples [Section titled “Examples”](#examples)
```ts
aparteGlobalConfig.setImagePolicy(['self', 'https://cdn.example.com']);
```
```ts
aparteGlobalConfig.setImagePolicy((url) => url.startsWith('https://images.example.com/') ? 'load' : 'hold');
```
##### decideImage() [Section titled “decideImage()”](#decideimage)
```ts
decideImage(url): AparteImageDecision;
```
Defined in: [packages/core/src/config/aparte-config.ts:722](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L722) What the picture at `url` does under this config’s image policy: `'load'`, `'hold'` (shown as a link that loads it on a click) or `'drop'`. For a plugin that draws pictures itself, as `@aparte/plugin-cards` does: ask before setting a `src`, because setting it is the request. ###### Parameters [Section titled “Parameters”](#parameters-15) | Parameter | Type | | --------- | -------- | | `url` | `string` | ###### Returns [Section titled “Returns”](#returns-19) [`AparteImageDecision`](#aparteimagedecision) ##### showImage() [Section titled “showImage()”](#showimage)
```ts
showImage(url): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:751](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L751) The reader chose to see the picture at `url`: from now on it loads wherever this config’s image policy would only have held it (a picture the policy drops stays dropped). Core calls it when a held picture’s link is clicked; a plugin calls it from its own “Show images”, then draws again. Nothing on screen is redrawn by this call. ###### Parameters [Section titled “Parameters”](#parameters-16) | Parameter | Type | | --------- | -------- | | `url` | `string` | ###### Returns [Section titled “Returns”](#returns-20) `void` ##### setSystemPrompt() [Section titled “setSystemPrompt()”](#setsystemprompt)
```ts
setSystemPrompt(template): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:768](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L768) Set the system prompt template. Supports `{{key}}` placeholders resolved via setSystemPromptVarsProvider. Pass undefined to clear. ###### Parameters [Section titled “Parameters”](#parameters-17) | Parameter | Type | | ---------- | ----------------------- | | `template` | `string` \| `undefined` | ###### Returns [Section titled “Returns”](#returns-21) `void` ##### getSystemPromptTemplate() [Section titled “getSystemPromptTemplate()”](#getsystemprompttemplate)
```ts
getSystemPromptTemplate(): string | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:773](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L773) Get the raw system prompt template (with unresolved placeholders). ###### Returns [Section titled “Returns”](#returns-22) `string` | `undefined` ##### setSystemPromptVarsProvider() [Section titled “setSystemPromptVarsProvider()”](#setsystempromptvarsprovider)
```ts
setSystemPromptVarsProvider(fn): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:782](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L782) Register a function that returns a map of variable name → value. Called at request time to resolve `{{key}}` placeholders in the system prompt. Example: () => ({ ‘settings.lang’: ‘French’ }) ###### Parameters [Section titled “Parameters”](#parameters-18) | Parameter | Type | | --------- | ------------------------------------------------------------------- | | `fn` | [`AparteSystemPromptVarsProvider`](#apartesystempromptvarsprovider) | ###### Returns [Section titled “Returns”](#returns-23) `void` ##### resolveSystemPrompt() [Section titled “resolveSystemPrompt()”](#resolvesystemprompt)
```ts
resolveSystemPrompt(): string | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:790](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L790) Resolve the system prompt template by substituting all `{{key}}` placeholders. Returns null if no template is set or the template is empty after trimming. ###### Returns [Section titled “Returns”](#returns-24) `string` | `null` ##### setIconProvider() [Section titled “setIconProvider()”](#seticonprovider)
```ts
setIconProvider(provider): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:803](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L803) Set a custom Icon provider (e.g., Lucide, FontAwesome, Material). It replaces the whole set, icons added with `registerIcons` included; a name it leaves out keeps core’s drawing. ###### Parameters [Section titled “Parameters”](#parameters-19) | Parameter | Type | Description | | ---------- | ------------------------------------------- | ------------------------------------------------ | | `provider` | [`AparteIconProvider`](#aparteiconprovider) | Object implementing AparteIconProvider interface | ###### Returns [Section titled “Returns”](#returns-25) `void` ##### registerIcons() [Section titled “registerIcons()”](#registericons)
```ts
registerIcons(icons): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:821](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L821) Add icons to the set, or redraw some of it, keeping the others. A name core does not draw is welcome: an action’s `icon`, `` and `` then find it. To type such a name, merge it into `AparteIconProvider`: `declare module '@aparte/core' { interface AparteIconProvider { share?: () => string } }`. ###### Parameters [Section titled “Parameters”](#parameters-20) | Parameter | Type | | --------- | ---------------------------------- | | `icons` | `Record`<`string`, () => `string`> | ###### Returns [Section titled “Returns”](#returns-26) `void` ###### Example [Section titled “Example”](#example-4)
```ts
aparteGlobalConfig.registerIcons({ share: () => '… ' });
aparteGlobalConfig.registerAction({ id: 'share', icon: 'share', label: 'Share', zones: ['bubble'] });
```
##### getIconProvider() [Section titled “getIconProvider()”](#geticonprovider)
```ts
getIconProvider(): Required> & AparteIconProvider;
```
Defined in: [packages/core/src/config/aparte-config.ts:846](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L846) The icon set as a **complete** provider: every name resolves, falling back to `APARTE_DEFAULT_ICON_FALLBACKS` for anything the registered provider doesn’t implement. Callers (bubble action bar, composer controls) can therefore invoke `icons.copy()` unconditionally. A registered provider may implement only a subset of the names; the missing ones fall back, so `icons.retry()` never throws “is not a function”. ###### Returns [Section titled “Returns”](#returns-27) `Required`<`Pick`<[`AparteIconProvider`](#aparteiconprovider), | `"error"` | `"stop"` | `"retry"` | `"copy"` | `"edit"` | `"thumbUp"` | `"thumbDown"` | `"info"` | `"loading"` | `"tool"` | `"image"` | `"check"` | `"send"` | `"expand"` | `"collapse"` | `"terminal"` | `"paperclip"` | `"file"` | `"scrollDown"` | `"prevBranch"` | `"nextBranch"` | `"close"` | `"archive"` | `"unarchive"` | `"download"` | `"more"` | `"pin"` | `"trash"` | `"menu"` | `"alertTriangle"` | `"messageSquare"` | `"pause"`>> & [`AparteIconProvider`](#aparteiconprovider) ##### setAvatarProvider() [Section titled “setAvatarProvider()”](#setavatarprovider)
```ts
setAvatarProvider(provider): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:866](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L866) Set a custom avatar renderer. Lets framework consumers (Angular, React, Vue, …) mount live components in place of the default avatar text/image. Cleared by passing `null`. ###### Parameters [Section titled “Parameters”](#parameters-21) | Parameter | Type | | ---------- | --------------------------------------------------------- | | `provider` | [`AparteAvatarProvider`](#aparteavatarprovider) \| `null` | ###### Returns [Section titled “Returns”](#returns-28) `void` ##### getAvatarProvider() [Section titled “getAvatarProvider()”](#getavatarprovider)
```ts
getAvatarProvider(): AparteAvatarProvider | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:873](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L873) Returns the registered avatar provider, or null if none. ###### Returns [Section titled “Returns”](#returns-29) [`AparteAvatarProvider`](#aparteavatarprovider) | `null` ##### setStatusRenderer() [Section titled “setStatusRenderer()”](#setstatusrenderer)
```ts
setStatusRenderer(renderer): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:883](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L883) Set a custom typing-indicator renderer. Replaces the inner markup of `` (avatar + animated dots + text) while the element keeps owning show/hide. Return a string or an HTMLElement. Cleared by passing `null`. Notifies mounted components so a live skin switch re-renders. ###### Parameters [Section titled “Parameters”](#parameters-22) | Parameter | Type | | ---------- | --------------------------------------------------------- | | `renderer` | [`AparteStatusRenderer`](#apartestatusrenderer) \| `null` | ###### Returns [Section titled “Returns”](#returns-30) `void` ##### getStatusRenderer() [Section titled “getStatusRenderer()”](#getstatusrenderer)
```ts
getStatusRenderer(): AparteStatusRenderer | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:889](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L889) Returns the registered status renderer, or null if none. ###### Returns [Section titled “Returns”](#returns-31) [`AparteStatusRenderer`](#apartestatusrenderer) | `null` ##### setErrorRenderer() [Section titled “setErrorRenderer()”](#seterrorrenderer)
```ts
setErrorRenderer(renderer): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:900](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L900) Set a custom error renderer. Drives the content of error bubbles (the built-in `error` segment) — return a string or an HTMLElement, e.g. a friendly message with a retry button. The bubble also carries `data-error` on its `.aparte-message` while errored, for CSS theming. Cleared with `null`. Notifies mounted components so a live change re-renders. ###### Parameters [Section titled “Parameters”](#parameters-23) | Parameter | Type | | ---------- | ------------------------------------------------------- | | `renderer` | [`AparteErrorRenderer`](#aparteerrorrenderer) \| `null` | ###### Returns [Section titled “Returns”](#returns-32) `void` ##### getErrorRenderer() [Section titled “getErrorRenderer()”](#geterrorrenderer)
```ts
getErrorRenderer(): AparteErrorRenderer | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:906](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L906) Returns the registered error renderer, or null if none. ###### Returns [Section titled “Returns”](#returns-33) [`AparteErrorRenderer`](#aparteerrorrenderer) | `null` ##### setAttachmentRenderer() [Section titled “setAttachmentRenderer()”](#setattachmentrenderer)
```ts
setAttachmentRenderer(renderer): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:917](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L917) Set a custom attachment renderer. Replaces the chip rendered for each attachment on a user message (default: image thumbnail / file chip) — return a string or an HTMLElement, e.g. a PDF preview. You own the interactions for custom output (see [AparteAttachmentRenderer](#aparteattachmentrenderer)). Cleared with `null`. Notifies mounted components so a live change re-renders. ###### Parameters [Section titled “Parameters”](#parameters-24) | Parameter | Type | | ---------- | ----------------------------------------------------------------- | | `renderer` | [`AparteAttachmentRenderer`](#aparteattachmentrenderer) \| `null` | ###### Returns [Section titled “Returns”](#returns-34) `void` ##### getAttachmentRenderer() [Section titled “getAttachmentRenderer()”](#getattachmentrenderer)
```ts
getAttachmentRenderer(): AparteAttachmentRenderer | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:923](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L923) Returns the registered attachment renderer, or null if none. ###### Returns [Section titled “Returns”](#returns-35) [`AparteAttachmentRenderer`](#aparteattachmentrenderer) | `null` ##### setSiblingNavRenderer() [Section titled “setSiblingNavRenderer()”](#setsiblingnavrenderer)
```ts
setSiblingNavRenderer(renderer): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:933](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L933) Set a custom sibling (branch) position indicator. Replaces the `‹ N / M ›` counter between the prev/next arrows — e.g. dots. Return a string or an HTMLElement (see [AparteSiblingNavRenderer](#apartesiblingnavrenderer)); the arrows keep their behavior. Cleared with `null`. Notifies mounted components. ###### Parameters [Section titled “Parameters”](#parameters-25) | Parameter | Type | | ---------- | ----------------------------------------------------------------- | | `renderer` | [`AparteSiblingNavRenderer`](#apartesiblingnavrenderer) \| `null` | ###### Returns [Section titled “Returns”](#returns-36) `void` ##### getSiblingNavRenderer() [Section titled “getSiblingNavRenderer()”](#getsiblingnavrenderer)
```ts
getSiblingNavRenderer(): AparteSiblingNavRenderer | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:939](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L939) Returns the registered sibling-nav renderer, or null if none. ###### Returns [Section titled “Returns”](#returns-37) [`AparteSiblingNavRenderer`](#apartesiblingnavrenderer) | `null` ##### setBubbleShellRenderer() [Section titled “setBubbleShellRenderer()”](#setbubbleshellrenderer)
```ts
setBubbleShellRenderer(renderer): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:950](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L950) Set a custom bubble shell renderer (advanced) — replaces the structural skeleton of `` while keeping its behavior. The shell must honor the class-hook contract (root `.aparte-message`, region hooks) — see [AparteBubbleShellRenderer](#apartebubbleshellrenderer). For a fully custom element use `renderBubble` (wrapper) instead. Cleared with `null`. Notifies mounted components. ###### Parameters [Section titled “Parameters”](#parameters-26) | Parameter | Type | | ---------- | ------------------------------------------------------------------- | | `renderer` | [`AparteBubbleShellRenderer`](#apartebubbleshellrenderer) \| `null` | ###### Returns [Section titled “Returns”](#returns-38) `void` ##### getBubbleShellRenderer() [Section titled “getBubbleShellRenderer()”](#getbubbleshellrenderer)
```ts
getBubbleShellRenderer(): AparteBubbleShellRenderer | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:956](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L956) Returns the registered bubble-shell renderer, or null if none. ###### Returns [Section titled “Returns”](#returns-39) [`AparteBubbleShellRenderer`](#apartebubbleshellrenderer) | `null` ##### setLocale() [Section titled “setLocale()”](#setlocale)
```ts
setLocale(locale): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:964](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L964) Set the current locale ###### Parameters [Section titled “Parameters”](#parameters-27) | Parameter | Type | Description | | --------- | ------------------------------------------------------------------------------------- | ---------------------------------------- | | `locale` | [`AparteLocale`](#apartelocale) & [`AparteLocaleExtensions`](#apartelocaleextensions) | AparteLocale object defining all strings | ###### Returns [Section titled “Returns”](#returns-40) `void` ##### resetLocale() [Section titled “resetLocale()”](#resetlocale)
```ts
resetLocale(): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:976](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L976) Restore the built-in English locale (the same `APARTE_DEFAULT_LOCALE` core ships with). Counterpart of [setLocale](#setlocale) for language toggles — avoids having to import `APARTE_DEFAULT_LOCALE` yourself. ###### Returns [Section titled “Returns”](#returns-41) `void` ##### getLocale() [Section titled “getLocale()”](#getlocale)
```ts
getLocale(): AparteLocale & AparteLocaleExtensions;
```
Defined in: [packages/core/src/config/aparte-config.ts:994](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L994) Get the current locale. Typed as the closed list PLUS the open half, and the asymmetry is the point: `t()` keys on `AparteLocale` alone — a typo there is a compile error — while a plugin reading its OWN key off this object gets `string | undefined` and supplies its own default at the call site. `t()` is the one that has to be narrow, because it is the one that fails silently: it returns `''` for a key nobody declared, and an empty label is invisible on screen and in the console. A misspelt read here is `undefined`, which the `?? 'fallback'` every caller already writes turns into the default. ###### Returns [Section titled “Returns”](#returns-42) [`AparteLocale`](#apartelocale) & [`AparteLocaleExtensions`](#apartelocaleextensions) ##### extendLocale() [Section titled “extendLocale()”](#extendlocale)
```ts
extendLocale(translations): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1003](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1003) Extend the current locale with partial translations. Useful for plugins to register their own strings. ###### Parameters [Section titled “Parameters”](#parameters-28) | Parameter | Type | Description | | -------------- | ------------------------------------------------------------------------------------------------ | ------------------------------ | | `translations` | `Partial`<[`AparteLocale`](#apartelocale)> & [`AparteLocaleExtensions`](#apartelocaleextensions) | Partial locale object to merge | ###### Returns [Section titled “Returns”](#returns-43) `void` ##### getIcon() [Section titled “getIcon()”](#geticon) ###### Call Signature [Section titled “Call Signature”](#call-signature)
```ts
getIcon(name): string;
```
Defined in: [packages/core/src/config/aparte-config.ts:1014](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1014) An icon’s markup by name: the registered drawing, else core’s. A name neither holds returns `undefined` — core’s names always resolve, and a name merged into `AparteIconProvider` stays possibly `undefined`: only the configs it was registered on draw it. ###### Parameters [Section titled “Parameters”](#parameters-29) | Parameter | Type | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | \| `"error"` \| `"stop"` \| `"retry"` \| `"copy"` \| `"edit"` \| `"thumbUp"` \| `"thumbDown"` \| `"info"` \| `"loading"` \| `"tool"` \| `"image"` \| `"check"` \| `"send"` \| `"expand"` \| `"collapse"` \| `"terminal"` \| `"paperclip"` \| `"file"` \| `"scrollDown"` \| `"prevBranch"` \| `"nextBranch"` \| `"close"` \| `"archive"` \| `"unarchive"` \| `"download"` \| `"more"` \| `"pin"` \| `"trash"` \| `"menu"` \| `"alertTriangle"` \| `"messageSquare"` \| `"pause"` | ###### Returns [Section titled “Returns”](#returns-44) `string` ###### Call Signature [Section titled “Call Signature”](#call-signature-1)
```ts
getIcon(name): string | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1015](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1015) An icon’s markup by name: the registered drawing, else core’s. A name neither holds returns `undefined` — core’s names always resolve, and a name merged into `AparteIconProvider` stays possibly `undefined`: only the configs it was registered on draw it. ###### Parameters [Section titled “Parameters”](#parameters-30) | Parameter | Type | | --------- | -------- | | `name` | `string` | ###### Returns [Section titled “Returns”](#returns-45) `string` | `undefined` ##### setKeyProvider() [Section titled “setKeyProvider()”](#setkeyprovider)
```ts
setKeyProvider(provider): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1029](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1029) Set a custom Key provider (e.g., AparteVault override) ###### Parameters [Section titled “Parameters”](#parameters-31) | Parameter | Type | | ---------- | ----------------------------------------- | | `provider` | [`AparteKeyProvider`](#apartekeyprovider) | ###### Returns [Section titled “Returns”](#returns-46) `void` ##### registerKeyProvider() [Section titled “registerKeyProvider()”](#registerkeyprovider)
```ts
registerKeyProvider(provider): () => void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1045](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1045) Add a key source beside the one [setKeyProvider()](#setkeyprovider) holds, and return the function that removes it. The sources are asked in the order they were added, then `setKeyProvider`’s, and the first answer wins. `AparteClient`’s `keyResolver` is registered this way, so the model selector can list a cloud provider’s models too. Each call is a source of its own, even with the same function. ###### Parameters [Section titled “Parameters”](#parameters-32) | Parameter | Type | | ---------- | ----------------------------------------- | | `provider` | [`AparteKeyProvider`](#apartekeyprovider) | ###### Returns [Section titled “Returns”](#returns-47) () => `void` ###### Example [Section titled “Example”](#example-5)
```ts
const release = aparteGlobalConfig.registerKeyProvider((providerId) =>
providerId === 'openrouter' ? localStorage.getItem('openrouter-key') : undefined);
// when what owns the key goes away:
release();
```
##### getKey() [Section titled “getKey()”](#getkey)
```ts
getKey(providerId): Promise | undefined>;
```
Defined in: [packages/core/src/config/aparte-config.ts:1071](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1071) The credentials for a provider: a key, or the `{ apiKey, endpoint }` record the transport and `fetchModels` both read. ONE resolution order, so the chat and the model list cannot disagree about what an endpoint is: a registered resolver (`AparteClient`’s `keyResolver`) first — which is the precedence the client has always documented — then `setKeyProvider`. Registered sources answer NEWEST first. A page that mounts a second chat, or remounts one to swap its options — the swap the wrappers document — leaves more than one source here, and insertion order made the first resolver the page ever registered answer for every later one, so the key could not be changed. The snapshot is deliberate too: a source torn down while an earlier one is being awaited must not shift the iteration underneath it. ###### Parameters [Section titled “Parameters”](#parameters-33) | Parameter | Type | | ------------ | -------- | | `providerId` | `string` | ###### Returns [Section titled “Returns”](#returns-48) `Promise`<`string` | `Record`<`string`, `string`> | `undefined`> ##### refreshProviderModels() [Section titled “refreshProviderModels()”](#refreshprovidermodels)
```ts
refreshProviderModels(providerId): Promise;
```
Defined in: [packages/core/src/config/aparte-config.ts:1088](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1088) Fetch a provider’s models, with the key and endpoint its key sources answer, so a component that lists models never handles a key. The list is kept, and `getCurrentModel()` reads the selected model’s capabilities from it. Answers `[]` for an unknown provider, one with no `fetchModels`, or a fetch that fails (with a console warning). ###### Parameters [Section titled “Parameters”](#parameters-34) | Parameter | Type | | ------------ | -------- | | `providerId` | `string` | ###### Returns [Section titled “Returns”](#returns-49) `Promise`<[`AparteAIModel`](/reference/core/messages/#aparteaimodel)\[]> ##### registerAIProvider() [Section titled “registerAIProvider()”](#registeraiprovider)
```ts
registerAIProvider(...providers): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1137](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1137) Register one or more AI providers (e.g., OpenRouter, Gemini, Anthropic). When this leaves exactly one provider registered, offering exactly one model it knows without a request (a scripted or an in-browser provider), and no model is selected, that model is selected. A provider that lists its models over the network selects nothing: name one with [setModelConfig()](#setmodelconfig), or let the person pick in ``. ###### Parameters [Section titled “Parameters”](#parameters-35) | Parameter | Type | Description | | ------------ | ------------------------------------------------------------------- | -------------------------------- | | …`providers` | [`AparteAIProvider`](/reference/core/messages/#aparteaiprovider)\[] | AparteAIProvider implementations | ###### Returns [Section titled “Returns”](#returns-50) `void` ###### Example [Section titled “Example”](#example-6)
```ts
aparteGlobalConfig.registerAIProvider(OpenRouterProvider);
aparteGlobalConfig.registerAIProvider(GeminiProvider, AnthropicProvider);
```
##### unregisterAIProvider() [Section titled “unregisterAIProvider()”](#unregisteraiprovider)
```ts
unregisterAIProvider(id): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1167](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1167) Unregister an AI provider ###### Parameters [Section titled “Parameters”](#parameters-36) | Parameter | Type | | --------- | -------- | | `id` | `string` | ###### Returns [Section titled “Returns”](#returns-51) `void` ##### getAIProviders() [Section titled “getAIProviders()”](#getaiproviders)
```ts
getAIProviders(): AparteAIProvider[];
```
Defined in: [packages/core/src/config/aparte-config.ts:1178](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1178) Get all registered AI providers Optionally filtered by enabled providers in config ###### Returns [Section titled “Returns”](#returns-52) [`AparteAIProvider`](/reference/core/messages/#aparteaiprovider)\[] ##### getAIProvider() [Section titled “getAIProvider()”](#getaiprovider)
```ts
getAIProvider(id): AparteAIProvider | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1191](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1191) Get a specific AI provider by ID ###### Parameters [Section titled “Parameters”](#parameters-37) | Parameter | Type | | --------- | -------- | | `id` | `string` | ###### Returns [Section titled “Returns”](#returns-53) [`AparteAIProvider`](/reference/core/messages/#aparteaiprovider) | `undefined` ##### setTransport() [Section titled “setTransport()”](#settransport)
```ts
setTransport(transport): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1201](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1201) Set the transport that decides where chat requests go and how auth is handled. Defaults to [AparteDirectTransport](/reference/core/transports/#apartedirecttransport) (browser-direct — BYOK/local). Use a `AparteBackendTransport` to keep API keys server-side (recommended for production). ###### Parameters [Section titled “Parameters”](#parameters-38) | Parameter | Type | | ----------- | ---------------------------------------------------------------- | | `transport` | [`AparteTransport`](/reference/core/transports/#apartetransport) | ###### Returns [Section titled “Returns”](#returns-54) `void` ##### getTransport() [Section titled “getTransport()”](#gettransport)
```ts
getTransport(): AparteTransport;
```
Defined in: [packages/core/src/config/aparte-config.ts:1206](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1206) Get the active transport (AparteDirectTransport by default). ###### Returns [Section titled “Returns”](#returns-55) [`AparteTransport`](/reference/core/transports/#apartetransport) ##### setModelPreferenceProvider() [Section titled “setModelPreferenceProvider()”](#setmodelpreferenceprovider)
```ts
setModelPreferenceProvider(provider): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1222](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1222) Register a model preference provider for agnostic persistence. The host app decides how/where to store the selected provider & model. `load` answers `{ provider, model }` — the names [AparteModelPreference](#apartemodelpreference) reads — and [restoreModelPreference()](#restoremodelpreference) applies it. ###### Parameters [Section titled “Parameters”](#parameters-39) | Parameter | Type | | ---------- | ----------------------------------------------------------------- | | `provider` | [`AparteModelPreferenceProvider`](#apartemodelpreferenceprovider) | ###### Returns [Section titled “Returns”](#returns-56) `void` ###### Example [Section titled “Example”](#example-7)
```ts
aparteGlobalConfig.setModelPreferenceProvider({
save: (provider, model) => localStorage.setItem('model', JSON.stringify({ provider, model })),
load: () => JSON.parse(localStorage.getItem('model') ?? 'null'),
});
aparteGlobalConfig.restoreModelPreference();
```
##### setApprovalPolicy() [Section titled “setApprovalPolicy()”](#setapprovalpolicy)
```ts
setApprovalPolicy(policy): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1248](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1248) Decide per CALL whether a tool runs, asks, or is refused — a mode, not a flag. With a policy registered, the client’s default approval channel evaluates it for every tool call: `allow` runs without asking, `ask` puts the call to the person exactly as a `needsApproval` tool is, `deny` refuses it with the policy’s own `reason` as what the model reads. `undefined` leaves the tool’s `needsApproval` to decide, as before. `null` removes the policy. `@aparte/plugin-approval` builds one from a classification of your tool names and a switchable mode (plan / ask / auto-edit / auto); a host that owns its own `approvalResolver` on `AparteClientOptions` is not affected — that resolver already decides everything. ###### Parameters [Section titled “Parameters”](#parameters-40) | Parameter | Type | | --------- | ---------------------------------------------------------------------------------- | | `policy` | [`AparteApprovalPolicy`](/reference/core/messages/#aparteapprovalpolicy) \| `null` | ###### Returns [Section titled “Returns”](#returns-57) `void` ###### Example [Section titled “Example”](#example-8)
```ts
aparteGlobalConfig.setApprovalPolicy((call) =>
call.name === 'run_command'
? { verdict: 'ask' }
: { verdict: 'allow' });
```
##### getApprovalPolicy() [Section titled “getApprovalPolicy()”](#getapprovalpolicy)
```ts
getApprovalPolicy(): AparteApprovalPolicy | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:1256](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1256) The registered approval policy, or `null`. ###### Returns [Section titled “Returns”](#returns-58) [`AparteApprovalPolicy`](/reference/core/messages/#aparteapprovalpolicy) | `null` ##### setCompactor() [Section titled “setCompactor()”](#setcompactor)
```ts
setCompactor(compactor): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1272](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1272) Register what makes the context smaller: the gauge’s Compact now, a separator’s Retry and the client’s pre-flight and overflow retry call it. `null` removes it. `@aparte/plugin-compaction`’s `setupCompaction()` registers itself here; core never compacts on its own, so a page without a compactor has a gauge that measures and a separator whose Retry falls back to the `aparte-compact` event. A chat reads the one on ITS config first (`resolveConfig(chat).getCompactor()`), then the client’s. Notifies like every other registration: a mounted gauge has to hear that “Compact now” became possible after it was drawn, or went away. ###### Parameters [Section titled “Parameters”](#parameters-41) | Parameter | Type | | ----------- | ------------------------------------------------------------------------ | | `compactor` | [`AparteCompactor`](/reference/core/messages/#apartecompactor) \| `null` | ###### Returns [Section titled “Returns”](#returns-59) `void` ##### getCompactor() [Section titled “getCompactor()”](#getcompactor)
```ts
getCompactor(): AparteCompactor | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:1278](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1278) The registered compactor, or `null`. ###### Returns [Section titled “Returns”](#returns-60) [`AparteCompactor`](/reference/core/messages/#apartecompactor) | `null` ##### ruleOnToolCall() [Section titled “ruleOnToolCall()”](#ruleontoolcall)
```ts
ruleOnToolCall(call): AparteApprovalRuling;
```
Defined in: [packages/core/src/config/aparte-config.ts:1287](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1287) What the policy says about one call, with the tool’s own `needsApproval` as the answer when it has no opinion. The one place the two are combined, so the client’s gate predicate and its approval channel cannot disagree. ###### Parameters [Section titled “Parameters”](#parameters-42) | Parameter | Type | | --------- | ------------------------------------------------------------ | | `call` | [`AparteToolCall`](/reference/core/messages/#apartetoolcall) | ###### Returns [Section titled “Returns”](#returns-61) [`AparteApprovalRuling`](/reference/core/messages/#aparteapprovalruling) ##### restoreModelPreference() [Section titled “restoreModelPreference()”](#restoremodelpreference)
```ts
restoreModelPreference(): AparteModelPreference | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:1300](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1300) Restore the saved model preference via the registered provider. Should be called once at app startup, before any component mounts. No-op if no provider is registered or nothing was saved. The saved selection is applied without being saved again. ###### Returns [Section titled “Returns”](#returns-62) [`AparteModelPreference`](#apartemodelpreference) | `null` ##### setModelConfig() [Section titled “setModelConfig()”](#setmodelconfig)
```ts
setModelConfig(config): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1316](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1316) Select the default provider and model, merged over the current selection. With a model-preference provider registered and both set, the selection is saved through it. ###### Parameters [Section titled “Parameters”](#parameters-43) | Parameter | Type | | --------- | ------------------------------------------------------------------ | | `config` | [`AparteModelConfig`](/reference/core/messages/#apartemodelconfig) | ###### Returns [Section titled “Returns”](#returns-63) `void` ##### subscribe() [Section titled “subscribe()”](#subscribe)
```ts
subscribe(callback): () => void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1331](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1331) Subscribe to configuration changes ###### Parameters [Section titled “Parameters”](#parameters-44) | Parameter | Type | | ---------- | ------------ | | `callback` | () => `void` | ###### Returns [Section titled “Returns”](#returns-64) Unsubscribe function () => `void` ##### getModelConfig() [Section titled “getModelConfig()”](#getmodelconfig)
```ts
getModelConfig(): AparteModelConfig;
```
Defined in: [packages/core/src/config/aparte-config.ts:1358](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1358) Get current model configuration ###### Returns [Section titled “Returns”](#returns-65) [`AparteModelConfig`](/reference/core/messages/#apartemodelconfig) ##### hasSelectedModel() [Section titled “hasSelectedModel()”](#hasselectedmodel)
```ts
hasSelectedModel(): boolean;
```
Defined in: [packages/core/src/config/aparte-config.ts:1366](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1366) True when the model config has BOTH a provider and a model selected — i.e. the chat can actually send. Used by the composer’s `require-model` gate. ###### Returns [Section titled “Returns”](#returns-66) `boolean` ##### setElicitationOptions() [Section titled “setElicitationOptions()”](#setelicitationoptions)
```ts
setElicitationOptions(options): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1395](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1395) Elicitation policy: whether a choice offers a free-text “Other…” escape. This is the HOST’s decision, not the model’s: the `ask_user` schema handed to the model carries no `allow_other` field, because a small model fills a field it does not understand (a question with `allow_other: true` and no options renders a radio list whose only entry is “Other…”). Default `true`. A direct `requestUserInput` caller can still set `allowOther` per field; that is the app talking, and it wins. `layout` decides how a form of SEVERAL questions is presented. `'stepped'` (default) asks them one at a time with a chip per question; `'stacked'` puts them all in the panel at once — the shape of an MCP elicitation FORM collecting structured data, which is why it stays an option, but not the right default for two different questions asked mid-conversation. `answerOnClick` decides how a question asked ON ITS OWN with a single choice — an `enum` without `multiple` or a `default`, a `boolean` without a `default` — is answered. `true` (default) renders the options as buttons and the click is the answer: one decision, one gesture, the shape every chat product uses for “which one?”. `false` keeps the radios and the composer’s button, so a person can change their mind before committing — the shape a form or a screen reader flow may prefer, and the one a host that wants a uniform “select, then send” across every question asks for. A form of several questions always collects and submits, whatever this says. ###### Parameters [Section titled “Parameters”](#parameters-45) | Parameter | Type | | ------------------------ | ------------------------------------------------------------------------------------------------- | | `options` | { `allowOther?`: `boolean`; `layout?`: `"stepped"` \| `"stacked"`; `answerOnClick?`: `boolean`; } | | `options.allowOther?` | `boolean` | | `options.layout?` | `"stepped"` \| `"stacked"` | | `options.answerOnClick?` | `boolean` | ###### Returns [Section titled “Returns”](#returns-67) `void` ##### getElicitationOptions() [Section titled “getElicitationOptions()”](#getelicitationoptions)
```ts
getElicitationOptions(): {
allowOther: boolean;
layout: "stepped" | "stacked";
answerOnClick: boolean;
};
```
Defined in: [packages/core/src/config/aparte-config.ts:1403](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1403) The elicitation policy (see [setElicitationOptions](#setelicitationoptions)). ###### Returns [Section titled “Returns”](#returns-68)
```ts
{
allowOther: boolean;
layout: "stepped" | "stacked";
answerOnClick: boolean;
}
```
###### allowOther [Section titled “allowOther”](#allowother)
```ts
allowOther: boolean;
```
###### layout [Section titled “layout”](#layout)
```ts
layout: "stepped" | "stacked";
```
###### answerOnClick [Section titled “answerOnClick”](#answeronclick)
```ts
answerOnClick: boolean;
```
##### setElicitationFieldRenderer() [Section titled “setElicitationFieldRenderer()”](#setelicitationfieldrenderer)
```ts
setElicitationFieldRenderer(fn): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1414](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1414) Render one field of the question panel yourself. See [AparteElicitationFieldRenderer](#aparteelicitationfieldrenderer). Return `null` for a field to let the built-in render it, which is what makes overriding a single kind practical. Pass `null` here to remove the renderer. ###### Parameters [Section titled “Parameters”](#parameters-46) | Parameter | Type | | --------- | -------------------------------------------------------------------------------- | | `fn` | \| [`AparteElicitationFieldRenderer`](#aparteelicitationfieldrenderer) \| `null` | ###### Returns [Section titled “Returns”](#returns-69) `void` ##### getElicitationFieldRenderer() [Section titled “getElicitationFieldRenderer()”](#getelicitationfieldrenderer)
```ts
getElicitationFieldRenderer():
| AparteElicitationFieldRenderer
| undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1420](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1420) The custom field renderer, if one is registered. ###### Returns [Section titled “Returns”](#returns-70) \| [`AparteElicitationFieldRenderer`](#aparteelicitationfieldrenderer) | `undefined` ##### setRequireModelSelection() [Section titled “setRequireModelSelection()”](#setrequiremodelselection)
```ts
setRequireModelSelection(required): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1430](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1430) Opt-in UX: when enabled, `` blocks sending and greys out until [hasSelectedModel](#hasselectedmodel) is true (e.g. while the model selector is still fetching its list). Off by default so single-model / backend setups that never select a model are unaffected. ###### Parameters [Section titled “Parameters”](#parameters-47) | Parameter | Type | | ---------- | --------- | | `required` | `boolean` | ###### Returns [Section titled “Returns”](#returns-71) `void` ##### getRequireModelSelection() [Section titled “getRequireModelSelection()”](#getrequiremodelselection)
```ts
getRequireModelSelection(): boolean;
```
Defined in: [packages/core/src/config/aparte-config.ts:1437](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1437) Whether the composer should gate on model selection (see [setRequireModelSelection](#setrequiremodelselection)). ###### Returns [Section titled “Returns”](#returns-72) `boolean` ##### getCurrentModel() [Section titled “getCurrentModel()”](#getcurrentmodel)
```ts
getCurrentModel(): AparteAIModel | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1446](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1446) Get the currently selected model object, if available synchronously. Returns undefined if no provider/model is selected, or if the provider’s models are only available asynchronously (fetchModels). ###### Returns [Section titled “Returns”](#returns-73) [`AparteAIModel`](/reference/core/messages/#aparteaimodel) | `undefined` ##### t() [Section titled “t()”](#t)
```ts
t(key): string;
```
Defined in: [packages/core/src/config/aparte-config.ts:1479](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1479) The locale’s string for `key`, or the default (English) locale’s when the locale leaves it out; `''` for a key neither declares. ###### Parameters [Section titled “Parameters”](#parameters-48) | Parameter | Type | | --------- | ------------------------------------- | | `key` | keyof [`AparteLocale`](#apartelocale) | ###### Returns [Section titled “Returns”](#returns-74) `string` ##### renderMarkdown() [Section titled “renderMarkdown()”](#rendermarkdown)
```ts
renderMarkdown(raw): string;
```
Defined in: [packages/core/src/config/aparte-config.ts:1498](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1498) Render a complete Markdown string to HTML: the one-shot provider when one is registered, else the incremental provider run over the whole string, else core’s default (escape + ` `). The middle step is what makes the incremental provider enough on its own. Without it a reply rendered two ways depending on how it arrived: rich while it streamed, escaped source once it came back complete — a restored conversation, a non-streaming provider, a stored segment. Same parser, same sanitizer, so the two cannot disagree. It needs a `document` to write into; without one (a server render) the default answers, as before. ###### Parameters [Section titled “Parameters”](#parameters-49) | Parameter | Type | | --------- | -------- | | `raw` | `string` | ###### Returns [Section titled “Returns”](#returns-75) `string` ##### highlightCode() [Section titled “highlightCode()”](#highlightcode)
```ts
highlightCode(
code,
lang,
options?): Promise;
```
Defined in: [packages/core/src/config/aparte-config.ts:1531](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1531) Highlight code block Fallback: Returns raw code wrapped in `` Supports Promise if provider is async/streaming ###### Parameters [Section titled “Parameters”](#parameters-50) | Parameter | Type | Description | | ------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `code` | `string` | - | | `lang` | `string` | - | | `options` | { `fallback?`: `boolean`; } | - | | `options.fallback?` | `boolean` | `false` rejects when the highlight provider fails, instead of answering the plain block: for a caller that keeps what it highlighted, so a failure (a highlighter still loading its grammars) is tried again rather than kept. | ###### Returns [Section titled “Returns”](#returns-76) `Promise`<`string`> ##### registerTool() [Section titled “registerTool()”](#registertool)
```ts
registerTool(tool, handler): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1556](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1556) Register a tool and its handler together. The handler is called when the AI invokes the tool during streaming. ###### Parameters [Section titled “Parameters”](#parameters-51) | Parameter | Type | | --------- | ------------------------------------------------------------------ | | `tool` | [`AparteTool`](/reference/core/messages/#apartetool) | | `handler` | [`AparteToolHandler`](/reference/core/messages/#apartetoolhandler) | ###### Returns [Section titled “Returns”](#returns-77) `void` ###### Example [Section titled “Example”](#example-9)
```ts
aparteGlobalConfig.registerTool(askUserTool, askUserHandler);
```
##### unregisterTool() [Section titled “unregisterTool()”](#unregistertool)
```ts
unregisterTool(name): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1561](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1561) Unregister a tool by name ###### Parameters [Section titled “Parameters”](#parameters-52) | Parameter | Type | | --------- | -------- | | `name` | `string` | ###### Returns [Section titled “Returns”](#returns-78) `void` ##### getTools() [Section titled “getTools()”](#gettools)
```ts
getTools(): AparteTool[];
```
Defined in: [packages/core/src/config/aparte-config.ts:1566](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1566) Get all registered tool definitions (to pass in AparteChatRequest) ###### Returns [Section titled “Returns”](#returns-79) [`AparteTool`](/reference/core/messages/#apartetool)\[] ##### resolveToolSystemPrompts() [Section titled “resolveToolSystemPrompts()”](#resolvetoolsystemprompts)
```ts
resolveToolSystemPrompts(): string | null;
```
Defined in: [packages/core/src/config/aparte-config.ts:1577](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1577) The registered tools’ own `systemPrompt`s, in registration order with a blank line between, or `null` if none sets one. `AparteClient` sends them with every request, as a system message after the app’s own ([resolveSystemPrompt()](#resolvesystemprompt)); a request you assemble yourself should send them the same way, or the model loses the tools’ instructions. ###### Returns [Section titled “Returns”](#returns-80) `string` | `null` ##### getToolHandler() [Section titled “getToolHandler()”](#gettoolhandler)
```ts
getToolHandler(name): AparteToolHandler | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1585](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1585) Get the handler for a tool by name ###### Parameters [Section titled “Parameters”](#parameters-53) | Parameter | Type | | --------- | -------- | | `name` | `string` | ###### Returns [Section titled “Returns”](#returns-81) [`AparteToolHandler`](/reference/core/messages/#apartetoolhandler) | `undefined` ##### registerToolRenderer() [Section titled “registerToolRenderer()”](#registertoolrenderer)
```ts
registerToolRenderer(match, renderer): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1617](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1617) Register a per-tool segment renderer. Controls what appears in the chat bubble when the AI calls this tool. Use this instead of the generic `tool_call` segment renderer for tool-specific UI. A renderer that needs a popover (a ``, a menu) cannot open one inside the row: the bubble is `content-visibility: auto`, which makes it the containing block for `position: fixed` descendants and clips a popover to its own box. Mount it on `document.body` and position it from the trigger’s rect instead — see [Custom tool renderer](https://apartejs.dev/guides/tools/#custom-tool-renderer). The matcher is an exact name, a RegExp, or `'*'` — the same rule as [registerToolDisplay](#registertooldisplay): the exact name wins, then the first pattern registered, then `'*'`, which is one renderer for every tool without its own. ###### Parameters [Section titled “Parameters”](#parameters-54) | Parameter | Type | | ---------- | -------------------------------------------------------------------- | | `match` | [`AparteToolMatcher`](/reference/core/messages/#apartetoolmatcher) | | `renderer` | [`AparteToolRenderer`](/reference/core/messages/#apartetoolrenderer) | ###### Returns [Section titled “Returns”](#returns-82) `void` ###### Examples [Section titled “Examples”](#examples-1)
```ts
// Custom pill for a web-search tool
aparteGlobalConfig.registerToolRenderer('web_search', { render: (seg) => `Searching...
` });
Calls already on screen follow: those this registration now draws are drawn again
by it (the renderer that drew them before gets its `cleanup`), and nothing else on
the page is touched.
```
```ts
// One look for every tool an MCP server brings
aparteGlobalConfig.registerToolRenderer(/^mcp__/, { render: (seg) => myMcpCard(seg) });
```
##### overrideToolRenderer() [Section titled “overrideToolRenderer()”](#overridetoolrenderer)
```ts
overrideToolRenderer(match, renderer): () => void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1640](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1640) Put `renderer` over whatever this matcher holds, and get back the function that takes it off again — the registration a component makes for as long as it is mounted. Overrides stack per matcher. The function restores what was there before THIS override, and taking off an override that is no longer on top changes nothing on screen: two components declaring the same tool, the newer wins, and unmounting the older does not take the newer’s away. When the last one goes, the matcher holds what it held before the first — another registration, or nothing. Calls on screen follow each change, as with [registerToolRenderer](#registertoolrenderer). The returned function is safe to call twice. ###### Parameters [Section titled “Parameters”](#parameters-55) | Parameter | Type | | ---------- | -------------------------------------------------------------------- | | `match` | [`AparteToolMatcher`](/reference/core/messages/#apartetoolmatcher) | | `renderer` | [`AparteToolRenderer`](/reference/core/messages/#apartetoolrenderer) | ###### Returns [Section titled “Returns”](#returns-83) () => `void` ###### Example [Section titled “Example”](#example-10)
```ts
const restore = aparteGlobalConfig.overrideToolRenderer('get_weather', weatherCard);
// …later, when the component that declared it unmounts:
restore();
```
##### setSegmentDefaults() [Section titled “setSegmentDefaults()”](#setsegmentdefaults)
```ts
setSegmentDefaults(type, defaults): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1707](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1707) Field defaults for a segment TYPE, filled in when a segment enters a message. One function for every type rather than one per field: a `setThinkingOpen()` would need a sibling the next time any type wanted a default, and the type key is a string, so a consumer’s own segment type is covered by the same call. The problem it solves: a consumer streaming a reply does not CONSTRUCT its segments — the parser does — so a per-segment field cannot express “reasoning blocks open in my app”: per-segment fields only reach segments you build yourself. Applied where identity is stamped (`utils/segments.ts`), so it covers every path a segment can arrive by — the parser, `addSegment`, and the segments seeded on an `appendMessage` — and no renderer has to look anything up. A field the producer set always wins, and identity is never defaulted. Read at insertion and baked in: changing a default later does not reach segments already on screen, because a block the reader opened has state the data does not. ###### Parameters [Section titled “Parameters”](#parameters-56) | Parameter | Type | | ---------- | -------------------------------------------------------------------------- | | `type` | `string` | | `defaults` | [`AparteSegmentDefaults`](/reference/core/messages/#apartesegmentdefaults) | ###### Returns [Section titled “Returns”](#returns-84) `void` ###### Examples [Section titled “Examples”](#examples-2)
```ts
// Reasoning blocks arrive open in this app, streaming or settled.
aparteGlobalConfig.setSegmentDefaults('thinking', { collapsed: false });
```
```ts
// A consumer's own type, same call.
aparteGlobalConfig.setSegmentDefaults('my-chart', { theme: 'dark' });
```
##### getSegmentDefaults() [Section titled “getSegmentDefaults()”](#getsegmentdefaults)
```ts
getSegmentDefaults(type): Readonly> | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1714](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1714) The defaults registered for a type, or undefined. ###### Parameters [Section titled “Parameters”](#parameters-57) | Parameter | Type | | --------- | -------- | | `type` | `string` | ###### Returns [Section titled “Returns”](#returns-85) `Readonly`<`Record`<`string`, `unknown`>> | `undefined` ##### clearSegmentDefaults() [Section titled “clearSegmentDefaults()”](#clearsegmentdefaults)
```ts
clearSegmentDefaults(type): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1719](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1719) Drop the defaults for a type. ###### Parameters [Section titled “Parameters”](#parameters-58) | Parameter | Type | | --------- | -------- | | `type` | `string` | ###### Returns [Section titled “Returns”](#returns-86) `void` ##### unregisterToolRenderer() [Section titled “unregisterToolRenderer()”](#unregistertoolrenderer)
```ts
unregisterToolRenderer(match): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1724](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1724) Unregister the renderer registered under this matcher. Calls on screen it drew go back to core’s row. ###### Parameters [Section titled “Parameters”](#parameters-59) | Parameter | Type | | --------- | ------------------------------------------------------------------ | | `match` | [`AparteToolMatcher`](/reference/core/messages/#apartetoolmatcher) | ###### Returns [Section titled “Returns”](#returns-87) `void` ##### getToolRenderer() [Section titled “getToolRenderer()”](#gettoolrenderer)
```ts
getToolRenderer(toolName): AparteToolRenderer | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1731](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1731) The renderer that draws a tool named `toolName` — exact, pattern or `'*'` — or undefined. ###### Parameters [Section titled “Parameters”](#parameters-60) | Parameter | Type | | ---------- | -------- | | `toolName` | `string` | ###### Returns [Section titled “Returns”](#returns-88) [`AparteToolRenderer`](/reference/core/messages/#apartetoolrenderer) | `undefined` ##### registerToolDisplay() [Section titled “registerToolDisplay()”](#registertooldisplay)
```ts
registerToolDisplay(match, display): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1773](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1773) Say how a tool’s calls are shown: a label in place of its identifier, an icon, what the call targets, how its arguments read, whether its row is drawn at all, and whether it opens. The matcher is an exact name, a RegExp, or `'*'` — “every tool nothing more specific describes”. One entry per matcher, and calls MERGE into it; the entry that applies to a tool is the exact name’s, else the first pattern registered that matches, else `'*'`’s — whole, never a mix of two. Registering tells the chats on the page, so a label reaches rows already drawn. Core never makes a label up: without one the row shows the identifier, which is the app’s wire format. ###### Parameters [Section titled “Parameters”](#parameters-61) | Parameter | Type | | --------- | ------------------------------------------------------------------ | | `match` | [`AparteToolMatcher`](/reference/core/messages/#apartetoolmatcher) | | `display` | [`AparteToolDisplay`](/reference/core/messages/#apartetooldisplay) | ###### Returns [Section titled “Returns”](#returns-89) `void` ###### Examples [Section titled “Examples”](#examples-3)
```ts
aparteGlobalConfig.registerToolDisplay('web_search', {
label: 'Web search',
icon: 'search',
summary: (segment) => String(segment.toolCall.input['query'] ?? ''),
});
```
```ts
// A consumer chat: the reply is what matters; the calls stay in the history.
aparteGlobalConfig.registerToolDisplay('*', { hidden: true });
```
```ts
// An agent's chat: the spinner, "Running" and "Done" (the default is quiet), on every
// tool without an entry of its own — a tool with one says `quiet: false` there too.
aparteGlobalConfig.registerToolDisplay('*', { quiet: false });
```
```ts
// The line, and no raw JSON behind it: nothing, or a detail of the app's own.
aparteGlobalConfig.registerToolDisplay('read_file', { label: 'Read a file', details: false });
aparteGlobalConfig.registerToolDisplay('web_search', {
label: 'Searched the web',
details: (segment) => sourcesList(segment.result),
});
```
##### unregisterToolDisplay() [Section titled “unregisterToolDisplay()”](#unregistertooldisplay)
```ts
unregisterToolDisplay(match): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1790](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1790) Forget the display registered under this matcher. ###### Parameters [Section titled “Parameters”](#parameters-62) | Parameter | Type | | --------- | ------------------------------------------------------------------ | | `match` | [`AparteToolMatcher`](/reference/core/messages/#apartetoolmatcher) | ###### Returns [Section titled “Returns”](#returns-90) `void` ##### getToolDisplay() [Section titled “getToolDisplay()”](#gettooldisplay)
```ts
getToolDisplay(toolName): Readonly | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1806](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1806) How a tool named `toolName` is shown — the entry that applies to it — or undefined. ###### Parameters [Section titled “Parameters”](#parameters-63) | Parameter | Type | | ---------- | -------- | | `toolName` | `string` | ###### Returns [Section titled “Returns”](#returns-91) `Readonly`<[`AparteToolDisplay`](/reference/core/messages/#apartetooldisplay)> | `undefined` ##### isToolHidden() [Section titled “isToolHidden()”](#istoolhidden)
```ts
isToolHidden(toolName): boolean;
```
Defined in: [packages/core/src/config/aparte-config.ts:1817](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1817) Whether a tool’s calls draw nothing: its display says `hidden`, and no renderer is registered for it MORE specifically. A `'*'` hide therefore leaves a tool with its own renderer drawn (a plugin’s receipt), while a hide as specific as the renderer wins — the app said so for that tool. A hidden call stays in the message, in storage and in the model’s history; only its row is empty. ###### Parameters [Section titled “Parameters”](#parameters-64) | Parameter | Type | | ---------- | -------- | | `toolName` | `string` | ###### Returns [Section titled “Returns”](#returns-92) `boolean` ##### registerToolSummary() [Section titled “registerToolSummary()”](#registertoolsummary)
```ts
registerToolSummary(match, summary): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1858](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1858) Say what a call targets, in the default row, after the tool’s name. The default row names the tool and keeps its arguments behind a disclosure, so a reader sees that a file was read, not which one. Replacing the row with `registerToolRenderer` for that one line would mean re-implementing its six states, the spinner, the disclosure and the relabel contract. This keeps all of them and adds the line. A tool with its own renderer draws its own row, so its summary is never read. The text is written as text, never parsed as HTML. It is read when the row renders, on every update to the call (its arguments may still be arriving), and on every config change — so registering one after a row is on screen shows up on that row’s next update. The `summary` field of [registerToolDisplay](#registertooldisplay), on its own: same matcher, same entry. ###### Parameters [Section titled “Parameters”](#parameters-65) | Parameter | Type | | --------- | ------------------------------------------------------------------ | | `match` | [`AparteToolMatcher`](/reference/core/messages/#apartetoolmatcher) | | `summary` | [`AparteToolSummary`](/reference/core/messages/#apartetoolsummary) | ###### Returns [Section titled “Returns”](#returns-93) `void` ###### Example [Section titled “Example”](#example-11)
```ts
// read_file skills.json
aparteGlobalConfig.registerToolSummary('read_file', (segment) =>
String(segment.toolCall.input['path'] ?? ''));
```
##### unregisterToolSummary() [Section titled “unregisterToolSummary()”](#unregistertoolsummary)
```ts
unregisterToolSummary(match): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1863](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1863) Drop the summary registered under this matcher; the rest of its display stays. ###### Parameters [Section titled “Parameters”](#parameters-66) | Parameter | Type | | --------- | ------------------------------------------------------------------ | | `match` | [`AparteToolMatcher`](/reference/core/messages/#apartetoolmatcher) | ###### Returns [Section titled “Returns”](#returns-94) `void` ##### getToolSummary() [Section titled “getToolSummary()”](#gettoolsummary)
```ts
getToolSummary(toolName): AparteToolSummary | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1868](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1868) The summary that applies to a tool named `toolName`, or undefined. ###### Parameters [Section titled “Parameters”](#parameters-67) | Parameter | Type | | ---------- | -------- | | `toolName` | `string` | ###### Returns [Section titled “Returns”](#returns-95) [`AparteToolSummary`](/reference/core/messages/#apartetoolsummary) | `undefined` ##### registerToolInputFormatter() [Section titled “registerToolInputFormatter()”](#registertoolinputformatter)
```ts
registerToolInputFormatter(match, formatter): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1883](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1883) Show a tool’s arguments as a person reads them, in the approval panel and in the default tool row’s disclosure — one formatter for both. Without one, both show the JSON the model sent. The `formatInput` field of [registerToolDisplay](#registertooldisplay), on its own: same matcher, same entry. ###### Parameters [Section titled “Parameters”](#parameters-68) | Parameter | Type | | ----------- | -------------------------------------------------------------------------------- | | `match` | [`AparteToolMatcher`](/reference/core/messages/#apartetoolmatcher) | | `formatter` | [`AparteToolInputFormatter`](/reference/core/messages/#apartetoolinputformatter) | ###### Returns [Section titled “Returns”](#returns-96) `void` ###### Example [Section titled “Example”](#example-12)
```ts
// Approve "write_file notes.md (2 KB)" rather than a JSON object.
aparteGlobalConfig.registerToolInputFormatter('write_file', (input) =>
`${String(input['path'] ?? '')} (${Math.ceil(String(input['content'] ?? '').length / 1024)} KB)`);
```
##### unregisterToolInputFormatter() [Section titled “unregisterToolInputFormatter()”](#unregistertoolinputformatter)
```ts
unregisterToolInputFormatter(match): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1888](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1888) Drop the input formatter registered under this matcher; the rest of its display stays. ###### Parameters [Section titled “Parameters”](#parameters-69) | Parameter | Type | | --------- | ------------------------------------------------------------------ | | `match` | [`AparteToolMatcher`](/reference/core/messages/#apartetoolmatcher) | ###### Returns [Section titled “Returns”](#returns-97) `void` ##### getToolInputFormatter() [Section titled “getToolInputFormatter()”](#gettoolinputformatter)
```ts
getToolInputFormatter(toolName): AparteToolInputFormatter | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1893](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1893) The input formatter that applies to a tool named `toolName`, or undefined. ###### Parameters [Section titled “Parameters”](#parameters-70) | Parameter | Type | | ---------- | -------- | | `toolName` | `string` | ###### Returns [Section titled “Returns”](#returns-98) [`AparteToolInputFormatter`](/reference/core/messages/#apartetoolinputformatter) | `undefined` ##### registerStreamBlock() [Section titled “registerStreamBlock()”](#registerstreamblock)
```ts
registerStreamBlock(block): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1917](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1917) Teach the stream parser a tagged block: `… ` in the model’s prose becomes the segment `toSegment` builds, streamed delta by delta. The parser does the work once for every grammar — the earliest opening tag wins against a code fence and a reasoning delimiter, a tag cut at a chunk boundary is held back, attributes are parsed quoted or bare, and the block is closed at `` or at the end of the stream. What the segment IS is yours: a `type` of your own with a renderer from `registerSegmentRenderer`, or a built-in one. One grammar per tag; registering the same tag again replaces it. Read by the stream adapter when a turn starts, so a block registered mid-turn applies from the next turn. See [AparteStreamBlock](/reference/core/messages/#apartestreamblock). ###### Parameters [Section titled “Parameters”](#parameters-71) | Parameter | Type | | --------- | ------------------------------------------------------------------ | | `block` | [`AparteStreamBlock`](/reference/core/messages/#apartestreamblock) | ###### Returns [Section titled “Returns”](#returns-99) `void` ###### Example [Section titled “Example”](#example-13)
```ts
aparteGlobalConfig.registerStreamBlock({
tag: 'cite',
toSegment: ({ attrs, id }) => ({ id, type: 'citation', url: attrs['url'] ?? '', content: '' }),
});
```
##### unregisterStreamBlock() [Section titled “unregisterStreamBlock()”](#unregisterstreamblock)
```ts
unregisterStreamBlock(tag): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1923](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1923) Forget a block grammar by its tag. ###### Parameters [Section titled “Parameters”](#parameters-72) | Parameter | Type | | --------- | -------- | | `tag` | `string` | ###### Returns [Section titled “Returns”](#returns-100) `void` ##### getStreamBlocks() [Section titled “getStreamBlocks()”](#getstreamblocks)
```ts
getStreamBlocks(): AparteStreamBlock[];
```
Defined in: [packages/core/src/config/aparte-config.ts:1928](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1928) The registered block grammars, in registration order. ###### Returns [Section titled “Returns”](#returns-101) [`AparteStreamBlock`](/reference/core/messages/#apartestreamblock)\[] ##### setConversationManager() [Section titled “setConversationManager()”](#setconversationmanager)
```ts
setConversationManager(manager): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1940](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1940) Register a AparteConversationManager so any UI controller can persist & load conversations without coupling to a framework wrapper. ###### Parameters [Section titled “Parameters”](#parameters-73) | Parameter | Type | | --------- | --------------------------------------------------------------------------------------- | | `manager` | [`AparteConversationManager`](/reference/core/conversations/#aparteconversationmanager) | ###### Returns [Section titled “Returns”](#returns-102) `void` ##### getConversationManager() [Section titled “getConversationManager()”](#getconversationmanager)
```ts
getConversationManager(): AparteConversationManager | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1945](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1945) Returns the registered AparteConversationManager, or undefined if none. ###### Returns [Section titled “Returns”](#returns-103) [`AparteConversationManager`](/reference/core/conversations/#aparteconversationmanager) | `undefined` ##### setElicitationPresenter() [Section titled “setElicitationPresenter()”](#setelicitationpresenter)
```ts
setElicitationPresenter(presenter, owner?): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1965](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1965) Register the presenter that renders typed input requests (a choice, a confirmation, a text field, a form) and resolves with the user’s answer. The `` Web Component registers itself here; an app can override with its own framework-native presenter. Pass `null` to clear. Several can be registered, one per chat: `owner` is an element of the chat the presenter belongs to (`` passes itself). A request whose `target` is inside that chat reaches its presenter; a request with no `target`, or from a chat with no presenter of its own, reaches the most recently registered one. Registering a presenter again makes it the most recent. ###### Parameters [Section titled “Parameters”](#parameters-74) | Parameter | Type | | ----------- | ------------------------------------------------------------------------------------------------- | | `presenter` | [`AparteElicitationPresenter`](/reference/core/elicitation/#aparteelicitationpresenter) \| `null` | | `owner?` | `HTMLElement` | ###### Returns [Section titled “Returns”](#returns-104) `void` ##### removeElicitationPresenter() [Section titled “removeElicitationPresenter()”](#removeelicitationpresenter)
```ts
removeElicitationPresenter(presenter): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:1985](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1985) Withdraw ONE presenter, named, leaving any others registered. This is what an unmounting `` needs and what `setElicitationPresenter(null)` could not express: clearing the slot took every other mounted chat’s presenter down with it. Removing a presenter that is not registered is a no-op. ###### Parameters [Section titled “Parameters”](#parameters-75) | Parameter | Type | | ----------- | --------------------------------------------------------------------------------------- | | `presenter` | [`AparteElicitationPresenter`](/reference/core/elicitation/#aparteelicitationpresenter) | ###### Returns [Section titled “Returns”](#returns-105) `void` ##### getElicitationPresenter() [Section titled “getElicitationPresenter()”](#getelicitationpresenter)
```ts
getElicitationPresenter(): AparteElicitationPresenter | undefined;
```
Defined in: [packages/core/src/config/aparte-config.ts:1993](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L1993) The presenter a request with no `target` would reach — the most recently registered one. Kept for the callers that ask “is anybody able to present?”. ###### Returns [Section titled “Returns”](#returns-106) [`AparteElicitationPresenter`](/reference/core/elicitation/#aparteelicitationpresenter) | `undefined` ##### requestUserInput() [Section titled “requestUserInput()”](#requestuserinput)
```ts
requestUserInput(request): Promise;
```
Defined in: [packages/core/src/config/aparte-config.ts:2039](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L2039) Ask the person for typed input in the middle of a run, and wait for the answer. The primitive behind `ask_user` and tool approval: the kind of question is its schema. **Resolves** `accept` with the value, or `decline` when the person declines. **Rejects**, with no answer, with an [AparteElicitationAbortError](/reference/core/elicitation/#aparteelicitationaborterror) (its `name` is `'AbortError'`) whose `reason` is `'aborted'` — the turn was stopped, the signal fired, or another request took the question away — or `'no-presenter'`, when nothing is mounted to ask it (with a console warning, once). `await` it in a `try`, or attach a `.catch()`. The question goes to the presenter of the chat that holds `request.target` (see [setElicitationPresenter()](#setelicitationpresenter)); `` is the default one, and registers itself once it is in the DOM. A chat shows one question at a time: a second request in the same chat waits until the first is answered or ends, and requests with no `target` share one queue. ###### Parameters [Section titled “Parameters”](#parameters-76) | Parameter | Type | | --------- | ----------------------------------------------------------------------------------- | | `request` | [`AparteElicitationRequest`](/reference/core/elicitation/#aparteelicitationrequest) | ###### Returns [Section titled “Returns”](#returns-107) `Promise`<[`AparteElicitationResult`](/reference/core/elicitation/#aparteelicitationresult)> ##### reset() [Section titled “reset()”](#reset)
```ts
reset(): void;
```
Defined in: [packages/core/src/config/aparte-config.ts:2133](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L2133) Put the configuration back to its defaults: the providers and the selected model, the tools with their renderers and summaries, the renderers and render hooks, the Markdown and highlight providers, the code-language renderers, the sanitizer, the system prompt, the locale, icons, avatars, actions and host handlers, the conversation manager, the question presenters and their queue. Three things stay: the transport, the key sources added with [registerKeyProvider()](#registerkeyprovider) (an `AparteClient`’s `keyResolver` among them), and the [subscribe()](#subscribe) listeners. ###### Returns [Section titled “Returns”](#returns-108) `void` *** ## Functions [Section titled “Functions”](#functions) ### attachConfig() [Section titled “attachConfig()”](#attachconfig)
```ts
function attachConfig(el, config): void;
```
Defined in: [packages/core/src/config/config-context.ts:83](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/config-context.ts#L83) Attach an instance config to `el`, making it a resolution boundary: every component inside `el` resolves to `config` instead of the global singleton. Idempotent; pass the same element to replace its config. Anything already mounted inside `el` that implements [AparteConfigAware](#aparteconfigaware) is told, because attaching a boundary silently rewrites what those children resolve to and a registration they already made is now on the wrong object. #### Parameters [Section titled “Parameters”](#parameters-77) | Parameter | Type | | --------- | ------------------------------- | | `el` | `HTMLElement` | | `config` | [`AparteConfig`](#aparteconfig) | #### Returns [Section titled “Returns”](#returns-109) `void` *** ### detachConfig() [Section titled “detachConfig()”](#detachconfig)
```ts
function detachConfig(el): void;
```
Defined in: [packages/core/src/config/config-context.ts:101](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/config-context.ts#L101) Remove the instance-config boundary from `el` (e.g. in `disconnectedCallback`). Components under `el` fall back to the next boundary up, or the global. Registrants are told BEFORE they would silently re-resolve elsewhere, which is the half that leaked: a wrapper’s `unbind()` detaches the boundary before the framework removes the DOM, so by the time `disconnectedCallback` ran, the element’s own `resolveConfig(this)` already returned the global — its “am I still the registered one?” guard compared against the wrong config, found no match, and left the instance config holding a removed element for good. #### Parameters [Section titled “Parameters”](#parameters-78) | Parameter | Type | | --------- | ------------- | | `el` | `HTMLElement` | #### Returns [Section titled “Returns”](#returns-110) `void` *** ### resolveConfig() [Section titled “resolveConfig()”](#resolveconfig)
```ts
function resolveConfig(el): AparteConfig;
```
Defined in: [packages/core/src/config/config-context.ts:134](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/config-context.ts#L134) Resolve the config governing `el`: the nearest ancestor boundary’s instance config (including `el` itself), or [aparteGlobalConfig](#aparteglobalconfig) when none is present. Cheap — a single `closest()`. DO NOT cache this at `connectedCallback`. An earlier version of this comment advised exactly that, and two elements followed it into a real bug: a framework wrapper calls `AparteChatHost.bind()` — which is what runs `attachConfig` — from its POST-mount hook (React `useEffect`, Vue `onMounted`, Svelte `onMount`, Angular `ngAfterViewInit`), so children mounted in the same commit connect BEFORE the boundary exists. A connect-time cache therefore freezes the global config forever, and the `config` prop every wrapper advertises silently does nothing for that element. Resolve it live, in a getter. `closest()` on a shallow tree is not a cost worth a correctness bug — `aparte-chat-bubble` has done it that way from the start, and it is the one element that was never affected. That advice covers READERS, and it is not enough on its own. An element that WRITES to its config — registering a presenter, a renderer, a keyed listener — cannot fix the ordering by resolving live, because the write already happened. Those implement [AparteConfigAware](#aparteconfigaware) and re-register when told. The reader/writer distinction is the one this file missed the first time round: the sweep that applied the advice above fixed every reader and left both writers broken. #### Parameters [Section titled “Parameters”](#parameters-79) | Parameter | Type | | --------- | ---------------------------------- | | `el` | `Element` \| `null` \| `undefined` | #### Returns [Section titled “Returns”](#returns-111) [`AparteConfig`](#aparteconfig) *** ### runWithConfig() [Section titled “runWithConfig()”](#runwithconfig)
```ts
function runWithConfig(config, fn): T;
```
Defined in: [packages/core/src/config/config-context.ts:155](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/config-context.ts#L155) Run `fn` with `config` as the ambient render config (restored after). #### Type Parameters [Section titled “Type Parameters”](#type-parameters) | Type Parameter | | -------------- | | `T` | #### Parameters [Section titled “Parameters”](#parameters-80) | Parameter | Type | | --------- | ------------------------------- | | `config` | [`AparteConfig`](#aparteconfig) | | `fn` | () => `T` | #### Returns [Section titled “Returns”](#returns-112) `T` *** ### contextConfig() [Section titled “contextConfig()”](#contextconfig)
```ts
function contextConfig(el?): AparteConfig;
```
Defined in: [packages/core/src/config/config-context.ts:170](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/config-context.ts#L170) The ambient render config set by [runWithConfig](#runwithconfig), else the config resolved from `el` (when provided), else the global singleton. Capture it synchronously at the top of a renderer — never after an `await`. #### Parameters [Section titled “Parameters”](#parameters-81) | Parameter | Type | | --------- | ------------------- | | `el?` | `Element` \| `null` | #### Returns [Section titled “Returns”](#returns-113) [`AparteConfig`](#aparteconfig) *** ### subscribeConfigChange() [Section titled “subscribeConfigChange()”](#subscribeconfigchange)
```ts
function subscribeConfigChange(el, handler): () => void;
```
Defined in: [packages/core/src/config/config-subscribe.ts:36](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/config-subscribe.ts#L36) #### Parameters [Section titled “Parameters”](#parameters-82) | Parameter | Type | | --------- | ------------ | | `el` | `Element` | | `handler` | () => `void` | #### Returns [Section titled “Returns”](#returns-114) () => `void` *** ### isSafeUrl() [Section titled “isSafeUrl()”](#issafeurl)
```ts
function isSafeUrl(value, tag): boolean;
```
Defined in: [packages/core/src/config/sanitize.ts:221](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/sanitize.ts#L221) #### Parameters [Section titled “Parameters”](#parameters-83) | Parameter | Type | | --------- | -------- | | `value` | `string` | | `tag` | `string` | #### Returns [Section titled “Returns”](#returns-115) `boolean` *** ## Variables [Section titled “Variables”](#variables) ### APARTE\_DEFAULT\_BUBBLE\_ACTIONS [Section titled “APARTE\_DEFAULT\_BUBBLE\_ACTIONS”](#aparte_default_bubble_actions)
```ts
const APARTE_DEFAULT_BUBBLE_ACTIONS: {
copy: false;
retry: false;
edit: false;
feedback: false;
info: false;
};
```
Defined in: [packages/core/src/config/aparte-config.ts:82](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L82) The bubble-action defaults — all off: a message carries no button until the app asks for one. Retry and edit only do something when a host (`AparteClient`) re-sends and rewrites, and feedback/info only when the app listens for `aparte-feedback` / `aparte-message-info`; rendering them unconditionally showed dead buttons in every display-only integration — ours included, which is how we found it. Copy is the one core could honor alone, and it is off too: a help widget or a support chat is read, not quoted, and a chat product that wants it turns it on in one line (`setBubbleActions({ copy: true })`). Exported so a consumer can read the defaults instead of hard-coding them. #### Type Declaration [Section titled “Type Declaration”](#type-declaration) ##### copy [Section titled “copy”](#copy-1)
```ts
readonly copy: false = false;
```
##### retry [Section titled “retry”](#retry-1)
```ts
readonly retry: false = false;
```
##### edit [Section titled “edit”](#edit-1)
```ts
readonly edit: false = false;
```
##### feedback [Section titled “feedback”](#feedback-1)
```ts
readonly feedback: false = false;
```
##### info [Section titled “info”](#info-1)
```ts
readonly info: false = false;
```
*** ### APARTE\_DEFAULT\_HOST\_HANDLERS [Section titled “APARTE\_DEFAULT\_HOST\_HANDLERS”](#aparte_default_host_handlers)
```ts
const APARTE_DEFAULT_HOST_HANDLERS: {
attachmentPreview: false;
filePreview: false;
};
```
Defined in: [packages/core/src/config/aparte-config.ts:98](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L98) The host-handler declarations — nothing declared. Same rule as [APARTE\_DEFAULT\_BUBBLE\_ACTIONS](#aparte_default_bubble_actions), applied outside the action bar: an image tile you can click is a request core forwards to the app. Undeclared, it is not rendered (and the tile is not even signalled as clickable) instead of doing nothing. #### Type Declaration [Section titled “Type Declaration”](#type-declaration-1) ##### attachmentPreview [Section titled “attachmentPreview”](#attachmentpreview)
```ts
readonly attachmentPreview: false = false;
```
##### filePreview [Section titled “filePreview”](#filepreview)
```ts
readonly filePreview: false = false;
```
*** ### aparteGlobalConfig [Section titled “aparteGlobalConfig”](#aparteglobalconfig)
```ts
const aparteGlobalConfig: AparteConfig;
```
Defined in: [packages/core/src/config/aparte-config.ts:2244](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/aparte-config.ts#L2244) The page-wide configuration: every chat reads it unless an ancestor carries an instance of its own ([attachConfig](#attachconfig)). There is one per window, kept on `window`, so two copies of the package on one page share it; off the browser (a server render, a test) each import creates its own. *** ### APARTE\_HOST\_ATTR [Section titled “APARTE\_HOST\_ATTR”](#aparte_host_attr)
```ts
const APARTE_HOST_ATTR: "data-aparte-host" = 'data-aparte-host';
```
Defined in: [packages/core/src/config/config-context.ts:22](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/config-context.ts#L22) Marks an element as an instance-config boundary (used by `closest()`). *** ### APARTE\_CONFIG\_CHANGE [Section titled “APARTE\_CONFIG\_CHANGE”](#aparte_config_change)
```ts
const APARTE_CONFIG_CHANGE: "aparte-config-change" = 'aparte-config-change';
```
Defined in: [packages/core/src/config/config-subscribe.ts:34](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/config-subscribe.ts#L34) The event `AparteConfig._notify()` dispatches on `window`. *** ### APARTE\_DEFAULT\_ICON\_FALLBACKS [Section titled “APARTE\_DEFAULT\_ICON\_FALLBACKS”](#aparte_default_icon_fallbacks)
```ts
const APARTE_DEFAULT_ICON_FALLBACKS: Record = APARTE_ICON_GLYPHS;
```
Defined in: [packages/core/src/config/icon-provider.ts:104](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/icon-provider.ts#L104) The default drawing for every name, assembled from `icons/glyphs.ts`. `getIcon()` reads this by a COMPUTED key, so a bundler cannot tell which entries a build reaches and keeps the object whole. That is the constraint that shapes the icon set: what belongs here is what core itself draws, and nothing else — an icon nobody renders would still ship to everybody. Extra glyphs are individual exports a consumer imports by name, never members of this record. *** ### APARTE\_DEFAULT\_LOCALE [Section titled “APARTE\_DEFAULT\_LOCALE”](#aparte_default_locale)
```ts
const APARTE_DEFAULT_LOCALE: AparteLocale;
```
Defined in: [packages/core/src/config/locale.ts:563](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/locale.ts#L563) Default English Locale (Zero-dependency) Hardcoded to ensure the core works out-of-the-box. *** ### defaultSanitizer [Section titled “defaultSanitizer”](#defaultsanitizer)
```ts
const defaultSanitizer: AparteSanitizer;
```
Defined in: [packages/core/src/config/sanitize.ts:645](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/sanitize.ts#L645) The built-in sanitizer. Parses `html` with the platform DOMParser, rebuilds an allowlisted tree, and re-serializes it. Falls back to a regex scrub only when no DOMParser exists (non-browser runtime). *** ## Interfaces [Section titled “Interfaces”](#interfaces) ### AparteAction [Section titled “AparteAction”](#aparteaction) Defined in: [packages/core/src/config/action-provider.ts:34](https://github.com/apartejs/aparte/blob/main/packages/core/src/config/action-provider.ts#L34) A custom action button, registered once via `aparteGlobalConfig.registerAction(...)` and placed in the message (bubble) toolbar via `zones`. Declarative and framework-agnostic: clicking it emits an `aparte-action` CustomEvent (bubbles, composed) carrying `{ actionId, zone, … }`, exactly like the built-in retry/feedback buttons — so you wire it the same way in React/Vue/Svelte/Angular and in vanilla. An optional `onClick` callback fires alongside the event for imperative convenience. For a button in the composer, write an `` in your markup and listen for `aparte-action-click` — see that element’s docs. #### Example [Section titled “Example”](#example-14)
```ts
aparteGlobalConfig.registerAction({
id: 'share', icon: '