@amodalai/react
See SDK Overview for installation and Chat for ChatWidget and AmodalChat props.
AmodalProvider
Wrap your app to configure the clients used by provider-based hooks:
import { AmodalProvider } from '@amodalai/react';
<AmodalProvider runtimeUrl={window.location.origin}>{children}</AmodalProvider>;| Prop | Required | Meaning |
|---|---|---|
runtimeUrl | yes | Base URL of the agent's runtime server. |
getToken | no | Returns a bearer token for authenticated requests (sync or async). |
metadata | no | Observability-only values sent with chat requests from provider-based hooks and AmodalAction; a map, or a function read on each send. See Request metadata. |
AmodalChat inherits only the provider's URL, so pass getToken to it separately. See Authentication for which URL and token to use.
useAmodalContext() returns the provider's internals (client: RuntimeClient, sdk: SdkClient, runtimeUrl, getToken) for anything the hooks don't cover; it throws outside a provider.
Request metadata
Every chat request from the SDK carries metadata that tells Amodal where the message came from. See Chat request body for how the runtime records it.
The SDK collects these keys from the browser:
| Key | Value |
|---|---|
screen | Page path, without the query string or fragment. |
pageTitle | document.title, when set. |
referrer | Referrer origin and path, without query or fragment. |
userAgent | navigator.userAgent. |
locale | navigator.language. |
timezone | The browser's IANA time zone. |
viewport | Window size as <width>x<height>. |
Add what only your app knows through the metadata prop of AmodalProvider or ChatWidget. ChatWidget and AmodalChat send only their own metadata prop; the provider's value applies to provider-based hooks and AmodalAction. Your values replace the collected ones with the same key, so a readable screen name can replace the path. Pass a function to read current values on each message:
<AmodalProvider
runtimeUrl={window.location.origin}
metadata={() => ({ userId: currentUser.id, screen: currentScreenName(), plan: account.plan })}
>
{children}
</AmodalProvider>Values must be strings. The runtime rejects a request over its metadata limits, so the SDK drops any of your entries that breaks them and logs a console warning naming each one. Past 50 keys, it keeps your entries over the collected ones. Do not put secrets or sensitive personal data in metadata.
Reading and writing stores
These hooks call the runtime's direct store API. They use the scope that the token's scope_id claim pins, not ChatWidget.scopeId. See Embedding for the partition rules.
useStoreQuery
const { data, error, isLoading, refetch } = useStoreQuery<Submission>('submissions', {
where: { status: 'received' },
orderBy: 'updated_at',
order: 'desc',
limit: 50,
});
// data: Array<{ key: string; value: Submission; updatedAt: string }>where is an equality filter on payload fields; orderBy/order sort server-side. Without limit, the runtime returns 20 rows; set limit to read more. Limits above 500 are fetched in 500-row pages. Call refetch() after an action to pull in new rows.
useStoreEntry
Read one document by key and update its payload:
const { data, isLoading, mutate, refetch } = useStoreEntry<Submission>('submissions', 'sub_bistro_ember');mutate(next) POSTs the payload and refetches. The runtime derives the document key from the payload's key template, so next must include its key field(s).
useStoreActions
Use get and set in event handlers:
const submissions = useStoreActions<Submission>('submissions');
await submissions.set('sub_x', row);set(key, value) accepts the key for compatibility; the runtime derives the stored key from value. The exported remove(key) calls a DELETE endpoint that the runtime store router does not implement.
Writes through mutate or set to a store declared shared return 403 unless the caller has an operator credential.
A store declared toolsOnly returns 404 to every hook unless the caller has an operator credential. See Tools-Only Stores.
Running work
useToolCall
Read the result of a tool with an app trigger. The hook runs the tool on mount and again when the tool name, input, scopeId or scopeContext change. refetch() runs it again. The tool sees the signed-in user as ctx.userId. Nothing is stored. From an event handler, call sdk.callTool(name, input).
const terms = useToolCall<{ terms: FundTerm[] }>('list_fund_terms', { fund_id });
// terms.data?.terms, terms.isLoading, terms.error, terms.refetch()useToolRun
Invoke a tool with an invoke trigger from a button or form. run resolves with { sessionId, outcome }. Read the run status through useSession; tools can also write results to stores.
const analyze = useToolRun('analyze-submission');
await analyze.run({ submission_id });
// analyze.status: 'idle' | 'running' | 'succeeded' | 'failed'
// analyze.output.outcome, analyze.error, analyze.reset()run resolves when the session reaches a terminal or operator-facing state: if the runtime answers synchronously with an outcome it is used directly; a queued start is watched (polled) to its outcome. Pass scopeId and scopeContext in the second argument to useToolRun when the tool operates on a scoped resource.
useToolTrigger enqueues through POST /api/enqueue, then watches the session. It has the same launcher interface as useToolRun. See Tools.
useAutomation
useAutomation() schedules a tool with an invoke trigger, a subagent, or a prompt. schedule(target, { schedule, input?, label?, enabled?, replace? }) takes a tool name or { kind, ref } and a schedule of { cron, timezone? }, { every } (5m, 15m, 1h, 1d, or 1w), or { at }. An automation is keyed by its label, which defaults to the target's ref. It also returns list, enable, disable, and remove. useAutomations(query?, { pollInterval? }) lists the automations the caller can manage, refetching every pollInterval milliseconds when one is given; its intent filter is ignored. A failed refetch keeps the last list in data next to error. These calls need capabilities.automations on the agent; without it they reject with status 404 and code AUTOMATIONS_DISABLED.
An automation that a signed-in person schedules belongs to that person, whether they schedule it from a page or in chat. An automation scheduled with a credential that names no person, such as an API key or an SDK client token, has no owner and is shared within its scope.
- A signed-in person lists and manages their own automations and the ones with no owner in the scope. Another owner's automation is absent from the list, and
enable,disable, andremovereject it with status 404. - A credential that names no person lists and manages every automation in the scope.
- A label is unique per owner within a scope. Two people can use the same label, and the automations with no owner share one set of labels per scope.
- Scheduling a label the caller already uses replaces the caller's own automation, and
replace: falserejects with status 409 instead. A credential that names no person replaces only an automation with no owner.
An automation with an owner runs only while that person can use the agent. An automation with no owner is never refused or paused for this reason.
schedulerejects with status 403 anddetail.codeowner_not_eligiblewhen the signed-in person cannot use the agent, and for a public visitor.- Amodal pauses an automation at its next run once its owner can no longer use the agent. The list reports it with
enabled: falseanddisabled_reason: 'owner_revoked'. enablerejects an automation whose owner cannot use the agent with status 403 anddetail.codeowner_not_eligible. Enabling it once the owner can use the agent again clearsdisabled_reason.
useSkillAction
Send a chat prompt that asks the agent to use a declared skill, then collect its text response. The model chooses how to follow the prompt. Use a durable tool when the action requires a defined execution path.
const namer = useSkillAction('subject-line-writer');
namer.execute({ topic: 'renewal reminder', count: 3 }); // params are serialized into the generated prompt
// namer.result (string | null), namer.loading, namer.errorWorked example
This example displays global store rows and refetches them after a durable tool runs:
function SubmissionsScreen() {
const submissions = useStoreQuery<Submission>('submissions', { limit: 200 });
const findings = useStoreQuery<RiskFinding>('risk_findings', { limit: 200 });
const analyze = useToolRun('analyze-submission');
async function onAnalyze(id: string) {
await analyze.run({ submission_id: id });
await Promise.all([submissions.refetch(), findings.refetch()]);
}
if (!submissions.data?.length) return <EmptyState hint="send `seed` in chat first" />;
return <SubmissionsTable rows={submissions.data} findings={findings.data} onAnalyze={onAnalyze} />;
}Sessions
Use session hooks to display durable tool runs, scheduled work, and pending user input. The runtime history API hides sessions owned by another verified user and, when the token has a scope_id claim, sessions in other scopes. See Sessions. For a multi-tenant UI, point the provider at an application proxy that authorizes session access and retains runtime credentials.
| Hook | What it gives you |
|---|---|
useSessions(query?) | The agent's sessions as SessionListItem rows, kept live. See below. |
useSession(id) | Full detail for one session: status, metadata (surface, current step, pending input request, progress), messages. Poll via refetch, or pair with useAgentEvents for live updates. |
useSessionActions(id) | Operator actions: answer(value, edits?) resolves a pending requestInput (the runtime enforces eligible answerers), cancel(), restart(). |
useScheduledTools() | Sessions fired by schedules (cron), for a "scheduled runs" list. |
useToolCallLog({ sessionId }) | Per-session tool-call audit log (options also accept since and limit). |
useSessions returns data, error, isLoading, refetch(), and markRead(id). The runtime ignores query. Each row carries status, pending (what an awaiting-input session asks), last_turn_ended_at, and unread; a runtime without these fields reports null and false. The hook follows /api/events with the provider's getToken and refetches the list in the background when a session the caller may read changes, and once after each reconnect. markRead(id) marks a chat read for its owner and refetches. See Sessions.
sessionIndicator(row) maps a row to the one status a chat list shows, so every host applies the same order. The first matching rule wins:
running: statusrunningorqueued.waiting:pendingis set, or statusawaiting-input.failed: statusfailed.unread:unreadistrue.
Any other row returns null, including active from older runtimes, idle, cancelled, and durable-run waits such as scheduled or awaiting-webhook. Only the host knows which chat is on screen, so hiding unread for the open chat is up to the host.
Memory
useMemory({ archived?, topic?, scopeId? }) lists the agent's company memories and the signed-in user's private ones through /api/memory. With topic, it lists only the memories saved on exactly that topic. See Memory for the tiers and topics.
data.memoriesholds the entries:id,tier,content,topic,owner_id,updated_by,source_ids,share_requested,archived_at,archived_by,created_at, andupdated_at.share_requestedmarks a private memory the agent proposed for the company.data.writable_tierslists the tiers the caller may write. It is empty when memory is read-only for them.add({ content, tier?, topic?, sourceIds? })saves a memory.tierdefaults to the first writable tier,privatefor a signed-in user.update(id, patch)editscontent, setstopicor clears it with{ topic: null }, archives with{ archived: true }, restores with{ archived: false }, shares a private memory with{ tier: 'company' }, and makes a company memory private with{ tier: 'private' }. Only the memory's owner can changetier; anyone else getsNOT_OWNER.- Pass
baseUpdatedAt, theupdated_atof the entry the edit starts from, to refuse the edit when someone changed the memory since.updatethen rejects with aStaleMemoryEditError, anSdkErrorwith status 409 anddetail.codeSTALE_EDITwhosecurrentis the entry as it stands, and nothing is changed.
Without scopeId, the runtime uses the token's scope, as for chat. A memory that no longer exists makes update reject with NOT_FOUND. On an agent without memory, the hook's error is NOT_FOUND with detail.code MEMORY_DISABLED.
Notifications
useNotifications({ unreadOnly?, limit? }) lists the signed-in person's notifications through /api/notifications, newest first.
dataholdsnotifications,next_cursor, andunread_count. Each entry hasid,key,kind,title,body,link,email,session_id,created_at,updated_at, andread_at.unreadis the caller's unread count,0before the first response.markRead(ids)marks the listed ids read, or every notification with'all', and refetches.
limit defaults to 50 and can be at most 100. The hook follows /api/events and refetches in the background when a notification_created event arrives, and once after each reconnect.
useNotificationPrefs() reads the person's email setting for the agent. data holds email ('off' or 'each') and email_available, which is false on a preview deploy and when no email can reach the person. setEmail(email) saves the setting and refetches. See Email.
Live events
useAgentEvents subscribes to the runtime's event bus over SSE (/api/events):
const { events, latest, isConnected } = useAgentEvents({
include: ["tool_calls"], // server-side filter: categories or event-type names
sessionId, // optional client-side narrowing to one session
onEvent: (e) => { ... },
});Type predicates (isToolCallStarted, isToolCallCompleted, isToolCallFailed) narrow the discriminated AgentEvent union. Reconnects resume from the last delivered event id.
The hook opens a plain EventSource and does not send getToken. On a hosted runtime it therefore authenticates only through the same-origin session cookie, receives events without content fields such as argsSummary and error, and receives every event type regardless of include. It receives session events only for the sessions that cookie's user may read, so a cross-origin page without the cookie receives none. See Event Bus.
Chat components
AmodalAction
Fires a chat prompt from a button or other UI element:
import { AmodalAction } from '@amodalai/react';
<AmodalAction prompt="Summarize today's alerts" label="Get Summary" />;AmodalAction asks the model to follow a prompt. useToolRun invokes a named tool directly. The handler may itself call a model; determinism depends on its implementation.
Confirmation and review cards
Chat renders approval controls for confirmation_required events. These components are also exported for standalone approval UIs:
ConfirmCard: endpoint, method, reason, approve/deny.ReviewCard: the structured variant; full parameters, escalation badge, connection name.
Both take { confirmation, onApprove, onDeny }.
FormattedMarkdown, a prose-styled Markdown renderer, is exported for rendering agent output outside the chat surfaces. It shows an image only from the page's own origin and renders any other image as a link; see Images in answers. Set relativeLinksAsText on a page outside the app that embeds the agent, where a link such as /people/julian-marsh would open the wrong page.
MarkdownPreview renders Markdown as one run of text that keeps only bold, italic, strikethrough, and code formatting. It suits a line-clamped preview such as a notification body.
Chat hooks
For a custom chat surface without ChatWidget:
| Hook | Description |
|---|---|
useAmodalChat | Provider-based chat session: send messages, streamed state, confirmation callbacks. |
useChat | The widget's chat state machine over /chat/stream, serverUrl-based. files lists the conversation's uploaded files. |
useChatStream | The transport-agnostic reducer underneath useChat; you supply streamFn, and confirmFn to deliver approval answers (for example RuntimeClient.respondToConfirmation). |
useSessionHistory | List, retag, rename, and delete previous chat sessions. |
useDictation | Speech-to-text for a message box you render. |
useAmodalChat and useChat prepare a session through POST /sessions when they mount and send its ID with the first message, so the first reply skips the session setup. A hook that resumes a session prepares nothing, and reset prepares the next session. If the runtime cannot prepare one, useChat creates the session when the first message is sent, and keeps the message in the box if that fails. A runtime that answers 4xx to POST /sessions starts the session from the first message. A prepared session that is still unused is rebuilt in the background when the page regains focus after most of the runtime's idle timeout has passed, before the runtime evicts it. useChat and ChatWidget also rebuild it after the token returned by getToken changes. An application proxy can therefore see POST /sessions requests beyond the one at mount. Pass prepareSession: false to useAmodalChat or useChat where a mount rarely leads to a message; AmodalAction does.
useChat and ChatWidget send every message with continue_on_disconnect: true and a client turn_id. An active turn keeps running on the runtime if the view unmounts or disconnects. A view that resumes the session finds the active turn and observes it through GET /chat/sessions/:id/turns/:turnId.
ArtifactHost and useArtifactHost() share published files and registered artifacts between ChatWidget and surrounding application panels.
useAmodalBrief, useAmodalInsight, and useAmodalQuery each wrap one chat exchange through RuntimeClient.chatStream.
RuntimeClient.startTask and useAmodalTask call /task endpoints that neither the hosted runtime nor amodal dev serves. Use useToolTrigger with a durable tool for background work.
useDictation
useDictation runs the browser's speech recognition for a message box you render:
const inputRef = useRef<HTMLTextAreaElement>(null);
const [text, setText] = useState('');
const dictation = useDictation({ inputRef, onText: setText, onError: showNotice });
const send = () => {
dictation.cancel();
sendMessage(text);
};| Option | Description |
|---|---|
inputRef | The box being dictated into. Its text when dictation starts stays ahead of what is said, and it gets focus back when dictation ends. |
onText | Receives the box's full text on every recognition result. |
onError | Optional. Receives a message to show the user when dictation fails, such as a blocked microphone. |
The hook returns supported, listening, toggle, and cancel. supported is false in browsers without speech recognition, such as Firefox; hide the microphone button there. toggle starts dictation, or stops it and keeps what was said. cancel stops dictation and drops results still in flight; call it when the message is sent. Dictation also stops when the component unmounts.
Headless clients
Everything the hooks do is available imperatively:
-
SdkClient(viauseAmodalContext().sdkor constructed directly):callTool,runTool,triggerTool,watchSession, session actions, store access via.runtime, files (readFile,listDir; hosted runtime only), automations. Its calls reject withHttpError,NotImplementedError, orRefusal, where the hooks that wrap them reject with anSdkError. -
RuntimeClient:chatStream, store document reads. -
RuntimeClient.watchSessionChanges(onChange, signal): callsonChangeonce per burst of changes to sessions the caller may read, and once after each reconnect, untilsignalaborts. It is whatuseSessionsuses, so a host that keeps the session list in its own cache can refetch it the same way:import { RuntimeClient } from '@amodalai/react/client'; const controller = new AbortController(); void new RuntimeClient({ runtimeUrl, getToken }).watchSessionChanges( () => queryClient.invalidateQueries({ queryKey: ['sessions'] }), controller.signal, ); -
ChatClient/ChatStream: headless chat with typed events, no React. -
streamChat,createSession,listSessions,getSessionHistory(chat API),streamSSE/parseSSELine(SSE utilities): the lowest-level pieces, used by the clients above. -
runtimeFetch:fetchthat sends the page to the hosted sign-in when a same-origin request gets401 LOGIN_REQUIRED. Every client above uses it. -
fetchUploadLimitsanduploadFile: read the runtime's upload limits,nullwhen the agent takes no uploads, and upload one file with progress. Pass the result to a send as{ fileId, filename, mimeType, size, data: '' }; the chat request carries only the id.
@amodalai/react/client exports RuntimeClient, ChatClient, ChatStream, runtimeFetch, and the chat API and SSE utilities without the components and hooks. listSessions returns SessionListItem rows, the same shape useSessions returns. sessionIndicator is exported from both entry points. SdkClient is exported from the package root only.
Unsupported endpoints
These call endpoints the runtime does not serve:
useAuthanduseTeamMembers. They return aNOT_IMPLEMENTEDSdkErrorthrough theirerrorfield.useConnections, which requests a connection list endpoint that does not exist.useStoreActions().remove, described above.SdkClient.writeFile, which callsPUT /api/files/*. Neither the hosted runtime noramodal devserves that route.