Bridge API reference
The typed client your panel uses to talk to Chataway — context, files, host media, accounts, cards, badges, the user's AI, chats, folders, agent runs and events — plus the postMessage protocol underneath.
npm install @chataway/appsimport { connect } from '@chataway/apps/bridge';
import '@chataway/apps/theme.css';
const app = await connect();@chataway/apps/bridge has no dependencies and works with any framework. Everything is promise-based; errors are BridgeErrors.
#Connecting
#connect(options?)
Handshakes with the host and resolves with a ChatawayApp. Calling it again returns the same connection.
| Option | Type | Default | |
|---|---|---|---|
mock | boolean | MockHostOptions | auto | true forces the mock host, false forbids it. Default: mock only when the page isn't embedded in Chataway. |
timeoutMs | number | 30000 | Default per-request timeout. Pickers, connect and media use longer ones. |
connectTimeoutMs | number | 10000 | How long to wait for the host's first answer. |
applyTheme | boolean | true | Apply the host theme to <html> (palette, light/dark, exact colours) and keep it updated. |
#isEmbedded()
true when the page runs inside a Chataway panel or card.
#Context
#app.context
What the host sent on connect. Updated automatically on view and theme events.
| Field | Type | |
|---|---|---|
pluginId | string | Your app id. |
projectId | string | The current project (a local id — not the pseudonym your server sees). |
chatId | string | null | The active chat, if any. |
cardId | string | null | Set when this page is a webview card. |
params | object | Card params (webview cards). params.open = the file the user opened with your app ({ root, name, handlerId }, see onOpen). |
view | string | null | The selected header view. |
apiBase | string | Path prefix for host URLs. files.url() and host.media() already apply it. |
theme | HostTheme | The host palette as hex: bg, surface, hover, text, muted, dim, border, primary, primaryFg, danger, success, dark, palette. |
#app.getContext()
Re-reads the context from the host. Promise<AppContext>.
#Files
#app.pickFiles(options?)
Opens Chataway's file picker: Media library, project files, or upload from the device. Resolves with only the files the user chose. Needs files:receive.
| Option | Type | |
|---|---|---|
accept | string[] | MIME types or extensions: ['image/*', '.pdf']. |
multiple | boolean | Allow several files. Default false. |
Returns Promise<PickedFile[]>:
PickedFile | |
|---|---|
ref | Opaque plugin-file: ref — pass it to host.media and files.*. |
name | File name. |
type | MIME type. |
size | Bytes. |
blob() | Promise<Blob> — the bytes. |
url() | Promise<string> — a URL you can use in <img>, <video> or fetch. |
Rejects with cancelled when the user closes the picker. Default timeout: 15 minutes.
const files = await app.pickFiles({ accept: ['image/png', 'image/jpeg'], multiple: true });
const form = new FormData();
for (const f of files) form.append('file', await f.blob(), f.name);
await fetch('https://api.example.com/upload', { method: 'POST', body: form, headers: { Authorization: `Bearer ${token}` } });#app.files.url(ref)
A URL for a ref your app may see (a picked file, a host media result, a file you returned). Promise<string>.
#app.files.addToLibrary(ref)
Copies a file your app owns into the project's Media library. Promise<{ ref }> — the library copy's ref. Needs files:return.
#Host media
#app.host.media(op, ref, params?)
Runs a host media operation on a file and returns a new file. Needs host:media.
const out = await app.host.media('resize', photo.ref, { width: 512, height: 512, fit: 'cover', format: 'png' });
// out = { ref, url, info? }| Result | |
|---|---|
ref | The new file's ref. The source is never modified. |
url | Loadable URL of the result. |
info | For probe: { width, height, duration, codecs }. |
Default timeout: 11 minutes (jobs queue, at most 2 per app at a time).
#Accounts
#app.accounts.list()
Your declared accounts and whether each is connected. Promise<AccountState[]>: { id, label, connected, expiresAt }.
#app.accounts.connect(id)
Starts the OAuth flow. Resolves with the account state once connected; rejects with cancelled if the user gives up. Must be called from a user gesture (a click handler).
#app.accounts.getToken(id)
A fresh access token for calling your own API from the panel. Promise<{ accessToken, expiresAt }>. The host refreshes it when needed — ask again rather than caching it. Rejects with denied if the account isn't connected.
#Cards and jobs
#app.listCards(options?)
Your app's cards in this project. options.status: pending · resolved · expired · cancelled · info. Promise<PluginCard[]>.
#app.respondCard(cardId, actionId, values?)
Answers one of your cards from the panel — for example, approving a pending upload from a queue view. values carries form answers. Promise<PluginCard>. Only your own cards; others reject with denied.
#app.listJobs() · app.cancelJob(jobId)
Your app's recent jobs in this project (for example host media jobs), and cancelling one that's running.
#UI
#app.setBadge(view, count)
Shows a count on one of your header views. 0 clears it.
#App API 4
These need "requires": { "hostApi": 4 } in plugin.json and the grant in each heading (a missing grant is denied). On an older Chataway they fail with unsupported.
#Click-only methods
chat.send, chat.create, chat.open, folders.request, fs.trash and agent.run need the user's click or key press inside your panel — focus has to be in your app's frame; a click elsewhere in Chataway (another chat's composer, the sidebar) doesn't count — and one click allows one call of each kind, within 5 seconds. Answering one of your app's host dialogs (Allow on folders.request, Send, Move to Trash…) counts as a click for your app's next calls in those 5 seconds, so folders.request and then agent.run work in one handler. Anything else fails with needs-gesture, and so does every click-only method in a webview that can't prove clicks.
#AI — grant models
| Method | Params | Result |
|---|---|---|
app.models.run(options) | { prompt?, messages?, system?, images?, schema?, maxTokens?, tier? } | { text, json?, model: { label }, usage: { callsToday, limit } } |
app.models.stream(options) | the same | A ModelStream: for await (const delta of s), then await s.result → { text, model }; s.text so far; s.cancel() (or break) stops it (models.cancel) |
app.models.usage() | – | { callsToday, limit, unlimited } |
app.prompts.list() | – | Your prompt kits: [{ id, title, description?, text, vars, surfaces }] |
tier is fast, balanced (default) or best — never a model id. Every call counts in your app's daily budget. See AI & prompt kits.
#Chats
| Method | Params | Result |
|---|---|---|
app.chat.compose(options) | { text?, attachments?, promptId?, values?, mode?, chatId? } | { status: 'filled' | 'queued' } — fills the composer, never sends |
app.chat.send(options) | { text?, attachments?, chatId? } — click only | { status: 'sent' | 'busy' | 'no-chat', chatId? } |
app.chat.create(options?) | { title?, text?, attachments?, send? } — grant chats, click only | { chatId, status: 'created' | 'filled' | 'queued' | 'sent' | 'busy' | 'no-chat' } |
app.chat.list() | – grant chats | [{ chatId, title, createdAt, lastMessageAt }], latest first |
app.chat.open(chatId) | grant chats, click only | { opened: true } |
chat.compose and chat.send work at any app API level; promptId needs 4. See App chats.
#Folders and files — grant folders
| Method | Params | Result |
|---|---|---|
app.folders.list() | – | [{ id, label, suggested, extensions, access, reason, granted: { path, at } | null }] |
app.folders.request(id) | click only | { granted, root?, path? } |
app.folders.revoke(id) | – | { revoked: true } |
app.fs.list(options) | { root, path?, recursive? } | { entries: [{ path, name, kind, size, mtime, version? }], truncated } — version for files ≤ 1 MB, the first 200 |
app.fs.read(options) | { root, path, as? } | { path, mime, size, version, text?, data? } — text files as text, others as base64 data, unless as says |
app.fs.write(options) | { root, path, text? | data?, ifVersion? } | { path, version } — stale ifVersion → conflict |
app.fs.rename(options) | { root, from, to } | { path, version? } — never overwrites |
app.fs.trash(options) | { root, path } — click only; the host asks the user | { trashed } |
app.fs.restore(options) | { root, path } | { path, version } — the newest backup, one step back per call |
app.fs.watch(root) · app.fs.unwatch(root) | – | { watching } |
app.fs.onChange(root, handler) | – | Promise<() => void> — watch + fs-change handler for that root |
app.onOpen(handler) | – | Unsubscribe. Called with { root, name, handlerId } for context.params.open and every open event |
A root is folder:<id> (folderRoot(id) builds it), file:<handle> (a file opened with your app) or storage (your own storage, no grant). data may be base64, a Uint8Array, an ArrayBuffer or a Blob. See Folders & Open with.
#Agent runs — grants agent + models
| Method | Params | Result |
|---|---|---|
app.agent.run(options) | { task, roots, appTools?, tier?, maxSteps? } — click only | { runId } — a second run while one is going → busy |
app.agent.get(runId) | – | The run: { id, task, roots, status, model, stepCount, steps, result, error, startedAt, endedAt, … } |
app.agent.list() | – | Your recent runs in this project, newest first (up to 50, without steps) |
app.agent.stop(runId) | – | { stopped: true } |
app.agent.wait(runId, onUpdate?) | – | The run, once done, failed or stopped |
See Agent runs.
#Events
const off = app.on('card', card => updateQueue(card));
off(); // unsubscribe| Event | Payload | When |
|---|---|---|
view | string | The user switched the header view. |
theme | HostTheme | Palette or light/dark changed. Applied to <html> automatically unless applyTheme: false. |
card | PluginCard | One of your cards was created or changed (answered, expired…). |
job | PluginJob | One of your jobs progressed or finished. |
account | { pluginId, accountId, connected, error } | A connect flow finished, or the user disconnected. |
model-chunk · model-done · model-error | { streamId, delta } · { streamId, text, model, json? } · { streamId, error, code } | A models.stream answer. app.models.stream() handles these for you. |
fs-change | { root, path, kind, version? } | A file changed under a watched root — by your panel, the user's agent or anyone else. kind: changed, created, deleted. |
agent-run | { run, step? } | One of your agent runs took a step or changed status. run has stepCount, not steps. |
open | { root, name, handlerId } | The user opened a file with your app while the panel was open. |
app.off(event, handler) also unsubscribes. app.close() stops listening; pending requests reject with closed.
#Errors
Every failure is a BridgeError with a code and the method that failed:
code | Meaning |
|---|---|
cancelled | The user closed a picker or the connect flow, or said no (fs.trash, a message you asked to send). Usually not worth an error message. |
denied | A grant is missing, or it's not your card, job, file, kit, chat or run. Also: a folder that isn't granted, a secret file, a symbolic link out of the root, a file type you didn't declare, a write where you may only read, or a write to a hidden or agent-instructions file. |
timeout | No answer in time. |
unsupported | This version of Chataway doesn't know the method — ask the user to update. |
closed | app.close() was called. |
needs-gesture | The method speaks or acts for the user — call it from a click or key handler in your panel, once per click: chat.send, chat.create, chat.open, folders.request, fs.trash, agent.run (click only). |
budget | Your app used today's AI calls. The message says where the user changes the limit. |
conflict | fs.write with a stale ifVersion, or ifVersion: null for a file that exists (e.details.current is the version on disk now, or null). |
busy | An agent run of your app is already going in this project. |
host | Anything else; see message — for example an expired file: root, or fs.restore with no backup left. |
e.details holds any extra fields the host sent with the error.
import { BridgeError } from '@chataway/apps/bridge';
try {
await app.pickFiles();
} catch (e) {
if (e instanceof BridgeError && e.code === 'cancelled') return;
throw e;
}#Mock host
Opened directly in a browser (npm run ui with Vite), connect() uses a mock host so you can build the UI without Chataway. A small floating toolbar switches palette, light/dark and view.
const app = await connect({
mock: {
views: [{ id: 'library', label: 'Library' }, { id: 'uploads', label: 'Uploads' }],
accounts: [{ id: 'acme', label: 'Acme', connected: true }],
files: [{ name: 'test.png', type: 'image/png', bytes: pngBytes }],
dark: false,
},
});MockHostOptions | |
|---|---|
pluginId, projectId, chatId | Context values. |
views, view | Header views and the selected one. |
palette, dark | Initial theme. |
accounts | Accounts to pretend are declared. |
cards, jobs | Initial cards and jobs. |
files | Files pickFiles returns without a chooser. |
toolbar | Show the dev toolbar (default true in a browser). |
latencyMs | Simulated latency. |
For app API 4 the mock host has an echo model, an in-memory file system and fake agent runs:
MockHostOptions (app API 4) | |
|---|---|
manifest | Your plugin.json. Views, prompt kits, folders and file handlers come from it, and the mock refuses calls whose grant is missing, like Chataway. |
prompts, folders | Instead of the manifest's. |
grantedFolders | Folder ids already granted. |
grantFolders | false = the user says no to folders.request. Default true. |
fs | Files at start, per root: { 'folder:notes': { 'a.md': '# A' }, storage: { … } }. |
open | { name, content, handlerId? } — a file the panel was opened with (context.params.open). |
model | ({ messages, system, schema, tier, images }) => string | object — your fake model. Default: echoes the prompt, or an example object for schema. |
modelLimit | Daily AI calls. Default 300; null = no limit; 0 = AI off. |
streamChunkMs | Delay between streamed words (default 25). |
agent | (task, tools) => summary — a fake agent with tools.list / read / write limited to the run's roots. Default: lists each root. |
agentStepMs | Delay between fake agent steps (default 200). |
chats | Your app's chats at start. |
gestures | false = don't require a click for click-only methods. Default true (checked with navigator.userActivation; the mock doesn't limit calls per click or ask before sends). |
File versions, conflicts, backups (fs.restore) and fs-change events work as in Chataway.
app.isMock is true against the mock host, and app.mockHost lets you drive it from your dev tools:
app.mockHost | |
|---|---|
emit(event, payload) | Send any event to the page. |
setView(id) · setTheme(palette, dark) | Switch the header view or theme. |
writeFile(root, path, content) | Someone else changed a file: writes it and sends fs-change. Your next write with the old version gets a conflict. |
readFile(root, path) · deleteFile(root, path) | Look at or remove a file. |
openFile(name, content, handlerId?) | Play Open in …: makes a file: root and sends open. |
grantFolder(id, path?) | Grant a folder without asking. |
composed · chats · runs · callsToday · calls | What chat.* would have done, your chats, agent runs, today's AI calls, every request. |
#Protocol
The client is a thin layer over postMessage. You don't need this unless you're writing your own client.
// page → host
{ type: 'claw:request', id: 'r1', method: 'pickFiles', params: { accept: ['image/*'], multiple: true } }
// host → page
{ type: 'claw:response', id: 'r1', result: [ /* files */ ] }
{ type: 'claw:response', id: 'r1', error: 'cancelled by the user' }
{ type: 'claw:event', event: 'theme', payload: { bg: '#0b0b0c', /* … */ } }Methods: getContext, pickFiles, host.media, accounts.list, accounts.connect, accounts.getToken, files.url, files.addToLibrary, listCards, respondCard, listJobs, cancelJob, setBadge, chat.compose, chat.send. App API 4: models.run, models.stream, models.cancel, models.usage, prompts.list, chat.create, chat.list, chat.open, folders.list, folders.request, folders.revoke, fs.list, fs.read, fs.write, fs.rename, fs.trash, fs.restore, fs.watch, fs.unwatch, agent.run, agent.stop, agent.get, agent.list. Errors may be an object { code, message, …details }. The page posts to window.parent with target '*' (the sandboxed frame has an opaque origin); the host only accepts messages from your frame.